blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
612c6ace0c4ecccdb027a2a25e194ccd9e1c133e | f6439b5ed1614fd8db05fa963b47765eae225eb5 | /chrome/browser/password_manager/password_store_factory.cc | 41c95ca6a6ec3ea2abec55a617b6ccded5634563 | [
"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 | 10,193 | 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.
#include "chrome/browser/password_manager/password_store_factory.h"
#include "base/command_line.h"
#include "base/environment.h"
#include "base/prefs/pref_service.h"
#include "chrome/browser/password_manager/sync_metrics.h"
#include "chrome/browser/profiles/incognito_helpers.h"
#include "chrome/browser/sync/glue/sync_start_util.h"
#include "chrome/browser/webdata/web_data_service_factory.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_switches.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "components/os_crypt/os_crypt_switches.h"
#include "components/password_manager/core/browser/login_database.h"
#include "components/password_manager/core/browser/password_store.h"
#include "components/password_manager/core/browser/password_store_default.h"
#include "components/password_manager/core/common/password_manager_pref_names.h"
#include "components/pref_registry/pref_registry_syncable.h"
#include "content/public/browser/browser_thread.h"
#if defined(OS_WIN)
#include "chrome/browser/password_manager/password_store_win.h"
#include "components/password_manager/core/browser/webdata/password_web_data_service_win.h"
#elif defined(OS_MACOSX)
#include "chrome/browser/password_manager/password_store_mac.h"
#include "crypto/apple_keychain.h"
#include "crypto/mock_apple_keychain.h"
#elif defined(OS_CHROMEOS) || defined(OS_ANDROID)
// Don't do anything. We're going to use the default store.
#elif defined(USE_X11)
#include "base/nix/xdg_util.h"
#if defined(USE_GNOME_KEYRING)
#include "chrome/browser/password_manager/native_backend_gnome_x.h"
#endif
#include "chrome/browser/password_manager/native_backend_kwallet_x.h"
#include "chrome/browser/password_manager/password_store_x.h"
#endif
using password_manager::PasswordStore;
#if !defined(OS_CHROMEOS) && defined(USE_X11)
namespace {
const LocalProfileId kInvalidLocalProfileId =
static_cast<LocalProfileId>(0);
} // namespace
#endif
PasswordStoreService::PasswordStoreService(
scoped_refptr<PasswordStore> password_store)
: password_store_(password_store) {}
PasswordStoreService::~PasswordStoreService() {}
scoped_refptr<PasswordStore> PasswordStoreService::GetPasswordStore() {
return password_store_;
}
void PasswordStoreService::Shutdown() {
if (password_store_)
password_store_->Shutdown();
}
// static
scoped_refptr<PasswordStore> PasswordStoreFactory::GetForProfile(
Profile* profile,
Profile::ServiceAccessType sat) {
if (sat == Profile::IMPLICIT_ACCESS && profile->IsOffTheRecord()) {
NOTREACHED() << "This profile is OffTheRecord";
return NULL;
}
PasswordStoreFactory* factory = GetInstance();
PasswordStoreService* service = static_cast<PasswordStoreService*>(
factory->GetServiceForBrowserContext(profile, true));
if (!service)
return NULL;
return service->GetPasswordStore();
}
// static
PasswordStoreFactory* PasswordStoreFactory::GetInstance() {
return Singleton<PasswordStoreFactory>::get();
}
PasswordStoreFactory::PasswordStoreFactory()
: BrowserContextKeyedServiceFactory(
"PasswordStore",
BrowserContextDependencyManager::GetInstance()) {
DependsOn(WebDataServiceFactory::GetInstance());
}
PasswordStoreFactory::~PasswordStoreFactory() {}
#if !defined(OS_CHROMEOS) && defined(USE_X11)
LocalProfileId PasswordStoreFactory::GetLocalProfileId(
PrefService* prefs) const {
LocalProfileId id =
prefs->GetInteger(password_manager::prefs::kLocalProfileId);
if (id == kInvalidLocalProfileId) {
// Note that there are many more users than this. Thus, by design, this is
// not a unique id. However, it is large enough that it is very unlikely
// that it would be repeated twice on a single machine. It is still possible
// for that to occur though, so the potential results of it actually
// happening should be considered when using this value.
static const LocalProfileId kLocalProfileIdMask =
static_cast<LocalProfileId>((1 << 24) - 1);
do {
id = rand() & kLocalProfileIdMask;
// TODO(mdm): scan other profiles to make sure they are not using this id?
} while (id == kInvalidLocalProfileId);
prefs->SetInteger(password_manager::prefs::kLocalProfileId, id);
}
return id;
}
#endif
KeyedService* PasswordStoreFactory::BuildServiceInstanceFor(
content::BrowserContext* context) const {
Profile* profile = static_cast<Profile*>(context);
base::FilePath login_db_file_path = profile->GetPath();
login_db_file_path = login_db_file_path.Append(chrome::kLoginDataFileName);
scoped_ptr<password_manager::LoginDatabase> login_db(
new password_manager::LoginDatabase());
{
// TODO(paivanof@gmail.com): execution of login_db->Init() should go
// to DB thread. http://crbug.com/138903
base::ThreadRestrictions::ScopedAllowIO allow_io;
if (!login_db->Init(login_db_file_path)) {
LOG(ERROR) << "Could not initialize login database.";
return NULL;
}
}
scoped_refptr<base::SingleThreadTaskRunner> main_thread_runner(
base::MessageLoopProxy::current());
scoped_refptr<base::SingleThreadTaskRunner> db_thread_runner(
content::BrowserThread::GetMessageLoopProxyForThread(
content::BrowserThread::DB));
scoped_refptr<PasswordStore> ps;
#if defined(OS_WIN)
ps = new PasswordStoreWin(main_thread_runner,
db_thread_runner,
login_db.release(),
WebDataServiceFactory::GetPasswordWebDataForProfile(
profile, Profile::EXPLICIT_ACCESS));
#elif defined(OS_MACOSX)
crypto::AppleKeychain* keychain =
CommandLine::ForCurrentProcess()->HasSwitch(
os_crypt::switches::kUseMockKeychain) ?
new crypto::MockAppleKeychain() : new crypto::AppleKeychain();
ps = new PasswordStoreMac(
main_thread_runner, db_thread_runner, keychain, login_db.release());
#elif defined(OS_CHROMEOS) || defined(OS_ANDROID)
// For now, we use PasswordStoreDefault. We might want to make a native
// backend for PasswordStoreX (see below) in the future though.
ps = new password_manager::PasswordStoreDefault(
main_thread_runner, db_thread_runner, login_db.release());
#elif defined(USE_X11)
// On POSIX systems, we try to use the "native" password management system of
// the desktop environment currently running, allowing GNOME Keyring in XFCE.
// (In all cases we fall back on the basic store in case of failure.)
base::nix::DesktopEnvironment desktop_env;
std::string store_type =
CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
switches::kPasswordStore);
if (store_type == "kwallet") {
desktop_env = base::nix::DESKTOP_ENVIRONMENT_KDE4;
} else if (store_type == "gnome") {
desktop_env = base::nix::DESKTOP_ENVIRONMENT_GNOME;
} else if (store_type == "basic") {
desktop_env = base::nix::DESKTOP_ENVIRONMENT_OTHER;
} else {
// Detect the store to use automatically.
scoped_ptr<base::Environment> env(base::Environment::Create());
desktop_env = base::nix::GetDesktopEnvironment(env.get());
const char* name = base::nix::GetDesktopEnvironmentName(desktop_env);
VLOG(1) << "Password storage detected desktop environment: "
<< (name ? name : "(unknown)");
}
PrefService* prefs = profile->GetPrefs();
LocalProfileId id = GetLocalProfileId(prefs);
scoped_ptr<PasswordStoreX::NativeBackend> backend;
if (desktop_env == base::nix::DESKTOP_ENVIRONMENT_KDE4) {
// KDE3 didn't use DBus, which our KWallet store uses.
VLOG(1) << "Trying KWallet for password storage.";
backend.reset(new NativeBackendKWallet(id));
if (backend->Init())
VLOG(1) << "Using KWallet for password storage.";
else
backend.reset();
} else if (desktop_env == base::nix::DESKTOP_ENVIRONMENT_GNOME ||
desktop_env == base::nix::DESKTOP_ENVIRONMENT_UNITY ||
desktop_env == base::nix::DESKTOP_ENVIRONMENT_XFCE) {
#if defined(USE_GNOME_KEYRING)
VLOG(1) << "Trying GNOME keyring for password storage.";
backend.reset(new NativeBackendGnome(id));
if (backend->Init())
VLOG(1) << "Using GNOME keyring for password storage.";
else
backend.reset();
#endif // defined(USE_GNOME_KEYRING)
}
if (!backend.get()) {
LOG(WARNING) << "Using basic (unencrypted) store for password storage. "
"See http://code.google.com/p/chromium/wiki/LinuxPasswordStorage for "
"more information about password storage options.";
}
ps = new PasswordStoreX(main_thread_runner,
db_thread_runner,
login_db.release(),
backend.release());
#elif defined(USE_OZONE)
ps = new password_manager::PasswordStoreDefault(
main_thread_runner, db_thread_runner, login_db.release());
#else
NOTIMPLEMENTED();
#endif
std::string sync_username =
password_manager_sync_metrics::GetSyncUsername(profile);
if (!ps || !ps->Init(
sync_start_util::GetFlareForSyncableService(profile->GetPath()),
sync_username)) {
NOTREACHED() << "Could not initialize password manager.";
return NULL;
}
return new PasswordStoreService(ps);
}
void PasswordStoreFactory::RegisterProfilePrefs(
user_prefs::PrefRegistrySyncable* registry) {
#if !defined(OS_CHROMEOS) && defined(USE_X11)
// Notice that the preprocessor conditions above are exactly those that will
// result in using PasswordStoreX in BuildServiceInstanceFor().
registry->RegisterIntegerPref(
password_manager::prefs::kLocalProfileId,
kInvalidLocalProfileId,
user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
#endif
}
content::BrowserContext* PasswordStoreFactory::GetBrowserContextToUse(
content::BrowserContext* context) const {
return chrome::GetBrowserContextRedirectedInIncognito(context);
}
bool PasswordStoreFactory::ServiceIsNULLWhileTesting() const {
return true;
}
| [
"jhonnyjosearana@gmail.com"
] | jhonnyjosearana@gmail.com |
140deec929ac3e2b4d22fa47fa36643f1de051fe | 319f334b87d858345c533a5c6d3f3a08cec5320b | /chapter01/ex12.cpp | 8ff1e460d34c3800c144f214759f9fea9bb2538c | [] | no_license | katokun1001/C-Primer | d638cbdda2f12d58fb51ef74ba286af298c60c11 | e8cf6222abef907e05b5db590676739716f1e36b | refs/heads/master | 2020-08-31T05:00:01.990978 | 2017-06-16T21:59:30 | 2017-06-16T21:59:30 | 94,392,294 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 122 | cpp | #include<iostream>
int main(){
int sum = 0;
for (int i = -100; i<=100; ++i)
sum+=i;
std::cout << sum << std::endl;
}
| [
"amornsita@yahoo.com"
] | amornsita@yahoo.com |
0baa7ac94f96731a3efa3aaf8f3e52a27f65b2e5 | aa9e987219e9eec48828a73bbde0144d43c306ec | /shaders.h | 71daaa59c3161b93e76fbb43bf7e3454a32be18a | [] | no_license | tsleyson/Graphics-4-City-Scene | 317b9ffe297ef62aba261b68766435d9aee9d1c4 | 27660fb183cbb9c34856f4d49191ffad0a93344f | refs/heads/master | 2020-04-07T11:39:34.771168 | 2013-06-09T04:38:13 | 2013-06-09T04:38:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 184 | h | #include <string>
std::string read_shader(const char * filename);
void print_info_log(unsigned int obj);
void init_shaders(std::string vert, std::string frag, unsigned int& program);
| [
"tsleyson@ucdavis.edu"
] | tsleyson@ucdavis.edu |
cf1d798feeab36261f25965f65cf9897f1a309aa | 1a3ba93e2e6a1c504f09d6da7b0aaac9b5386f41 | /tests/raii_adapter.cpp | 7833ed5dd19e28127abcacdbe639f405c0cfceb2 | [
"MIT"
] | permissive | YarikTH/return_adapters | 50cfb58d784d66b53147831ef32c583148e2a0ae | 052fc7681b7cc262dde051a3f42c264072208f9b | refs/heads/master | 2023-03-28T09:45:27.935626 | 2020-09-02T05:35:24 | 2020-09-02T05:35:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,845 | cpp | #include "catch2/catch.hpp"
#include "return_adapters/raii_adapter.h"
#include "test_utils.h"
#include <cassert>
using namespace return_adapters;
namespace
{
struct Resource
{
Resource( bool& is_destructed ) : _is_destructed( is_destructed )
{
assert( !is_destructed );
};
bool& _is_destructed;
};
struct ResourceWithDtor : private Resource
{
using Resource::Resource;
~ResourceWithDtor()
{
_is_destructed = true;
}
};
template <typename R>
R* alloc_resource( bool& is_destructed )
{
return new R( is_destructed );
}
void free_resource( Resource* resource )
{
resource->_is_destructed = true;
delete resource;
}
struct free_resource_deleter
{
void operator()( Resource* resource ) const
{
free_resource( resource );
}
};
template <auto adapted>
void check_resource_is_freed()
{
STATIC_REQUIRE( adapted );
bool is_destructed = false;
{
auto resource = adapted( is_destructed );
}
CHECK( is_destructed );
}
REGISTER_TEST_CASE( check_resource_is_freed<to_unique_ptr<&alloc_resource<ResourceWithDtor>>>,
"Adapt return value to unique_ptr",
"[raii_adapter]" );
REGISTER_TEST_CASE( check_resource_is_freed<to_shared_ptr<&alloc_resource<ResourceWithDtor>>>,
"Adapt return value to shared_ptr",
"[raii_adapter]" );
REGISTER_TEST_CASE( (check_resource_is_freed<to_unique_ptr_with_f_deleter<&alloc_resource<Resource>, free_resource>>),
"Adapt return value to unique_ptr with function deleter",
"[raii_adapter]" );
REGISTER_TEST_CASE( (check_resource_is_freed<to_unique_ptr_with_deleter<&alloc_resource<Resource>, free_resource_deleter>>),
"Adapt return value to unique_ptr with deleter",
"[raii_adapter]" );
} // namespace
| [
"voivoid@mail.ru"
] | voivoid@mail.ru |
1f7291e2dc4d26b4cfc6b4584c8c384d3afd282f | d06856e6c22e37bb86856daa47cb7b51da78d698 | /Source/WebKit/chromium/src/WebRuntimeFeatures.cpp | de6cda186ff4eb7660a974a3d411b83531f30e56 | [
"BSD-2-Clause"
] | permissive | sfarbotka/py3webkit | 8ddd2288e72a08deefc18a2ddf661a06185ad924 | 4492fc82c67189931141ee64e1cc5df7e5331bf9 | refs/heads/master | 2016-09-05T17:32:02.639162 | 2012-02-08T15:14:28 | 2012-02-08T15:14:28 | 3,235,299 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,042 | cpp | /*
* Copyright (C) 2009 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "WebRuntimeFeatures.h"
#include "AbstractDatabase.h"
#include "RuntimeEnabledFeatures.h"
#include "WebMediaPlayerClientImpl.h"
#include "websockets/WebSocket.h"
#include <wtf/UnusedParam.h>
using namespace WebCore;
namespace WebKit {
void WebRuntimeFeatures::enableDatabase(bool enable)
{
#if ENABLE(SQL_DATABASE)
AbstractDatabase::setIsAvailable(enable);
#endif
}
bool WebRuntimeFeatures::isDatabaseEnabled()
{
#if ENABLE(SQL_DATABASE)
return AbstractDatabase::isAvailable();
#else
return false;
#endif
}
// FIXME: Remove the ability to enable this feature at runtime.
void WebRuntimeFeatures::enableLocalStorage(bool enable)
{
RuntimeEnabledFeatures::setLocalStorageEnabled(enable);
}
// FIXME: Remove the ability to enable this feature at runtime.
bool WebRuntimeFeatures::isLocalStorageEnabled()
{
return RuntimeEnabledFeatures::localStorageEnabled();
}
// FIXME: Remove the ability to enable this feature at runtime.
void WebRuntimeFeatures::enableSessionStorage(bool enable)
{
RuntimeEnabledFeatures::setSessionStorageEnabled(enable);
}
// FIXME: Remove the ability to enable this feature at runtime.
bool WebRuntimeFeatures::isSessionStorageEnabled()
{
return RuntimeEnabledFeatures::sessionStorageEnabled();
}
void WebRuntimeFeatures::enableMediaPlayer(bool enable)
{
#if ENABLE(VIDEO)
WebMediaPlayerClientImpl::setIsEnabled(enable);
#endif
}
bool WebRuntimeFeatures::isMediaPlayerEnabled()
{
#if ENABLE(VIDEO)
return WebMediaPlayerClientImpl::isEnabled();
#else
return false;
#endif
}
void WebRuntimeFeatures::enableSockets(bool enable)
{
#if ENABLE(WEB_SOCKETS)
WebCore::WebSocket::setIsAvailable(enable);
#endif
}
bool WebRuntimeFeatures::isSocketsEnabled()
{
#if ENABLE(WEB_SOCKETS)
return WebSocket::isAvailable();
#else
return false;
#endif
}
void WebRuntimeFeatures::enableNotifications(bool enable)
{
#if ENABLE(NOTIFICATIONS)
RuntimeEnabledFeatures::setWebkitNotificationsEnabled(enable);
#endif
}
bool WebRuntimeFeatures::isNotificationsEnabled()
{
#if ENABLE(NOTIFICATIONS)
return RuntimeEnabledFeatures::webkitNotificationsEnabled();
#else
return false;
#endif
}
void WebRuntimeFeatures::enableApplicationCache(bool enable)
{
RuntimeEnabledFeatures::setApplicationCacheEnabled(enable);
}
bool WebRuntimeFeatures::isApplicationCacheEnabled()
{
return RuntimeEnabledFeatures::applicationCacheEnabled();
}
void WebRuntimeFeatures::enableDataTransferItems(bool enable)
{
#if ENABLE(DATA_TRANSFER_ITEMS)
RuntimeEnabledFeatures::setDataTransferItemsEnabled(enable);
#endif
}
bool WebRuntimeFeatures::isDataTransferItemsEnabled()
{
#if ENABLE(DATA_TRANSFER_ITEMS)
return RuntimeEnabledFeatures::dataTransferItemsEnabled();
#else
return false;
#endif
}
void WebRuntimeFeatures::enableGeolocation(bool enable)
{
#if ENABLE(GEOLOCATION)
RuntimeEnabledFeatures::setGeolocationEnabled(enable);
#endif
}
bool WebRuntimeFeatures::isGeolocationEnabled()
{
#if ENABLE(GEOLOCATION)
return RuntimeEnabledFeatures::geolocationEnabled();
#else
return false;
#endif
}
void WebRuntimeFeatures::enableIndexedDatabase(bool enable)
{
#if ENABLE(INDEXED_DATABASE)
RuntimeEnabledFeatures::setWebkitIndexedDBEnabled(enable);
#endif
}
bool WebRuntimeFeatures::isIndexedDatabaseEnabled()
{
#if ENABLE(INDEXED_DATABASE)
return RuntimeEnabledFeatures::webkitIndexedDBEnabled();
#else
return false;
#endif
}
void WebRuntimeFeatures::enableWebAudio(bool enable)
{
#if ENABLE(WEB_AUDIO)
RuntimeEnabledFeatures::setWebkitAudioContextEnabled(enable);
#endif
}
bool WebRuntimeFeatures::isWebAudioEnabled()
{
#if ENABLE(WEB_AUDIO)
return RuntimeEnabledFeatures::webkitAudioContextEnabled();
#else
return false;
#endif
}
void WebRuntimeFeatures::enablePushState(bool enable)
{
RuntimeEnabledFeatures::setPushStateEnabled(enable);
}
bool WebRuntimeFeatures::isPushStateEnabled(bool enable)
{
return RuntimeEnabledFeatures::pushStateEnabled();
}
void WebRuntimeFeatures::enableTouch(bool enable)
{
#if ENABLE(TOUCH_EVENTS)
RuntimeEnabledFeatures::setTouchEnabled(enable);
#endif
}
bool WebRuntimeFeatures::isTouchEnabled()
{
#if ENABLE(TOUCH_EVENTS)
return RuntimeEnabledFeatures::touchEnabled();
#else
return false;
#endif
}
void WebRuntimeFeatures::enableDeviceMotion(bool enable)
{
RuntimeEnabledFeatures::setDeviceMotionEnabled(enable);
}
bool WebRuntimeFeatures::isDeviceMotionEnabled()
{
return RuntimeEnabledFeatures::deviceMotionEnabled();
}
void WebRuntimeFeatures::enableDeviceOrientation(bool enable)
{
RuntimeEnabledFeatures::setDeviceOrientationEnabled(enable);
}
bool WebRuntimeFeatures::isDeviceOrientationEnabled()
{
return RuntimeEnabledFeatures::deviceOrientationEnabled();
}
void WebRuntimeFeatures::enableSpeechInput(bool enable)
{
RuntimeEnabledFeatures::setSpeechInputEnabled(enable);
}
bool WebRuntimeFeatures::isSpeechInputEnabled()
{
return RuntimeEnabledFeatures::speechInputEnabled();
}
void WebRuntimeFeatures::enableXHRResponseBlob(bool enable)
{
#if ENABLE(XHR_RESPONSE_BLOB)
RuntimeEnabledFeatures::setXHRResponseBlobEnabled(enable);
#endif
}
bool WebRuntimeFeatures::isXHRResponseBlobEnabled()
{
#if ENABLE(XHR_RESPONSE_BLOB)
return RuntimeEnabledFeatures::xhrResponseBlobEnabled();
#else
return false;
#endif
}
void WebRuntimeFeatures::enableFileSystem(bool enable)
{
#if ENABLE(FILE_SYSTEM)
RuntimeEnabledFeatures::setFileSystemEnabled(enable);
#endif
}
bool WebRuntimeFeatures::isFileSystemEnabled()
{
#if ENABLE(FILE_SYSTEM)
return RuntimeEnabledFeatures::fileSystemEnabled();
#else
return false;
#endif
}
void WebRuntimeFeatures::enableJavaScriptI18NAPI(bool enable)
{
#if ENABLE(JAVASCRIPT_I18N_API)
RuntimeEnabledFeatures::setJavaScriptI18NAPIEnabled(enable);
#endif
}
bool WebRuntimeFeatures::isJavaScriptI18NAPIEnabled()
{
#if ENABLE(JAVASCRIPT_I18N_API)
return RuntimeEnabledFeatures::javaScriptI18NAPIEnabled();
#else
return false;
#endif
}
void WebRuntimeFeatures::enableQuota(bool enable)
{
#if ENABLE(QUOTA)
RuntimeEnabledFeatures::setQuotaEnabled(enable);
#endif
}
bool WebRuntimeFeatures::isQuotaEnabled()
{
#if ENABLE(QUOTA)
return RuntimeEnabledFeatures::quotaEnabled();
#else
return false;
#endif
}
void WebRuntimeFeatures::enableMediaStream(bool enable)
{
#if ENABLE(MEDIA_STREAM)
RuntimeEnabledFeatures::setMediaStreamEnabled(enable);
#else
UNUSED_PARAM(enable);
#endif
}
bool WebRuntimeFeatures::isMediaStreamEnabled()
{
#if ENABLE(MEDIA_STREAM)
return RuntimeEnabledFeatures::mediaStreamEnabled();
#else
return false;
#endif
}
void WebRuntimeFeatures::enableFullScreenAPI(bool enable)
{
#if ENABLE(FULLSCREEN_API)
RuntimeEnabledFeatures::setWebkitFullScreenAPIEnabled(enable);
#else
UNUSED_PARAM(enable);
#endif
}
bool WebRuntimeFeatures::isFullScreenAPIEnabled()
{
#if ENABLE(FULLSCREEN_API)
return RuntimeEnabledFeatures::webkitFullScreenAPIEnabled();
#else
return false;
#endif
}
void WebRuntimeFeatures::enablePointerLock(bool enable)
{
#if ENABLE(POINTER_LOCK)
RuntimeEnabledFeatures::setWebkitPointerLockEnabled(enable);
#else
UNUSED_PARAM(enable);
#endif
}
bool WebRuntimeFeatures::isPointerLockEnabled()
{
#if ENABLE(POINTER_LOCK)
return RuntimeEnabledFeatures::webkitPointerLockEnabled();
#else
return false;
#endif
}
void WebRuntimeFeatures::enableMediaSource(bool enable)
{
#if ENABLE(MEDIA_SOURCE)
RuntimeEnabledFeatures::setWebkitMediaSourceEnabled(enable);
#else
UNUSED_PARAM(enable);
#endif
}
bool WebRuntimeFeatures::isMediaSourceEnabled()
{
#if ENABLE(MEDIA_SOURCE)
return RuntimeEnabledFeatures::webkitMediaSourceEnabled();
#else
return false;
#endif
}
void WebRuntimeFeatures::enableVideoTrack(bool enable)
{
#if ENABLE(VIDEO_TRACK)
RuntimeEnabledFeatures::setWebkitVideoTrackEnabled(enable);
#else
UNUSED_PARAM(enable);
#endif
}
bool WebRuntimeFeatures::isVideoTrackEnabled()
{
#if ENABLE(VIDEO_TRACK)
return RuntimeEnabledFeatures::webkitVideoTrackEnabled();
#else
return false;
#endif
}
void WebRuntimeFeatures::enableGamepad(bool enable)
{
#if ENABLE(GAMEPAD)
RuntimeEnabledFeatures::setWebkitGamepadsEnabled(enable);
#else
UNUSED_PARAM(enable);
#endif
}
bool WebRuntimeFeatures::isGamepadEnabled()
{
#if ENABLE(GAMEPAD)
return RuntimeEnabledFeatures::webkitGamepadsEnabled();
#else
return false;
#endif
}
} // namespace WebKit
| [
"z8sergey8z@gmail.com"
] | z8sergey8z@gmail.com |
26566b446421b9c4b72abd317243d181dade1547 | 12ed83c96f38889cf5e81d02d83e96f82a7ea273 | /src/IO/S3/AWSLogger.cpp | 48c30ccf88131d4e4bfeee376641606520674c20 | [
"Apache-2.0"
] | permissive | wangzhen11aaa/ClickHouse | 033f0bcca126b798fe2bab593b29dd3e25f8542e | a7db8d1d71f15dbbc9b5490c147913334fd006b9 | refs/heads/master | 2023-04-16T05:54:54.238993 | 2023-04-10T04:25:51 | 2023-04-10T04:25:51 | 204,945,732 | 2 | 0 | Apache-2.0 | 2022-02-11T06:32:58 | 2019-08-28T14:03:07 | C++ | UTF-8 | C++ | false | false | 2,744 | cpp | #include <IO/S3/AWSLogger.h>
#if USE_AWS_S3
#include <aws/core/utils/logging/LogLevel.h>
namespace
{
const char * S3_LOGGER_TAG_NAMES[][2] = {
{"AWSClient", "AWSClient"},
{"AWSAuthV4Signer", "AWSClient (AWSAuthV4Signer)"},
};
const std::pair<DB::LogsLevel, Poco::Message::Priority> & convertLogLevel(Aws::Utils::Logging::LogLevel log_level)
{
/// We map levels to our own logger 1 to 1 except WARN+ levels. In most cases we failover such errors with retries
/// and don't want to see them as Errors in our logs.
static const std::unordered_map<Aws::Utils::Logging::LogLevel, std::pair<DB::LogsLevel, Poco::Message::Priority>> mapping =
{
{Aws::Utils::Logging::LogLevel::Off, {DB::LogsLevel::none, Poco::Message::PRIO_INFORMATION}},
{Aws::Utils::Logging::LogLevel::Fatal, {DB::LogsLevel::information, Poco::Message::PRIO_INFORMATION}},
{Aws::Utils::Logging::LogLevel::Error, {DB::LogsLevel::information, Poco::Message::PRIO_INFORMATION}},
{Aws::Utils::Logging::LogLevel::Warn, {DB::LogsLevel::information, Poco::Message::PRIO_INFORMATION}},
{Aws::Utils::Logging::LogLevel::Info, {DB::LogsLevel::information, Poco::Message::PRIO_INFORMATION}},
{Aws::Utils::Logging::LogLevel::Debug, {DB::LogsLevel::debug, Poco::Message::PRIO_TEST}},
{Aws::Utils::Logging::LogLevel::Trace, {DB::LogsLevel::trace, Poco::Message::PRIO_TEST}},
};
return mapping.at(log_level);
}
}
namespace DB::S3
{
AWSLogger::AWSLogger(bool enable_s3_requests_logging_)
: enable_s3_requests_logging(enable_s3_requests_logging_)
{
for (auto [tag, name] : S3_LOGGER_TAG_NAMES)
tag_loggers[tag] = &Poco::Logger::get(name);
default_logger = tag_loggers[S3_LOGGER_TAG_NAMES[0][0]];
}
Aws::Utils::Logging::LogLevel AWSLogger::GetLogLevel() const
{
if (enable_s3_requests_logging)
return Aws::Utils::Logging::LogLevel::Trace;
else
return Aws::Utils::Logging::LogLevel::Info;
}
void AWSLogger::Log(Aws::Utils::Logging::LogLevel log_level, const char * tag, const char * format_str, ...) // NOLINT
{
callLogImpl(log_level, tag, format_str); /// FIXME. Variadic arguments?
}
void AWSLogger::LogStream(Aws::Utils::Logging::LogLevel log_level, const char * tag, const Aws::OStringStream & message_stream)
{
callLogImpl(log_level, tag, message_stream.str().c_str());
}
void AWSLogger::callLogImpl(Aws::Utils::Logging::LogLevel log_level, const char * tag, const char * message)
{
const auto & [level, prio] = convertLogLevel(log_level);
if (tag_loggers.contains(tag))
LOG_IMPL(tag_loggers[tag], level, prio, fmt::runtime(message));
else
LOG_IMPL(default_logger, level, prio, "{}: {}", tag, message);
}
}
#endif
| [
"antonio@clickhouse.com"
] | antonio@clickhouse.com |
f4d5ece6b1310a79c69af7d796d13393b82385a2 | 3b3ac5c67ab3fa8317227116b379d6214f864ae6 | /include/wheel_module_audio.h | 9784f5f5820e1be37014b03765e64ea4eb7f4c89 | [
"MIT"
] | permissive | ronchaine/wheel | dfc399655517982035562c3497c5e77de6fe7943 | be0471f2d5aba0201ff1520712fd62dc96516734 | refs/heads/master | 2020-04-06T06:55:54.291907 | 2016-08-31T10:54:41 | 2016-08-31T10:54:41 | 8,633,920 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 817 | h | /*!
@file
\brief General audio interface
\author Jari Ronkainen
*/
#ifndef WHEEL_MODULE_AUDIO_INTERFACE_H
#define WHEEL_MODULE_AUDIO_INTERFACE_H
#include "wheel_core_module.h"
namespace wheel
{
namespace interface
{
//! Interface for audio modules
class Audio : public Module
{
public:
//! Opens an audio device and creates associated context.
/*!
\return <code>WHEEL_OK</code> on success, or a value depicting an error.
*/
virtual uint32_t OpenDevice(const string& s = "", size_t channels = 32) = 0;
//! Plays a sound
/*!
*/
virtual uint32_t Play(const string& sound) = 0;
virtual std::vector<string> ListDevices() = 0;
};
}
}
#endif | [
"ronchaine@gmail.com"
] | ronchaine@gmail.com |
9e7006b34f27ae35c778a57e19f013ce7b962318 | 2d008a7810f69f6dcf3f6c2943f9125cedcfb452 | /WavToMfcc.h | c0e6e4854310ac89bc768488e313c5dd19028b27 | [] | no_license | Yuuon/DTW_CPP | d5e24428cdca251a87123580ea7f376b031abd86 | ab53ef8c2719a26f58c3fd4d22d141166c855cb4 | refs/heads/master | 2021-03-27T12:37:07.009689 | 2016-11-21T13:34:53 | 2016-11-21T13:34:53 | 74,005,818 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,108 | h | /*******************************************************************************
*
* Drone control through voice recognition -- PC to drone communication
* Team GYTAM, feb. 2016
*
* @author Tom Lucas
*
******************************************************************************/
#pragma once
#include <stdint.h> // for int16_t and int32_t
#include <iostream>
/** Functions use to convert a WAVE file to mfcc coefficient
*
* @file
*/
/**
* Structure for the header of a Wave file
*
**/
struct wavfile
{
char id[4]; // should always contain "RIFF"
int totallength; // total file length minus 8
char wavefmt[8]; // should be "WAVEfmt "
int format; // 16 for PCM format
short pcm; // 1 for PCM format
short channels; // channels
int frequency; // sampling frequency
int bytes_per_second; // Number of bytes per seconde
short bytes_by_capture; // Number of bytes by capture
short bits_per_sample; // Number of bits per sample
char data[4]; // should always contain "data"
int bytes_in_data; // Data of the file
};
/**
* Safety function to ensure the system use big endian
*
* @param none
* @return true or false
*/
int is_big_endian(void);
/**
* Read a wave file.
*
* @param p_wav (OUT) pointer to a file descriptor
* @param filename (IN) pointer to the name of the file
* @param p_header (OUT) pointer to a wave header structure
* @return none
*/
void wavRead(FILE **p_wav, char *filename, wavfile *p_header);
/**
* Transform the wav extension into mfc extension.
*
* @param filename (IN) pointer to the name of the file
* @param mfcName OUT) pointer to the new name of the file with .mfc ext
* @return none
*/
void nameWavToMfc(char *filename, char * mfcName);
/**
* Remove silence of the signal at the start and the end
*
* @param x (IN) the signal
* @param Nx (IN) the length of the signal
* @param xFiltered (OUT) a buffer for the signal without silence
* @param newLength (OUT) the length of the signal without silence
* @param threshold (IN) for the sensibility (silence detection)
* @return The signal without silence
*/
void removeSilence(int16_t * x, int Nx, int16_t ** xFiltered, int * newLength, float threshold);
/**
* Compute MFCC of a signal
*
* @param OUT float **X_mfcc Adress of a buffer to store MFCC coefficient
* @param OUT int *length_xmfcc Pointer to the length of the buffer
* @param IN int16_t *x The signal to process
* @param IN int Nx The length of the signal
* @param IN wavfile header wave header structure
* @param IN int frame_length Frame length
* @param IN int frame_step Step between each frame to allow overlapping. 160frame step = 10ms frames
* @param IN int dim_mfcc Number of MFCC coefficient kept
* @param IN int num_filter Number of filter for the mfcc algorithm
* @return none
*/
void computeMFCC(float **X_mfcc, int *length_xmfcc, int16_t *x, int Nx, int frequency, int sample_length, int sample_step, int dim_mfcc, int num_filter); | [
"yuuon.himemiya@gmail.com"
] | yuuon.himemiya@gmail.com |
f69e8fd0e84448473509f585fa3b8bde8a392647 | c31d21622bddca33ca7479d790f513a02f5b5682 | /lmath.cpp | 9d6a1b529a8cb76e7439ddeabfe019ebd215943e | [] | no_license | Slenderchat/lmath | 2210a18b796bf6365d89afe876ee679f522e7dd7 | d40f508685e0635cdba4d6df573d61382d7bd769 | refs/heads/master | 2021-09-21T02:03:12.984735 | 2018-08-19T06:03:23 | 2018-08-19T06:03:23 | 145,270,156 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,380 | cpp | #include "lmath.h"
//region Constructors
lint::lint() {
this->num.push_back(0);
}
lint::lint(lint *x) {
this->num = x->num;
}
lint::lint(const char *x) {
string s = x;
for (int i = static_cast<int>(s.length()); i > 0; i -= 19) {
if (i < 19) {
this->num.push_back(strtoull(s.substr(0, i).c_str(), nullptr, 10));
} else {
this->num.push_back(strtoull(s.substr(i - 19, 19).c_str(), nullptr, 10));
}
}
reverse(this->num.begin(), this->num.end());
}
lint::lint(long long x) {
if (x > NUMBASE - 1) {
do {
this->num.push_back(x % NUMBASE);
x /= NUMBASE;
} while (x > 0);
} else {
this->num.push_back(x);
}
reverse(this->num.begin(), this->num.end());
}
//endregion
//region Operators
//region Operator=
lint &lint::operator=(lint x) {
this->num = x.num;
return (*this);
}
lint &lint::operator=(long long x) {
this->num = lint(x).num;
return (*this);
}
//endregion
//region Operator+
lint lint::operator+(lint x) {
lint b = *this;
while (b.num.size() < x.num.size()) {
b.num.push_back(0);
}
while (b.num.size() > x.num.size()) {
x.num.push_back(0);
}
unsigned long long overflow = 0;
for (int i = static_cast<int>(b.num.size() - 1); i >= 0; i--) {
unsigned long long buff = b.num[i] + x.num[i];
if (overflow > 0) {
buff += overflow;
overflow = 0;
}
if (buff < NUMBASE - 1) {
b.num[i] = buff;
} else {
b.num[i] = NUMBASE - 1;
overflow += buff % NUMBASE;
}
}
return (b);
}
lint lint::operator+(long long x) {
lint b(*this + lint(x));
return (b);
}
lint &lint::operator+=(lint x) {
*this = *this + x;
return (*this);
}
lint &lint::operator+=(long long x) {
*this = *this + lint(x);
return (*this);
}
//endregion
//region Operator-
lint lint::operator-(lint x) {
lint b = *this;
if (this->num.size() < x.num.size()) this->isneg = true;
while (b.num.size() < x.num.size()) {
b.num.insert(b.num.begin(), 0);
}
while (b.num.size() > x.num.size()) {
x.num.insert(x.num.begin(), 0);
}
for (int i = 0; i < b.num.size(); i++) {
long long buff = b.num[i] - x.num[i];
if (buff > 0) {
b.num[i] = buff;
} else if (buff < 0 && i < (b.num.size() - 1)) {
if (b.num[i + 1] > 0) {
b.num[i + 1] -= 1;
buff = (b.num[i] + NUMBASE) - x.num[i];
b.num[i] = buff;
}
} else if (buff < 0 && i == (b.num.size() - 1)) {
b.num[i] = abs(buff);
b.isneg = true;
}
}
int i = 0;
while (b.num[i] == 0) {
b.num.erase(b.num.begin() + i);
++i;
}
return (b);
}
lint lint::operator-(long long x) {
lint b(*this - lint(x));
return (b);
}
lint &lint::operator-=(lint x) {
*this = *this - x;
return (*this);
}
lint &lint::operator-=(long long x) {
*this = *this - lint(x);
return (*this);
}
//endregion
//region Operator/
lint lint::operator/(lint x) {
lint b = *this;
while (b.num.size() < x.num.size()) {
b.num.push_back(0);
}
while (b.num.size() > x.num.size()) {
x.num.push_back(0);
}
for (int i = static_cast<int>(b.num.size() - 1); i >= 0; i--) {
}
return (b);
}
lint lint::operator/(long long x) {
}
lint &lint::operator/=(lint x) {
}
lint &lint::operator/=(long long x) {
}
//endregion
//region Operator*
lint lint::operator*(lint x) {
lint b = *this;
while (b.num.size() < x.num.size()) {
b.num.push_back(0);
}
while (b.num.size() > x.num.size()) {
x.num.push_back(0);
}
for (int i = static_cast<int>(b.num.size() - 1); i >= 0; i--) {
}
return (b);
}
lint lint::operator*(long long x) {
}
lint &lint::operator*=(lint x) {
}
lint &lint::operator*=(long long x) {
}
//endregion
//region Operator%
lint lint::operator%(lint x) {
}
lint lint::operator%(long long x) {
}
lint &lint::operator%=(lint x) {
}
lint &lint::operator%=(long long x) {
}
//endregion
//region Comparision Operators
bool lint::operator==(lint x) {
lint b = *this - x;
return ((b.num.size() == 1) && (b.num[0] == 0));
}
bool lint::operator<(lint x) {
lint b = *this - x;
return (b.isneg);
}
bool lint::operator>(lint x) {
lint b = *this - x;
return (!b.isneg);
}
bool lint::operator<=(lint x) {
lint b = *this - x;
return ((b.isneg) && (*this == x));
}
bool lint::operator>=(lint x) {
lint b = *this - x;
return ((!b.isneg) && (*this == x));
}
//endregion
//endregion
//region Members
void lint::print(IO x) {
short z = static_cast<short>(NUMBASEZEROES * (this->num.size() - 1));
stringstream b;
string o;
for (int i = 0; i < this->num.size(); i++) {
b << this->num[i];
}
b >> o;
if (o.length() < z) {
do {
b << '0';
b >> o;
} while (o.length() < z);
}
if (x == FL) {
std::fstream iof;
iof.open("OUTPUT.TXT", ios::out);
if (iof.is_open()) {
iof << o.c_str();
}
iof.close();
} else {
printf(o.c_str());
}
}
//endregion
| [
"steeplike@gmail.com"
] | steeplike@gmail.com |
f4d46da6b214c538375993c9b3fed1bed35b1154 | df5f010740f23be860590f6ea157f7896bdaf8ca | /src/luanode_datagram_udp.h | 0b135afe76098580268d2e1765d4f7c84a981f02 | [
"MIT"
] | permissive | CoolisTheName007/LuaNode | 995c48cd058c03b29158f2a280b19c8aeed7c45c | dae58cd7d239a9a39d0adc09ad749105b809fd70 | refs/heads/master | 2021-01-18T10:23:14.864755 | 2012-09-30T00:07:07 | 2012-09-30T00:07:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,384 | h | #pragma once
#include "../deps/LuaCppBridge51/lcbHybridObjectWithProperties.h"
#include <boost/asio/ip/udp.hpp>
#include <boost/asio/streambuf.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/array.hpp>
namespace LuaNode {
namespace Datagram {
void RegisterFunctions(lua_State* L);
int IsIP(lua_State* L);
class Socket : public LuaCppBridge::HybridObjectWithProperties<Socket>
{
public:
// Normal constructor
Socket(lua_State* L);
// Constructor used when we accept a connection
Socket(lua_State* L, boost::asio::ip::udp::socket*);
virtual ~Socket(void);
public:
LCB_HOWP_DECLARE_EXPORTABLE(Socket);
static int tostring_T(lua_State* L);
int SetOption(lua_State* L);
int Bind(lua_State* L);
int Listen(lua_State* L);
int Connect(lua_State* L);
int SendTo(lua_State* L);
int Read(lua_State* L);
int Close(lua_State* L);
int Shutdown(lua_State* L);
int GetLocalAddress(lua_State* L);
int GetRemoteAddress(lua_State* L);
public:
boost::asio::ip::udp::socket& GetSocketRef() { return *m_socket; };
private:
void HandleSendTo(int reference, int callback, const boost::system::error_code& error, size_t bytes_transferred);
void HandleRead(int reference, const boost::system::error_code& error, size_t bytes_transferred);
void HandleReceive(int reference, const boost::system::error_code& error, size_t bytes_transferred);
void HandleConnect(int reference, const boost::system::error_code& error);
private:
lua_State* m_L;
const unsigned int m_socketId;
bool m_close_pending;
//bool m_read_shutdown_pending;
bool m_write_shutdown_pending;
unsigned long m_pending_writes;
unsigned long m_pending_reads;
boost::shared_ptr< boost::asio::ip::udp::socket > m_socket;
boost::asio::streambuf m_inputBuffer;
//boost::array<char, 4> m_inputArray; // agrandar esto y poolearlo
//boost::array<char, 32> m_inputArray; // agrandar esto y poolearlo
//boost::array<char, 64> m_inputArray; // agrandar esto y poolearlo
//boost::array<char, 128> m_inputArray; // agrandar esto y poolearlo (el test simple\test-http-upgrade-server necesita un buffer grande sino falla)
boost::array<char, 8192> m_inputArray; // agrandar esto y poolearlo (el test simple\test-http-upgrade-server necesita un buffer grande sino falla)
};
}
}
| [
"ignaciob@inconcertcc.com"
] | ignaciob@inconcertcc.com |
a877b52ce8a52dedd41d955661388a1e28fb4d1c | 0419f4224114faf596a6ec552a1ed331eb0fefdc | /Practical4/p2.cpp | 9e7663818414a8caf7447306e28805693bd70c0a | [] | no_license | ayushgupta0110/OS-Practicals | a4b0ed26536c24d5f39a818ac545d52a184c61da | 093169099c3e8bc9d00ec7c861a588bc7f0b3c1d | refs/heads/main | 2023-09-05T21:00:29.729200 | 2021-11-22T13:45:35 | 2021-11-22T13:45:35 | 407,865,945 | 0 | 1 | null | 2021-10-16T12:09:04 | 2021-09-18T13:20:04 | C++ | UTF-8 | C++ | false | false | 193 | cpp | #include <stdio.h>
#include <unistd.h>
int main()
{
/* fork a child process */
fork();
/* fork another child process */
fork();
/* and fork another */
fork();
sleep(10);
return 0;
}
| [
"ayushgupta747492@gmail.com"
] | ayushgupta747492@gmail.com |
ef509cf863d8ad0e9d03281b6a889e6a93e45945 | 382b7da013c1d176a71b6edce14936aca027dec5 | /RenduUML-3201-3209/Objets/Capteur.cpp | deab61e588f5d7e87c8a6704a3a6d117a15517ea | [] | no_license | SebGoll/ProjetUML | 8a9d3d7fb1213dffe0db393616e0f87b4e43e5d9 | e3f61f35927b00e3fc45d7b2db839eb747fb1205 | refs/heads/main | 2023-05-13T13:25:38.215286 | 2021-06-04T15:54:44 | 2021-06-04T15:54:44 | 365,221,932 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,865 | cpp | /**
* Objet Capteur
* @file Capteur.cpp
* @author ABHAY Annie, GOLL Sebastien, HASENFRATZ Louis, NGOV Sophanna
*/
#include "Capteur.h"
#include <cmath>
Capteur::Capteur() {
this->id = 0;
this->latitude = 0.0;
this->longitude = 0.0;
this->fiable = true;
}
Capteur::~Capteur() {
}
Capteur::Capteur(unsigned long id, float latitude, float longitude) : id(id), latitude(latitude), longitude(longitude) {
this->fiable = true;
}
ostream &operator<<(ostream &flux, const Capteur &c) {
flux << "Capteur " << c.getId() << " Lat=" << c.getLatitude() << " Long=" << c.getLongitude();
if (c.isFiable()) {
flux << " Ce capteur est fiable";
} else {
flux << " Ce capteur est non-fiable";
}
return flux;
}
float Capteur::distance(float la, float lo) {
return sqrt(pow(this->latitude - la, 2) + pow(this->longitude - lo, 2));
}
void Capteur::ajouterMesure(Mesure *m) {
this->mesures.push_back(m);
}
UtilisateurPrive Capteur::getProprietaire() const {
return proprietaire;
}
void Capteur::setProprietaire(UtilisateurPrive proprietaire) {
Capteur::proprietaire = proprietaire;
}
bool Capteur::isFiable() const {
return fiable;
}
void Capteur::setFiable(bool fiable) {
Capteur::fiable = fiable;
}
unsigned long Capteur::getId() const {
return id;
}
void Capteur::setId(unsigned long id) {
Capteur::id = id;
}
float Capteur::getLatitude() const {
return latitude;
}
void Capteur::setLatitude(float latitude) {
Capteur::latitude = latitude;
}
float Capteur::getLongitude() const {
return longitude;
}
void Capteur::setLongitude(float longitude) {
Capteur::longitude = longitude;
}
const list<Mesure *> &Capteur::getMesures() const {
return mesures;
}
void Capteur::setMesures(const list<Mesure *> &mesures) {
Capteur::mesures = mesures;
}
| [
"59894122+lhasenfrat@users.noreply.github.com"
] | 59894122+lhasenfrat@users.noreply.github.com |
484ab53a2328d9c5a12bf098c246be198417a2f4 | 428989cb9837b6fedeb95e4fcc0a89f705542b24 | /erle/ros2_ws/build/rcl_interfaces/rosidl_typesupport_opensplice_cpp/rcl_interfaces/srv/dds_opensplice/Sample_SetParameters_Request_Dcps.h | 87a3c5ebccb7ed14b6be9996f8d7b92db84edbb8 | [] | no_license | swift-nav/ros_rover | 70406572cfcf413ce13cf6e6b47a43d5298d64fc | 308f10114b35c70b933ee2a47be342e6c2f2887a | refs/heads/master | 2020-04-14T22:51:38.911378 | 2016-07-08T21:44:22 | 2016-07-08T21:44:22 | 60,873,336 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 15,764 | h | //******************************************************************
//
// Generated by IDL to C++ Translator
//
// File name: Sample_SetParameters_Request_Dcps.h
// Source: /home/erle/ros2_ws/build/rcl_interfaces/rosidl_typesupport_opensplice_cpp/rcl_interfaces/srv/dds_opensplice/Sample_SetParameters_Request_Dcps.idl
// Generated: Sat Nov 7 23:02:17 2015
// OpenSplice V6.4.140407OSS
//
//******************************************************************
#ifndef _SAMPLE_SETPARAMETERS_REQUEST_DCPS_H_
#define _SAMPLE_SETPARAMETERS_REQUEST_DCPS_H_
#include "sacpp_mapping.h"
#include "sacpp_DDS_DCPS.h"
#include "Sample_SetParameters_Request_.h"
#include "dds_dcps.h"
namespace rcl_interfaces
{
namespace srv
{
namespace dds_
{
class Sample_SetParameters_Request_TypeSupportInterface;
typedef Sample_SetParameters_Request_TypeSupportInterface * Sample_SetParameters_Request_TypeSupportInterface_ptr;
typedef DDS_DCPSInterface_var < Sample_SetParameters_Request_TypeSupportInterface> Sample_SetParameters_Request_TypeSupportInterface_var;
typedef DDS_DCPSInterface_out < Sample_SetParameters_Request_TypeSupportInterface> Sample_SetParameters_Request_TypeSupportInterface_out;
class Sample_SetParameters_Request_DataWriter;
typedef Sample_SetParameters_Request_DataWriter * Sample_SetParameters_Request_DataWriter_ptr;
typedef DDS_DCPSInterface_var < Sample_SetParameters_Request_DataWriter> Sample_SetParameters_Request_DataWriter_var;
typedef DDS_DCPSInterface_out < Sample_SetParameters_Request_DataWriter> Sample_SetParameters_Request_DataWriter_out;
class Sample_SetParameters_Request_DataReader;
typedef Sample_SetParameters_Request_DataReader * Sample_SetParameters_Request_DataReader_ptr;
typedef DDS_DCPSInterface_var < Sample_SetParameters_Request_DataReader> Sample_SetParameters_Request_DataReader_var;
typedef DDS_DCPSInterface_out < Sample_SetParameters_Request_DataReader> Sample_SetParameters_Request_DataReader_out;
class Sample_SetParameters_Request_DataReaderView;
typedef Sample_SetParameters_Request_DataReaderView * Sample_SetParameters_Request_DataReaderView_ptr;
typedef DDS_DCPSInterface_var < Sample_SetParameters_Request_DataReaderView> Sample_SetParameters_Request_DataReaderView_var;
typedef DDS_DCPSInterface_out < Sample_SetParameters_Request_DataReaderView> Sample_SetParameters_Request_DataReaderView_out;
struct Sample_SetParameters_Request_Seq_uniq_ {};
typedef DDS_DCPSUVLSeq < Sample_SetParameters_Request_, struct Sample_SetParameters_Request_Seq_uniq_> Sample_SetParameters_Request_Seq;
typedef DDS_DCPSSequence_var < Sample_SetParameters_Request_Seq> Sample_SetParameters_Request_Seq_var;
typedef DDS_DCPSSequence_out < Sample_SetParameters_Request_Seq> Sample_SetParameters_Request_Seq_out;
class Sample_SetParameters_Request_TypeSupportInterface
:
virtual public DDS::TypeSupport
{
public:
typedef Sample_SetParameters_Request_TypeSupportInterface_ptr _ptr_type;
typedef Sample_SetParameters_Request_TypeSupportInterface_var _var_type;
static Sample_SetParameters_Request_TypeSupportInterface_ptr _duplicate (Sample_SetParameters_Request_TypeSupportInterface_ptr obj);
DDS::Boolean _local_is_a (const char * id);
static Sample_SetParameters_Request_TypeSupportInterface_ptr _narrow (DDS::Object_ptr obj);
static Sample_SetParameters_Request_TypeSupportInterface_ptr _unchecked_narrow (DDS::Object_ptr obj);
static Sample_SetParameters_Request_TypeSupportInterface_ptr _nil () { return 0; }
static const char * _local_id;
Sample_SetParameters_Request_TypeSupportInterface_ptr _this () { return this; }
protected:
Sample_SetParameters_Request_TypeSupportInterface () {};
~Sample_SetParameters_Request_TypeSupportInterface () {};
private:
Sample_SetParameters_Request_TypeSupportInterface (const Sample_SetParameters_Request_TypeSupportInterface &);
Sample_SetParameters_Request_TypeSupportInterface & operator = (const Sample_SetParameters_Request_TypeSupportInterface &);
};
class Sample_SetParameters_Request_DataWriter
:
virtual public DDS::DataWriter
{
public:
typedef Sample_SetParameters_Request_DataWriter_ptr _ptr_type;
typedef Sample_SetParameters_Request_DataWriter_var _var_type;
static Sample_SetParameters_Request_DataWriter_ptr _duplicate (Sample_SetParameters_Request_DataWriter_ptr obj);
DDS::Boolean _local_is_a (const char * id);
static Sample_SetParameters_Request_DataWriter_ptr _narrow (DDS::Object_ptr obj);
static Sample_SetParameters_Request_DataWriter_ptr _unchecked_narrow (DDS::Object_ptr obj);
static Sample_SetParameters_Request_DataWriter_ptr _nil () { return 0; }
static const char * _local_id;
Sample_SetParameters_Request_DataWriter_ptr _this () { return this; }
virtual DDS::LongLong register_instance (const Sample_SetParameters_Request_& instance_data) = 0;
virtual DDS::LongLong register_instance_w_timestamp (const Sample_SetParameters_Request_& instance_data, const DDS::Time_t& source_timestamp) = 0;
virtual DDS::Long unregister_instance (const Sample_SetParameters_Request_& instance_data, DDS::LongLong handle) = 0;
virtual DDS::Long unregister_instance_w_timestamp (const Sample_SetParameters_Request_& instance_data, DDS::LongLong handle, const DDS::Time_t& source_timestamp) = 0;
virtual DDS::Long write (const Sample_SetParameters_Request_& instance_data, DDS::LongLong handle) = 0;
virtual DDS::Long write_w_timestamp (const Sample_SetParameters_Request_& instance_data, DDS::LongLong handle, const DDS::Time_t& source_timestamp) = 0;
virtual DDS::Long dispose (const Sample_SetParameters_Request_& instance_data, DDS::LongLong handle) = 0;
virtual DDS::Long dispose_w_timestamp (const Sample_SetParameters_Request_& instance_data, DDS::LongLong handle, const DDS::Time_t& source_timestamp) = 0;
virtual DDS::Long writedispose (const Sample_SetParameters_Request_& instance_data, DDS::LongLong handle) = 0;
virtual DDS::Long writedispose_w_timestamp (const Sample_SetParameters_Request_& instance_data, DDS::LongLong handle, const DDS::Time_t& source_timestamp) = 0;
virtual DDS::Long get_key_value (Sample_SetParameters_Request_& key_holder, DDS::LongLong handle) = 0;
virtual DDS::LongLong lookup_instance (const Sample_SetParameters_Request_& instance_data) = 0;
protected:
Sample_SetParameters_Request_DataWriter () {};
~Sample_SetParameters_Request_DataWriter () {};
private:
Sample_SetParameters_Request_DataWriter (const Sample_SetParameters_Request_DataWriter &);
Sample_SetParameters_Request_DataWriter & operator = (const Sample_SetParameters_Request_DataWriter &);
};
class Sample_SetParameters_Request_DataReader
:
virtual public DDS::DataReader
{
public:
typedef Sample_SetParameters_Request_DataReader_ptr _ptr_type;
typedef Sample_SetParameters_Request_DataReader_var _var_type;
static Sample_SetParameters_Request_DataReader_ptr _duplicate (Sample_SetParameters_Request_DataReader_ptr obj);
DDS::Boolean _local_is_a (const char * id);
static Sample_SetParameters_Request_DataReader_ptr _narrow (DDS::Object_ptr obj);
static Sample_SetParameters_Request_DataReader_ptr _unchecked_narrow (DDS::Object_ptr obj);
static Sample_SetParameters_Request_DataReader_ptr _nil () { return 0; }
static const char * _local_id;
Sample_SetParameters_Request_DataReader_ptr _this () { return this; }
virtual DDS::Long read (Sample_SetParameters_Request_Seq& received_data, DDS::SampleInfoSeq& info_seq, DDS::Long max_samples, DDS::ULong sample_states, DDS::ULong view_states, DDS::ULong instance_states) = 0;
virtual DDS::Long take (Sample_SetParameters_Request_Seq& received_data, DDS::SampleInfoSeq& info_seq, DDS::Long max_samples, DDS::ULong sample_states, DDS::ULong view_states, DDS::ULong instance_states) = 0;
virtual DDS::Long read_w_condition (Sample_SetParameters_Request_Seq& received_data, DDS::SampleInfoSeq& info_seq, DDS::Long max_samples, DDS::ReadCondition_ptr a_condition) = 0;
virtual DDS::Long take_w_condition (Sample_SetParameters_Request_Seq& received_data, DDS::SampleInfoSeq& info_seq, DDS::Long max_samples, DDS::ReadCondition_ptr a_condition) = 0;
virtual DDS::Long read_next_sample (Sample_SetParameters_Request_& received_data, DDS::SampleInfo& sample_info) = 0;
virtual DDS::Long take_next_sample (Sample_SetParameters_Request_& received_data, DDS::SampleInfo& sample_info) = 0;
virtual DDS::Long read_instance (Sample_SetParameters_Request_Seq& received_data, DDS::SampleInfoSeq& info_seq, DDS::Long max_samples, DDS::LongLong a_handle, DDS::ULong sample_states, DDS::ULong view_states, DDS::ULong instance_states) = 0;
virtual DDS::Long take_instance (Sample_SetParameters_Request_Seq& received_data, DDS::SampleInfoSeq& info_seq, DDS::Long max_samples, DDS::LongLong a_handle, DDS::ULong sample_states, DDS::ULong view_states, DDS::ULong instance_states) = 0;
virtual DDS::Long read_next_instance (Sample_SetParameters_Request_Seq& received_data, DDS::SampleInfoSeq& info_seq, DDS::Long max_samples, DDS::LongLong a_handle, DDS::ULong sample_states, DDS::ULong view_states, DDS::ULong instance_states) = 0;
virtual DDS::Long take_next_instance (Sample_SetParameters_Request_Seq& received_data, DDS::SampleInfoSeq& info_seq, DDS::Long max_samples, DDS::LongLong a_handle, DDS::ULong sample_states, DDS::ULong view_states, DDS::ULong instance_states) = 0;
virtual DDS::Long read_next_instance_w_condition (Sample_SetParameters_Request_Seq& received_data, DDS::SampleInfoSeq& info_seq, DDS::Long max_samples, DDS::LongLong a_handle, DDS::ReadCondition_ptr a_condition) = 0;
virtual DDS::Long take_next_instance_w_condition (Sample_SetParameters_Request_Seq& received_data, DDS::SampleInfoSeq& info_seq, DDS::Long max_samples, DDS::LongLong a_handle, DDS::ReadCondition_ptr a_condition) = 0;
virtual DDS::Long return_loan (Sample_SetParameters_Request_Seq& received_data, DDS::SampleInfoSeq& info_seq) = 0;
virtual DDS::Long get_key_value (Sample_SetParameters_Request_& key_holder, DDS::LongLong handle) = 0;
virtual DDS::LongLong lookup_instance (const Sample_SetParameters_Request_& instance) = 0;
protected:
Sample_SetParameters_Request_DataReader () {};
~Sample_SetParameters_Request_DataReader () {};
private:
Sample_SetParameters_Request_DataReader (const Sample_SetParameters_Request_DataReader &);
Sample_SetParameters_Request_DataReader & operator = (const Sample_SetParameters_Request_DataReader &);
};
class Sample_SetParameters_Request_DataReaderView
:
virtual public DDS::DataReaderView
{
public:
typedef Sample_SetParameters_Request_DataReaderView_ptr _ptr_type;
typedef Sample_SetParameters_Request_DataReaderView_var _var_type;
static Sample_SetParameters_Request_DataReaderView_ptr _duplicate (Sample_SetParameters_Request_DataReaderView_ptr obj);
DDS::Boolean _local_is_a (const char * id);
static Sample_SetParameters_Request_DataReaderView_ptr _narrow (DDS::Object_ptr obj);
static Sample_SetParameters_Request_DataReaderView_ptr _unchecked_narrow (DDS::Object_ptr obj);
static Sample_SetParameters_Request_DataReaderView_ptr _nil () { return 0; }
static const char * _local_id;
Sample_SetParameters_Request_DataReaderView_ptr _this () { return this; }
virtual DDS::Long read (Sample_SetParameters_Request_Seq& received_data, DDS::SampleInfoSeq& info_seq, DDS::Long max_samples, DDS::ULong sample_states, DDS::ULong view_states, DDS::ULong instance_states) = 0;
virtual DDS::Long take (Sample_SetParameters_Request_Seq& received_data, DDS::SampleInfoSeq& info_seq, DDS::Long max_samples, DDS::ULong sample_states, DDS::ULong view_states, DDS::ULong instance_states) = 0;
virtual DDS::Long read_w_condition (Sample_SetParameters_Request_Seq& received_data, DDS::SampleInfoSeq& info_seq, DDS::Long max_samples, DDS::ReadCondition_ptr a_condition) = 0;
virtual DDS::Long take_w_condition (Sample_SetParameters_Request_Seq& received_data, DDS::SampleInfoSeq& info_seq, DDS::Long max_samples, DDS::ReadCondition_ptr a_condition) = 0;
virtual DDS::Long read_next_sample (Sample_SetParameters_Request_& received_data, DDS::SampleInfo& sample_info) = 0;
virtual DDS::Long take_next_sample (Sample_SetParameters_Request_& received_data, DDS::SampleInfo& sample_info) = 0;
virtual DDS::Long read_instance (Sample_SetParameters_Request_Seq& received_data, DDS::SampleInfoSeq& info_seq, DDS::Long max_samples, DDS::LongLong a_handle, DDS::ULong sample_states, DDS::ULong view_states, DDS::ULong instance_states) = 0;
virtual DDS::Long take_instance (Sample_SetParameters_Request_Seq& received_data, DDS::SampleInfoSeq& info_seq, DDS::Long max_samples, DDS::LongLong a_handle, DDS::ULong sample_states, DDS::ULong view_states, DDS::ULong instance_states) = 0;
virtual DDS::Long read_next_instance (Sample_SetParameters_Request_Seq& received_data, DDS::SampleInfoSeq& info_seq, DDS::Long max_samples, DDS::LongLong a_handle, DDS::ULong sample_states, DDS::ULong view_states, DDS::ULong instance_states) = 0;
virtual DDS::Long take_next_instance (Sample_SetParameters_Request_Seq& received_data, DDS::SampleInfoSeq& info_seq, DDS::Long max_samples, DDS::LongLong a_handle, DDS::ULong sample_states, DDS::ULong view_states, DDS::ULong instance_states) = 0;
virtual DDS::Long read_next_instance_w_condition (Sample_SetParameters_Request_Seq& received_data, DDS::SampleInfoSeq& info_seq, DDS::Long max_samples, DDS::LongLong a_handle, DDS::ReadCondition_ptr a_condition) = 0;
virtual DDS::Long take_next_instance_w_condition (Sample_SetParameters_Request_Seq& received_data, DDS::SampleInfoSeq& info_seq, DDS::Long max_samples, DDS::LongLong a_handle, DDS::ReadCondition_ptr a_condition) = 0;
virtual DDS::Long return_loan (Sample_SetParameters_Request_Seq& received_data, DDS::SampleInfoSeq& info_seq) = 0;
virtual DDS::Long get_key_value (Sample_SetParameters_Request_& key_holder, DDS::LongLong handle) = 0;
virtual DDS::LongLong lookup_instance (const Sample_SetParameters_Request_& instance) = 0;
protected:
Sample_SetParameters_Request_DataReaderView () {};
~Sample_SetParameters_Request_DataReaderView () {};
private:
Sample_SetParameters_Request_DataReaderView (const Sample_SetParameters_Request_DataReaderView &);
Sample_SetParameters_Request_DataReaderView & operator = (const Sample_SetParameters_Request_DataReaderView &);
};
}
}
}
#endif
| [
"igdoty@swiftnav.com"
] | igdoty@swiftnav.com |
fd9367baf6174b704d1c4a56cfc7f9ddfde7dc6a | 74264c0b50a9447ec608bfb9a03c2bf5bc8e57e5 | /lab03/car/Car.cpp | f1970107f3a57325743ccd9ea91f2df6db9a6b56 | [] | no_license | col3name/oop | e7c09f6e60336c4332395fd2708b6b4d2954c0c7 | f76d6304631fc9778e898aa8d5375f4d279ac5aa | refs/heads/master | 2022-02-28T16:52:53.698029 | 2019-09-01T00:57:04 | 2019-09-01T00:57:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,200 | cpp | #include "stdafx.h"
#include "Car.h"
bool CCar::IsTurnedOnEngine() const
{
return m_turnedOn;
}
int CCar::GetSpeed() const
{
return std::abs(m_speed);
}
Gear CCar::GetGear() const
{
return m_gear;
}
std::string CCar::GetDirectionMovement() const
{
if (m_speed == 0)
{
return "not moving";
}
else if (m_speed < 0)
{
return "backword moving";
}
else
{
return "forward moving";
}
}
bool CCar::TurnOnEngine()
{
if (m_turnedOn)
{
return false;
}
m_gear = Gear::Neutral;
m_turnedOn = true;
return true;
}
bool CCar::TurnOffEngine()
{
if (m_turnedOn && m_gear == Gear::Neutral && m_speed == 0)
{
m_turnedOn = false;
return true;
}
return false;
}
constexpr int MIN_SPEED = -20;
constexpr int MAX_SPEED = 150;
static const std::map<Gear, SpeedRange> GEAR_SPEED_RANGE = {
{ Gear::Reverse, { -20, 0 } },
{ Gear::Neutral, { MIN_SPEED, MAX_SPEED } },
{ Gear::First, { 0, 30 } },
{ Gear::Second, { 20, 50 } },
{ Gear::Third, { 30, 60 } },
{ Gear::Fourth, { 40, 90 } },
{ Gear::Fifth, { 50, 150 } }
};
bool CCar::IsPermissibleGearForSpeed(Gear gear, int speed) const
{
SpeedRange rangeOfSpeed = GEAR_SPEED_RANGE.at(gear);
return speed >= rangeOfSpeed.min && speed <= rangeOfSpeed.max;
}
bool CCar::TransmissionCanBeSwitched(Gear gear) const
{
return (m_speed == 0 && (gear == Gear::Reverse || (gear == Gear::First && m_gear == Gear::Reverse)))
|| (IsPermissibleGearForSpeed(gear, m_speed) && gear != Gear::Reverse);
}
bool CCar::SetGear(int gear)
{
if (gear < -1 || gear > 5)
{
return false;
}
Gear gearType = static_cast<Gear>(gear);
if ((m_turnedOn && TransmissionCanBeSwitched(gearType))
|| (!m_turnedOn && gearType == Gear::Neutral))
{
m_gear = gearType;
return true;
}
return false;
}
bool CCar::SetSpeed(int speed)
{
if (m_turnedOn)
{
if (m_gear == Gear::Reverse)
{
speed = -speed;
}
if ((IsPermissibleGearForSpeed(m_gear, speed) && m_gear != Gear::Neutral)
|| (m_gear == Gear::Neutral && abs(speed) <= abs(m_speed)))
{
m_speed = speed;
return true;
}
}
return false;
}
| [
"ya.mikushoff@gmail.com"
] | ya.mikushoff@gmail.com |
457331362e25df88dcd4205089bf6a97d3eec915 | 402910c154417b1eb08b4209554b97e0461a0ced | /packages/drafter/src/SourceMapUtils.cc | 780ca9cf0dedc9c1fb054dfc0548046ec9cabf0d | [
"MIT",
"BSL-1.0"
] | permissive | apiaryio/drafter | b5010628384e9420fcc516aded9eb5a046589102 | 8d77123fff15b606e08d6608cdea856530e550a2 | refs/heads/master | 2023-08-21T14:44:59.802478 | 2023-07-29T15:30:32 | 2023-07-29T15:30:32 | 30,541,396 | 328 | 85 | MIT | 2023-07-31T09:13:42 | 2015-02-09T15:05:57 | C++ | UTF-8 | C++ | false | false | 2,159 | cc | #include "SourceMapUtils.h"
#include <algorithm>
#include "utils/Utf8.h"
#include <iostream>
namespace drafter
{
const AnnotationPosition GetLineFromMap(const NewLinesIndex& linesEndIndex, const mdp::Range& range)
{
// Finds starting line and column position
AnnotationPosition out;
if (linesEndIndex.empty()) { // to avoid std::prev() on empty
return out;
}
auto annotationPositionIt = std::upper_bound(linesEndIndex.begin(), linesEndIndex.end(), range.location);
if (annotationPositionIt != linesEndIndex.end()) {
out.fromLine = std::distance(linesEndIndex.begin(), annotationPositionIt);
out.fromColumn = range.location - *std::prev(annotationPositionIt) + 1;
}
// Finds ending line and column position
annotationPositionIt
= std::lower_bound(linesEndIndex.begin(), linesEndIndex.end(), range.location + range.length);
//
// FIXME: workaround for byte mapping
// handle just case when position is after latest newline
// remove once all sourceMaps will correctly send character ranges
//
if (linesEndIndex.back() < (range.location + range.length)) {
out.toLine = linesEndIndex.size();
out.toColumn = 1;
return out;
}
// end of byte mapping workarround
if (annotationPositionIt != linesEndIndex.end()) {
out.toLine = std::distance(linesEndIndex.begin(), annotationPositionIt);
out.toColumn = (range.location + range.length) - *(std::prev(annotationPositionIt));
}
return out;
}
const NewLinesIndex GetLinesEndIndex(const std::string& source)
{
NewLinesIndex out;
out.push_back(0);
utils::utf8::input_iterator<std::string::const_iterator> it(source);
utils::utf8::input_iterator<std::string::const_iterator> e{ source.end(), source.end() };
int i = 1;
for (; it != e; ++it, ++i) {
if (*it == '\n')
out.push_back(i);
}
return out;
}
} // namespace drafter
| [
"kratochvil@klok.cz"
] | kratochvil@klok.cz |
167569f5e3e6a2d772c831182f32ef8790207cc6 | 719217b1b6b59b6934bb1558c62b3a77011a5a08 | /geant/src/test/root.cc | dadc685890142af49ec51b8a9ee4c6018a379194 | [] | no_license | HEP-KBFI/genSun | 09797dbfdaea0505d14da8b4785ad8d7b549d84e | 7197f3af041d5925fdbe0889791f6b35cdd65c40 | refs/heads/master | 2016-09-06T09:22:03.961579 | 2014-05-02T14:12:31 | 2014-05-02T14:12:31 | 7,684,005 | 0 | 1 | null | 2013-08-14T13:51:21 | 2013-01-18T09:31:03 | C++ | UTF-8 | C++ | false | false | 596 | cc | #include <iostream>
#include "TRandom.h"
#include "TFile.h"
#include "TDirectory.h"
#include "TH1F.h"
using namespace std;
bool p_quiet = false;
int main() {
TRandom *rnd = new TRandom(time(0));
TH1F h1("unit", "", 20, 0, 1);
TH1F h2("real", "", 50, -5, 5);
//h.SetDirectory(&dir);
for(int i=0; i<10000; i++) {
h1.Fill(rnd->Rndm());
h2.Fill(rnd->Rndm()*2 - 0.5);
}
TFile* tfile = new TFile("ofile.root", "RECREATE");
TDirectory* dir = tfile->mkdir("dir1")->mkdir("dir2");
dir->cd();
h1.Write();
h2.Write();
//tfile->cd();
tfile->ls();
tfile->Close();
return 0;
}
| [
"morten.piibeleht@gmail.com"
] | morten.piibeleht@gmail.com |
cfa14ed9a1ca0acc9efd29451d39bc4419877885 | 6fbf7d4855a0639eb57d37eb4a02758fc137e77e | /ModuleAlgorithm/src/implement/decomposer/DummyGateDecomposer.cpp | c15b7182ebeaedc0ccc4fd726247fe3d91c4eade | [] | no_license | wws2003/Research | f9abb8ea7acd98ed829f23a39cb05a80d738bb6d | 3c839b7b35ddfcc5373f96808c3dc7125200da94 | refs/heads/master | 2020-04-06T07:04:28.103498 | 2016-08-10T06:18:04 | 2016-08-10T06:18:04 | 33,717,928 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 210 | cpp | /*
* DummyGateDecomposer.cpp
*
* Created on: Oct 18, 2015
* Author: pham
*/
#include "DummyGateDecomposer.h"
#include "DummyElementDecomposer.cpp"
template class DummyElementDecomposer<GatePtr>;
| [
"pham@apecsa-indonesia.com"
] | pham@apecsa-indonesia.com |
6d5df60cd365801df2867463e227b761c043dcb7 | e80c5a2c5db97e5e6191cac5b68d23b73636c2ac | /spring2016/NLP/Assignments/Assignment_2/tools/openfst-1.5.1/src/include/fst/memory.h | 03b310f22d354d1183e63a3f6f529e9225a30595 | [
"Apache-2.0"
] | permissive | batu/codex | e2bdfbe8d0a6e86d21c6caedea80ac6375e000dc | 35171929dec936810b8994cc476f205b8af5adb6 | refs/heads/master | 2021-01-17T07:00:16.055807 | 2016-12-09T22:52:22 | 2016-12-09T22:52:22 | 51,299,933 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,481 | h | // See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
//
// FST memory utilities.
#ifndef FST_LIB_MEMORY_H__
#define FST_LIB_MEMORY_H__
#include <list>
#include <memory>
#include <utility>
#include <fst/types.h>
#include <fstream>
namespace fst {
//
// MEMORY ALLOCATION UTILITIES
//
// Default block allocation size
const int kAllocSize = 64;
// Minimum number of allocations per block
const int kAllocFit = 4;
// Base class for MemoryArena that allows e.g. MemoryArenaCollection to
// easily manipulate collections of variously sized arenas.
class MemoryArenaBase {
public:
virtual ~MemoryArenaBase() {}
virtual size_t Size() const = 0;
};
// Allocates 'size' unintialized memory chunks of size sizeof(T) from
// underlying blocks of (at least) size 'block_size * sizeof(T)'. All
// blocks are freed when this class is deleted. Result of allocate()
// will be aligned to sizeof(T).
template <typename T>
class MemoryArena : public MemoryArenaBase {
public:
explicit MemoryArena(size_t block_size = kAllocSize)
: block_size_(block_size * sizeof(T)), block_pos_(0) {
blocks_.push_front(new char[block_size_]);
}
~MemoryArena() override {
for (auto it = blocks_.begin(); it != blocks_.end(); ++it) {
delete[] * it;
}
}
void *Allocate(size_t size) {
size_t byte_size = size * sizeof(T);
if (byte_size * kAllocFit > block_size_) {
// large block; add new large block
char *ptr = new char[byte_size];
blocks_.push_back(ptr);
return ptr;
}
if (block_pos_ + byte_size > block_size_) {
// Doesn't fit; add new standard block
char *ptr = new char[block_size_];
block_pos_ = 0;
blocks_.push_front(ptr);
}
// Fits; use current block
char *ptr = blocks_.front() + block_pos_;
block_pos_ += byte_size;
return ptr;
}
size_t Size() const override { return sizeof(T); }
private:
size_t block_size_; // default block size in bytes
size_t block_pos_; // current position in block in bytes
std::list<char *> blocks_; // list of allocated blocks
DISALLOW_COPY_AND_ASSIGN(MemoryArena);
};
// Base class for MemoryPool that allows e.g. MemoryPoolCollection to
// easily manipulate collections of variously sized pools.
class MemoryPoolBase {
public:
virtual ~MemoryPoolBase() {}
virtual size_t Size() const = 0;
};
// Allocates and frees initially uninitialized memory chunks of size
// sizeof(T). Keeps an internal list of freed chunks that are reused
// (as is) on the next allocation if available. Chunks are constructed
// in blocks of size 'pool_size'. All memory is freed when the class is
// deleted. The result of Allocate() will be suitably memory-aligned.
//
// Combined with placement operator new and destroy fucntions for the
// T class, this can be used to improve allocation efficiency. See
// nlp/fst/lib/visit.h (global new) and
// nlp/fst/lib/dfs-visit.h (class new) for examples of this usage.
template <typename T>
class MemoryPool : public MemoryPoolBase {
public:
struct Link {
char buf[sizeof(T)];
Link *next;
};
// 'pool_size' specifies the size of the initial pool and how it is extended
explicit MemoryPool(size_t pool_size = kAllocSize)
: mem_arena_(pool_size), free_list_(0) {}
~MemoryPool() override {}
void *Allocate() {
if (free_list_ == 0) {
Link *link = static_cast<Link *>(mem_arena_.Allocate(1));
link->next = 0;
return link;
} else {
Link *link = free_list_;
free_list_ = link->next;
return link;
}
}
void Free(void *ptr) {
if (ptr) {
Link *link = static_cast<Link *>(ptr);
link->next = free_list_;
free_list_ = link;
}
}
size_t Size() const override { return sizeof(T); }
private:
MemoryArena<Link> mem_arena_;
Link *free_list_;
DISALLOW_COPY_AND_ASSIGN(MemoryPool);
};
//
// MEMORY ALLOCATION COLLECTION UTILITIES
//
// Stores a collection of memory arenas
class MemoryArenaCollection {
public:
// 'block_size' specifies the block size of the arenas
explicit MemoryArenaCollection(size_t block_size = kAllocSize)
: block_size_(block_size), ref_count_(1) {}
~MemoryArenaCollection() {
for (size_t i = 0; i < arenas_.size(); ++i) delete arenas_[i];
}
template <typename T>
MemoryArena<T> *Arena() {
if (sizeof(T) >= arenas_.size()) arenas_.resize(sizeof(T) + 1, 0);
MemoryArenaBase *arena = arenas_[sizeof(T)];
if (arena == 0) {
arena = new MemoryArena<T>(block_size_);
arenas_[sizeof(T)] = arena;
}
return static_cast<MemoryArena<T> *>(arena);
}
size_t BlockSize() const { return block_size_; }
size_t RefCount() const { return ref_count_; }
size_t IncrRefCount() { return ++ref_count_; }
size_t DecrRefCount() { return --ref_count_; }
private:
size_t block_size_;
size_t ref_count_;
std::vector<MemoryArenaBase *> arenas_;
DISALLOW_COPY_AND_ASSIGN(MemoryArenaCollection);
};
// Stores a collection of memory pools
class MemoryPoolCollection {
public:
// 'pool_size' specifies the size of initial pool and how it is extended
explicit MemoryPoolCollection(size_t pool_size = kAllocSize)
: pool_size_(pool_size), ref_count_(1) {}
~MemoryPoolCollection() {
for (size_t i = 0; i < pools_.size(); ++i) delete pools_[i];
}
template <typename T>
MemoryPool<T> *Pool() {
if (sizeof(T) >= pools_.size()) pools_.resize(sizeof(T) + 1, 0);
MemoryPoolBase *pool = pools_[sizeof(T)];
if (pool == 0) {
pool = new MemoryPool<T>(pool_size_);
pools_[sizeof(T)] = pool;
}
return static_cast<MemoryPool<T> *>(pool);
}
size_t PoolSize() const { return pool_size_; }
size_t RefCount() const { return ref_count_; }
size_t IncrRefCount() { return ++ref_count_; }
size_t DecrRefCount() { return --ref_count_; }
private:
size_t pool_size_;
size_t ref_count_;
std::vector<MemoryPoolBase *> pools_;
DISALLOW_COPY_AND_ASSIGN(MemoryPoolCollection);
};
//
// STL MEMORY ALLOCATORS
//
// STL allocator using memory arenas. Memory is allocated from
// underlying blocks of size 'block_size * sizeof(T)'. Memory is freed
// only when all objects using this allocator are destroyed and there
// is otherwise no reuse (unlike PoolAllocator).
//
// This allocator has object-local state so it should not be used with
// splicing or swapping operations between objects created with
// different allocators nor should it be used if copies must be
// thread-safe. The result of allocate() will be suitably
// memory-aligned.
template <typename T>
class BlockAllocator {
public:
typedef std::allocator<T> A;
typedef typename A::size_type size_type;
typedef typename A::difference_type difference_type;
typedef typename A::pointer pointer;
typedef typename A::const_pointer const_pointer;
typedef typename A::reference reference;
typedef typename A::const_reference const_reference;
typedef typename A::value_type value_type;
template <typename U>
struct rebind {
typedef BlockAllocator<U> other;
};
explicit BlockAllocator(size_t block_size = kAllocSize)
: arenas_(new MemoryArenaCollection(block_size)) {}
BlockAllocator(const BlockAllocator<T> &arena_alloc)
: arenas_(arena_alloc.Arenas()) {
Arenas()->IncrRefCount();
}
template <typename U>
BlockAllocator(const BlockAllocator<U> &arena_alloc)
: arenas_(arena_alloc.Arenas()) {
Arenas()->IncrRefCount();
}
~BlockAllocator() {
if (Arenas()->DecrRefCount() == 0) delete Arenas();
}
pointer address(reference ref) const { return A().address(ref); }
const_pointer address(const_reference ref) const { return A().address(ref); }
size_type max_size() const { return A().max_size(); }
template <class U, class... Args>
void construct(U *p, Args &&... args) {
A().construct(p, std::forward<Args>(args)...);
}
void destroy(pointer p) { A().destroy(p); }
pointer allocate(size_type n, const void *hint = 0) {
if (n * kAllocFit <= kAllocSize) {
return static_cast<pointer>(Arena()->Allocate(n));
} else {
return A().allocate(n, hint);
}
}
void deallocate(pointer p, size_type n) {
if (n * kAllocFit > kAllocSize) {
A().deallocate(p, n);
}
}
MemoryArenaCollection *Arenas() const { return arenas_; }
private:
MemoryArena<T> *Arena() { return arenas_->Arena<T>(); }
MemoryArenaCollection *arenas_;
BlockAllocator<T> operator=(const BlockAllocator<T> &);
};
template <typename T, typename U>
bool operator==(const BlockAllocator<T> &alloc1,
const BlockAllocator<U> &alloc2) {
return false;
}
template <typename T, typename U>
bool operator!=(const BlockAllocator<T> &alloc1,
const BlockAllocator<U> &alloc2) {
return true;
}
// STL allocator using memory pools. Memory is allocated from underlying
// blocks of size 'block_size * sizeof(T)'. Keeps an internal list of freed
// chunks thare are reused on the next allocation.
//
// This allocator has object-local state so it should not be used with
// splicing or swapping operations between objects created with
// different allocators nor should it be used if copies must be
// thread-safe. The result of allocate() will be suitably
// memory-aligned.
template <typename T>
class PoolAllocator {
public:
typedef std::allocator<T> A;
typedef typename A::size_type size_type;
typedef typename A::difference_type difference_type;
typedef typename A::pointer pointer;
typedef typename A::const_pointer const_pointer;
typedef typename A::reference reference;
typedef typename A::const_reference const_reference;
typedef typename A::value_type value_type;
template <typename U>
struct rebind {
typedef PoolAllocator<U> other;
};
explicit PoolAllocator(size_t pool_size = kAllocSize)
: pools_(new MemoryPoolCollection(pool_size)) {}
PoolAllocator(const PoolAllocator<T> &pool_alloc)
: pools_(pool_alloc.Pools()) {
Pools()->IncrRefCount();
}
template <typename U>
PoolAllocator(const PoolAllocator<U> &pool_alloc)
: pools_(pool_alloc.Pools()) {
Pools()->IncrRefCount();
}
~PoolAllocator() {
if (Pools()->DecrRefCount() == 0) delete Pools();
}
pointer address(reference ref) const { return A().address(ref); }
const_pointer address(const_reference ref) const { return A().address(ref); }
size_type max_size() const { return A().max_size(); }
template <class U, class... Args>
void construct(U *p, Args &&... args) {
A().construct(p, std::forward<Args>(args)...);
}
void destroy(pointer p) { A().destroy(p); }
pointer allocate(size_type n, const void *hint = 0) {
if (n == 1) {
return static_cast<pointer>(Pool<1>()->Allocate());
} else if (n == 2) {
return static_cast<pointer>(Pool<2>()->Allocate());
} else if (n <= 4) {
return static_cast<pointer>(Pool<4>()->Allocate());
} else if (n <= 8) {
return static_cast<pointer>(Pool<8>()->Allocate());
} else if (n <= 16) {
return static_cast<pointer>(Pool<16>()->Allocate());
} else if (n <= 32) {
return static_cast<pointer>(Pool<32>()->Allocate());
} else if (n <= 64) {
return static_cast<pointer>(Pool<64>()->Allocate());
} else {
return A().allocate(n, hint);
}
}
void deallocate(pointer p, size_type n) {
if (n == 1) {
Pool<1>()->Free(p);
} else if (n == 2) {
Pool<2>()->Free(p);
} else if (n <= 4) {
Pool<4>()->Free(p);
} else if (n <= 8) {
Pool<8>()->Free(p);
} else if (n <= 16) {
Pool<16>()->Free(p);
} else if (n <= 32) {
Pool<32>()->Free(p);
} else if (n <= 64) {
Pool<64>()->Free(p);
} else {
A().deallocate(p, n);
}
}
MemoryPoolCollection *Pools() const { return pools_; }
private:
template <int n>
struct TN {
T buf[n];
};
template <int n>
MemoryPool<TN<n>> *Pool() {
return pools_->Pool<TN<n>>();
}
MemoryPoolCollection *pools_;
PoolAllocator<T> operator=(const PoolAllocator<T> &);
};
template <typename T, typename U>
bool operator==(const PoolAllocator<T> &alloc1,
const PoolAllocator<U> &alloc2) {
return false;
}
template <typename T, typename U>
bool operator!=(const PoolAllocator<T> &alloc1,
const PoolAllocator<U> &alloc2) {
return true;
}
} // namespace fst
#endif // FST_LIB_MEMORY_H__
| [
"ba921@nyu.edu"
] | ba921@nyu.edu |
c831772127194016f75c38346569cfee2cef772a | b8effe11d7e93de6241787e74411abb25bb980cc | /new_foo.cpp | fbb908f2d5afcd3d5a4b6d28f4c767a224d2b3a6 | [] | no_license | AidarAlimbayev/training_cpp | 2fd1eafbacf3303343d2ea1d840185b7f1a63b03 | 179e99b6cec830d22267e579de1344998d0354f3 | refs/heads/master | 2021-05-12T01:09:14.664738 | 2020-03-25T05:23:01 | 2020-03-25T05:23:01 | 117,553,014 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 554 | cpp | #include <iostream>
#include <vector>
using namespace std;
int main() {
int n;
cin >> n;
vector <int> a;
//считывание
for (int i = 0; i < n; i++) {
int temp;
cin >> temp;
if (temp > 0) {
a.push_back(temp);
}
}
//обработка и вывод
int num_min = 0; //номер минимального элемента
for (int i = 0; i < a.size(); i++) {
if (a[i] < a[num_min]) {
num_min = i;
}
}
cout << a[num_min];
return 0;
} | [
"transcription@rambler.ru"
] | transcription@rambler.ru |
49e2bea2135e8da4342a2d33e67384f3312da780 | 41383bfbe38eef928c1cd1cebc2232eb49be85f9 | /cldc/src/vm/share/ROM/BinaryObjectWriter.cpp | 3b15b21a4cd5a08c9af0526a2c7a3a5828594917 | [] | no_license | ruitaomu/pspkvm | d208d608f667fd64238b00f25b403177e14c739a | 9f68194f987ff038d35409f4d386598025600ef0 | refs/heads/master | 2021-03-27T11:49:53.137601 | 2011-09-03T16:48:34 | 2011-09-03T16:48:34 | 60,471,263 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,031 | cpp | /*
*
*
* Copyright 1990-2007 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details (a copy is
* included at /legal/license.txt).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*/
#include "incls/_precompiled.incl"
#include "incls/_BinaryObjectWriter.cpp.incl"
#if ENABLE_ROM_GENERATOR
void BinaryObjectWriter::start_block(ROMWriter::BlockType type,
int preset_count JVM_TRAPS) {
_current_type = type;
_offset = 0;
(void)preset_count;
switch (_current_type) {
case ROMWriter::TEXT_BLOCK:
_method_variable_parts =
Universe::new_obj_array(_writer->count_methods() JVM_CHECK);
break;
case ROMWriter::DATA_BLOCK:
case ROMWriter::HEAP_BLOCK:
case ROMWriter::PERSISTENT_HANDLES_BLOCK:
case ROMWriter::SYSTEM_SYMBOLS_BLOCK:
break;
default:
SHOULD_NOT_REACH_HERE();
}
}
void BinaryObjectWriter::begin_object(Oop *object JVM_TRAPS) {
(void)object;
#if !defined(PRODUCT) || ENABLE_MONET_DEBUG_DUMP
const ROMWriter::BlockType type = writer()->block_type_of(object JVM_CHECK);
GUARANTEE(type == _current_type, "sanity");
GUARANTEE(!ROM::system_contains(object->obj()), "sanity");
int skip_words = writer()->skip_words_of(object JVM_CHECK);
int skip_bytes = sizeof(jobject) * skip_words;
count(object, -skip_bytes);
#endif
#if ENABLE_MONET_DEBUG_DUMP
bool dumpit = true;
if (ROM::system_text_contains(object->obj())) {
// IMPL_NOTE: why are we here anyway?
dumpit = false;
}
if (type == ROMWriter::HEAP_BLOCK &&
object->obj() <= ROM::romized_heap_marker()) {
dumpit = false;
}
if (dumpit) {
dump_object(object, skip_words);
}
#endif
#ifdef AZZERT
int my_calculated_offset = writer()->offset_of(object JVM_CHECK);
int real_offset = _offset - skip_bytes;
GUARANTEE(my_calculated_offset == real_offset,
"calculated address != real address");
#endif
}
void BinaryObjectWriter::end_object(Oop *object JVM_TRAPS) {
JVM_IGNORE_TRAPS;
(void)object;
}
void BinaryObjectWriter::put_reference(Oop *owner, int offset, Oop *object
JVM_TRAPS) {
(void)offset;
(void)owner;
#ifdef AZZERT
if (owner->not_null()) {
ROMWriter::BlockType owner_type = writer()->block_type_of(owner JVM_CHECK);
GUARANTEE(owner_type == _current_type, "sanity");
}
GUARANTEE(ROMWriter::write_by_value(owner), "sanity");
#endif
if (object->is_null()) {
writer()->writebinary_null();
} else {
ROMizerHashEntry::Raw entry = writer()->info_for(object JVM_CHECK);
int oop_offset = entry().offset();
ROMWriter::BlockType type = (ROMWriter::BlockType)entry().type();
switch (type) {
case ROMWriter::TEXT_BLOCK: {
if (!ROM::system_text_contains(object->obj())) {
#if ENABLE_LIB_IMAGES
if (ROM::in_any_loaded_bundle_of_current_task(object->obj())) {
writer()->writebinary_lib_int_ref(
Task::current()->encode_reference((int)object->obj()));
} else {
// A reference to another objects in the binary ROM TEXT block
GUARANTEE(oop_offset != -1, "Offset not set");
writer()->writebinary_int_ref(writer()->binary_text_block_addr() +
oop_offset);
}
#else
// A reference to another objects in the binary ROM TEXT block
GUARANTEE(oop_offset != -1, "Offset not set");
writer()->writebinary_int_ref(writer()->binary_text_block_addr() +
oop_offset);
#endif
} else {
// A reference to the system ROM TEXT block
writer()->writebinary_const_int_ref(object->obj());
}
}
break;
case ROMWriter::DATA_BLOCK: {
GUARANTEE(ROM::system_data_contains(object->obj()),
"Binary ROM contains no DATA objects");
writer()->writebinary_const_int_ref(object->obj());
}
break;
case ROMWriter::HEAP_BLOCK: {
if (object->obj() > ROM::romized_heap_marker()) {
// A reference to another objects in the binary ROM HEAP block
GUARANTEE(oop_offset != -1, "Offset not set");
writer()->writebinary_int_ref(writer()->binary_heap_block_addr() +
oop_offset);
} else {
#ifndef PRODUCT
if (Verbose) {
tty->print("Heap ref to: 0x%x ",
((int)object->obj() - (int)_heap_start));
object->print_value_on(tty);
tty->print_cr("");
}
#endif
if (object->equals(Universe::empty_obj_array())) {
int encoded_value = (int)Universe::rom_text_empty_obj_array()->obj();
GUARANTEE(ROM::system_text_contains((OopDesc*)encoded_value), "sanity");
writer()->writebinary_const_int_ref((OopDesc*)encoded_value);
} else {
GUARANTEE(_current_type != ROMWriter::TEXT_BLOCK,
"Heap references are not allowed in TEXT block");
writer()->writebinary_int_ref(ROM::encode_heap_reference(object));
}
}
}
break;
default:
SHOULD_NOT_REACH_HERE();
}
writer()->set_eol_comment_object(object);
}
_offset += sizeof(int);
}
void BinaryObjectWriter::put_int(Oop *owner, jint value JVM_TRAPS) {
#ifdef AZZERT
ROMWriter::BlockType owner_type = writer()->block_type_of(owner JVM_CHECK);
GUARANTEE(owner_type == _current_type, "sanity");
#else
JVM_IGNORE_TRAPS;
(void)owner;
#endif
writer()->writebinary_int(value);
_offset += sizeof(int);
}
void BinaryObjectWriter::put_int_by_mask(Oop *owner, jint be_word,
jint le_word,
jint typemask JVM_TRAPS) {
// This is not done in BinaryObjectWriter since there's no cross-endian
// issue.
(void)owner;
(void)be_word;
(void)le_word;
(void)typemask;
JVM_IGNORE_TRAPS;
SHOULD_NOT_REACH_HERE();
}
void BinaryObjectWriter::put_long(Oop *owner, jint msw, jint lsw JVM_TRAPS) {
// This is not done in BinaryObjectWriter since there's no cross-endian
// issue.
(void)owner;
(void)msw;
(void)lsw;
JVM_IGNORE_TRAPS;
SHOULD_NOT_REACH_HERE();
}
void BinaryObjectWriter::put_double(Oop *owner, jint msw, jint lsw JVM_TRAPS) {
// This is not done in BinaryObjectWriter since there's no cross-endian
// issue.
(void)owner;
(void)msw;
(void)lsw;
JVM_IGNORE_TRAPS;
SHOULD_NOT_REACH_HERE();
}
void BinaryObjectWriter::put_symbolic(Oop *owner, int offset JVM_TRAPS) {
#ifdef AZZERT
ROMWriter::BlockType owner_type = writer()->block_type_of(owner JVM_CHECK);
GUARANTEE(owner_type == _current_type, "sanity");
#endif
FarClass blueprint = owner->blueprint();
InstanceSize instance_size = blueprint.instance_size();
switch (instance_size.value()) {
case InstanceSize::size_method:
put_method_symbolic((Method*)owner, offset JVM_CHECK);
break;
case InstanceSize::size_obj_array_class:
case InstanceSize::size_type_array_class:
case InstanceSize::size_far_class:
writer()->writebinary_int(owner->int_field(offset));
break;
default:
SHOULD_NOT_REACH_HERE();
}
_offset += sizeof(int);
}
void BinaryObjectWriter::put_method_symbolic(Method *method, int offset
JVM_TRAPS) {
GUARANTEE(!method->is_quick_native(),
"loaded classes cannot have quick natives");
if ((method->is_native() || method->is_abstract()) &&
offset == Method::native_code_offset()) {
writer()->writebinary_symbolic((address)method->int_field(offset));
} else if (offset == Method::variable_part_offset()) {
put_method_variable_part(method JVM_CHECK);
} else if (offset == Method::heap_execution_entry_offset()) {
#if USE_AOT_COMPILATION
if (method->has_compiled_code()) {
CompiledMethod cm = method->compiled_code();
writer()->writebinary_compiled_code_reference(&cm JVM_CHECK);
} else
#endif
{
writer()->writebinary_symbolic((address)method->int_field(offset));
}
} else {
// We're writing the bytecodes
writer()->writebinary_int(method->int_field(offset));
}
}
void BinaryObjectWriter::put_method_variable_part(Method *method JVM_TRAPS) {
JVM_IGNORE_TRAPS;
// Note: if you want to put method in heap, you have to add code to
// relocate its variable_part
GUARANTEE(_current_type != ROMWriter::HEAP_BLOCK,"can't put method in heap");
if (has_split_variable_part(method)) {
_method_variable_parts.obj_at_put(_variable_parts_offset, method);
int vpart_start_offset = writer()->binary_method_variable_parts_addr();
int vpart_offset = vpart_start_offset + _variable_parts_offset*sizeof(int);
writer()->writebinary_int_ref(vpart_offset);
_variable_parts_offset ++;
} else {
const int delta =
Method::heap_execution_entry_offset() - Method::variable_part_offset();
int ref = _offset + delta;
switch (_current_type) {
case ROMWriter::TEXT_BLOCK:
ref += writer()->binary_text_block_addr();
break;
case ROMWriter::HEAP_BLOCK:
ref += writer()->binary_heap_block_addr();
break;
case ROMWriter::DATA_BLOCK:
default:
SHOULD_NOT_REACH_HERE();
}
writer()->writebinary_int_ref(ref);
}
}
bool BinaryObjectWriter::has_split_variable_part(Method *method) {
#if USE_IMAGE_MAPPING
#if USE_AOT_COMPILATION
if (GenerateROMImage && method->has_compiled_code()) {
return false;
}
#endif
// The method may be in a read-only mmap'ed region, so we must put the
// variable part in a separate, writeable block
return !method->is_impossible_to_compile();
#else
(void)method;
// The method is either in the preloaded heap region, or in a LargeObject,
// so it's always writeable. No need to split variable part
return false;
#endif
}
void BinaryObjectWriter::print_method_variable_parts(JVM_SINGLE_ARG_TRAPS) {
JVM_IGNORE_TRAPS;
int variable_parts_count = _variable_parts_offset;
GUARANTEE(variable_parts_count == writer()->variable_parts_count(),"sanity");
for (int i=0; i<variable_parts_count; i++) {
Method::Raw method = _method_variable_parts.obj_at(i);
jint addr = method().int_field(Method::heap_execution_entry_offset());
writer()->writebinary_symbolic((address)addr);
}
}
#if USE_ROM_LOGGING
void BinaryObjectWriter::count(Oop *object, int adjustment) {
FarClass blueprint = object->blueprint();
InstanceSize instance_size = blueprint.instance_size();
int num_bytes = object->object_size() + adjustment;
switch (instance_size.value()) {
case InstanceSize::size_symbol:
count(mc_symbol, num_bytes);
break;
case InstanceSize::size_generic_near:
case InstanceSize::size_java_near:
case InstanceSize::size_obj_near:
count(mc_meta, num_bytes);
break;
case InstanceSize::size_type_array_1:
count(mc_array1, num_bytes);
break;
case InstanceSize::size_type_array_2:
if (object->is_char_array()) {
count(mc_array2c, num_bytes);
} else {
count(mc_array2s, num_bytes);
}
break;
case InstanceSize::size_type_array_4:
count(mc_array4, num_bytes);
break;
case InstanceSize::size_type_array_8:
count(mc_array8, num_bytes);
break;
case InstanceSize::size_obj_array:
count(mc_obj_array, num_bytes);
break;
case InstanceSize::size_method: {
Method *method = (Method*)object;
int body_size = method->code_size();
int header_size = num_bytes - body_size;
if (has_split_variable_part(method)) {
num_bytes = method->object_size() + adjustment;
mc_variable_parts.add_data_bytes(sizeof(MethodVariablePart));
mc_total.add_data_bytes(sizeof(MethodVariablePart));
}
count(mc_method, num_bytes);
count(mc_method_header, header_size);
if (body_size > 0) {
count(mc_method_body, body_size);
}
if (method->is_native()) {
count(mc_native_method, num_bytes);
}
if (method->is_abstract()) {
count(mc_abstract_method, num_bytes);
}
if (!method->is_static()) {
count(mc_virtual_method, num_bytes);
}
Symbol name = method->name();
if (name.equals(Symbols::class_initializer_name())) {
count(mc_clinit_method, num_bytes);
}
if (name.equals(Symbols::unknown())) {
count(mc_renamed_method, num_bytes);
if (method->is_abstract()) {
count(mc_renamed_abstract_method, num_bytes);
}
}
TypeArray::Raw exception_table = method->exception_table();
if (exception_table().length() > 0) {
int bytes = exception_table().length() * 2 + 8;
count(mc_exception_table, bytes);
}
}
break;
case InstanceSize::size_compiled_method:
count(mc_compiled_method, num_bytes);
break;
case InstanceSize::size_constant_pool:
count(mc_constant_pool, num_bytes);
break;
case InstanceSize::size_obj_array_class:
case InstanceSize::size_type_array_class:
count(mc_array_class, num_bytes);
break;
case InstanceSize::size_class_info:
{
ClassInfo::Raw info = object;
count(mc_class_info, num_bytes);
if (info().vtable_length() > 0) {
count(mc_vtable, info().vtable_length() * sizeof(jobject));
}
if (info().itable_length() > 0) {
count(mc_itable, info().itable_size());
}
}
break;
case InstanceSize::size_stackmap_list:
{
count(mc_stackmap, num_bytes);
StackmapList entry = object;
int entry_count = entry.entry_count();
for (int i = 0; i < entry_count; i++) {
if(!entry.is_short_map(i)) {
TypeArray longmap = entry.get_long_map(i);
SETUP_ERROR_CHECKER_ARG;
int skip = writer()->skip_words_of(&longmap JVM_NO_CHECK);
GUARANTEE(!CURRENT_HAS_PENDING_EXCEPTION, "sanity");
count(mc_longmaps, longmap.object_size() - skip* sizeof(int));
}
}
}
break;
case InstanceSize::size_far_class:
count(mc_meta, num_bytes);
break;
case InstanceSize::size_instance_class: {
count(mc_instance_class, num_bytes);
InstanceClass *ic = (InstanceClass *)object;
if (!ic->is_romized() && ic->is_initialized()) {
count(mc_inited_class, num_bytes);
}
Symbol name = ic->name();
if (name.equals(Symbols::unknown())) {
count(mc_renamed_class, num_bytes);
}
if (ic->static_field_size() > 0) {
// Classes with static fields must live in heap so that
// write barriers by byte codes can be done efficiently
GUARANTEE(_current_type == ROMWriter::HEAP_BLOCK,
"Classes with static fields must live in heap");
count(mc_static_fields, ic->static_field_size());
}
}
break;
default:
if (object->is_string()) {
count(mc_string, num_bytes);
} else {
count(mc_other, num_bytes);
}
break;
}
count(mc_total, num_bytes);
}
void BinaryObjectWriter::count(MemCounter& counter, int bytes) {
switch (_current_type) {
case ROMWriter::TEXT_BLOCK:
counter.add_text(bytes);
break;
case ROMWriter::DATA_BLOCK:
counter.add_data(bytes);
break;
case ROMWriter::HEAP_BLOCK:
counter.add_heap(bytes);
break;
default:
SHOULD_NOT_REACH_HERE();
}
}
#endif // USE_ROM_LOGGING
#if ENABLE_MONET_DEBUG_DUMP
void BinaryObjectWriter::dump_object(Oop *object, int skip_words) {
UsingFastOops fast_oops;
FarClass::Fast blueprint = object->blueprint();
InstanceSize i = blueprint().instance_size();
writer()->flush_eol_comment();
Stream *st = &writer()->_dump_stream;
switch (i.value()) {
case InstanceSize::size_obj_array:
st->print("obj_array"); break;
case InstanceSize::size_type_array_1:
st->print("type_array_1"); break;
case InstanceSize::size_type_array_2:
st->print("type_array_2"); break;
case InstanceSize::size_type_array_4:
st->print("type_array_4"); break;
case InstanceSize::size_type_array_8:
st->print("type_array_8"); break;
case InstanceSize::size_instance_class:
#ifndef PRODUCT
((InstanceClass*)object)->print_value_on(st);
#else
st->print("instance_class");
#endif
break;
case InstanceSize::size_obj_array_class:
st->print("obj_array_class"); break;
case InstanceSize::size_type_array_class:
st->print("type_array_class"); break;
case InstanceSize::size_generic_near:
st->print("type_array_class"); break;
case InstanceSize::size_java_near:
#ifndef PRODUCT
((JavaNear*)object)->print_value_on(st);
#else
st->print("java_near");
#endif
break;
case InstanceSize::size_obj_near:
st->print("obj_array_class"); break;
case InstanceSize::size_far_class:
st->print("far_class"); break;
case InstanceSize::size_mixed_oop:
st->print("mixed_oop"); break;
case InstanceSize::size_task_mirror:
st->print("task_mirror"); break;
case InstanceSize::size_boundary:
st->print("boundary"); break;
case InstanceSize::size_entry_activation:
st->print("entry_activation"); break;
case InstanceSize::size_execution_stack:
st->print("execution_stack"); break;
case InstanceSize::size_constant_pool:
st->print("constant_pool"); break;
case InstanceSize::size_class_info:
st->print("class_info"); break;
case InstanceSize::size_compiled_method:
st->print("compiled_method"); break;
case InstanceSize::size_stackmap_list:
st->print("stackmap_list"); break;
case InstanceSize::size_refnode:
st->print("refnode"); break;
case InstanceSize::size_symbol:
{
st->print("symbol: #");
Symbol::Raw symbol = object->obj();
symbol().print_symbol_on(st, true);
}
break;
case InstanceSize::size_method:
{
st->print("method ");
UsingFastOops fast_oops_inside;
Method::Fast method = object->obj();
InstanceClass::Fast ic = method().holder();
Symbol::Fast symbol = ic().name();
symbol().print_symbol_on(st, true);
st->print(".");
symbol = method().name();
symbol().print_symbol_on(st, true);
}
break;
default:
{
GUARANTEE(i.value() > 0, "sanity");
if (blueprint.equals(Universe::string_class())) {
st->print("String \"");
String::Raw str = object->obj();
str().print_string_on(st);
st->print("\"");
} else {
st->print("java_object");
}
}
break;
}
int word_size = object->object_size() / 4;
st->print(" %d ", word_size);
if (skip_words > 0) {
st->print("- %d = %d ", skip_words, word_size - skip_words);
}
st->print("words");
}
#endif
#endif //ENABLE_ROM_GENERATOR
| [
"max_mu@2af63af8-f945-0410-af61-887fe020137e"
] | max_mu@2af63af8-f945-0410-af61-887fe020137e |
77c1a17f277ed932ff5f7e24a81712a6c5ec9183 | 582c16eadadb75506cddb7a62e4b347e675684d1 | /src/Professor.cpp | a135d22efce1b010042de15da3d3c639a327de61 | [] | no_license | BrunoJpng/Projeto-ATAL | 0f61364627a9df40a2215ff626355fa8de573dd5 | 84462bff477727e5ba3b0df2fc6056da25dbab27 | refs/heads/master | 2023-01-30T20:29:53.788849 | 2020-12-13T02:06:00 | 2020-12-13T02:06:00 | 319,504,438 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 360 | cpp | #include <Professor.h>
Professor::Professor(string Nome, int CargaHoraria) {
this -> Nome = Nome;
this -> CargaHoraria = CargaHoraria;
}
string Professor::getNome() {
return this -> Nome;
}
void Professor::setCargaHoraria(int CargaHoraria) {
this -> CargaHoraria = CargaHoraria;
}
int Professor::getCargaHoraria() {
return this -> CargaHoraria;
} | [
"brunoob14540@gmail.com"
] | brunoob14540@gmail.com |
f9a094a8506fe6c81f330056a37239b6e043e964 | d4ad87efd10b36c5919f9a413648a2d8e67d02b1 | /s9/a5.cpp | 01ba859ef9ee8de6abc140d2981547edffaeb6d9 | [] | no_license | Cetzcher/eprog | 647a1cff50377c730fecee7c79ed89a49c413182 | 95fc4e833b3e759d5b3d85527254d460631fc46c | refs/heads/master | 2020-04-01T18:34:22.341705 | 2019-01-22T13:08:05 | 2019-01-22T13:08:05 | 153,500,421 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,685 | cpp | #include "a5.hpp"
#include <ctime>
#include <iostream>
#include <cmath>
#include <unistd.h>
#include <iomanip>
using namespace std;
Stopwatch::Stopwatch() {
started = false;
}
void Stopwatch::startStop() {
if(started) {
// stop the clock here, calc time
end = clock();
} else {
start = clock();
}
started = !started;
}
void Stopwatch::reset() {
started = false;
}
void Stopwatch::print() {
auto diffTimeMS = floor(((double)(end - start)) / CLOCKS_PER_SEC * 1000);
auto ms = fmodf(diffTimeMS, 1000);
auto secs = diffTimeMS / 1000;
auto mins = secs / 60;
auto hrs = mins / 60;
secs = floor(fmodf(secs, 60)), mins = floor(fmodf(mins, 60)), hrs = floor(fmodf(hrs, 24));
cout << "Stopwatch time: " << setfill('0') << setw(2) << hrs
<< ":" << setw(2) << mins
<< ":" << setw(2) << secs
<< ":" << setw(3) << ms
<< endl;
}
void testFunc() {
double sum;
for(int j=0; j<100*1000*1000; ++j)
sum += 1./j;
}
void jpower3() {
long double res = 0;
for(int i = 0; i < 100 * 1000 * 1000; i++) {
res += pow(i, 3);
}
}
void jpower3noPow() {
long double res = 0;
for(int i = 0; i < 100 * 1000 * 1000; i++) {
res += i * i * i;
}
}
int main() {
cout << "starting" << endl;
Stopwatch S;
S.startStop();
testFunc();
S.startStop();
S.print();
S.reset();
cout << "sum(pow(j, 3)):" << endl;
S.startStop();
jpower3();
S.startStop();
S.print();
S.reset();
cout << "sum( j * j * j)" << endl;
S.startStop();
jpower3noPow();
S.startStop();
S.print();
} | [
"pierre.rieger.rcc@gmail.com"
] | pierre.rieger.rcc@gmail.com |
dbd07c2e154ab738fd2ed701e4c24be64fd2afb8 | 2eb2b8e4cab96c64747d98d60277c775a6903b36 | /arrayset.cpp | 8681daedcd95d6d6bb58f0953ebf5d42b6244b75 | [
"Apache-2.0"
] | permissive | Mohamed742/C-AIMS-SA-2018 | 271c7609b0fa8d47a9b8fe09aa66bee8f45839d7 | a59ba718872dfae0f8ee216b10dbb66db3e8a921 | refs/heads/master | 2020-04-11T07:24:19.938391 | 2019-02-07T15:45:03 | 2019-02-07T15:45:03 | 161,609,143 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 479 | cpp | #include <array>
#include <iostream>
//#include<bits/stdcc++.h>
using namespace std;
int main(int argc, char** argv)
{
//std::array<pair<int,int>,4 > a = {};
//int x,y ,w;
//cin>>x>>y>>w;
//a[x].push_back({x,y});
//a[y].push_back({w,x});
//std::cout << a.size() << std::endl; // 4
//for(auto i : a)
//std::cout<< i<<std::endl;
deque<vector<pair<int,int>>> d{};
d = {{{3,4},{1,2}}};
for (auto i :d) {
for(auto j :i)
cout <<j.first <<' ' << j.second << '\n';
}
}
| [
"mohameda@debmower_ajd"
] | mohameda@debmower_ajd |
cd5778b718920c8cf34fc1ec20156e150a15a1b0 | cebd786b7b893700d526bc9b5b001bc326043c9a | /STRING/12_BinaryStringWithEqual01.cpp | c6d76a5ad4b8f83d550f07759a496cdf6d0d93a2 | [] | no_license | Healer-kid/CODING | 2b2ff52d05c2376cb03c4f1bf62a3b545568eff4 | 76a4b2835a9897bae41db557553b8b52c90e37a7 | refs/heads/main | 2023-07-23T01:24:32.316712 | 2021-08-27T08:07:03 | 2021-08-27T08:07:03 | 349,797,195 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,158 | cpp | Split the binary string into substrings with equal number of 0s and 1s
Given a binary string str of length N, the task is to find the maximum count of substrings str can be divided into such that all the substrings are balanced i.e. they have equal number of 0s and 1s. If it is not possible to split str satisfying the conditions then print -1.
Example:
Input: str = “0100110101”
Output: 4
The required substrings are “01”, “0011”, “01” and “01”.
Input: str = “0111100010”
Output: 3
TIME:O(N)
LOGIC:
1)use two variable to keep track of the no of zeros and no of ones and increment the count if they both are equal at any instance.
2) if the no of zeros and the no of ones are not equal in the given string then return -1
int cnt = 0;
for (int i = 0; i < n; i++) {
if (str[i] == '0') {
count0++;
}
else {
count1++;
}
if (count0 == count1) {
cnt++;
}
}
// It is not possible to
// split the string
if (count0 != count1) {
return -1;
}
return cnt;
| [
"noreply@github.com"
] | noreply@github.com |
05272952db97cbb3cc5e1680d847dc085918bf00 | e29bf1dd6f59838864798128c265e798e417252c | /Object Oriented Programming/new and delete function.cpp | 71ad53cd32acb2a9c3cd2b205a4c70512c322c3f | [] | no_license | jps27CSE/C-PlusPlus-Programming- | 9367b18fd81aafa03d149ac8d6ac56cce4e2a5dd | 5a3936701013e9ddf846b8fff5e4a615c7c2b1ae | refs/heads/master | 2023-01-14T16:14:12.275666 | 2020-11-16T14:10:40 | 2020-11-16T14:10:40 | 275,437,175 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 263 | cpp | #include<iostream>
using namespace std;
int main()
{
int *p;
p=new int; // allocate room for an integer
if(!p)
{
cout<<"error";
return 1;
}
*p=100;
cout<<*p;
delete p; //release memory
} | [
"noreply@github.com"
] | noreply@github.com |
29f90d5ba911c1c0b3dd6245754826cbbb1ea225 | 38e2760e5687d7447f006179696b2ac695f9e346 | /traveltime.cc | 4c004ec4aff36255d508d515f19b8e5296c08238 | [
"MIT"
] | permissive | lehoangha/tomo2d_HeriotWatt | c96d735ec9eff3814064f7251b8ac1fe1dab036e | 48477115ed2455a8255521570e4e81ffe754be08 | refs/heads/master | 2021-01-10T08:37:27.282716 | 2015-10-02T12:31:24 | 2015-10-02T12:31:24 | 43,548,323 | 3 | 2 | null | 2015-10-04T08:18:14 | 2015-10-02T11:01:13 | C++ | UTF-8 | C++ | false | false | 7,017 | cc | /*
* traveltime.cc - travel time integration along a ray path
*
* Jun Korenaga, MIT/WHOI
* January 1999
*/
#include "traveltime.h"
#include "interface.h"
#include <iostream>
#include <fstream>
double calcTravelTime(const SlownessMesh2d& smesh,
const Array1d<Point2d>& path,
const BetaSpline2d& bs,
const Array1d<const Point2d*>& pp,
Array1d<Point2d>& Q)
{
int np = path.size();
int nintp = bs.numIntp();
Index2d guess_index = smesh.nodeIndex(smesh.nearest(*pp(1)));
double ttime=0.0;
for (int i=1; i<=np+1; i++){
int j1=i;
int j2=i+1;
int j3=i+2;
int j4=i+3;
bs.interpolate(*pp(j1),*pp(j2),*pp(j3),*pp(j4),Q);
if (smesh.inWater(Q(nintp/2))){
// rectangular integration
for (int j=2; j<=nintp; j++){
Point2d midp = 0.5*(Q(j-1)+Q(j));
double u0 = smesh.at(midp,guess_index);
double dist = Q(j).distance(Q(j-1));
ttime += u0*dist;
}
}else{
// trapezoidal integration along one segment
double u0 = smesh.at(Q(1),guess_index);
for (int j=2; j<=nintp; j++){
double u1 = smesh.at(Q(j),guess_index);
double dist= Q(j).distance(Q(j-1));
ttime += 0.5*(u0+u1)*dist;
u0 = u1;
}
}
}
return ttime;
}
double calcTravelTime(const SlownessMesh2d& smesh,
const Array1d<Point2d>& path,
int ndiv)
{
int np = path.size();
Index2d guess_index = smesh.nodeIndex(smesh.nearest(path(1)));
double dd = 1.0/ndiv;
double ttime=0.0;
for (int i=2; i<=np; i++){
double dist= path(i).distance(path(i-1));
Point2d midp = 0.5*(path(i-1)+path(i));
if (smesh.inWater(midp)){
// rectangular integration
ttime += smesh.atWater()*dist;
}else{
// trapezoidal integration
double ddist = dist*dd;
double u0 = smesh.at(path(i-1),guess_index);
for (int j=1; j<=ndiv; j++){
double ratio = j*dd;
Point2d tmpp = (1-ratio)*path(i-1)+ratio*path(i);
double u1 = smesh.at(tmpp,guess_index);
ttime += 0.5*(u0+u1)*ddist;
u0 = u1;
}
}
}
return ttime;
}
void calc_dTdV2(const SlownessMesh2d& smesh, const Array1d<Point2d>& path,
const BetaSpline2d& bs, Array1d<Point2d>& dTdV,
const Array1d<const Point2d*>& pp,
Array1d<Point2d>& Q, Array1d<Point2d>& dQdu)
{
int np = path.size();
Array1d<Point2d> path2(np);
for (int i=1; i<=np; i++) path2(i) = path(i);
Array1d<const Point2d*> pp2;
makeBSpoints(path2,pp2);
double dx=0.0001;
dTdV(1).set(0.0,0.0); // end points are fixed
dTdV(np).set(0.0,0.0);
for (int i=2; i<np; i++){
double orig=path2(i).x();
path2(i).x(orig+dx);
double t1 = calcTravelTime(smesh,path2,bs,pp2,Q);
path2(i).x(orig-dx);
double t2 = calcTravelTime(smesh,path2,bs,pp2,Q);
dTdV(i).x((t1-t2)/(2*dx));
path2(i).x(orig);
orig=path2(i).y();
path2(i).y(orig+dx);
t1 = calcTravelTime(smesh,path2,bs,pp2,Q);
path2(i).y(orig-dx);
t2 = calcTravelTime(smesh,path2,bs,pp2,Q);
dTdV(i).y((t1-t2)/(2*dx));
path2(i).y(orig);
}
}
void calc_dTdV3(const SlownessMesh2d& smesh, const Array1d<Point2d>& path,
const BetaSpline2d& bs, Array1d<Point2d>& dTdV,
const Array1d<const Point2d*>& pp,
Array1d<Point2d>& Q, Array1d<Point2d>& dQdu,
const Array1d<int>& start_i,
const Array1d<int>& end_i,
const Array1d<const Interface2d*>& interf)
{
int np = path.size();
Array1d<Point2d> path2(np);
for (int i=1; i<=np; i++) path2(i) = path(i);
Array1d<const Point2d*> pp2;
makeBSpoints(path2,pp2);
double dx=0.0001;
dTdV(1).set(0.0,0.0); // end points are fixed
dTdV(np).set(0.0,0.0);
int a=1;
for (int i=2; i<np; i++){
if (i==start_i(a)){
double origx=path2(i).x();
double origy=path2(i).y();
for (int j=i; j<=end_i(a); j++){
path2(j).x(origx+dx);
path2(j).y(interf(a)->z(origx+dx));
}
double t1 = calcTravelTime(smesh,path2,bs,pp2,Q);
for (int j=i; j<=end_i(a); j++){
path2(j).x(origx-dx);
path2(j).y(interf(a)->z(origx-dx));
}
double t2 = calcTravelTime(smesh,path2,bs,pp2,Q);
double dtdv = (t1-t2)/(2*dx);
dtdv /= 3.0;
cerr << "\n" << "dtdv3: t1=" << t1 << " t2=" << t2
<< " dtdv=" << dtdv << '\n';
for (int j=i; j<=end_i(a); j++){
dTdV(j).x(dtdv);
dTdV(j).y(0.0);
}
for (int j=i; j<=end_i(a); j++){
path2(j).x(origx);
path2(j).y(origy);
}
i = end_i(a);
a++;
}else{
// move x
double orig=path2(i).x();
path2(i).x(orig+dx);
double t1 = calcTravelTime(smesh,path2,bs,pp2,Q);
path2(i).x(orig-dx);
double t2 = calcTravelTime(smesh,path2,bs,pp2,Q);
dTdV(i).x((t1-t2)/(2*dx));
path2(i).x(orig);
// move y
orig=path2(i).y();
path2(i).y(orig+dx);
t1 = calcTravelTime(smesh,path2,bs,pp2,Q);
path2(i).y(orig-dx);
t2 = calcTravelTime(smesh,path2,bs,pp2,Q);
dTdV(i).y((t1-t2)/(2*dx));
path2(i).y(orig);
}
}
}
void calc_dTdV(const SlownessMesh2d& smesh, const Array1d<Point2d>& path,
const BetaSpline2d& bs, Array1d<Point2d>& dTdV,
const Array1d<const Point2d*>& pp,
Array1d<Point2d>& Q, Array1d<Point2d>& dQdu)
{
int np = path.size();
int nintp = bs.numIntp();
double du = 1.0/(nintp-1);
dTdV(1).set(0.0,0.0); // end points are fixed
dTdV(np).set(0.0,0.0);
Index2d guess_index = smesh.nodeIndex(smesh.nearest(*pp(1)));
for (int i=2; i<np; i++){
double dTdVx=0.0, dTdVz=0.0;
// loop over four segments affected by the point Vi
int iseg_start = i-1;
int iseg_end = i+2; // min(i+2,np-1);
for (int j=iseg_start; j<=iseg_end; j++){
int j1=j;
int j2=j+1;
int j3=j+2;
int j4=j+3;
bs.interpolate(*pp(j1),*pp(j2),*pp(j3),*pp(j4),Q,dQdu);
int i_j = i-j;
// trapezoidal integration along one segment
double dudx0, dudz0, dudx1, dudz1;
Point2d startp = 0.9*Q(1)+0.1*Q(2); // in order to avoid singularity
double u0 = smesh.at(startp,guess_index,dudx0,dudz0);
double dQnorm0 = dQdu(1).norm();
double integx0, integz0;
if (dQnorm0==0.0){
integx0 = integz0 = 0.0;
}else{
double tmp1 = u0*bs.coeff_dbdu(i_j,1)/dQnorm0;
double tmp2 = dQnorm0*bs.coeff_b(i_j,1);
integx0 = tmp1*dQdu(1).x()+tmp2*dudx0;
integz0 = tmp1*dQdu(1).y()+tmp2*dudz0;
}
for (int m=2; m<=nintp; m++){
double u1;
if (m==nintp){
Point2d endp = 0.1*Q(m-1)+0.9*Q(m); // in order to avoid singularity
u1 = smesh.at(endp,guess_index,dudx1,dudz1);
}else{
u1 = smesh.at(Q(m),guess_index,dudx1,dudz1);
}
double dQnorm1 = dQdu(m).norm();
double integx1, integz1;
if (dQnorm1==0.0){
integx1 = integz1 = 0.0;
}else{
double tmp1 = u1*bs.coeff_dbdu(i_j,m)/dQnorm1;
double tmp2 = dQnorm1*bs.coeff_b(i_j,m);
integx1 = tmp1*dQdu(m).x()+tmp2*dudx1;
integz1 = tmp1*dQdu(m).y()+tmp2*dudz1;
}
dTdVx += 0.5*(integx0+integx1)*du;
dTdVz += 0.5*(integz0+integz1)*du;
integx0 = integx1;
integz0 = integz1;
}
}
dTdV(i).set(dTdVx,dTdVz);
}
}
| [
"lehoangha.info@gmail.com"
] | lehoangha.info@gmail.com |
e96bebce15671c6e0b781184ddf25f35b3e82529 | eb39d58f56a84c42fda1b899459b02cbe2f6b399 | /CLASS CODES/Week7/Example1/Employee.cpp | 3be47da5a04a78835f8bf767d15087259b76e8e8 | [] | no_license | mousters/FM_CPP_1 | f680c7dea8a1da0ee497176aca1fca61b7397066 | be30c836d61bd4081e9a0418ce1e12bcf4f11a4d | refs/heads/master | 2022-04-22T13:57:10.709580 | 2020-04-12T02:27:53 | 2020-04-12T02:27:53 | 236,399,759 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 185 | cpp | #include "Employee.h"
#include <iostream>
Employee::Employee(string name, string email, string job)
: Person(name, email),
job_(job)
{}
string Employee::GetJob()
{
return job_;
} | [
"lolmousters@users.noreply.github.com"
] | lolmousters@users.noreply.github.com |
e59e4f331ca48e3c27706955df44f945fd65ac60 | 051211c627f63aa37cce1cf085bf8b33cd6494af | /EPI/EPI_bak/06_BinaryTrees/include/Binary_tree_utils.h | aad946fc968fef1c3eedcfbdeaf0bf4f71ea0bd9 | [] | no_license | roykim0823/Interview | 32994ea0ec341ec19a644c7f3ef3b0774b228f2c | 660ab546a72ca86b4c4a91d3c7279a8171398652 | refs/heads/master | 2020-03-24T02:37:01.125120 | 2019-11-19T05:25:15 | 2019-11-19T05:25:15 | 139,811,693 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,487 | h | // Copyright (c) 2013 Elements of Programming Interviews. All rights reserved.
#ifndef SOLUTIONS_BINARY_TREE_UTILS_H_
#define SOLUTIONS_BINARY_TREE_UTILS_H_
#include <limits>
#include <list>
#include <memory>
#include <random>
#include <string>
#include <vector>
#include "Binary_tree_prototype.h"
using std::default_random_engine;
using std::list;
using std::make_shared;
using std::numeric_limits;
using std::random_device;
using std::unique_ptr;
using std::string;
using std::uniform_int_distribution;
using std::vector;
template <typename T>
unique_ptr<BinaryTreeNode<T>> generate_rand_binary_tree(int n,
bool is_unique = false) {
default_random_engine gen((random_device())());
list<unique_ptr<BinaryTreeNode<T>>*> l;
uniform_int_distribution<int> dis(0, numeric_limits<int>::max());
auto root =
unique_ptr<BinaryTreeNode<T>>(new BinaryTreeNode<T>{(is_unique ? n-- : dis(gen))});
l.emplace_back(&(root->left));
l.emplace_back(&(root->right));
while (n--) {
uniform_int_distribution<int> x_dis(0, l.size() - 1);
int x = x_dis(gen);
typename list<unique_ptr<BinaryTreeNode<T>>*>::iterator it = l.begin();
advance(it, x);
**it = unique_ptr<BinaryTreeNode<T>>(new BinaryTreeNode<T>{(is_unique ? n : dis(gen))});
l.emplace_back(&((**it)->left));
l.emplace_back(&((**it)->right));
l.erase(it);
}
return root;
}
template <typename T>
void delete_binary_tree(unique_ptr<BinaryTreeNode<T>>* n) {
if (n) {
if ((*n)->left.get()) {
delete_binary_tree(&((*n)->left));
}
if ((*n)->right.get()) {
delete_binary_tree(&((*n)->right));
}
n->reset(nullptr);
}
}
template <typename T>
bool is_two_binary_trees_equal(const unique_ptr<BinaryTreeNode<T>>& r1,
const unique_ptr<BinaryTreeNode<T>>& r2) {
if (r1 && r2) {
return is_two_binary_trees_equal(r1->left, r2->left) &&
is_two_binary_trees_equal(r1->right, r2->right) &&
r1->data == r2->data;
} else if (!r1 && !r2) {
return true;
} else {
return false;
}
}
template <typename T>
void generate_preorder_helper(const unique_ptr<BinaryTreeNode<T>>& r,
vector<T>* ret) {
if (r) {
ret->emplace_back(r->data);
generate_preorder_helper(r->left, ret);
generate_preorder_helper(r->right, ret);
}
}
template <typename T>
vector<T> generate_preorder(const unique_ptr<BinaryTreeNode<T>>& r) {
vector<T> ret;
generate_preorder_helper(r, &ret);
return ret;
}
template <typename T>
void generate_inorder_helper(const unique_ptr<BinaryTreeNode<T>>& r,
vector<T>* ret) {
if (r) {
generate_inorder_helper(r->left, ret);
ret->emplace_back(r->data);
generate_inorder_helper(r->right, ret);
}
}
template <typename T>
vector<T> generate_inorder(const unique_ptr<BinaryTreeNode<T>>& r) {
vector<T> ret;
generate_inorder_helper(r, &ret);
return ret;
}
template <typename T>
void generate_postorder_helper(const unique_ptr<BinaryTreeNode<T>>& r,
vector<T>* ret) {
if (r) {
generate_postorder_helper(r->left, ret);
generate_postorder_helper(r->right, ret);
ret->emplace_back(r->data);
}
}
template <typename T>
vector<T> generate_postorder(const unique_ptr<BinaryTreeNode<T>>& r) {
vector<T> ret;
generate_postorder_helper(r, &ret);
return ret;
}
#endif // SOLUTIONS_BINARY_TREE_UTILS_H_
| [
"roykim0823@gmail.com"
] | roykim0823@gmail.com |
bb1e8e08c391449a139f05494807f0deee678eaa | 36597ca6d8b08baaef52cddf46bca3d13f0a97a5 | /Plugins/Core/src/ImgProc/Blur.hpp | 0d10634fe700a9a64442634fcfb7aa78d7c8ac22 | [
"BSD-3-Clause"
] | permissive | Essarelle/EagleEye | 169f3ce17d1a6ae298a3b764784f29be7ce49280 | 341132edb21b4899ebbe0b52460c4e72e36e4b6d | refs/heads/master | 2020-02-27T21:55:27.725746 | 2017-10-10T06:28:23 | 2017-10-10T06:28:23 | 101,608,078 | 1 | 1 | null | 2017-09-05T06:46:26 | 2017-08-28T05:47:15 | C++ | UTF-8 | C++ | false | false | 558 | hpp | #pragma once
#include <Aquila/nodes/Node.hpp>
#include <Aquila/types/SyncedMemory.hpp>
#include "Aquila/rcc/external_includes/cv_cudafilters.hpp"
namespace aq
{
namespace nodes
{
class MedianBlur: public Node
{
public:
MO_DERIVE(MedianBlur, Node)
INPUT(SyncedMemory, input, nullptr)
PARAM(int, window_size, 5)
PARAM(int, partition, 128)
OUTPUT(SyncedMemory, output, {})
MO_END
protected:
bool processImpl();
cv::Ptr<cv::cuda::Filter> _median_filter;
};
}
}
| [
"dtmoodie@gmail.com"
] | dtmoodie@gmail.com |
9be54aeec56a8cec51a85adb4d67cce797ba8d21 | ccfb6c1fb542b5ad3251c8c01fb23b714efbe10a | /Roguemon/Tile.hpp | 002802a0885f3cfd4e473af29d92c0bacb147fa1 | [] | no_license | guidolippi94/Roguemon | d2e396cd2182bc5484964e4217af71aa37c9ad35 | e57f1f9e8e730106f69fe79e081184b2d9622a6c | refs/heads/master | 2021-01-10T11:00:03.046345 | 2016-03-31T21:57:56 | 2016-03-31T21:57:56 | 54,490,193 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 123 | hpp |
#ifndef Tile_hpp
#define Tile_hpp
#include <stdio.h>
class Tile {
public:
};
#endif /* Tile_hpp */
| [
"francesco.pegoraro@hotmail.it"
] | francesco.pegoraro@hotmail.it |
66b720507701029c227834cab10b74a8b24ff0a3 | e4e9f5330b0bcffe5953f6706c8825220a6da732 | /Advanced/PAT-Advanced-99.cpp | cbe08661db40f80ae5ef853e21053d2ea461837f | [] | no_license | sandexp/Pat-Algorithm | b8a76aeaae6277430e01cdeeeb8e8960b4cebdaa | f8f94bf472942e9c33e5824be56ad0292ff1d05f | refs/heads/master | 2022-03-29T18:33:52.031320 | 2020-01-15T17:09:01 | 2020-01-15T17:09:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,833 | cpp | #include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;
/*
考虑不全面
考虑n1<n2的两个日期
TODO 通过从n1加到n2的方式来计算话费
*/
struct Node{
string name;
int mon;int day;int h;int m;
string sta;
void show(){
cout<<name<<" "<<mon<<":"<<day<<":"<<h<<":"<<m<<" "<<sta<<"\n";
}
};
int charge[24];
bool cmp(Node n1,Node n2){
if(n1.name==n2.name && n1.mon==n2.mon && n1.day==n2.day && n1.h==n2.h) return n1.m<n2.m;
if(n1.name==n2.name && n1.mon==n2.mon && n1.day==n2.day) return n1.h<n2.h;
if(n1.name==n2.name && n1.mon==n2.mon) return n1.day<n2.day;
if(n1.name==n2.name) return n1.mon<n2.mon;
return n1.name<n2.name;
}
struct Result{
double val;
int minutes;
void show(){
printf("%d $%.2f\n",this->minutes,this->val);
}
};
map<string,double> mp;
vector<Node> v;
Result caculate(Node n1,Node n2){
// 计算时差 不考虑跨日期
int h1,h2,minutes=0,basem=0;
int cost=0;
int temp=0;
bool flag=false;
double res;
int base=n2.day-n1.day;
if(base!=0){
for (int i = 0; i < 24; i++)
temp+=60*charge[i];
basem=base*24*60;
base=base*temp;
}
if(n1.h>n2.h){
swap(n1,n2);
flag=true;
}
if(n1.m==0)
h1=n1.h;
else
h1=n1.h+1;
h2=n2.h;
for (int i = h1; i < h2; i++){
cost+=60*charge[i];
minutes+=60;
}
cost+=n2.m*charge[h2];
minutes+=n2.m;
cost+=(60-n1.m)*charge[h1-1];
minutes+=(60-n1.m);
if(flag){
minutes=basem-minutes;
cost=base-cost;
}
else{
minutes=basem+minutes;
cost+=base;
}
res=(double)cost/100;
return Result{res,minutes};
}
int main(int argc, char const *argv[])
{
string id,sta;
int mon,day,h,m;
for (int i = 0; i < 24; i++)
scanf("%d",&charge[i]);
int n;
scanf("%d",&n);
for (int i = 0; i < n; i++){
cin>>id;
scanf("%02d:%02d:%02d:%02d",&mon,&day,&h,&m);
cin>>sta;
v.push_back(Node{id,mon,day,h,m,sta});
}
sort(v.begin(),v.end(),cmp);
for (int i = 0; i < v.size()-1; i++){
if((i!=0 && v[i-1].name!=v[i].name) || i==0){
cout<<v[i].name;
printf(" %02d\n",v[i].mon);
}
if(v[i].name==v[i+1].name && v[i].sta=="on-line" && v[i+1].sta=="off-line" && v[i].mon){
printf("%02d:%02d:%02d %02d:%02d:%02d ",v[i].day,v[i].h,v[i].m,v[i+1].day,v[i+1].h,v[i+1].m);
Result res=caculate(v[i],v[i+1]);
res.show();
mp[v[i].name]+=res.val;
}
if((v[i].name!=v[i+1].name || i==v.size()-2)){
printf("Total amount: $%.2f\n",mp[v[i].name]);
}
}
return 0;
}
| [
"XieYunfei0921@126.com"
] | XieYunfei0921@126.com |
5deb10c00676e5eede52c56c4ae2daed725474d1 | 8043662a3181b2352e80632af62be294997395d6 | /hw6/insertion_sort.h | bc41ab126a05076de5ab9854cc8156f92f3275d7 | [] | no_license | rcrocomb/old_classwork_cs345_data_structures | 4661aad65dd8dd2caba6623e180932ef8b284324 | 49162266795802ba9e8c87884f22da3ff7e75207 | refs/heads/master | 2020-04-15T04:50:56.877887 | 2019-01-07T08:21:47 | 2019-01-07T08:21:47 | 164,398,410 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 259 | h | #ifndef INSERTION_SORT_H
#define INSERTION_SORT_H
#include "sort.h"
class insertion_sort
{
public:
static void sort(svector &v) { sort(v, 0, v.size() - 1); }
static void sort(svector &v, const int l, const int r);
};
#endif // INSERTION_SORT_H
| [
"rcrocomb@ieee.org"
] | rcrocomb@ieee.org |
b96ca4227b6c95d84c5f26d5256420e8893f26d7 | 0a5058bff1961f6564c662224362995ee8fa3944 | /components/viz/service/display/display_perftest.cc | 8cf41d8418825b23868817498b13f0d35b0b0f08 | [
"BSD-3-Clause"
] | permissive | DongKai/chromium | d0208df711d2bad1e4324ca3b10a261c336758a0 | b7bb401aedab4fbe5af173a5baeaf91c8dbe726a | refs/heads/master | 2022-12-05T17:16:47.586163 | 2020-09-02T23:37:00 | 2020-09-02T23:37:00 | 292,435,006 | 0 | 0 | BSD-3-Clause | 2020-09-03T01:31:29 | 2020-09-03T01:31:28 | null | UTF-8 | C++ | false | false | 14,692 | cc | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <vector>
#include "base/bind.h"
#include "base/test/null_task_runner.h"
#include "base/time/time.h"
#include "base/timer/lap_timer.h"
#include "components/viz/common/display/renderer_settings.h"
#include "components/viz/common/quads/compositor_frame.h"
#include "components/viz/common/quads/compositor_render_pass.h"
#include "components/viz/common/quads/draw_quad.h"
#include "components/viz/common/quads/texture_draw_quad.h"
#include "components/viz/common/surfaces/aggregated_frame.h"
#include "components/viz/common/surfaces/frame_sink_id.h"
#include "components/viz/service/display/display.h"
#include "components/viz/service/display/display_scheduler.h"
#include "components/viz/service/display/output_surface.h"
#include "components/viz/service/display/overlay_processor_stub.h"
#include "components/viz/service/display/shared_bitmap_manager.h"
#include "components/viz/service/display_embedder/server_shared_bitmap_manager.h"
#include "components/viz/test/fake_output_surface.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/perf/perf_result_reporter.h"
namespace viz {
namespace {
static const int kTimeLimitMillis = 3000;
static const int kWarmupRuns = 5;
static const int kTimeCheckInterval = 10;
static const int kHeight = 1000;
static const int kWidth = 1000;
constexpr char kMetricPrefixRemoveOverdrawQuad[] = "RemoveOverdrawQuad.";
constexpr char kMetricOverlapThroughputRunsPerS[] = "overlap_throughput";
constexpr char kMetricIsolatedThroughputRunsPerS[] = "isolated_throughput";
constexpr char kMetricPartialOverlapThroughputRunsPerS[] =
"partial_overlap_throughput";
constexpr char kMetricAdjacentThroughputRunsPerS[] = "adjacent_throughput";
perf_test::PerfResultReporter SetUpRemoveOverdrawQuadReporter(
const std::string& story) {
perf_test::PerfResultReporter reporter(kMetricPrefixRemoveOverdrawQuad,
story);
reporter.RegisterImportantMetric(kMetricOverlapThroughputRunsPerS, "runs/s");
reporter.RegisterImportantMetric(kMetricIsolatedThroughputRunsPerS, "runs/s");
reporter.RegisterImportantMetric(kMetricPartialOverlapThroughputRunsPerS,
"runs/s");
reporter.RegisterImportantMetric(kMetricAdjacentThroughputRunsPerS, "runs/s");
return reporter;
}
class RemoveOverdrawQuadPerfTest : public testing::Test {
public:
RemoveOverdrawQuadPerfTest()
: timer_(kWarmupRuns,
base::TimeDelta::FromMilliseconds(kTimeLimitMillis),
kTimeCheckInterval),
task_runner_(base::MakeRefCounted<base::NullTaskRunner>()) {}
std::unique_ptr<Display> CreateDisplay() {
FrameSinkId frame_sink_id(3, 3);
auto scheduler = std::make_unique<DisplayScheduler>(&begin_frame_source_,
task_runner_.get(), 1);
std::unique_ptr<FakeOutputSurface> output_surface =
FakeOutputSurface::Create3d();
auto overlay_processor = std::make_unique<OverlayProcessorStub>();
auto display = std::make_unique<Display>(
&bitmap_manager_, RendererSettings(), &debug_settings_, frame_sink_id,
std::move(output_surface), std::move(overlay_processor),
std::move(scheduler), task_runner_.get());
return display;
}
// Create an arbitrary SharedQuadState for the given |render_pass|.
SharedQuadState* CreateSharedQuadState(AggregatedRenderPass* render_pass,
gfx::Rect rect) {
gfx::Transform quad_transform = gfx::Transform();
bool is_clipped = false;
bool are_contents_opaque = true;
float opacity = 1.f;
int sorting_context_id = 65536;
SkBlendMode blend_mode = SkBlendMode::kSrcOver;
SharedQuadState* state = render_pass->CreateAndAppendSharedQuadState();
state->SetAll(quad_transform, rect, rect,
/*rounded_corner_bounds=*/gfx::RRectF(), rect, is_clipped,
are_contents_opaque, opacity, blend_mode, sorting_context_id);
return state;
}
// Append draw quads to a given |shared_quad_state|.
void AppendQuads(SharedQuadState* shared_quad_state,
int quad_height,
int quad_width) {
bool needs_blending = false;
ResourceId resource_id = 1;
bool premultiplied_alpha = true;
gfx::PointF uv_top_left(0, 0);
gfx::PointF uv_bottom_right(1, 1);
SkColor background_color = SK_ColorRED;
float vertex_opacity[4] = {1.f, 1.f, 1.f, 1.f};
bool y_flipped = false;
bool nearest_neighbor = true;
int x_left = shared_quad_state->visible_quad_layer_rect.x();
int x_right = x_left + shared_quad_state->visible_quad_layer_rect.width();
int y_top = shared_quad_state->visible_quad_layer_rect.y();
int y_bottom = y_top + shared_quad_state->visible_quad_layer_rect.height();
int i = x_left;
int j = y_top;
while (i + quad_width <= x_right) {
while (j + quad_height <= y_bottom) {
auto* quad = frame_.render_pass_list.front()
->CreateAndAppendDrawQuad<TextureDrawQuad>();
gfx::Rect rect(i, j, quad_width, quad_height);
quad->SetNew(shared_quad_state, rect, rect, needs_blending, resource_id,
premultiplied_alpha, uv_top_left, uv_bottom_right,
background_color, vertex_opacity, y_flipped,
nearest_neighbor, /*secure_output_only=*/false,
gfx::ProtectedVideoType::kClear);
j += quad_height;
}
j = y_top;
i += quad_width;
}
}
// All SharedQuadState are overlapping the same region.
// +--------+
// | s1/2/3 |
// +--------+
void IterateOverlapShareQuadStates(const std::string& story,
int shared_quad_state_count,
int quad_count) {
frame_.render_pass_list.push_back(std::make_unique<AggregatedRenderPass>());
CreateOverlapShareQuadStates(shared_quad_state_count, quad_count);
std::unique_ptr<Display> display = CreateDisplay();
timer_.Reset();
do {
display->RemoveOverdrawQuads(&frame_);
timer_.NextLap();
} while (!timer_.HasTimeLimitExpired());
auto reporter = SetUpRemoveOverdrawQuadReporter(story);
reporter.AddResult(kMetricOverlapThroughputRunsPerS,
timer_.LapsPerSecond());
frame_ = AggregatedFrame{};
}
void CreateOverlapShareQuadStates(int shared_quad_state_count,
int quad_count) {
int quad_height = kHeight / quad_count;
int quad_width = kWidth / quad_count;
int total_shared_quad_state =
shared_quad_state_count * shared_quad_state_count;
for (int i = 0; i < total_shared_quad_state; i++) {
gfx::Rect rect(0, 0, kHeight, kWidth);
SharedQuadState* new_shared_state(
CreateSharedQuadState(frame_.render_pass_list.front().get(), rect));
AppendQuads(new_shared_state, quad_height, quad_width);
}
}
// SharedQuadState are non-overlapped as shown in the figure below.
// +---+
// |s1 |
// +---+---+
// |s2 |
// +---+---+
// |s3 |
// +---+
void IterateIsolatedSharedQuadStates(const std::string& story,
int shared_quad_state_count,
int quad_count) {
frame_.render_pass_list.push_back(std::make_unique<AggregatedRenderPass>());
CreateIsolatedSharedQuadStates(shared_quad_state_count, quad_count);
std::unique_ptr<Display> display = CreateDisplay();
timer_.Reset();
do {
display->RemoveOverdrawQuads(&frame_);
timer_.NextLap();
} while (!timer_.HasTimeLimitExpired());
auto reporter = SetUpRemoveOverdrawQuadReporter(story);
reporter.AddResult(kMetricIsolatedThroughputRunsPerS,
timer_.LapsPerSecond());
frame_ = AggregatedFrame{};
}
void CreateIsolatedSharedQuadStates(int shared_quad_state_count,
int quad_count) {
int shared_quad_state_height =
kHeight / (shared_quad_state_count * shared_quad_state_count);
int shared_quad_state_width =
kWidth / (shared_quad_state_count * shared_quad_state_count);
int quad_height = shared_quad_state_height / quad_count;
int quad_width = shared_quad_state_width / quad_count;
int i = 0;
int j = 0;
while (i + shared_quad_state_height <= kWidth ||
j + shared_quad_state_height <= kHeight) {
gfx::Rect rect(i, j, shared_quad_state_height, shared_quad_state_width);
SharedQuadState* new_shared_state(
CreateSharedQuadState(frame_.render_pass_list.front().get(), rect));
AppendQuads(new_shared_state, quad_height, quad_width);
j += shared_quad_state_height;
i += shared_quad_state_width;
}
}
// SharedQuadState are overlapped as shown in the figure below.
// +----+
// | +----+
// | | +----+
// +-| | +----+
// +--| | |
// +--| |
// +----+
void IteratePartiallyOverlapSharedQuadStates(const std::string& story,
int shared_quad_state_count,
float percentage_overlap,
int quad_count) {
frame_.render_pass_list.push_back(std::make_unique<AggregatedRenderPass>());
CreatePartiallyOverlapSharedQuadStates(shared_quad_state_count,
percentage_overlap, quad_count);
std::unique_ptr<Display> display = CreateDisplay();
timer_.Reset();
do {
display->RemoveOverdrawQuads(&frame_);
timer_.NextLap();
} while (!timer_.HasTimeLimitExpired());
auto reporter = SetUpRemoveOverdrawQuadReporter(story);
reporter.AddResult(kMetricPartialOverlapThroughputRunsPerS,
timer_.LapsPerSecond());
frame_ = AggregatedFrame{};
}
void CreatePartiallyOverlapSharedQuadStates(int shared_quad_state_count,
float percentage_overlap,
int quad_count) {
int shared_quad_state_height =
kHeight / (shared_quad_state_count * shared_quad_state_count);
int shared_quad_state_width =
kWidth / (shared_quad_state_count * shared_quad_state_count);
int quad_height = shared_quad_state_height / quad_count;
int quad_width = shared_quad_state_width / quad_count;
int i = 0;
int j = 0;
for (int count = 0; count < shared_quad_state_count; count++) {
gfx::Rect rect(i, j, shared_quad_state_height, shared_quad_state_width);
SharedQuadState* new_shared_state(
CreateSharedQuadState(frame_.render_pass_list.front().get(), rect));
AppendQuads(new_shared_state, quad_height, quad_width);
i += shared_quad_state_width * percentage_overlap;
j += shared_quad_state_height * percentage_overlap;
}
}
// SharedQuadState are all adjacent to each other and added as the order shown
// in the figure below.
// +----+----+
// | s1 | s3 |
// +----+----+
// | s2 | s4 |
// +----+----+
void IterateAdjacentSharedQuadStates(const std::string& story,
int shared_quad_state_count,
int quad_count) {
frame_.render_pass_list.push_back(std::make_unique<AggregatedRenderPass>());
CreateAdjacentSharedQuadStates(shared_quad_state_count, quad_count);
std::unique_ptr<Display> display = CreateDisplay();
timer_.Reset();
do {
display->RemoveOverdrawQuads(&frame_);
timer_.NextLap();
} while (!timer_.HasTimeLimitExpired());
auto reporter = SetUpRemoveOverdrawQuadReporter(story);
reporter.AddResult(kMetricAdjacentThroughputRunsPerS,
timer_.LapsPerSecond());
frame_ = AggregatedFrame{};
}
void CreateAdjacentSharedQuadStates(int shared_quad_state_count,
int quad_count) {
int shared_quad_state_height = kHeight / shared_quad_state_count;
int shared_quad_state_width = kWidth / shared_quad_state_count;
int quad_height = shared_quad_state_height / quad_count;
int quad_width = shared_quad_state_width / quad_count;
int i = 0;
int j = 0;
while (i + shared_quad_state_height <= kWidth) {
while (j + shared_quad_state_width <= kHeight) {
gfx::Rect rect(i, j, shared_quad_state_height, shared_quad_state_width);
SharedQuadState* new_shared_state =
CreateSharedQuadState(frame_.render_pass_list.front().get(), rect);
AppendQuads(new_shared_state, quad_height, quad_width);
j += shared_quad_state_height;
}
j = 0;
i += shared_quad_state_width;
}
}
private:
DebugRendererSettings debug_settings_;
AggregatedFrame frame_;
base::LapTimer timer_;
StubBeginFrameSource begin_frame_source_;
scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
ServerSharedBitmapManager bitmap_manager_;
};
TEST_F(RemoveOverdrawQuadPerfTest, IterateOverlapShareQuadStates) {
IterateOverlapShareQuadStates("4_sqs_with_4_quads", 2, 2);
IterateOverlapShareQuadStates("4_sqs_with_100_quads", 2, 10);
IterateOverlapShareQuadStates("100_sqs_with_4_quads", 10, 2);
IterateOverlapShareQuadStates("100_sqs_with_100_quads", 10, 10);
}
TEST_F(RemoveOverdrawQuadPerfTest, IterateIsolatedSharedQuadStates) {
IterateIsolatedSharedQuadStates("2_sqs_with_4_quads", 2, 2);
IterateIsolatedSharedQuadStates("2_sqs_with_100_quads", 2, 10);
IterateIsolatedSharedQuadStates("10_sqs_with_4_quads", 10, 2);
IterateIsolatedSharedQuadStates("10_sqs_with_100_quads", 10, 10);
}
TEST_F(RemoveOverdrawQuadPerfTest, IteratePartiallyOverlapSharedQuadStates) {
IteratePartiallyOverlapSharedQuadStates("2_sqs_with_4_quads", 2, 0.5, 2);
IteratePartiallyOverlapSharedQuadStates("2_sqs_with_100_quads", 2, 0.5, 10);
IteratePartiallyOverlapSharedQuadStates("10_sqs_with_4_quads", 10, 0.5, 2);
IteratePartiallyOverlapSharedQuadStates("10_sqs_with_100_quads", 10, 0.5, 10);
}
TEST_F(RemoveOverdrawQuadPerfTest, IterateAdjacentSharedQuadStates) {
IterateAdjacentSharedQuadStates("4_sqs_with_4_quads", 2, 2);
IterateAdjacentSharedQuadStates("4_sqs_with_100_quads", 2, 10);
IterateAdjacentSharedQuadStates("100_sqs_with_4_quads", 10, 2);
IterateAdjacentSharedQuadStates("100_sqs_with_100_quads", 10, 10);
}
} // namespace
} // namespace viz
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
2a24b2d21a3c39068cb61d1db364000ea4182580 | e7e86d516add424fe9f1b31060425e8b3f84c9d1 | /SmartyGLEngine/cFollowPathBehaviour.cpp | 6783788d8938f5560a36d247807ced4b3951ca43 | [] | no_license | kkerrigan/Game-Jam | b6beb984938ab30209b53b5c6d327deabb55d736 | b8173f9bd6b94036e8877beef73b9d4e3d5fd72e | refs/heads/master | 2020-12-28T06:50:28.605004 | 2020-02-04T15:34:15 | 2020-02-04T15:34:15 | 238,218,338 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,655 | cpp | /*
* Name: cFollowPathBehaviour.h
* Author: Daniel Maclam
* Date 2019-03-03 5:58 PM
*/
#include "cFollowPathBehaviour.h"
#include "cPathFinding.h"
cFollowPathBehaviour::cFollowPathBehaviour(): is_finished(false), current_node(0), direction(1)
{
}
void cFollowPathBehaviour::update(cEntity* entity, float delta_time)
{
if(is_finished) return;
cTransformComponent* transform_component = static_cast<cTransformComponent*>(entity->components[1]);
//check if we are at a node
glm::vec3 entity_position = transform_component->get_position();
glm::vec3 current_node_position = this->nodes[this->current_node];
float distance_to_current_node = glm::abs(glm::distance(entity_position, current_node_position));
//if we are at the node then change the next node if we have one
if(distance_to_current_node <= 0.05f)
{
//goal node (reverse direction)
size_t end_node = this->nodes.size() - 1;
//we are at the end node so stop
if(this->nodes[this->current_node] == this->nodes[end_node])
{
is_finished = true;
return;
}
this->current_node = (this->current_node + direction);
}
current_node_position = this->nodes[this->current_node];
//change the entities directions to face the current node
glm::vec3 direction = glm::normalize(current_node_position - entity_position);
glm::quat orientation_to_current_node = glm::quat(glm::inverse(glm::lookAt(entity_position, entity_position - direction, glm::vec3(0.0f, 1.0f, 0.0f))));
//if we are close to the current node start turning towards the next node
distance_to_current_node = glm::distance(entity_position, current_node_position);
if(distance_to_current_node >= 3.0f)
{
orientation_to_current_node = glm::mix(transform_component->getQOrientation(), orientation_to_current_node, 0.05f);
}
transform_component->setQOrientation(orientation_to_current_node);
glm::vec3 forward = glm::toMat3(transform_component->getQOrientation()) * glm::vec3(0.0f, 0.0f, 1.0f);
transform_component->set_position(entity_position + forward * delta_time);
}
void cFollowPathBehaviour::add_node(glm::vec3 node, int index)
{
//no index passed
if(index == -1)
{
this->nodes.push_back(node);
return;
}
std::vector<glm::vec3>::iterator it = this->nodes.begin() + index;
this->nodes.insert(it, 1, node);
}
void cFollowPathBehaviour::set_path(std::vector<glm::vec3> nodes)
{
this->nodes = nodes;
}
void cFollowPathBehaviour::set_path(cPathFinding::path_info path_info)
{
this->nodes = path_info.nodes;
}
glm::vec3 cFollowPathBehaviour::get_last_node()
{
return this->nodes.back();
}
bool cFollowPathBehaviour::is_finsihed() const
{
return this->is_finished;
}
| [
"k.burnard@hotmail.com"
] | k.burnard@hotmail.com |
4498e9b14553f953a841e46063538d0f02f7451b | 37c155b31697c8bd9f9468f46c2a5d32e206d8f1 | /FinalEMG/filters_defs.h | a9d1fea24688741cda978ed735bf78a51e05effc | [] | no_license | choiyuuuna/SNUprosthetic | e84c5e5f865d9cff11ad20ed381c9143387c3b20 | 6146ebaf2d6cf18e8f7ddb17fc1fc1a437f507f9 | refs/heads/master | 2020-12-10T22:40:52.896813 | 2020-01-14T02:11:40 | 2020-01-14T02:11:40 | 233,733,304 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 568 | h | #pragma once
// #define LIBFILTER_USE_DOUBLE
#ifndef LIBFILTER_USE_DOUBLE
typedef float float_t;
typedef int int_t;
#else
typedef double float_t;
typedef int64_t int_t;
#endif
namespace IIR {
const uint8_t MAX_ORDER = 5;
enum class ORDER : uint8_t { OD1 = 0, OD2, OD3, OD4 };//, OD5};
enum class TYPE : uint8_t { LOWPASS = 0, HIGHPASS = 1 };
const float_t SQRT2 = sqrt(2.0);
const float_t SQRT3 = sqrt(3.0);
const float_t SQRT5 = sqrt(5.0);
const float_t EPSILON = 0.00001;
const float_t WEPSILON = 0.00010;
const float_t KM = 100.0;
} | [
"chldbsk2220@naver.com"
] | chldbsk2220@naver.com |
30f195df05a7ceab9178175a4b138c64f4eb8a22 | 0014ad9d3279cbdc94e1b5249fb78e87799500f2 | /Graphs/Creating adjacency list normal way.cpp | 32bed29155a87a260576704530b0bcd4d61bcd65 | [] | no_license | bharat1234567/code | 874ef7c8196dea8b97f7d3037c32adddc81feb90 | 5032a76b2f0c2d21145f84bf939a915138c1a5a3 | refs/heads/master | 2021-01-09T05:53:39.670488 | 2017-07-06T14:36:37 | 2017-07-06T14:36:37 | 80,860,481 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,129 | cpp | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
/*
for directly creating an adjacency list .. without graph datastructure this is another way!!
FYI here as you can see.. we can create multiple constuctors in a class.
*/
class node
{
private:
int value;
node *next;
public:
node() // empty constuctor
{
}
node(int v,node * k) // node when value and next pointer is given.
{
value=v;
next=k;
}
void addedge(node **ptr,int src,int dest)
{
node * abc = new node(dest-1,ptr[src-1]);
ptr[src-1]= abc;
node *cdf = new node(src-1,ptr[dest-1]);
ptr[dest-1]=cdf;
}
void printlist(node **ptr,int n)
{
for(int i=0;i<n;i++)
{
cout << i << " ";
node *x= ptr[i];
while(x)
{
cout << x->value << " ";
x= x->next;
}
cout << endl;
}
}
};
int main()
{
int n,m; // n is number of vertices, m is number of edges
cin >> n >>m;
node *adj[n]; // i.e. every adj[i] is a pointer which can point to a node sturcture , (node stucture contains a value variable and next pointer )
// infact adj is a pointer to pointer which is pointing to continuous location of size n. each location can store only location of a node type. so adj is a pointer to pointer of type node while adj[0]
for(int i=0;i<n;i++)
adj[i]= NULL; // every adj[i] is initially pointing to NULL.
node **ptr; // TO tranverse this adj[](array of pointers) what we need is a pointer to a pointer of type node.
ptr= adj; // ptr now points to adj[0], this proves both adj and ptr are double pointers. so when i write adj[0] it becomes single pointer.
for(int i=0;i<m;i++) // for every edge i will need to insert into adjacency list
{
int x;int y;
cin >> x >>y;
/*
Now adj is array of pointer to node.
adj[0] infact is element of array.
to access any variable or fuction of a class.
If its an Object --> use dot "." notation
if its an array --> use pointing "->" notation.
*/
adj[i]->addedge(ptr,x,y); // see how fuction is accessed.
}
adj[0]->printlist(ptr,n);
return 0;
}
| [
"bharatkumarmakhija14@gmail.com"
] | bharatkumarmakhija14@gmail.com |
16de9ccd25280e36cc3bce93c88041327c585a01 | ce29e9c78e854ef49b116e3b82703a083221ca04 | /system/v1.1/Interface.cpp | f8a1bb77a6127e118ea862a0ca2a31fc080d9f4c | [] | no_license | venkatarajasekhar/system | 2abb0b60a49701edeb2db7e567d924b6c49ab869 | 23c30cd23bff9c0827be91d3e82c9a27a4427008 | refs/heads/master | 2021-01-11T16:27:35.823940 | 2012-12-25T12:45:55 | 2012-12-25T12:45:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,092 | cpp | /*
* This file contains basic functions of Interface.
*
* by Qichen Pan.
*/
#include "util.h"
#include "lib.h"
int CM_Port = 0, TM_Port = 0;
char CM_IP[80] = "", TM_IP[80] = "";
char Source_Code_Path[512] = "", Program_Path[512] = "", Input_Path[512] = "";
int Device_Parameter = -1;
void* conn_to_TM(void*);
void* conn_to_CM(void*);
int main()
{
// Get CM information
FILE* CM_Info;
CM_Info = fopen("CM_Info", "r");
fscanf(CM_Info, "%s", CM_IP);
fscanf(CM_Info, "%d", &CM_Port);
fclose(CM_Info);
// Get TM information
FILE* TM_Info = fopen("TM_Info", "r");
fscanf(TM_Info, "%s", TM_IP);
fscanf(TM_Info, "%d", &TM_Port);
fscanf(TM_Info, "%d", &TM_Port);
fscanf(TM_Info, "%d", &TM_Port);
// Get user information
printf("Please type in the source code path: \n");
scanf("%s", Source_Code_Path);
printf("Please typpe in the input file path: \n");
scanf("%s", Input_Path);
printf("Please type in the device parameter: \n");
scanf("%d", &Device_Parameter);
// Create thread to deal with CM
pthread_t thread_conn_to_CM;
pthread_create(&thread_conn_to_CM, NULL, conn_to_CM, NULL);
// Create thread to deal with TM
pthread_t thread_conn_to_TM;
pthread_create(&thread_conn_to_TM, NULL, conn_to_TM, NULL);
pthread_join(thread_conn_to_CM, NULL);
pthread_join(thread_conn_to_TM, NULL);
return 0;
}
void* conn_to_CM(void* args)
{
int sockfd_CM = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd_CM < 0)
{
perror("Error opening socket.\n");
exit(1);
}
struct sockaddr_in CM_Addr;
struct hostent *CM_Host;
CM_Addr.sin_family = AF_INET;
CM_Host = gethostbyname(CM_IP);
memcpy(&CM_Addr.sin_addr.s_addr, CM_Host->h_addr, CM_Host->h_length);
CM_Addr.sin_port = htons(CM_Port);
while(connect(sockfd_CM, (sockaddr*)&CM_Addr, sizeof(CM_Addr)) == -1)
{
sleep(1);
}
while(strcmp(Source_Code_Path, "") == 0)
{
sleep(1);
}
char tmp[1024] = "";
sprintf(tmp, "0 %s", Source_Code_Path);
send(sockfd_CM, tmp, 1024, 0);
recv(sockfd_CM, tmp, 1024, 0);
while(1)
{
if(tmp[0] == '1')
break;
else
{
sleep(1);
recv(sockfd_CM, tmp, 1024, 0);
}
}
sscanf(tmp + 2 * sizeof(char), "%s", Program_Path);
printf("Program_Path: %s\n", Program_Path);
close(sockfd_CM);
return NULL;
}
void* conn_to_TM(void* args)
{
char tmp[1024] = "";
int sockfd_TM = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd_TM < 0)
{
printf("Error occurs when opening socket.\n");
exit(1);
}
struct sockaddr_in TM_Addr;
struct hostent *TM_Host;
TM_Addr.sin_family = AF_INET;
TM_Host = gethostbyname(TM_IP);
//error check
memcpy(&TM_Addr.sin_addr.s_addr, TM_Host->h_addr, TM_Host->h_length);
TM_Addr.sin_port = htons(TM_Port);
while(connect(sockfd_TM, (sockaddr*)&TM_Addr, sizeof(TM_Addr)) == -1)
{
sleep(1);
}
while(strcmp(Program_Path, "") == 0)
{
sleep(1);
}
sprintf(tmp, "2 %s %d %s", Program_Path, Device_Parameter, Input_Path);
send(sockfd_TM, tmp, 1024, 0);
recv(sockfd_TM, tmp, 1024, 0);
while(tmp[0] != 'b')
{
sleep(1);
recv(sockfd_TM, tmp, 1024, 0);
}
printf("Job is done!.\nExit.\n");
close(sockfd_TM);
return NULL;
}
| [
"pan@ubuntu.(none)"
] | pan@ubuntu.(none) |
a9bfe49f332827933c0927d38d5a74dab1fc94b8 | f4d00a2c70fa9644e766ef219d0c4ecba6b55fec | /Vol1/problemaBus/problemaBus/Clientes.h | 426b46c614407367bef3bda12755ffa155228a0c | [] | no_license | dylandSteven/Ciclo-1-y-2 | bee06931584a97153a17e08d156d3bd813a0810d | a52795242bc3541971a9720e189b6c850f1e458f | refs/heads/master | 2023-01-31T18:30:56.653826 | 2020-12-16T04:03:14 | 2020-12-16T04:03:14 | 287,107,182 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 793 | h | #pragma once
#include"Cliente.h"
#include<iostream>
#include<string>
#include<vector>
#include"Autoh.h"
using namespace std;
typedef unsigned long us;
class Clientes {
private:
vector< Cliente*>arrcliente;
vector<Auto*>nue;
public:
Clientes() {}
void agregarCliente() {
string nombreaux;
us dniaux;
Cliente*nuevo;
cout << "Nombre: "; cin >>nombreaux;
cout << "DNI: "; cin >> dniaux;
nuevo =new Cliente(nombreaux, dniaux);
//nuevo->datosAutos();
arrcliente.push_back(nuevo);
}
void mostrarDatosCliente() {
for (int i = 0; i <arrcliente.size(); i++) {
cout<< endl;
cout<<arrcliente[i]->getNombree();
cout<<arrcliente[i]->getdni();
//cout << "Placa: "<< nue[i]->getPlaca();
//cout << "NUmero de galones: " << nue[i]->getCangalo();
}
}
}; | [
"stevendylandsaldana@gmail.com"
] | stevendylandsaldana@gmail.com |
65a0715dbe494fa5f31071e5844c090b5eec3070 | 8beed1350bdb7436fe52eaa3821699fdbdc6d8ed | /src/libs/data/pdzBase/_internal/DiagnosticItem.h | ac7dc48fbe618523d2a2e64cc5cbfe1ed1eca9f6 | [
"BSD-3-Clause"
] | permissive | eirTony/PixDeZ | 3b30b018b6eff5451018fa9dc6543ee6e3f5e97b | 6fa38bc7ee3245c83814c423d4158a0630871823 | refs/heads/master | 2021-01-01T05:14:51.862797 | 2016-04-24T08:46:23 | 2016-04-24T08:46:23 | 56,960,666 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,150 | h | #ifndef DIAGNOSTICITEM_H
#define DIAGNOSTICITEM_H
#include "../pdzBase.h"
#include <QtDebug>
#include <QDateTime>
#include <QList>
#include <QSet>
#include <QString>
class QFile;
class QFileInfo;
#include "../BasicId.h"
class PDZBASESHARED_EXPORT DiagnosticItem
{
public:
enum Command
{
BeginTest,
EndTest,
ReportTodo,
ReportTest,
};
public:
DiagnosticItem(void);
DiagnosticItem(const QtMsgType msgtype,
const QString & function,
const QString & fileName,
const int fileLine,
const QString & format,
const QVariant & var1=QVariant(),
const QVariant & var2=QVariant(),
const QVariant & var3=QVariant(),
const QVariant & var4=QVariant());
DiagnosticItem(const Command cmd,
const QVariant var);
public: // static
static void boolean(const QtMsgType msgtype,
const QString & function,
const QString & fileName,
const int fileLine,
const bool expectation,
const bool actual,
const QString expression,
const QString & message = QString());
static void todo(const QtMsgType msgtype,
const QString & function,
const QString & fileName,
const int fileLine,
const QString & message,
const QString & expression);
static void beginTest(const BasicId & testId);
static void endTest(const BasicId & testId);
static bool inTest(void);
static bool reportTodo(QIODevice * iod=0);
static bool reportTest(QIODevice * iod=0);
static void exec(const QString & orgName,
const QString & appName);
private:
QString createMessage(void) const;
void handleTest(const QtMsgType msgtype,
const QString & message);
void sendMessage(const QtMsgType msgtype,
const QString & message);
private: // static
static BasicId lineId(const QString & fileName,
const int fileLine, const QString &expr);
static QString formatMessage(const QString & format,
QVariantList vars);
static void startTodoFile(const QFileInfo & fi);
static void startLogFile(const QFileInfo & fi);
static void execTodo(const QString & todoMsg);
static void execLog(const DiagnosticItem & di);
private:
const QDateTime cmTimestamp;
const QtMsgType cmMsgType = QtDebugMsg;
const QString cmFunction;
const QString cmFileName;
const int cmFileLine = 0;
const BasicId cmLineId;
const QString cmFormat;
const QVariantList cmVarList;
private: // static
static bool smExec;
static QList<DiagnosticItem> smItemList;
static QMap<BasicId, QString> smTodoLineMessageMap;
static QMap<BasicId, QString> smTestLineMessageMap;
static QList<BasicId> smTestIdList;
static QSet<BasicId> smCompletedTestIdSet;
static QFile * smpTodoFile;
static QFile * smpLogFile;
};
#define TRACE_PFX ">Trace: "
#define INFO_PFX "-Info: "
#define WARN_PFX "+Warn: "
#define CRIT_PFX "*Crit: "
#define FATAL_PFX "#Fatal: "
#define DO_PFX "DO-->"
#define USE_PFX "USE->"
#define __DIAGITEM(typ, msg, args...) \
{ DiagnosticItem di(typ, Q_FUNC_INFO, \
__FILE__, __LINE__, msg ,##args); } \
#define __BOOLITEM(typ, tru, act, msg) \
{ DiagnosticItem::boolean(typ, Q_FUNC_INFO, \
__FILE__, __LINE__, \
tru, act, #act, msg); }\
#define __TODOITEM(typ, msg, exp) \
{ DiagnosticItem::todo(typ, Q_FUNC_INFO, \
__FILE__, __LINE__, msg, exp); } \
#define _FMTITEM(typ, pfx, fmt, args...) \
__DIAGITEM(typ, pfx fmt ,##args) \
#endif // DIAGNOSTICITEM_H
| [
"tony.dyndez@gmail.com"
] | tony.dyndez@gmail.com |
fed99ee68e6ca748fba551577492a0d795268412 | 27d485637faabbc56ceee5e8d75cd23dc66acbcc | /native/physics3d/src/reactphysics3d/collision/shapes/TriangleShape.cpp | 8c01994a6e45d708e067bc4d07c3cc0d8c9f4827 | [] | no_license | d954mas/game-space-defender | 98d9d6b23279fd8fdae5e537e6e49649288007fa | ab208b9636882f990eb1325debec89fba94fcdeb | refs/heads/master | 2023-04-06T17:57:54.148986 | 2021-04-23T09:21:45 | 2021-04-23T09:21:45 | 356,860,283 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,252 | cpp | /********************************************************************************
* ReactPhysics3D physics library, http://www.reactphysics3d.com *
* Copyright (c) 2010-2019 Daniel Chappuis *
*********************************************************************************
* *
* 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. *
* *
********************************************************************************/
// Libraries
#include "collision/shapes/TriangleShape.h"
#include "collision/ProxyShape.h"
#include "mathematics/mathematics_functions.h"
#include "collision/RaycastInfo.h"
#include "utils/Profiler.h"
#include "configuration.h"
#include <cassert>
using namespace reactphysics3d;
// Constructor
/**
* Do not use this constructor. It is supposed to be used internally only.
* Use a ConcaveMeshShape instead.
* @param point1 First point of the triangle
* @param point2 Second point of the triangle
* @param point3 Third point of the triangle
* @param verticesNormals The three vertices normals for smooth mesh collision
* @param margin The collision margin (in meters) around the collision shape
*/
TriangleShape::TriangleShape(const Vector3* vertices, const Vector3* verticesNormals, uint shapeId,
MemoryAllocator& allocator)
: ConvexPolyhedronShape(CollisionShapeName::TRIANGLE), mFaces{HalfEdgeStructure::Face(allocator), HalfEdgeStructure::Face(allocator)} {
mPoints[0] = vertices[0];
mPoints[1] = vertices[1];
mPoints[2] = vertices[2];
// Compute the triangle normal
mNormal = (vertices[1] - vertices[0]).cross(vertices[2] - vertices[0]);
mNormal.normalize();
mVerticesNormals[0] = verticesNormals[0];
mVerticesNormals[1] = verticesNormals[1];
mVerticesNormals[2] = verticesNormals[2];
// Faces
mFaces[0].faceVertices.reserve(3);
mFaces[0].faceVertices.add(0);
mFaces[0].faceVertices.add(1);
mFaces[0].faceVertices.add(2);
mFaces[0].edgeIndex = 0;
mFaces[1].faceVertices.reserve(3);
mFaces[1].faceVertices.add(0);
mFaces[1].faceVertices.add(2);
mFaces[1].faceVertices.add(1);
mFaces[1].edgeIndex = 1;
// Edges
for (uint i=0; i<6; i++) {
switch(i) {
case 0:
mEdges[0].vertexIndex = 0;
mEdges[0].twinEdgeIndex = 1;
mEdges[0].faceIndex = 0;
mEdges[0].nextEdgeIndex = 2;
break;
case 1:
mEdges[1].vertexIndex = 1;
mEdges[1].twinEdgeIndex = 0;
mEdges[1].faceIndex = 1;
mEdges[1].nextEdgeIndex = 5;
break;
case 2:
mEdges[2].vertexIndex = 1;
mEdges[2].twinEdgeIndex = 3;
mEdges[2].faceIndex = 0;
mEdges[2].nextEdgeIndex = 4;
break;
case 3:
mEdges[3].vertexIndex = 2;
mEdges[3].twinEdgeIndex = 2;
mEdges[3].faceIndex = 1;
mEdges[3].nextEdgeIndex = 1;
break;
case 4:
mEdges[4].vertexIndex = 2;
mEdges[4].twinEdgeIndex = 5;
mEdges[4].faceIndex = 0;
mEdges[4].nextEdgeIndex = 0;
break;
case 5:
mEdges[5].vertexIndex = 0;
mEdges[5].twinEdgeIndex = 4;
mEdges[5].faceIndex = 1;
mEdges[5].nextEdgeIndex = 3;
break;
}
}
mRaycastTestType = TriangleRaycastSide::FRONT;
mId = shapeId;
}
// This method compute the smooth mesh contact with a triangle in case one of the two collision
// shapes is a triangle. The idea in this case is to use a smooth vertex normal of the triangle mesh
// at the contact point instead of the triangle normal to avoid the internal edge collision issue.
// This method will return the new smooth world contact
// normal of the triangle and the the local contact point on the other shape.
void TriangleShape::computeSmoothTriangleMeshContact(const CollisionShape* shape1, const CollisionShape* shape2,
Vector3& localContactPointShape1, Vector3& localContactPointShape2,
const Transform& shape1ToWorld, const Transform& shape2ToWorld,
decimal penetrationDepth, Vector3& outSmoothVertexNormal) {
assert(shape1->getName() != CollisionShapeName::TRIANGLE || shape2->getName() != CollisionShapeName::TRIANGLE);
// If one the shape is a triangle
bool isShape1Triangle = shape1->getName() == CollisionShapeName::TRIANGLE;
if (isShape1Triangle || shape2->getName() == CollisionShapeName::TRIANGLE) {
const TriangleShape* triangleShape = isShape1Triangle ? static_cast<const TriangleShape*>(shape1):
static_cast<const TriangleShape*>(shape2);
// Compute the smooth triangle mesh contact normal and recompute the local contact point on the other shape
triangleShape->computeSmoothMeshContact(isShape1Triangle ? localContactPointShape1 : localContactPointShape2,
isShape1Triangle ? shape1ToWorld : shape2ToWorld,
isShape1Triangle ? shape2ToWorld.getInverse() : shape1ToWorld.getInverse(),
penetrationDepth, isShape1Triangle,
isShape1Triangle ? localContactPointShape2 : localContactPointShape1,
outSmoothVertexNormal);
}
}
// This method implements the technique described in Game Physics Pearl book
// by Gino van der Bergen and Dirk Gregorius to get smooth triangle mesh collision. The idea is
// to replace the contact normal of the triangle shape with the precomputed normal of the triangle
// mesh at this point. Then, we need to recompute the contact point on the other shape in order to
// stay aligned with the new contact normal. This method will return the new smooth world contact
// normal of the triangle and the the local contact point on the other shape.
void TriangleShape::computeSmoothMeshContact(Vector3 localContactPointTriangle, const Transform& triangleShapeToWorldTransform,
const Transform& worldToOtherShapeTransform, decimal penetrationDepth, bool isTriangleShape1,
Vector3& outNewLocalContactPointOtherShape, Vector3& outSmoothWorldContactTriangleNormal) const {
// Get the smooth contact normal of the mesh at the contact point on the triangle
Vector3 triangleLocalNormal = computeSmoothLocalContactNormalForTriangle(localContactPointTriangle);
// Convert the local contact normal into world-space
Vector3 triangleWorldNormal = triangleShapeToWorldTransform.getOrientation() * triangleLocalNormal;
// Penetration axis with direction from triangle to other shape
Vector3 triangleToOtherShapePenAxis = isTriangleShape1 ? outSmoothWorldContactTriangleNormal : -outSmoothWorldContactTriangleNormal;
// The triangle normal should be the one in the direction out of the current colliding face of the triangle
if (triangleWorldNormal.dot(triangleToOtherShapePenAxis) < decimal(0.0)) {
triangleWorldNormal = -triangleWorldNormal;
triangleLocalNormal = -triangleLocalNormal;
}
// Compute the final contact normal from shape 1 to shape 2
outSmoothWorldContactTriangleNormal = isTriangleShape1 ? triangleWorldNormal : -triangleWorldNormal;
// Re-align the local contact point on the other shape such that it is aligned along the new contact normal
Vector3 otherShapePointTriangleSpace = localContactPointTriangle - triangleLocalNormal * penetrationDepth;
Vector3 otherShapePoint = worldToOtherShapeTransform * triangleShapeToWorldTransform * otherShapePointTriangleSpace;
outNewLocalContactPointOtherShape.setAllValues(otherShapePoint.x, otherShapePoint.y, otherShapePoint.z);
}
// Get a smooth contact normal for collision for a triangle of the mesh
/// This is used to avoid the internal edges issue that occurs when a shape is colliding with
/// several triangles of a concave mesh. If the shape collide with an edge of the triangle for instance,
/// the computed contact normal from this triangle edge is not necessarily in the direction of the surface
/// normal of the mesh at this point. The idea to solve this problem is to use the real (smooth) surface
/// normal of the mesh at this point as the contact normal. This technique is described in the chapter 5
/// of the Game Physics Pearl book by Gino van der Bergen and Dirk Gregorius. The vertices normals of the
/// mesh are either provided by the user or precomputed if the user did not provide them. Note that we only
/// use the interpolated normal if the contact point is on an edge of the triangle. If the contact is in the
/// middle of the triangle, we return the true triangle normal.
Vector3 TriangleShape::computeSmoothLocalContactNormalForTriangle(const Vector3& localContactPoint) const {
// Compute the barycentric coordinates of the point in the triangle
decimal u, v, w;
computeBarycentricCoordinatesInTriangle(mPoints[0], mPoints[1], mPoints[2], localContactPoint, u, v, w);
// If the contact is in the middle of the triangle face (not on the edges)
if (u > MACHINE_EPSILON && v > MACHINE_EPSILON && w > MACHINE_EPSILON) {
// We return the true triangle face normal (not the interpolated one)
return mNormal;
}
// We compute the contact normal as the barycentric interpolation of the three vertices normals
return (u * mVerticesNormals[0] + v * mVerticesNormals[1] + w * mVerticesNormals[2]).getUnit();
}
// Update the AABB of a body using its collision shape
/**
* @param[out] aabb The axis-aligned bounding box (AABB) of the collision shape
* computed in world-space coordinates
* @param transform Transform used to compute the AABB of the collision shape
*/
void TriangleShape::computeAABB(AABB& aabb, const Transform& transform) const {
const Vector3 worldPoint1 = transform * mPoints[0];
const Vector3 worldPoint2 = transform * mPoints[1];
const Vector3 worldPoint3 = transform * mPoints[2];
const Vector3 xAxis(worldPoint1.x, worldPoint2.x, worldPoint3.x);
const Vector3 yAxis(worldPoint1.y, worldPoint2.y, worldPoint3.y);
const Vector3 zAxis(worldPoint1.z, worldPoint2.z, worldPoint3.z);
aabb.setMin(Vector3(xAxis.getMinValue(), yAxis.getMinValue(), zAxis.getMinValue()));
aabb.setMax(Vector3(xAxis.getMaxValue(), yAxis.getMaxValue(), zAxis.getMaxValue()));
}
// Raycast method with feedback information
/// This method use the line vs triangle raycasting technique described in
/// Real-time Collision Detection by Christer Ericson.
bool TriangleShape::raycast(const Ray& ray, RaycastInfo& raycastInfo, ProxyShape* proxyShape, MemoryAllocator& allocator) const {
RP3D_PROFILE("TriangleShape::raycast()", mProfiler);
const Vector3 pq = ray.point2 - ray.point1;
const Vector3 pa = mPoints[0] - ray.point1;
const Vector3 pb = mPoints[1] - ray.point1;
const Vector3 pc = mPoints[2] - ray.point1;
// Test if the line PQ is inside the eges BC, CA and AB. We use the triple
// product for this test.
const Vector3 m = pq.cross(pc);
decimal u = pb.dot(m);
if (mRaycastTestType == TriangleRaycastSide::FRONT) {
if (u < decimal(0.0)) return false;
}
else if (mRaycastTestType == TriangleRaycastSide::BACK) {
if (u > decimal(0.0)) return false;
}
decimal v = -pa.dot(m);
if (mRaycastTestType == TriangleRaycastSide::FRONT) {
if (v < decimal(0.0)) return false;
}
else if (mRaycastTestType == TriangleRaycastSide::BACK) {
if (v > decimal(0.0)) return false;
}
else if (mRaycastTestType == TriangleRaycastSide::FRONT_AND_BACK) {
if (!sameSign(u, v)) return false;
}
decimal w = pa.dot(pq.cross(pb));
if (mRaycastTestType == TriangleRaycastSide::FRONT) {
if (w < decimal(0.0)) return false;
}
else if (mRaycastTestType == TriangleRaycastSide::BACK) {
if (w > decimal(0.0)) return false;
}
else if (mRaycastTestType == TriangleRaycastSide::FRONT_AND_BACK) {
if (!sameSign(u, w)) return false;
}
// If the line PQ is in the triangle plane (case where u=v=w=0)
if (approxEqual(u, 0) && approxEqual(v, 0) && approxEqual(w, 0)) return false;
// Compute the barycentric coordinates (u, v, w) to determine the
// intersection point R, R = u * a + v * b + w * c
decimal denom = decimal(1.0) / (u + v + w);
u *= denom;
v *= denom;
w *= denom;
// Compute the local hit point using the barycentric coordinates
const Vector3 localHitPoint = u * mPoints[0] + v * mPoints[1] + w * mPoints[2];
const decimal hitFraction = (localHitPoint - ray.point1).length() / pq.length();
if (hitFraction < decimal(0.0) || hitFraction > ray.maxFraction) return false;
Vector3 localHitNormal = (mPoints[1] - mPoints[0]).cross(mPoints[2] - mPoints[0]);
if (localHitNormal.dot(pq) > decimal(0.0)) localHitNormal = -localHitNormal;
raycastInfo.body = proxyShape->getBody();
raycastInfo.proxyShape = proxyShape;
raycastInfo.worldPoint = localHitPoint;
raycastInfo.hitFraction = hitFraction;
raycastInfo.worldNormal = localHitNormal;
return true;
}
| [
"d954mas@gmail.com"
] | d954mas@gmail.com |
28aaf2f34db7b560144bde9f1b6a0c3cfe8455e4 | a859bb44c87946b12f07d5cc2d66a436ed3a5bde | /src/qt/intro.cpp | 20bed7e798da75fa1e8ad2aab4aeabc6c5f42677 | [
"MIT"
] | permissive | alex10819/snekcoin | d6d723da0ce7b4229ddc3facf966401d31674dff | 30a07ea888973c0e35dac4a9534ab04f33da2642 | refs/heads/master | 2021-06-28T11:01:22.460224 | 2017-09-16T03:09:14 | 2017-09-16T03:09:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,799 | cpp | // Copyright (c) 2011-2014 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 "intro.h"
#include "ui_intro.h"
#include "guiutil.h"
#include "util.h"
#include <boost/filesystem.hpp>
#include <QFileDialog>
#include <QSettings>
#include <QMessageBox>
/* Minimum free space (in bytes) needed for data directory */
static const uint64_t GB_BYTES = 1000000000LL;
static const uint64_t BLOCK_CHAIN_SIZE = 20LL * GB_BYTES;
/* Check free space asynchronously to prevent hanging the UI thread.
Up to one request to check a path is in flight to this thread; when the check()
function runs, the current path is requested from the associated Intro object.
The reply is sent back through a signal.
This ensures that no queue of checking requests is built up while the user is
still entering the path, and that always the most recently entered path is checked as
soon as the thread becomes available.
*/
class FreespaceChecker : public QObject
{
Q_OBJECT
public:
FreespaceChecker(Intro *intro);
enum Status {
ST_OK,
ST_ERROR
};
public slots:
void check();
signals:
void reply(int status, const QString &message, quint64 available);
private:
Intro *intro;
};
#include "intro.moc"
FreespaceChecker::FreespaceChecker(Intro *intro)
{
this->intro = intro;
}
void FreespaceChecker::check()
{
namespace fs = boost::filesystem;
QString dataDirStr = intro->getPathToCheck();
fs::path dataDir = GUIUtil::qstringToBoostPath(dataDirStr);
uint64_t freeBytesAvailable = 0;
int replyStatus = ST_OK;
QString replyMessage = tr("A new data directory will be created.");
/* Find first parent that exists, so that fs::space does not fail */
fs::path parentDir = dataDir;
fs::path parentDirOld = fs::path();
while(parentDir.has_parent_path() && !fs::exists(parentDir))
{
parentDir = parentDir.parent_path();
/* Check if we make any progress, break if not to prevent an infinite loop here */
if (parentDirOld == parentDir)
break;
parentDirOld = parentDir;
}
try {
freeBytesAvailable = fs::space(parentDir).available;
if(fs::exists(dataDir))
{
if(fs::is_directory(dataDir))
{
QString separator = "<code>" + QDir::toNativeSeparators("/") + tr("name") + "</code>";
replyStatus = ST_OK;
replyMessage = tr("Directory already exists. Add %1 if you intend to create a new directory here.").arg(separator);
} else {
replyStatus = ST_ERROR;
replyMessage = tr("Path already exists, and is not a directory.");
}
}
} catch (const fs::filesystem_error&)
{
/* Parent directory does not exist or is not accessible */
replyStatus = ST_ERROR;
replyMessage = tr("Cannot create data directory here.");
}
emit reply(replyStatus, replyMessage, freeBytesAvailable);
}
Intro::Intro(QWidget *parent) :
QDialog(parent),
ui(new Ui::Intro),
thread(0),
signalled(false)
{
ui->setupUi(this);
ui->sizeWarningLabel->setText(ui->sizeWarningLabel->text().arg(BLOCK_CHAIN_SIZE/GB_BYTES));
startThread();
}
Intro::~Intro()
{
delete ui;
/* Ensure thread is finished before it is deleted */
emit stopThread();
thread->wait();
}
QString Intro::getDataDirectory()
{
return ui->dataDirectory->text();
}
void Intro::setDataDirectory(const QString &dataDir)
{
ui->dataDirectory->setText(dataDir);
if(dataDir == getDefaultDataDirectory())
{
ui->dataDirDefault->setChecked(true);
ui->dataDirectory->setEnabled(false);
ui->ellipsisButton->setEnabled(false);
} else {
ui->dataDirCustom->setChecked(true);
ui->dataDirectory->setEnabled(true);
ui->ellipsisButton->setEnabled(true);
}
}
QString Intro::getDefaultDataDirectory()
{
return GUIUtil::boostPathToQString(GetDefaultDataDir());
}
void Intro::pickDataDirectory()
{
namespace fs = boost::filesystem;
QSettings settings;
/* If data directory provided on command line, no need to look at settings
or show a picking dialog */
if(!GetArg("-datadir", "").empty())
return;
/* 1) Default data directory for operating system */
QString dataDir = getDefaultDataDirectory();
/* 2) Allow QSettings to override default dir */
dataDir = settings.value("strDataDir", dataDir).toString();
if(!fs::exists(GUIUtil::qstringToBoostPath(dataDir)) || GetBoolArg("-choosedatadir", false))
{
/* If current default data directory does not exist, let the user choose one */
Intro intro;
intro.setDataDirectory(dataDir);
intro.setWindowIcon(QIcon(":icons/bitcoin"));
while(true)
{
if(!intro.exec())
{
/* Cancel clicked */
exit(0);
}
dataDir = intro.getDataDirectory();
try {
TryCreateDirectory(GUIUtil::qstringToBoostPath(dataDir));
break;
} catch (const fs::filesystem_error&) {
QMessageBox::critical(0, tr("Snekcoin Core"),
tr("Error: Specified data directory \"%1\" cannot be created.").arg(dataDir));
/* fall through, back to choosing screen */
}
}
settings.setValue("strDataDir", dataDir);
}
/* Only override -datadir if different from the default, to make it possible to
* override -datadir in the bitcoin.conf file in the default data directory
* (to be consistent with bitcoind behavior)
*/
if(dataDir != getDefaultDataDirectory())
SoftSetArg("-datadir", GUIUtil::qstringToBoostPath(dataDir).string()); // use OS locale for path setting
}
void Intro::setStatus(int status, const QString &message, quint64 bytesAvailable)
{
switch(status)
{
case FreespaceChecker::ST_OK:
ui->errorMessage->setText(message);
ui->errorMessage->setStyleSheet("");
break;
case FreespaceChecker::ST_ERROR:
ui->errorMessage->setText(tr("Error") + ": " + message);
ui->errorMessage->setStyleSheet("QLabel { color: #800000 }");
break;
}
/* Indicate number of bytes available */
if(status == FreespaceChecker::ST_ERROR)
{
ui->freeSpace->setText("");
} else {
QString freeString = tr("%n GB of free space available", "", bytesAvailable/GB_BYTES);
if(bytesAvailable < BLOCK_CHAIN_SIZE)
{
freeString += " " + tr("(of %n GB needed)", "", BLOCK_CHAIN_SIZE/GB_BYTES);
ui->freeSpace->setStyleSheet("QLabel { color: #800000 }");
} else {
ui->freeSpace->setStyleSheet("");
}
ui->freeSpace->setText(freeString + ".");
}
/* Don't allow confirm in ERROR state */
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(status != FreespaceChecker::ST_ERROR);
}
void Intro::on_dataDirectory_textChanged(const QString &dataDirStr)
{
/* Disable OK button until check result comes in */
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
checkPath(dataDirStr);
}
void Intro::on_ellipsisButton_clicked()
{
QString dir = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(0, "Choose data directory", ui->dataDirectory->text()));
if(!dir.isEmpty())
ui->dataDirectory->setText(dir);
}
void Intro::on_dataDirDefault_clicked()
{
setDataDirectory(getDefaultDataDirectory());
}
void Intro::on_dataDirCustom_clicked()
{
ui->dataDirectory->setEnabled(true);
ui->ellipsisButton->setEnabled(true);
}
void Intro::startThread()
{
thread = new QThread(this);
FreespaceChecker *executor = new FreespaceChecker(this);
executor->moveToThread(thread);
connect(executor, SIGNAL(reply(int,QString,quint64)), this, SLOT(setStatus(int,QString,quint64)));
connect(this, SIGNAL(requestCheck()), executor, SLOT(check()));
/* make sure executor object is deleted in its own thread */
connect(this, SIGNAL(stopThread()), executor, SLOT(deleteLater()));
connect(this, SIGNAL(stopThread()), thread, SLOT(quit()));
thread->start();
}
void Intro::checkPath(const QString &dataDir)
{
mutex.lock();
pathToCheck = dataDir;
if(!signalled)
{
signalled = true;
emit requestCheck();
}
mutex.unlock();
}
QString Intro::getPathToCheck()
{
QString retval;
mutex.lock();
retval = pathToCheck;
signalled = false; /* new request can be queued now */
mutex.unlock();
return retval;
}
| [
"dfran1991@gmail.com"
] | dfran1991@gmail.com |
74ea9d529f278b34598e550aa5f8a8ea3653fd1f | 296992b2ac454754ca15da53117aa07128ba54b4 | /BearScriptCtrls/Scribble Pad.cpp | 592b33d300872f210a088581dce2320eae1d9766 | [] | no_license | get-over-here/X-Studio | 0893e7edce4780caa4dfdbce84ba6af467863887 | 66ae0ed8c2e017e32d60de979abf44997511510e | refs/heads/master | 2022-10-22T22:27:11.495043 | 2020-06-11T15:30:16 | 2020-06-11T15:30:16 | 271,582,106 | 0 | 0 | null | 2020-06-11T15:29:45 | 2020-06-11T15:29:44 | null | UTF-8 | C++ | false | false | 2,968 | cpp | //
// Scribble Pad.cpp : Testing grounds
//
// NB: Best viewed with tab size of 3 characters and Visual Studio's 'XML Doc Comment' syntax colouring
// set to a colour that highly contrasts the 'C/C++ comment' syntax colouring
//
#include "stdafx.h"
/// /////////////////////////////////////////////////////////////////////////////////////////
/// DECLARATIONS
/// /////////////////////////////////////////////////////////////////////////////////////////
/// /////////////////////////////////////////////////////////////////////////////////////////
/// CREATION / DESTRUCTION
/// /////////////////////////////////////////////////////////////////////////////////////////
/// /////////////////////////////////////////////////////////////////////////////////////////
/// FUNCTIONS
/// /////////////////////////////////////////////////////////////////////////////////////////
/// /////////////////////////////////////////////////////////////////////////////////////////
/// HELPERS
/// /////////////////////////////////////////////////////////////////////////////////////////
/// /////////////////////////////////////////////////////////////////////////////////////////
/// MODIFIED
/// /////////////////////////////////////////////////////////////////////////////////////////
/// Function name : removeCodeEditSelectionText9
// Description : Deletes the current text selection, repositions the caret and invalidates the affected lines
//
// CODE_EDIT_DATA* pWindowData : [in] Window data
//
/// UNUSED: Implementing removing characters with the iterator is too weird at the moment, im tired.
//
//VOID removeCodeEditSelectionText9(CODE_EDIT_DATA* pWindowData)
//{
// CODE_EDIT_ITERATOR* pIterator; // Character data iterator
//
// // [CHECK] Ensure selection exists
// if (!hasCodeEditSelection(pWindowData))
// return;
//
// // Prepare
// pIterator = createCodeEditMultipleLineIterator(pWindowData, pWindowData->oSelection.oOrigin, pWindowData->oCaret.oLocation);
//
// /// Delete all characters within selection
// //removeCodeEditIteratorCharacters(pIterator);
//
// // [SINGLE LINE] Redraw line
// if (pIterator->oStart.iLine == pIterator->oFinish.iLine)
// updateCodeEditSingleLine(pWindowData, pIterator->oStart.iLine);
//
// // [MULTIPLE LINES] Redraw initial line and all below it
// else
// updateCodeEditMultipleLines(pWindowData, pIterator->oStart.iLine);
//
// /// Move the caret to the selection origin
// setCodeEditCaretLocation(pWindowData, &pWindowData->oSelection.oOrigin);
//
// /// Manually remove selection flag
// pWindowData->oSelection.bExists = FALSE;
//
// // Cleanup
// deleteCodeEditIterator(pIterator);
//}
| [
"nicholas.crowley@gmail.com"
] | nicholas.crowley@gmail.com |
25de10823d746a216743d85ef043e1a85316ebd0 | ddf2a5c2288a53ebdb458936c9a898b0a6d49676 | /Client Lourd/DLL/Partie/PartieRapide.cpp | 670c528a5d75cec6e174d111b34fc6e82451ccb7 | [] | no_license | FelixLeChat/Projet-3-Informatique | 6e99a6f634d39eabe6b8216e9fbac236fc999553 | 0fcb2997c59c9858ccb3c1e2cd13a7c60ba9b506 | refs/heads/master | 2021-01-01T05:19:39.461193 | 2016-04-13T18:18:18 | 2016-04-13T18:18:18 | 56,165,237 | 2 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 12,504 | cpp | ////////////////////////////////////////////////////////////////////////////////////
/// @file PartieRapide.cpp
/// @author Nicolas Blais, Jérôme Daigle
/// @date 2015-03-17
/// @version 1.0
///
/// @addtogroup inf2990 INF2990
/// @{
////////////////////////////////////////////////////////////////////////////////////
#include "PartieRapide.h"
#include "Configuration/Config.h"
#include "Affichage/Affichage.h"
#include <FTGL/ftgl.h>
#include "Reseau/NetworkManager.h"
#include "Sons/ClasseSons.h"
#include "Joueurs/JoueurManagerLocal.h"
#include "Joueurs/JoueurManagerEnLigne.h"
#include "Event/CollisionEvent.h"
#include "Event/NewBallEvent.h"
#include "Event/EventManager.h"
#include "Event/BallLostEvent.h"
#include "Event/TimeEvent.h"
#include "Event/ScoreSyncEvent.h"
#include "Event/DisconnectEvent.h"
#include "Event/SyncAllRequest.h"
////////////////////////////////////////////////////////////////////////
///
/// @fn PartieRapide::PartieRapide(bool nbJoueurs, bool humain, std::string chemin)
///
/// Constructeur de la partie rapide. Permet d'assigner le nombre de joueurs,
/// si le deuxième joueur est humain et le chemin du fichier xml.
///
/// @param[in] nbJoueurs : le nombre de joueurs ( 1 si 1 joueur et 0 si 2 joueurs
/// humain : si le deuxième joueur est un humain(1) ou une intelligence artificielle(0)
/// chemin : le chemin du fichier xml de la partie
///
/// @return Aucune.
///
////////////////////////////////////////////////////////////////////////
PartieRapide::PartieRapide(int nbJoueurs, bool humain, string chemin){
EventManager::GetInstance()->subscribe(this, TIMEEVENT);
EventManager::GetInstance()->subscribe(this, BALLLOST);
EventManager::GetInstance()->subscribe(this, COLLISIONEVENT);
EventManager::GetInstance()->subscribe(this, NEWBALL);
zoneCourante_ = new ZoneDeJeu(chemin);
zoneCourante_->load();
joueurManager_ =new JoueurManagerLocal(nbJoueurs, !humain);
auto controles = zoneCourante_->obtenirControles();
joueurManager_->assignerControles(controles,zoneCourante_);
estTerminee_ = false;
estGagnee_ = false;
pointage_ = 0;
pointageDerniereBille_ = 0;
estHost_ = false;
partieEnLigne_ = false;
}
PartieRapide::PartieRapide(vector<string> playerIds, string zone, int nb_ai, bool estHost, string matchId, bool estRejoin )
{
zoneCourante_ = new ZoneDeJeu(zone);
zoneCourante_->load();
joueurManager_ = new JoueurManagerEnLigne(playerIds,nb_ai,true, estHost);
auto controles = zoneCourante_->obtenirControles();
joueurManager_->assignerControles(controles, zoneCourante_);
estTerminee_ = false;
estGagnee_ = false;
pointage_ = 0;
pointageDerniereBille_ = 0;
matchId_ = matchId;
estHost_ = estHost;
partieEnLigne_ = true;
estTerminee_ = false;
estGagnee_ = false;
if (estRejoin)
{
EventManager::GetInstance()->subscribe(this, TIMEEVENT);
EventManager::GetInstance()->subscribe(this, SYNCALL);
NetworkManager::getInstance()->requestGlobalSync();
}
else
{
EventManager::GetInstance()->subscribe(this, BALLLOST);
EventManager::GetInstance()->subscribe(this, COLLISIONEVENT);
EventManager::GetInstance()->subscribe(this, NEWBALL);
EventManager::GetInstance()->subscribe(this, SCORESYNC);
EventManager::GetInstance()->subscribe(this, TIMEEVENT);
if (estHost_)
{
EventManager::GetInstance()->subscribe(this, SYNCALLREQUEST);
EventManager::GetInstance()->subscribe(this, DISCONNECTEVENT);
}
}
}
PartieRapide::~PartieRapide()
{
EventManager::GetInstance()->unsubscribe(this, TIMEEVENT);
EventManager::GetInstance()->unsubscribe(this, BALLLOST);
EventManager::GetInstance()->unsubscribe(this, COLLISIONEVENT);
EventManager::GetInstance()->unsubscribe(this, NEWBALL);
EventManager::GetInstance()->unsubscribe(this, SCORESYNC);
EventManager::GetInstance()->unsubscribe(this, SYNCALL);
EventManager::GetInstance()->unsubscribe(this, SYNCALLREQUEST);
EventManager::GetInstance()->unsubscribe(this, DISCONNECTEVENT);
}
////////////////////////////////////////////////////////////////////////
///
/// @fn bool Partie::demarrerPartie()
///
/// Cette fonction permet de démarrer une partie.
///
/// @param[in] Aucun.
///
/// @return Si une partie est démarrée.
///
////////////////////////////////////////////////////////////////////////
bool PartieRapide::demarrerPartie()
{
pointage_ = 0;
pointageDerniereBille_ = 0;
nbBillesReserve_ = Config::obtenirInstance()->getNbBilles();
ClasseSons::obtenirInstance()->jouerSon(TYPE_SON_MUSIQUE, true, 0);
return PartieBase::demarrerPartie();
}
NoeudBille* PartieRapide::lancerBille()
{
if (estHost_ || !partieEnLigne_) // Multijoueur
{
tempsAvantProchaineBille_ = 1.5;
nbBillesEnJeu_++;
auto bille = zoneCourante_->lancerBille();
nbBillesReserve_--;
if(partieEnLigne_)
{
auto pos = bille->obtenirPositionRelative();
auto vit = bille->obtenirVitesse();
NetworkManager::getInstance()->lancerBille(bille->obtenirId(), pos.x, pos.y, vit.x, vit.y);
}
return bille;
}
return nullptr;
}
void PartieRapide::perdreBille()
{
PartieBase::perdreBille();
if (nbBillesReserve_ == 0 && nbBillesEnJeu_ == 0)
{
estTerminee_ = true;
ClasseSons::obtenirInstance()->jouerSon(TYPE_SON_GAME_OVER, false);
}
}
void PartieRapide::lancerBilleEnLigne(int id, glm::dvec3 pos, glm::dvec2 vitesse, double scale)
{
tempsAvantProchaineBille_ = 1.5;
nbBillesEnJeu_++;
nbBillesReserve_--;
auto bille = zoneCourante_->lancerBille(id, pos, vitesse, false);
bille->assignerAgrandissement(glm::dvec3(scale));
}
//Pour synchroniser lorsque un joueur REjoins une partie
void PartieRapide::toutSynchroniser(SyncAllEvent* SyncEvent)
{
auto eventManager = EventManager::GetInstance();
for each(auto bille in SyncEvent->billes_en_jeu())
{
eventManager->throwEvent(&bille);
}
for each(auto cible in SyncEvent->cibles_activees())
{
eventManager->throwEvent(&cible);
}
for each(auto powerUpActif in SyncEvent->power_up_actifs())
{
eventManager->throwEvent(&powerUpActif);
}
for each(auto palette in SyncEvent->palettes())
{
eventManager->throwEvent(&palette);
}
pointage_ = SyncEvent->pointages()[0];
nbBillesReserve_ = SyncEvent->nb_billes_restantes()[0];
}
void PartieRapide::envoiSynchronisationGlobale()
{
auto zoneNum = 0;
auto pointage = vector<int>(1, pointage_);
auto nbBillesRest = vector<int>(1, nbBillesReserve_);
auto billes = zoneCourante_->obtenirEtatBilles();
auto cibles = zoneCourante_->obtenirEtatCibles();
auto powerUps = zoneCourante_->obtenirEtatPowerUps();
auto palettes = static_cast<JoueurManagerEnLigne *> (joueurManager_)->obtenirEtatPalettes();
NetworkManager::getInstance()->SyncAll(zoneNum, pointage, nbBillesRest, billes, cibles, powerUps, palettes);
}
void PartieRapide::tick(double dt)
{
if (estHost_ || !partieEnLigne_)
{
if (tempsAvantProchaineBille_ > 0)
tempsAvantProchaineBille_ -= dt;
if (tempsAvantProchaineBille_ <= 0 &&
nbBillesReserve_ > 0 &&
(nbBillesEnJeu_ == 0 ||
(nbBillesEnJeu_ == 1 && Config::obtenirInstance()->getMode2Billes())))
{
lancerBille();
}
}
if(partieEnLigne_)
{
NetworkManager::getInstance()->SyncReceivedMessages();
}
zoneCourante_->animer(dt);
}
void PartieRapide::afficherPointage() const
{
glUniform1i(glGetUniformLocation(Affichage::obtenirInstance()->obtenirProgNuanceur(), "avecShader"), false);
int cloture[4];
glGetIntegerv(GL_VIEWPORT, cloture);
FTGLPixmapFont font("C:/Windows/Fonts/Arial.ttf");
FTPoint coordScore(10, cloture[1] + cloture[3] - 40, 0);
FTPoint coordVies(10, cloture[1] + cloture[3] - 60, 0);
if (font.Error()){
cout << "Probleme de police dans partieRapide.cpp" << endl;
return;
}
glPushAttrib(GL_ALL_ATTRIB_BITS);
glPushMatrix();
glLoadIdentity();
glColor4f(1, 0, 0, 1);
font.FaceSize(16);
char score[255];
char vies[255];
sprintf_s(score, "Score: %d", pointage_);
font.Render(score, -1, coordScore);
sprintf(vies, "Vies Restantes: %d ", nbBillesReserve_);
font.Render(vies, -1, coordVies);
glPopMatrix();
glPopAttrib();
glUniform1i(glGetUniformLocation(Affichage::obtenirInstance()->obtenirProgNuanceur(), "avecShader"), true);
}
void PartieRapide::afficher()
{
PartieBase::afficher();
//afficherPointage();
}
////////////////////////////////////////////////////////////////////////
///
/// @fn void PartieRapide::analyserPointage()
///
/// Analyse du pointage à savoir si le pointage permet d'obtenir une nouvelle bille
///
/// @param[in] Aucun.
///
/// @return Aucune.
///
////////////////////////////////////////////////////////////////////////
void PartieRapide::analyserPointage()
{
if (!partieEnLigne_ || estHost_)
{
int pointageActuel = pointage_ - pointageDerniereBille_ + (pointageDerniereBille_ % (zoneCourante_->getPointBilleGratuite()));
if (pointage_ >= zoneCourante_->getPointBilleGratuite())
{
while (pointageActuel >= zoneCourante_->getPointBilleGratuite())
{
pointageActuel -= zoneCourante_->getPointBilleGratuite();
nbBillesReserve_++;
ClasseSons::obtenirInstance()->jouerSon(TYPE_SON_BILLE_GRATUITE, false);
}
if (nbBillesEnJeu_ == 1 && Config::obtenirInstance()->getMode2Billes())
{
lancerBille();
nbBillesReserve_--;
}
}
pointageDerniereBille_ = pointage_;
}
}
void PartieRapide::update(IEvent * e)
{
switch (e->getType())
{
case COLLISIONEVENT:
{
CollisionEvent* collision = static_cast<CollisionEvent*>(e);
string noeudCollision = collision->getTypeNoeud();
if (noeudCollision == ArbreRenduINF2990::NOM_BUTOIRCIRCULAIRE)
pointage_ += int(zoneCourante_->getPointButoirCercle()*collision->getFacteurMultiplicatif());
else if (noeudCollision == ArbreRenduINF2990::NOM_BUTOIRTRIANGULAIREDROIT
|| noeudCollision == ArbreRenduINF2990::NOM_BUTOIRTRIANGULAIREGAUCHE)
pointage_ += int(zoneCourante_->getPointButoirTriangle()*collision->getFacteurMultiplicatif());
else if (noeudCollision == ArbreRenduINF2990::NOM_CIBLE)
pointage_ += int(zoneCourante_->getPointCible()*collision->getFacteurMultiplicatif());
//lancer event pour sync score - si multijoueur
if (estHost_)
{
NetworkManager::getInstance()->SyncScore(0, pointage_);
analyserPointage();
}
}
break;
case BALLLOST:
{
BallLostEvent* ballEvent = static_cast<BallLostEvent*>(e);
zoneCourante_->perdreBille(ballEvent->getBallId());
perdreBille();
}
break;
case NEWBALL:
{
if (!estHost_ && partieEnLigne_)
{
// add playerId a bille and check
NewBallEvent* ev = static_cast<NewBallEvent *>(e);
lancerBilleEnLigne(ev->ballId(), glm::dvec3(ev->pos_x(), ev->pos_y(), 0.0), glm::dvec2(ev->vit_x(), ev->vit_y()), ev->scale());
}
}
break;
case TIMEEVENT:
{
TimeEvent* timeEvent = static_cast<TimeEvent*>(e);
this->tick(timeEvent->getDt());
}
break;
case SCORESYNC:
{
if(!estHost_)
{
ScoreSyncEvent* sync = static_cast<ScoreSyncEvent*>(e);
pointage_ = sync->score();
analyserPointage();
}
}
break;
case SYNCALL:
{
if (!estHost_)
{
SyncAllEvent* sync = (SyncAllEvent*)e;
EventManager::GetInstance()->unsubscribe(this, SYNCALL);
EventManager::GetInstance()->subscribe(this, BALLLOST);
EventManager::GetInstance()->subscribe(this, COLLISIONEVENT);
EventManager::GetInstance()->subscribe(this, NEWBALL);
EventManager::GetInstance()->subscribe(this, SCORESYNC);
toutSynchroniser(sync);
}
}
break;
case SYNCALLREQUEST:
{ // Reconnect
if (estHost_)
{
auto syncRequest = static_cast<SyncAllRequest *>(e);
envoiSynchronisationGlobale();
joueurManager_->reconnect(syncRequest->user_id());
zoneCourante_->assignerBillesLocales(joueurManager_->obtenirPlayerNum(syncRequest->user_id()), false);
}
}
break;
case DISCONNECTEVENT:
{
auto disconnect = static_cast<DisconnectEvent *>(e);
zoneCourante_->assignerBillesLocales(joueurManager_->obtenirPlayerNum(disconnect->user_id()), true);
}
break;
default: break;
}
}
bool PartieRapide::obtenirEstGagnee()
{
return estGagnee_;
}
int PartieRapide::obtenirScoreJoueur(int joueur) const
{
return pointage_;
}
int PartieRapide::obtenirBillesRestantesJoueur(int joueur_num) const
{
return nbBillesReserve_;
}
int PartieRapide::obtenirMonPointage()
{
return pointage_;
}
int PartieRapide::obtenirMonNbBilles()
{
return nbBillesReserve_;
}
void PartieRapide::reinitialiser() {
if (!partieEnLigne_)
{
zoneCourante_->reinitialiser();
estGagnee_ = false;
estTerminee_ = false;
pointage_ = 0;
joueurManager_->assignerControles(zoneCourante_->obtenirControles(), zoneCourante_);
}
} | [
"felixlrc21@gmail.com"
] | felixlrc21@gmail.com |
b4c0016d1ed3f2166672de030d0354b034e28b72 | 8ded7c00ee602b557b31d09f8b1516597a9171aa | /cpp/const_reference.cpp | 23aa6256b02122099b10e9492b53d5ea13dbbf31 | [] | no_license | mugur9/cpptruths | 1a8d6999392ed0d941147a5d5874dc387aecb34d | 87204023817e263017f64060353dd793f182c558 | refs/heads/master | 2020-12-04T17:00:20.550500 | 2019-09-06T15:40:30 | 2019-09-06T15:40:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 279 | cpp | #include <iostream>
#include <string>
void func (const std::string & s)
{
std::cout << "void func (const std::string & s)\n";
}
void func (std::string & s)
{
std::cout << "void func (std::string & s)\n";
}
int main(void)
{
std::string str("Vanderbilt");
func(str);
}
| [
"sutambe@5d8ea2c6-beef-6e74-2977-a7573b526670"
] | sutambe@5d8ea2c6-beef-6e74-2977-a7573b526670 |
9ba7b803a27292147f6dfd5cb92449c97fcebb4a | 1b9e23e600031b868c0609127c64c2a31504b4dd | /client_template/main.cpp | bd9847834d58d6870245cbef9acb139579497818 | [] | no_license | codders/hereos-installer | 4b79f0d5441e21ea9dd76dadc2ee8d794482044d | 84edd2357438676b4288a781e3fc5795454864ff | refs/heads/master | 2020-04-03T17:23:43.069719 | 2018-11-22T13:46:01 | 2018-11-22T13:46:01 | 155,442,791 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,925 | cpp | #include <iostream>
#include <memory>
#include <string>
#include <grpcpp/grpcpp.h>
#include "echo.grpc.pb.h"
using grpc::Channel;
using grpc::ClientContext;
using grpc::Status;
using echo::EchoRequest;
using echo::EchoReply;
using echo::Echo;
class EchoClient {
public:
EchoClient(std::shared_ptr<Channel> channel)
: stub_(Echo::NewStub(channel)) {}
// Assembles the client's payload, sends it and presents the response back
// from the server.
std::string Shout(const std::string& message) {
// Data we are sending to the server.
EchoRequest request;
request.set_message(message);
// Container for the data we expect from the server.
EchoReply reply;
// Context for the client. It could be used to convey extra information to
// the server and/or tweak certain RPC behaviors.
ClientContext context;
// The actual RPC.
Status status = stub_->Shout(&context, request, &reply);
// Act upon its status.
if (status.ok()) {
return reply.message();
} else {
std::cout << status.error_code() << ": " << status.error_message()
<< std::endl;
return "RPC failed - is echo service running?";
}
}
private:
std::unique_ptr<Echo::Stub> stub_;
};
int main(int argc, char **argv)
{
// Instantiate the client. It requires a channel, out of which the actual RPCs
// are created. This channel models a connection to an endpoint (in this case,
// localhost at port 50051). We indicate that the channel isn't authenticated
// (use of InsecureChannelCredentials()).
EchoClient echo(grpc::CreateChannel(
"localhost:50051", grpc::InsecureChannelCredentials()));
std::string message;
if (argc > 1) {
message = std::string(argv[1]);
} else {
message = std::string("Echo!!");
}
std::string reply = echo.Shout(message);
std::cout << "Echo Client received: " << reply << std::endl;
return 0;
}
| [
"arthur.taylor@here.com"
] | arthur.taylor@here.com |
217726755b5b995b7c08db3cf75a35f58c332ee3 | 494912fbd6b2d147b7ea6b2d1bbc7333f174aec6 | /include/port.hpp | 23a46b2f5702f94d59084081769892060285114e | [] | no_license | bmacneil/processor | 51634de4dd66cdf0573eb02d7863a945edd2192e | a4a7bdbce1647da56e15f4bf13ee03448771d0cd | refs/heads/master | 2020-03-09T21:04:31.952262 | 2018-04-11T00:21:13 | 2018-04-11T00:21:13 | 129,000,362 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 756 | hpp | #ifndef PORTS_H
#define PORTS_H
#include "VProcessor.h"
#include "verilated.h"
#include <verilated_vcd_c.h>
#include <iostream>
#include <string>
#include <bitset>
struct OUTPUT_PORT {
VProcessor *m_core;
std::string version = "v1.0";
bitset < 1 > o_memwrite; // MSBF
bitset < 32 > o_Address; // MSBF
bitset < 32 > o_WriteData; // MSBF
void reset();
void state();
bool run_all_tests(std::string & msg);
bool o_memwrite_test(std::string & msg);
bool o_Address_test(std::string & msg);
bool o_WriteData_test(std::string & msg);
template < size_t N > bool bitTest(bitset < N > testBits,
int moduleOutput, std::string & msg);
};
#endif //PORTS_H
| [
"brad.macneil5@gmail.com"
] | brad.macneil5@gmail.com |
ab7cf420807115a31d0fed9a03b93c5c128787a4 | aac54dda8e3334c0f3839c1ab293c43ca6a6563a | /external/clipp/examples/timing.cpp | 15f05d15ebad7e0eb26a9d3fbb560d6a6046cd36 | [
"GPL-3.0-only",
"MIT"
] | permissive | black-sat/black | beecb287bd759d972cde3d48716e51a454ce455e | 79bebc2468b174f132ea4464ee1eac1e74f99463 | refs/heads/master | 2023-06-27T15:35:06.392733 | 2023-04-26T14:01:36 | 2023-04-26T14:01:36 | 174,530,006 | 12 | 5 | MIT | 2023-06-08T12:17:47 | 2019-03-08T11:58:05 | C++ | UTF-8 | C++ | false | false | 1,222 | cpp | /*****************************************************************************
*
* demo program - part of CLIPP (command line interfaces for modern C++)
*
* released under MIT license
*
* (c) 2017-2018 André Müller; foss@andremueller-online.de
*
*****************************************************************************/
#include <iostream>
#include <string>
#include <vector>
#include <clipp.h>
int main(int argc, char* argv[])
{
using namespace clipp;
using std::string;
using std::cout;
int n = 1;
bool errStop = false;
string exe;
std::vector<string> args;
auto cli = (
option("-n", "--repeat") & value("times", n) % "execute multiple times",
option("-s", "--stop-on-error").set(errStop) % "stop on error",
value("executable", exe) % "client program",
option("--") & values("args", args) % "client arguments"
);
if(!parse(argc, argv, cli)) {
cout << make_man_page(cli, argv[0]) << '\n';
}
cout << "call: " << exe;
for(const auto& a : args) cout << ' ' << a;
cout << '\n';
cout << n << " times\n";
if(errStop) cout << "execution will be stopped on any error\n";
}
| [
"noreply@github.com"
] | noreply@github.com |
7a2eabe77e0e1459386630d38f6f7b8a6b7fc9ba | 5bedc81b358597ca6ebe916f29bf2360c4f87049 | /IO.h | 8c3a672e41853afb7b2fa4d22abb8c91a43f36eb | [] | no_license | tjwudi/kruskal-algorithm | 7819ecd8e2354ff4bedd6f1acdbbf68a413fb820 | 059e579d574678a3e5656545885f9a771f70134b | refs/heads/master | 2021-01-23T17:18:46.176280 | 2014-07-15T06:30:14 | 2014-07-15T06:30:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 195 | h | #include <string>
using namespace std;
#ifndef IO_H
#define IO_H
class IO {
public:
static void greet();
static string prompt(string message);
static void put(string message);
};
#endif | [
"webmaster@leapoahead.com"
] | webmaster@leapoahead.com |
6325a7a433e8afc4d39ad286c8447fe3ef08a02b | 184180d341d2928ab7c5a626d94f2a9863726c65 | /issuestests/AGread/inst/testfiles/interpolate_IMU/interpolate_IMU_DeepState_TestHarness.cpp | 1bdc3bec9b12c1f1f5a8ab1a5411c984e2640bc9 | [
"MIT"
] | permissive | akhikolla/RcppDeepStateTest | f102ddf03a22b0fc05e02239d53405c8977cbc2b | 97e73fe4f8cb0f8e5415f52a2474c8bc322bbbe5 | refs/heads/master | 2023-03-03T12:19:31.725234 | 2021-02-12T21:50:12 | 2021-02-12T21:50:12 | 254,214,504 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,248 | cpp | #include <fstream>
#include <RInside.h>
#include <iostream>
#include <RcppDeepState.h>
#include <qs.h>
#include <DeepState.hpp>
NumericVector interpolate_IMU(NumericVector original_samples, int target_frequency);
TEST(AGread_deepstate_test,interpolate_IMU_test){
RInside R;
std::cout << "input starts" << std::endl;
NumericVector original_samples = RcppDeepState_NumericVector();
qs::c_qsave(original_samples,"/home/akhila/R/x86_64-pc-linux-gnu-library/3.6/RcppDeepState/extdata/issuestests/AGread/inst/testfiles/interpolate_IMU/inputs/original_samples.qs",
"high", "zstd", 1, 15, true, 1);
std::cout << "original_samples values: "<< original_samples << std::endl;
IntegerVector target_frequency(1);
target_frequency[0] = RcppDeepState_int();
qs::c_qsave(target_frequency,"/home/akhila/R/x86_64-pc-linux-gnu-library/3.6/RcppDeepState/extdata/issuestests/AGread/inst/testfiles/interpolate_IMU/inputs/target_frequency.qs",
"high", "zstd", 1, 15, true, 1);
std::cout << "target_frequency values: "<< target_frequency << std::endl;
std::cout << "input ends" << std::endl;
try{
interpolate_IMU(original_samples,target_frequency[0]);
}
catch(Rcpp::exception& e){
std::cout<<"Exception Handled"<<std::endl;
}
}
| [
"akhilakollasrinu424jf@gmail.com"
] | akhilakollasrinu424jf@gmail.com |
563c6b42c892240e84299efea8506370560bc977 | e66c546edec32cf45c440f19618e07f6247b5f39 | /MoldMachine/MoldMachine/xmlFileSetting.cpp | 70806dba202c54269c548ede59ccce311541cfc3 | [] | no_license | luanjianbing/MoldMachine | 8dccd8537b03864d88023d70fd4156051dc0bed9 | a91f68e7677b46bf2fbcb8220207b4749b59c115 | refs/heads/master | 2022-11-25T16:39:49.796570 | 2020-07-30T06:10:29 | 2020-07-30T06:10:29 | 265,991,181 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,446 | cpp | #include "xmlFileSetting.h"
XMLFile::XMLFile(const char *xmlFileName)
{
m_xmlFileName = new char[30];
strcpy(m_xmlFileName, xmlFileName);
m_pDocument = NULL;
m_pDeclaration = NULL;
}
XMLFile::~XMLFile()
{
if (m_xmlFileName != NULL)
delete m_xmlFileName;
if (m_pDocument != NULL)
delete m_pDocument;
//if (m_pDeclaration != NULL) // create XML时需要将这里注释
// delete m_pDeclaration;
}
void XMLFile::CreateXML(std::vector<std::vector<int>> block, int moldId) {
std::string _name[5] = { "BlockId", "PointX", "PointY", "Width", "Height"};
std::vector<std::string> block_name(_name, _name + 5);
//创建XML文档指针
m_pDocument = new TiXmlDocument(m_xmlFileName);
if (NULL == m_pDocument)
{
return;
}
//声明XML
m_pDeclaration = new TiXmlDeclaration("1.0", "UTF-8", "");
if (NULL == m_pDeclaration)
{
return;
}
m_pDocument->LinkEndChild(m_pDeclaration);
//创建根节点
std::string xmlFileName = m_xmlFileName;
std::string rootName = (xmlFileName.substr(0, xmlFileName.find(".")));//根节点元素名为文件名去掉.xml
TiXmlElement *pRoot = new TiXmlElement(rootName.c_str());
if (NULL == pRoot)
{
return;
}
//关联XML文档,成为XML文档的根节点
m_pDocument->LinkEndChild(pRoot);
TiXmlText *pText = new TiXmlText("CycleStep");
pRoot->LinkEndChild(pText);
pRoot->SetAttribute("MoldObjId", moldId);
//for (int i = 0; i < vec_modify.size(); i++) {
// for (int j = 0; j < vec_modify[i].size(); j++)
// {
// std::cout << vec_modify[i][j] << " ";
// }
// std::cout << std::endl;
//}
for (int i = 0; i < block.size(); i++) {
TiXmlElement *pId = new TiXmlElement(_name[0].c_str());
TiXmlText *pIdText = new TiXmlText(std::to_string(i + 1).c_str());
pId->LinkEndChild(pIdText);
pRoot->LinkEndChild(pId);
for (int j = 0; j < block[i].size(); j++)
{
TiXmlElement *pBlock = new TiXmlElement(_name[j + 1].c_str());
TiXmlText *pBlockText = new TiXmlText(std::to_string(block[i][j]).c_str());
pBlock->LinkEndChild(pBlockText);
pId->LinkEndChild(pBlock);
}
}
m_pDocument->SaveFile(m_xmlFileName);
}
void XMLFile::CreateXML(std::vector<std::vector<std::string>> vec_modify, int moldId) {
std::string _name[37] = { "CurrentStep", "clear_input_buffer", "step_input_1", "step_input_2", "step_input_3", "step_input_4",
"step_input_5", "step_input_6", "step_overlook_without_input", "step_button",
"step_counter", "step_overlook_CNT_0", "step_output_1", "step_output_2", "step_output_3", "step_output_4",
"step_output_5", "step_output_6", "step_delay", "step_img_1", "step_img_2",
"step_img_3", "step_img_4", "step_img_5", "step_img_6", "step_check_img",
"step_overlook_stop", "step_run", "step_cycle", "step_log", "next_step" };
std::vector<std::string> step_name(_name, _name + 37);
//创建XML文档指针
m_pDocument = new TiXmlDocument(m_xmlFileName);
if (NULL == m_pDocument)
{
return;
}
//声明XML
m_pDeclaration = new TiXmlDeclaration("1.0", "UTF-8", "");
if (NULL == m_pDeclaration)
{
return;
}
m_pDocument->LinkEndChild(m_pDeclaration);
//创建根节点
std::string xmlFileName = m_xmlFileName;
std::string rootName = (xmlFileName.substr(0, xmlFileName.find(".")));//根节点元素名为文件名去掉.xml
TiXmlElement *pRoot = new TiXmlElement(rootName.c_str());
if (NULL == pRoot)
{
return;
}
//关联XML文档,成为XML文档的根节点
m_pDocument->LinkEndChild(pRoot);
TiXmlText *pText = new TiXmlText("CycleStep");
pRoot->LinkEndChild(pText);
pRoot->SetAttribute("MoldObjId", moldId);
//for (int i = 0; i < vec_modify.size(); i++) {
// for (int j = 0; j < vec_modify[i].size(); j++)
// {
// std::cout << vec_modify[i][j] << " ";
// }
// std::cout << std::endl;
//}
for (int i = 0; i < vec_modify.size(); i++) {
TiXmlElement *pId = new TiXmlElement(_name[0].c_str());
TiXmlText *pIdText = new TiXmlText(std::to_string(i + 1).c_str());
pId->LinkEndChild(pIdText);
pRoot->LinkEndChild(pId);
for (int j = 0; j < vec_modify[i].size(); j++)
{
TiXmlElement *pStep = new TiXmlElement(_name[j + 1].c_str());
TiXmlText *pStepText = new TiXmlText(vec_modify[i][j].c_str());
pStep->LinkEndChild(pStepText);
pId->LinkEndChild(pStep);
}
}
m_pDocument->SaveFile(m_xmlFileName);
}
void XMLFile::CreateXML(std::map<std::string, std::string> map) {
//创建XML文档指针
m_pDocument = new TiXmlDocument(m_xmlFileName);
if (NULL == m_pDocument)
{
return;
}
//声明XML
m_pDeclaration = new TiXmlDeclaration("1.0", "UTF-8", "");
if (NULL == m_pDeclaration)
{
return;
}
m_pDocument->LinkEndChild(m_pDeclaration);
//创建根节点
std::string xmlFileName = m_xmlFileName;
std::string rootName = (xmlFileName.substr(0, xmlFileName.find(".")));//根节点元素名为文件名去掉.xml
TiXmlElement *pRoot = new TiXmlElement(rootName.c_str());
if (NULL == pRoot)
{
return;
}
//关联XML文档,成为XML文档的根节点
m_pDocument->LinkEndChild(pRoot);
TiXmlText *pText = new TiXmlText(rootName.c_str());
pRoot->LinkEndChild(pText);
for (std::map<std::string, std::string>::iterator it = map.begin(); it != map.end(); it++) {
TiXmlElement *pMap = new TiXmlElement(it->first.c_str());
TiXmlText *pMapText = new TiXmlText(it->second.c_str());
pMap->LinkEndChild(pMapText);
pRoot->LinkEndChild(pMap);
}
m_pDocument->SaveFile(m_xmlFileName);
}
void XMLFile::CreateXML(std::map<std::string, std::string> ioName, std::map<std::string, std::string> ioStatus, std::map<std::string, std::string> ioEnet) {
//创建XML文档指针
m_pDocument = new TiXmlDocument(m_xmlFileName);
if (NULL == m_pDocument)
{
return;
}
//声明XML
m_pDeclaration = new TiXmlDeclaration("1.0", "UTF-8", "");
if (NULL == m_pDeclaration)
{
return;
}
m_pDocument->LinkEndChild(m_pDeclaration);
//创建根节点
std::string xmlFileName = m_xmlFileName;
std::string rootName = (xmlFileName.substr(0, xmlFileName.find(".")));//根节点元素名为文件名去掉.xml
TiXmlElement *pRoot = new TiXmlElement(rootName.c_str());
if (NULL == pRoot)
{
return;
}
//关联XML文档,成为XML文档的根节点
m_pDocument->LinkEndChild(pRoot);
TiXmlText *pText = new TiXmlText("IOService");
pRoot->LinkEndChild(pText);
for (std::map<std::string, std::string>::iterator it = ioName.begin(); it != ioName.end(); it++) {
TiXmlElement *pIOName = new TiXmlElement(it->first.c_str());
TiXmlText *pIONameText = new TiXmlText(it->second.c_str());
pIOName->LinkEndChild(pIONameText);
pRoot->LinkEndChild(pIOName);
}
for (std::map<std::string, std::string>::iterator it = ioStatus.begin(); it != ioStatus.end(); it++) {
TiXmlElement *pIOStatus = new TiXmlElement(it->first.c_str());
TiXmlText *pIOStatusText = new TiXmlText(it->second.c_str());
pIOStatus->LinkEndChild(pIOStatusText);
pRoot->LinkEndChild(pIOStatus);
}
for (std::map<std::string, std::string>::iterator it = ioEnet.begin(); it != ioEnet.end(); it++) {
TiXmlElement *pIOEnet = new TiXmlElement(it->first.c_str());
TiXmlText *pIOEnetText = new TiXmlText(it->second.c_str());
pIOEnet->LinkEndChild(pIOEnetText);
pRoot->LinkEndChild(pIOEnet);
}
m_pDocument->SaveFile(m_xmlFileName);
}
void XMLFile::CreateXML(const char *times, const char *cnt1, const char *cnt2, const char *delay1, const char *delay2)
{
//创建XML文档指针
m_pDocument = new TiXmlDocument(m_xmlFileName);
if (NULL == m_pDocument)
{
return;
}
//声明XML
m_pDeclaration = new TiXmlDeclaration("1.0", "UTF-8", "");
if (NULL == m_pDeclaration)
{
return;
}
m_pDocument->LinkEndChild(m_pDeclaration);
//创建根节点
std::string xmlFileName = m_xmlFileName;
std::string rootName = (xmlFileName.substr(0, xmlFileName.find(".")));//根节点元素名为文件名去掉.xml
TiXmlElement *pRoot = new TiXmlElement(rootName.c_str());
if (NULL == pRoot)
{
return;
}
//关联XML文档,成为XML文档的根节点
m_pDocument->LinkEndChild(pRoot);
TiXmlText *pText = new TiXmlText("CycleCounterDelayValue");
pRoot->LinkEndChild(pText);
TiXmlElement *pCycleValue = new TiXmlElement("CycleTimes");
TiXmlText *pCycleValueText = new TiXmlText(times);
pCycleValue->LinkEndChild(pCycleValueText);
TiXmlElement *pCounter1Value = new TiXmlElement("Counter1");
TiXmlText *pCounter1ValueText = new TiXmlText(cnt1);
pCounter1Value->LinkEndChild(pCounter1ValueText);
TiXmlElement *pCounter2Value = new TiXmlElement("Counter2");
TiXmlText *pCounter2ValueText = new TiXmlText(cnt2);
pCounter2Value->LinkEndChild(pCounter2ValueText);
TiXmlElement *pDelay1Value = new TiXmlElement("Delay1");
TiXmlText *pDelay1ValueText = new TiXmlText(delay1);
pDelay1Value->LinkEndChild(pDelay1ValueText);
TiXmlElement *pDelay2Value = new TiXmlElement("Delay2");
TiXmlText *pDelay2ValueText = new TiXmlText(delay2);
pDelay2Value->LinkEndChild(pDelay2ValueText);
pRoot->LinkEndChild(pCycleValue);
pRoot->LinkEndChild(pCounter1Value);
pRoot->LinkEndChild(pCounter2Value);
pRoot->LinkEndChild(pDelay1Value);
pRoot->LinkEndChild(pDelay2Value);
m_pDocument->SaveFile(m_xmlFileName);
//delete m_pDocument;
//delete m_pDeclaration;
//delete pRoot;
//delete pText;
//delete pCycleValue;
//delete pCycleValueText;
}
//读取XML文件完整内容
void XMLFile::ReadXML()
{
// 需要重新分配空间?
m_pDocument = new TiXmlDocument(m_xmlFileName);
if (m_xmlFileName == NULL)
{
std::cout << " null " << std::endl;
return;
}
m_pDocument->LoadFile(m_xmlFileName);
m_pDocument->Print();
//delete m_pDocument;
}
//读取XML声明,例如:<?xml version="1.0" encoding="UTF-8" ?>
void XMLFile::ReadDeclaration(std::string &version, std::string &encoding, std::string &standalone)
{
m_pDocument = new TiXmlDocument(m_xmlFileName);
m_pDocument->LoadFile(m_xmlFileName);
TiXmlNode *pNode = m_pDocument->FirstChild();
if (NULL != pNode)
{
//获取声明指针
m_pDeclaration = pNode->ToDeclaration();
if (NULL != m_pDeclaration)
{
version = m_pDeclaration->Version();
encoding = m_pDeclaration->Encoding();
standalone = m_pDeclaration->Standalone();
}
}
}
//根据节点名,判断节点是否存在
bool XMLFile::FindNode(TiXmlElement *pRoot, const std::string nodeName, TiXmlElement *&pNode)
{
const char *value = pRoot->Value();
if (strcmp(pRoot->Value(), nodeName.c_str()) == 0)
{
pNode = pRoot;
return true;
}
TiXmlElement *p = pRoot;
for (p = p->FirstChildElement(); p != NULL; p = p->NextSiblingElement())
{
if (p->Value() == nodeName) {
pNode = p;
return true;
}
}
return false;
}
// 读取XML文件内容,返回一张map(用于ioService)
void XMLFile::XML2Map(std::map<std::string, std::string> &res) {
// 需要重新分配空间?
m_pDocument = new TiXmlDocument(m_xmlFileName);
m_pDocument->LoadFile(m_xmlFileName);
if (NULL == m_pDocument)
{
return;
}
TiXmlElement *pRoot = m_pDocument->RootElement();
const char *value = pRoot->Value();
if (NULL == pRoot)
{
return;
}
TiXmlElement *p = pRoot;
for (p = p->FirstChildElement(); p != NULL; p = p->NextSiblingElement())
{
res.insert(std::pair <std::string, std::string> (p->Value(), p->GetText()));
}
}
// 读取XML文件内容,返回一个vector(用于CycleStep)
void XMLFile::XML2Vect(std::vector<std::vector<std::string>> &vect) {
std::vector<std::string> _vect;
m_pDocument = new TiXmlDocument(m_xmlFileName);
m_pDocument->LoadFile(m_xmlFileName);
if (NULL == m_pDocument)
{
return;
}
TiXmlElement *pRoot = m_pDocument->RootElement();
const char *value = pRoot->Value();
if (NULL == pRoot)
{
return;
}
TiXmlElement *p = pRoot;
for (p = p->FirstChildElement(); p != NULL; p = p->NextSiblingElement())
{
_vect.push_back(p->GetText());
TiXmlElement *step = p;
for (step = step->FirstChildElement(); step != NULL; step = step->NextSiblingElement())
{
_vect.push_back(step->GetText());
}
vect.push_back(_vect);
while(!_vect.empty()){
_vect.pop_back();
}
}
std::string moldId = pRoot->Attribute("MoldObjId");
if (vect[0].size() == 5) { // block
for (int i = 0; i < vect.size(); i++) {
vect[i][0] = moldId;
}
}
else { // step
for (int i = 0; i < vect.size(); i++) {
vect[i].push_back(moldId);
}
}
//for (int i = 0; i < vect.size(); i++) {
// for (int j = 0; j < vect[i].size(); j++) {
// std::cout << vect[i][j] << " ";
// }
// std::cout << std::endl;
//}
//std::cout << pRoot->Attribute("MoldObjId") << std::endl;
}
//根据节点名,获取该节点文本
bool XMLFile::GetNodeText(const std::string nodeName, const char *&text)
{
// 需要重新分配空间?
m_pDocument = new TiXmlDocument(m_xmlFileName);
m_pDocument->LoadFile(m_xmlFileName);
if (NULL == m_pDocument)
{
return false;
}
TiXmlElement *pRoot = m_pDocument->RootElement();
const char *value = pRoot->Value();
if (NULL == pRoot)
{
return false;
}
TiXmlElement *pNode = NULL;
if (FindNode(pRoot, nodeName, pNode))
{
text = pNode->GetText();
return true;
}
return false;
}
//获取根据节点名, 获取节点属性
bool XMLFile::GetNodeAttribute(const std::string nodeName, std::map<std::string, std::string> &mapAttribute)
{
m_pDocument->LoadFile(m_xmlFileName);
if (NULL == m_pDocument)
{
return false;
}
TiXmlElement *pRoot = m_pDocument->RootElement();
if (NULL == pRoot)
{
return false;
}
TiXmlElement *pNode = NULL;
if (FindNode(pRoot, nodeName, pNode))
{
TiXmlAttribute *pAttr = NULL;
for (pAttr = pNode->FirstAttribute(); pAttr != NULL; pAttr = pAttr->Next())
{
std::string name = pAttr->Name();
std::string value = pAttr->Value();
mapAttribute.insert(make_pair(name, value));
}
return true;
}
return false;
}
//删除节点
bool XMLFile::DeleteNode(const std::string nodeName)
{
m_pDocument->LoadFile(m_xmlFileName);
TiXmlElement *pRoot = m_pDocument->RootElement();
if (NULL == pRoot)
{
return false;
}
TiXmlElement *pNode = NULL;
if (FindNode(pRoot, nodeName, pNode))
{
if (pNode == pRoot)
{//如果是根节点
m_pDocument->RemoveChild(pRoot);
m_pDocument->SaveFile(m_xmlFileName);
return true;
}
else
{//子节点
TiXmlNode *parent = pNode->Parent();//找到该节点的父节点
if (NULL == parent)
{
return false;
}
TiXmlElement *parentElem = parent->ToElement();
if (NULL == parentElem)
{
return false;
}
parentElem->RemoveChild(pNode);
m_pDocument->SaveFile(m_xmlFileName);
return true;
}
}
return false;
}
//修改节点文本
bool XMLFile::modifyText(const std::string nodeName, const std::string text)
{
// 需要重新分配空间?
m_pDocument = new TiXmlDocument(m_xmlFileName);
m_pDocument->LoadFile(m_xmlFileName);
TiXmlElement *pRoot = m_pDocument->RootElement();
if (NULL == pRoot)
{
return false;
}
TiXmlElement *pNode = NULL;
if (FindNode(pRoot, nodeName, pNode))
{
pNode->Clear();//删除原节点下的其他元素
TiXmlText *pText = new TiXmlText(text.c_str());
pNode->LinkEndChild(pText);
m_pDocument->SaveFile(m_xmlFileName);
return true;
}
return false;
}
//修改节点属性
bool XMLFile::modifyAttribution(const std::string nodeName, std::map<std::string, std::string> &mapAttribute)
{
m_pDocument->LoadFile(m_xmlFileName);
TiXmlElement *pRoot = m_pDocument->RootElement();
if (NULL == pRoot)
{
return false;
}
TiXmlElement *pNode = NULL;
if (FindNode(pRoot, nodeName, pNode))
{
TiXmlAttribute *pAttr = pNode->FirstAttribute();
char *strName = NULL;
for (; pAttr != NULL; pAttr = pAttr->Next())
{
strName = const_cast<char *>(pAttr->Name());
for (auto it = mapAttribute.begin(); it != mapAttribute.end(); ++it)
{
if (strName == it->first)
{
pNode->SetAttribute(strName, it->second.c_str());
}
}
}
m_pDocument->SaveFile(m_xmlFileName);
return true;
}
return false;
}
//在名为nodeName的节点下插入子节点
bool XMLFile::AddNode(const std::string nodeName, const char * newNodeName, const char *text)
{
m_pDocument->LoadFile(m_xmlFileName);
TiXmlElement *pRoot = m_pDocument->RootElement();
if (NULL == pRoot)
{
return false;
}
TiXmlElement *pNode = NULL;
if (FindNode(pRoot, nodeName, pNode))
{
TiXmlElement *pNewNode = new TiXmlElement(newNodeName);
TiXmlText *pNewText = new TiXmlText(text);
pNewNode->LinkEndChild(pNewText);
pNode->InsertEndChild(*pNewNode);
m_pDocument->SaveFile(m_xmlFileName);
return true;
}
return false;
}
| [
"794315704@qq.com"
] | 794315704@qq.com |
a2742b87580b300ee53ea442f43319c67f290cda | 28135952ffb3e2ad0bc55427085f3eb4bbb6b8ee | /src/model/CreditCard.cpp | cb8d78516cdcc728c54364147dc9daec9a33abbe | [] | no_license | bartlomiejgraczyk/bank-library | 305c8d2a46fe080d3149737ecb2b7be0cbb8b0d0 | 22ec4ed0a5e9ac62cf337cb1e543464a0fec4916 | refs/heads/master | 2023-04-15T00:17:42.064061 | 2021-04-15T19:13:07 | 2021-04-15T19:13:07 | 358,366,224 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,120 | cpp | //
// Created by student on 21.12.2019.
//
#include <boost/uuid/uuid_io.hpp>
#include "model/CreditCard.h"
#include "model/CardClass.h"
#include "model/Client.h"
#include "model/Amount.h"
#include "model/Account.h"
#include "exceptions/CardExceptions.h"
#include "../exceptions/ExceptionsMessages.cpp"
using namespace std;
CreditCard::CreditCard(const ClientSPtr &owner, const AccountSPtr &account) : Card(owner, account) {
balance.reset(new Amount(0, 0, getAmount()->getCurrency()));
}
CreditCard::~CreditCard() = default;
const AmountUPtr &CreditCard::getBalance() const {
return balance;
}
bool CreditCard::payBack(const AmountUPtr &amount) {
if (amount == nullptr) {
throw CardMethodException(NULL_AMOUNT);
}
if (*amount < Amount(0L, 0, amount->getCurrency())) {
throw CardMethodException(NEGATIVE_AMOUNT);
}
if (amount->getCurrency() != getAmount()->getCurrency()) {
throw CardMethodException(CURRENCY);
}
auto account = getAccount();
auto owner = getOwner();
if (*balance - *amount < Amount(0L, 0, amount->getCurrency()) || *balance == *amount) {
if (*balance - *amount < Amount(0L, 0, amount->getCurrency())) {
owner->setFounds(AmountUPtr(new Amount(*owner->getFounds()[amount->getCurrency()] + (*amount - *balance))));
}
account->setAmount(AmountUPtr(new Amount(*getAmount() + *balance)));
balance.reset(new Amount(0L, 0, amount->getCurrency()));
return true;
}
account->setAmount(AmountUPtr(new Amount(*getAmount() + *amount)));
balance.reset(new Amount(*balance - *amount));
return false;
}
bool CreditCard::makePayment(AmountUPtr amount) {
if (amount == nullptr) {
throw CardMethodException(NULL_AMOUNT);
}
balance.reset(new Amount(*balance + *amount));
return Card::makePayment(move(amount));
}
string CreditCard::briefCardInfo() const {
string owner = ", Owner: " + getOwner()->getFirstName() + " " + getOwner()->getLastName();
return "Credit Card, Class: " + getCardClass()->briefCardClassInfo() + " Balance: " + balance->toString() + ", Max Amount: " + (*getAccount()->getAmount() + *balance).toString() + owner;
}
string CreditCard::toString() const {
stringstream stream;
stream << "=========================================================\n";
stream << "Type: | Credit Card" << "\n";
stream << "Currency | " << Amount::currencyToString(getAmount()->getCurrency(), false) << "\n";
stream << "Max Amount: | " << *getAmount() + *balance << "\n";
stream << "Remaining Amount: | " << *getAmount() << "\n";
stream << "Balance: | " << *balance << "%\n";
stream << "---------------------------------------------------------\n";
stream << "Owner:\n" << getOwner()->briefClientInfo() << "\n";
stream << "---------------------------------------------------------\n";
stream << "UUID: | " << boost::uuids::to_string(*getUuid()) << "\n";
stream << "=========================================================";
return stream.str();
}
| [
"224301@edu.p.lodz.pl"
] | 224301@edu.p.lodz.pl |
ae12cb1b1cbdc46edca7f7663f9dc368692ee26e | f5e5ac7a0ed4f5fd6309d0d096195fc30eda1291 | /source/utils.cpp | 96ac6d5d874b04ba82669551f5a571b3e2cc4315 | [] | no_license | PingguSoft/HexaPodMega | a134ef8f8c0e406a08412a651b68745a2cb42837 | 233fe36acf5cb150de5dcc5c2a0a1ae4eb8f682a | refs/heads/master | 2016-09-06T04:34:46.692900 | 2015-12-01T06:25:59 | 2015-12-01T06:25:59 | 39,239,556 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,533 | cpp | /*
This project is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
see <http://www.gnu.org/licenses/>
*/
#include <stdarg.h>
#include <EEPROM.h>
#include "config.h"
#include "common.h"
#include "utils.h"
#ifdef CONFIG_DBG_SERIAL
void printf(char *fmt, ... )
{
char buf[128]; // resulting string limited to 128 chars
va_list args;
va_start (args, fmt );
vsnprintf(buf, 128, fmt, args);
va_end (args);
CONFIG_DBG_SERIAL.print(buf);
}
void printf(const __FlashStringHelper *fmt, ... )
{
char buf[128]; // resulting string limited to 128 chars
va_list args;
va_start (args, fmt);
#ifdef __AVR__
vsnprintf_P(buf, sizeof(buf), (const char *)fmt, args); // progmem for AVR
#else
vsnprintf(buf, sizeof(buf), (const char *)fmt, args); // for the rest of the world
#endif
va_end(args);
CONFIG_DBG_SERIAL.print(buf);
}
#else
void printf(char *fmt, ... )
{
}
void printf(const __FlashStringHelper *fmt, ... )
{
}
#endif
static bool mBoolSeqActive = FALSE;
static bool mBoolCycleDone = FALSE;
static bool mBoolOn = FALSE;
static u16 mPatterns[5];
static u8 mIdx = 0;
static u32 mLastToggleTime = 0;
void soundOff(void){
if (mBoolOn)
digitalWrite(PIN_SOUND, LOW);
}
void setTiming(u16 pulse, u16 pause)
{
if (!mBoolOn && (millis() >= (mLastToggleTime + pause)) && pulse != 0) {
mBoolOn = TRUE;
digitalWrite(PIN_SOUND, HIGH);
mLastToggleTime = millis();
} else if (mBoolOn && (pulse == 0 || (millis() >= mLastToggleTime + pulse))) {
mBoolOn = FALSE;
mBoolCycleDone = TRUE;
digitalWrite(PIN_SOUND, LOW);
mLastToggleTime = millis();
}
}
void Utils::handleSound(void) {
if (mBoolSeqActive) {
if (mIdx < 3) {
if (mPatterns[mIdx] != 0)
setTiming(mPatterns[mIdx], mPatterns[4]);
} else if (mLastToggleTime < (millis() - mPatterns[3])) { //sequence is over: reset everything
mIdx = 0;
mBoolSeqActive = FALSE; //sequence is now done, mBoolCycleDone sequence may begin
soundOff();
return;
}
if (mBoolCycleDone || mPatterns[mIdx] == 0) { //single on off cycle is done
if (mIdx < 3) {
mIdx++;
}
mBoolCycleDone = FALSE;
soundOff();
}
} else {
soundOff();
}
}
void Utils::sound(u16 first,u16 second,u16 third,u16 cyclepause, u16 endpause)
{
if (!mBoolSeqActive) {
mBoolSeqActive = TRUE;
mPatterns[0] = first;
mPatterns[1] = second;
mPatterns[2] = third;
mPatterns[3] = endpause;
mPatterns[4] = cyclepause;
handleSound();
}
}
void Utils::dumpEEPROM(u16 addr, u16 cnt)
{
u8 i;
u8 b;
while (cnt) {
printf(F("%08x - "), addr);
for (i = 0; (i < 16) && (i < cnt); i ++) {
b = EEPROM.read(addr + i);
printf(F("%02x "), b);
}
printf(F(" : "));
for (i = 0; (i < 16) && (i < cnt); i ++) {
b = EEPROM.read(addr + i);
if ((b > 0x1f) && (b < 0x7f))
printf(F("%c"), b);
else
printf(F("."));
}
printf(F("\n"));
addr += i;
cnt -= i;
}
}
u16 Utils::getCmdLineNum(byte **ppszCmdLine)
{
u8 *psz = *ppszCmdLine;
u16 w = 0;
while (*psz == ' ')
psz++;
if ((*psz == '0') && ((*(psz+1) == 'x') || (*(psz+1) == 'X'))) {
// Hex mode
psz += 2;
for (;;) {
if ((*psz >= '0') && (*psz <= '9'))
w = w * 16 + *psz++ - '0';
else if ((*psz >= 'a') && (*psz <= 'f'))
w = w * 16 + *psz++ - 'a' + 10;
else if ((*psz >= 'A') && (*psz <= 'F'))
w = w * 16 + *psz++ - 'A' + 10;
else
break;
}
} else {
// decimal mode
while ((*psz >= '0') && (*psz <= '9'))
w = w * 10 + *psz++ - '0';
}
*ppszCmdLine = psz;
return w;
}
| [
"pinggusoft@gmail.com"
] | pinggusoft@gmail.com |
a0d6809166f99cad2361d86767e795245040632b | b5bc86dd7decfc6f1951c8f3a9bfa94e381a2f54 | /kernel/font.cpp | 90d1abbd729ac5db5fa869b067b72812f7854d14 | [] | no_license | mszoek/hydrogen | 0238fc5b123ed97f50d624177af5ab29fe2d6d09 | 61b14c7e91b6c093bb26eaf61f2af1ba66551e37 | refs/heads/master | 2021-03-17T07:18:14.841314 | 2020-03-13T03:06:57 | 2020-03-13T03:06:57 | 246,973,194 | 40 | 4 | null | 2020-03-13T02:48:14 | 2020-03-13T02:35:42 | C++ | UTF-8 | C++ | false | false | 1,098 | cpp | #include <fonts/font.h>
fontEntry systemFonts[FONT_MAX] =
{
{
"Anonymous Pro 16px",
FONT_WIDTH_anon16,
FONT_HEIGHT_anon16,
FONT_BPP_anon16,
anon16_glyph_dsc,
anon16_glyph_bitmap
},
{
"Anonymous Pro 20px",
FONT_WIDTH_anon20,
FONT_HEIGHT_anon20,
FONT_BPP_anon20,
anon20_glyph_dsc,
anon20_glyph_bitmap
},
{
"Hack 16px",
FONT_WIDTH_hack16,
FONT_HEIGHT_hack16,
FONT_BPP_hack16,
hack16_glyph_dsc,
hack16_glyph_bitmap
},
{
"Hack 20px",
FONT_WIDTH_hack20,
FONT_HEIGHT_hack20,
FONT_BPP_hack20,
hack20_glyph_dsc,
hack20_glyph_bitmap
},
{
"IBM Plex 16px",
FONT_WIDTH_plex16,
FONT_HEIGHT_plex16,
FONT_BPP_plex16,
plex16_glyph_dsc,
plex16_glyph_bitmap
},
{
"IBM Plex 20px",
FONT_WIDTH_plex20,
FONT_HEIGHT_plex20,
FONT_BPP_plex20,
plex20_glyph_dsc,
plex20_glyph_bitmap
}
};
| [
"zoe@pixin.net"
] | zoe@pixin.net |
c9b8266e38715a7d85f0b5477f52ab04dc10f826 | d705c238defa23086a8999f49619fe33c302015c | /protocols/platform/android/PluginFactory.cpp | 44688ebf75385da21f08ec52042537a82163ffe7 | [
"MIT"
] | permissive | bianfeng-shenbin/plugin | eb13e05009e949abd88ff8a7f8fd5c565e9f273c | 286a665d69745b1c07b4646224d48ff0858dc71e | refs/heads/master | 2021-01-10T14:12:44.878193 | 2015-05-28T01:05:34 | 2015-05-28T01:05:34 | 36,332,180 | 5 | 6 | null | 2015-05-28T01:18:21 | 2015-05-27T00:25:45 | Objective-C | UTF-8 | C++ | false | false | 4,699 | cpp | /****************************************************************************
Copyright (c) 2012-2013 cocos2d-x.org
http://www.cocos2d-x.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 "PluginFactory.h"
#include "PluginUtils.h"
#include "PluginJniHelper.h"
#include "ProtocolAds.h"
#include "ProtocolAnalytics.h"
#include "ProtocolIAP.h"
#include "ProtocolShare.h"
#include "ProtocolUser.h"
#include "ProtocolSocial.h"
#include "ProtocolPush.h"
#include "ProtocolPay.h"
#include "ProtocolTk.h"
#include "ProtocolSysfuncPlus.h"
namespace cocos2d { namespace plugin {
enum {
kPluginAds = 1,
kPluginAnalytics,
kPluginIAP,
kPluginShare,
kPluginUser,
kPluginSocial,
kPluginPush,
kPluginPay,
kPluginTk = 9,
kPluginSysfuncPlus = 10
};
#define ANDROID_PLUGIN_PACKAGE_PREFIX "org/cocos2dx/plugin/"
static PluginFactory* s_pFactory = NULL;
PluginFactory::PluginFactory()
{
}
PluginFactory::~PluginFactory()
{
}
PluginFactory* PluginFactory::getInstance()
{
if (NULL == s_pFactory)
{
s_pFactory = new PluginFactory();
}
return s_pFactory;
}
void PluginFactory::purgeFactory()
{
if (NULL != s_pFactory)
{
delete s_pFactory;
s_pFactory = NULL;
}
}
/** create the plugin by name */
PluginProtocol* PluginFactory::createPlugin(const char* name)
{
PluginProtocol* pRet = NULL;
do
{
if (name == NULL || strlen(name) == 0) break;
std::string jClassName = ANDROID_PLUGIN_PACKAGE_PREFIX;
jClassName.append(name);
PluginUtils::outputLog("PluginFactory", "Java class name of plugin %s is : %s", name, jClassName.c_str());
PluginJniMethodInfo t;
if (! PluginJniHelper::getStaticMethodInfo(t
, "org/cocos2dx/plugin/PluginWrapper"
, "initPlugin"
, "(Ljava/lang/String;)Ljava/lang/Object;"))
{
PluginUtils::outputLog("PluginFactory", "Can't find method initPlugin in class org.cocos2dx.plugin.PluginWrapper");
break;
}
jstring clsName = t.env->NewStringUTF(jClassName.c_str());
jobject jObj = t.env->CallStaticObjectMethod(t.classID, t.methodID, clsName);
t.env->DeleteLocalRef(clsName);
t.env->DeleteLocalRef(t.classID);
if (jObj == NULL)
{
PluginUtils::outputLog("PluginFactory", "Can't find java class %s", jClassName.c_str());
break;
}
if (! PluginJniHelper::getStaticMethodInfo(t
, "org/cocos2dx/plugin/PluginWrapper"
, "getPluginType"
, "(Ljava/lang/Object;)I"))
{
PluginUtils::outputLog("PluginFactory", "Can't find method getPluginType in class org.cocos2dx.plugin.PluginWrapper");
break;
}
int curType = t.env->CallStaticIntMethod(t.classID, t.methodID, jObj);
t.env->DeleteLocalRef(t.classID);
PluginUtils::outputLog("PluginFactory", "The type of plugin %s is : %d", name, curType);
switch (curType)
{
case kPluginAds:
pRet = new ProtocolAds();
break;
case kPluginAnalytics:
pRet = new ProtocolAnalytics();
break;
case kPluginIAP:
pRet = new single::ProtocolIAP();
break;
case kPluginShare:
pRet = new ProtocolShare();
break;
case kPluginUser:
pRet = new ProtocolUser();
break;
case kPluginSocial:
pRet = new ProtocolSocial();
break;
case kPluginPush:
pRet = new ProtocolPush();
break;
case kPluginPay:
pRet = new combined::ProtocolPay();
break;
case kPluginTk:
pRet = new ProtocolTk();
break;
case kPluginSysfuncPlus:
pRet = new ProtocolSysfuncPlus();
break;
default:
break;
}
if (pRet != NULL)
{
pRet->setPluginName(name);
PluginUtils::initJavaPlugin(pRet, jObj, jClassName.c_str());
}
} while(0);
return pRet;
}
}} //namespace cocos2d { namespace plugin {
| [
"shenbin@bianfeng.com"
] | shenbin@bianfeng.com |
da9a5ac28b52b1028212f10ebe78d296eaddede6 | 7e48d392300fbc123396c6a517dfe8ed1ea7179f | /RodentVR/Intermediate/Build/Win64/RodentVR/Inc/Engine/SpotLight.generated.h | 07956d948eb0ce05685b7c1124553af77e16d0dc | [] | no_license | WestRyanK/Rodent-VR | f4920071b716df6a006b15c132bc72d3b0cba002 | 2033946f197a07b8c851b9a5075f0cb276033af6 | refs/heads/master | 2021-06-14T18:33:22.141793 | 2020-10-27T03:25:33 | 2020-10-27T03:25:33 | 154,956,842 | 1 | 1 | null | 2018-11-29T09:56:21 | 2018-10-27T11:23:11 | C++ | UTF-8 | C++ | false | false | 4,707 | h | // Copyright Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "UObject/ObjectMacros.h"
#include "UObject/ScriptMacros.h"
PRAGMA_DISABLE_DEPRECATION_WARNINGS
#ifdef ENGINE_SpotLight_generated_h
#error "SpotLight.generated.h already included, missing '#pragma once' in SpotLight.h"
#endif
#define ENGINE_SpotLight_generated_h
#define Engine_Source_Runtime_Engine_Classes_Engine_SpotLight_h_13_SPARSE_DATA
#define Engine_Source_Runtime_Engine_Classes_Engine_SpotLight_h_13_RPC_WRAPPERS \
\
DECLARE_FUNCTION(execSetOuterConeAngle); \
DECLARE_FUNCTION(execSetInnerConeAngle);
#define Engine_Source_Runtime_Engine_Classes_Engine_SpotLight_h_13_RPC_WRAPPERS_NO_PURE_DECLS \
\
DECLARE_FUNCTION(execSetOuterConeAngle); \
DECLARE_FUNCTION(execSetInnerConeAngle);
#define Engine_Source_Runtime_Engine_Classes_Engine_SpotLight_h_13_INCLASS_NO_PURE_DECLS \
private: \
static void StaticRegisterNativesASpotLight(); \
friend struct Z_Construct_UClass_ASpotLight_Statics; \
public: \
DECLARE_CLASS(ASpotLight, ALight, COMPILED_IN_FLAGS(0 | CLASS_Config), CASTCLASS_None, TEXT("/Script/Engine"), ENGINE_API) \
DECLARE_SERIALIZER(ASpotLight)
#define Engine_Source_Runtime_Engine_Classes_Engine_SpotLight_h_13_INCLASS \
private: \
static void StaticRegisterNativesASpotLight(); \
friend struct Z_Construct_UClass_ASpotLight_Statics; \
public: \
DECLARE_CLASS(ASpotLight, ALight, COMPILED_IN_FLAGS(0 | CLASS_Config), CASTCLASS_None, TEXT("/Script/Engine"), ENGINE_API) \
DECLARE_SERIALIZER(ASpotLight)
#define Engine_Source_Runtime_Engine_Classes_Engine_SpotLight_h_13_STANDARD_CONSTRUCTORS \
/** Standard constructor, called after all reflected properties have been initialized */ \
ENGINE_API ASpotLight(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()); \
DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(ASpotLight) \
DECLARE_VTABLE_PTR_HELPER_CTOR(ENGINE_API, ASpotLight); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(ASpotLight); \
private: \
/** Private move- and copy-constructors, should never be used */ \
ENGINE_API ASpotLight(ASpotLight&&); \
ENGINE_API ASpotLight(const ASpotLight&); \
public:
#define Engine_Source_Runtime_Engine_Classes_Engine_SpotLight_h_13_ENHANCED_CONSTRUCTORS \
/** Standard constructor, called after all reflected properties have been initialized */ \
ENGINE_API ASpotLight(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()) : Super(ObjectInitializer) { }; \
private: \
/** Private move- and copy-constructors, should never be used */ \
ENGINE_API ASpotLight(ASpotLight&&); \
ENGINE_API ASpotLight(const ASpotLight&); \
public: \
DECLARE_VTABLE_PTR_HELPER_CTOR(ENGINE_API, ASpotLight); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(ASpotLight); \
DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(ASpotLight)
#define Engine_Source_Runtime_Engine_Classes_Engine_SpotLight_h_13_PRIVATE_PROPERTY_OFFSET
#define Engine_Source_Runtime_Engine_Classes_Engine_SpotLight_h_10_PROLOG
#define Engine_Source_Runtime_Engine_Classes_Engine_SpotLight_h_13_GENERATED_BODY_LEGACY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
Engine_Source_Runtime_Engine_Classes_Engine_SpotLight_h_13_PRIVATE_PROPERTY_OFFSET \
Engine_Source_Runtime_Engine_Classes_Engine_SpotLight_h_13_SPARSE_DATA \
Engine_Source_Runtime_Engine_Classes_Engine_SpotLight_h_13_RPC_WRAPPERS \
Engine_Source_Runtime_Engine_Classes_Engine_SpotLight_h_13_INCLASS \
Engine_Source_Runtime_Engine_Classes_Engine_SpotLight_h_13_STANDARD_CONSTRUCTORS \
public: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#define Engine_Source_Runtime_Engine_Classes_Engine_SpotLight_h_13_GENERATED_BODY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
Engine_Source_Runtime_Engine_Classes_Engine_SpotLight_h_13_PRIVATE_PROPERTY_OFFSET \
Engine_Source_Runtime_Engine_Classes_Engine_SpotLight_h_13_SPARSE_DATA \
Engine_Source_Runtime_Engine_Classes_Engine_SpotLight_h_13_RPC_WRAPPERS_NO_PURE_DECLS \
Engine_Source_Runtime_Engine_Classes_Engine_SpotLight_h_13_INCLASS_NO_PURE_DECLS \
Engine_Source_Runtime_Engine_Classes_Engine_SpotLight_h_13_ENHANCED_CONSTRUCTORS \
static_assert(false, "Unknown access specifier for GENERATED_BODY() macro in class SpotLight."); \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
template<> ENGINE_API UClass* StaticClass<class ASpotLight>();
#undef CURRENT_FILE_ID
#define CURRENT_FILE_ID Engine_Source_Runtime_Engine_Classes_Engine_SpotLight_h
PRAGMA_ENABLE_DEPRECATION_WARNINGS
| [
"west.ryan.k@gmail.com"
] | west.ryan.k@gmail.com |
226eee5b1350a9687ee980da20d9cb86be036ada | f4b798fa3134b5bf47c05bbb01b8ec16e12dd443 | /UTComputer/operators/stack_operators/OperatorCLEAR.cpp | 6bc5c9570792ce1c06112be1fa7164acd1c278fd | [] | no_license | Pierre-Gilles/ut-computer | 0785e34377e9a62e55878a165eea6497cd6e9f6b | 2240ae8df713bb374ef9f58f6b38d823b03af1ad | refs/heads/master | 2021-01-18T21:43:34.265176 | 2016-06-12T20:09:02 | 2016-06-12T20:09:02 | 55,587,957 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,002 | cpp | #include "OperatorCLEAR.h"
// ===============================================================================================================
// ====================== Implement superclass interface ==========================
// ===============================================================================================================
/*
* Address of stack must not be changed, but "st" do not point to a const stack : we use a constant pointer
* and not a pointer to constant
*/
void OperatorCLEAR::execute(StackUTComputer *const st){
StackOperator::execute(st); // check usual possible errors
try {
st->clear();
}
catch (UTComputerException e) {
UTComputerException e1(e.getMessage());
e1.insertBefore(" --> ");
e1.insertBefore("Error in applying OperatorCLEAR ");
throw e1;
}
}
// ===============================================================================================================
| [
"raphael.hamonnais@gmail.com"
] | raphael.hamonnais@gmail.com |
92332c8235df49799565a25d623a93f211170d34 | d8de102af8efbd2c2fac8ada0c09d8a37b967031 | /day03/ex01/ScavTrap.hpp | 140f982763ea72803006de0370a069ccf8935997 | [] | no_license | akhanye1/cpp_bootcamp | f10c006bc8cb379bbd7745776cb9f2cdc4dd1916 | 06c6811a5865168d7754088bd4e337873e6f941f | refs/heads/master | 2020-03-19T04:59:41.420330 | 2018-06-12T11:44:22 | 2018-06-12T11:44:22 | 135,889,348 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,030 | hpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ScavTrap .hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: akhanye <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/06/08 10:23:52 by akhanye #+# #+# */
/* Updated: 2018/06/08 16:21:12 by akhanye ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef SCAVTRAP_HPP
#define SCAVTRAP_HPP
#include <iostream>
#include <time.h>
#include <stdlib.h>
class ScavTrap {
private:
int _hitPoints;
int _maxHitPoints;
int _energyPoints;
int _maxEnergyPoints;
int _level;
std::string _name;
int _meleeAttackDamage;
int _rangedAttackDamage;
int _armorDamageReduction;
void _setDefaults(void);
public:
ScavTrap(void);
ScavTrap(std::string name);
ScavTrap(ScavTrap const &);
ScavTrap & operator=(ScavTrap const &);
~ScavTrap(void);
void rangedAttack(std::string const &target);
void meleeAttack(std::string const & target);
void takeDamage(unsigned int amount);
void beRepaired(unsigned int amount);
int getHitPoints(void) const;
int getMaxHitPoints(void) const;
int getEnergyPoints(void) const;
int getMaxEnergyPoints(void) const;
int getLevel(void) const;
std::string getName(void) const;
int getMeleeAttackDamage(void) const;
int getRangedAttackDamage(void) const;
int getArmorDamageReduction(void) const;
void challengeNewcomer(std::string const & target);
};
#endif
| [
"akhanye@e4r23p3.wethinkcode.co.za"
] | akhanye@e4r23p3.wethinkcode.co.za |
6720c4a14548991bc8f3fe817348691554afa226 | 8d1f98fb263b6963dca57068ff4205ccb70c8a33 | /Coding Solutions/START01.cpp | 97c7ac485157a6bad3b3213e2f4301e7d7f80c9a | [] | no_license | ritwikgoel/CodeChef-Beginner-Level-Codes | 18e72b627ca04b68c6f993a588dfeb4dca85afab | 964fdd6489c6fc2b97aeb076673ec4a7def96da1 | refs/heads/main | 2023-05-05T19:55:25.547097 | 2021-05-29T13:48:03 | 2021-05-29T13:48:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 119 | cpp | //Dev Wadhwa
#include<iostream>
using namespace std;
int main()
{
int n;
cin>>n;
cout<<n;
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
a9c3dae78913aeaf9c1c0af8e9da72920afd83bd | 18676762fd139694b0dbe9ffb599202f86a676cc | /QSCquadtree/util.cpp | 4d67512a3377a7faa5811bcf2f98825c75c276f7 | [] | no_license | HongMok/QSCquadtree | 05b55d09b4db25c0a1f5fe81779fa0e32233d5cf | 5cbf0191f2a7f5a30a3c1a6de46dba71e085cd55 | refs/heads/master | 2020-05-18T22:54:02.148556 | 2013-05-04T08:59:07 | 2013-05-04T08:59:07 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,736 | cpp | #include "functions.h"
/************************************************************************/
/*
输出树节点内容,深度遍历
*/
/************************************************************************/
void display(Node *root)
{
if(root->isLeaf())
{
cout<<"1 ";
}
else
{
cout<<"0 ";
display(root->nw);
display(root->ne);
display(root->sw);
display(root->se);
}
}
/************************************************************************/
/*
计算PSNR(peak signal to noise ratio),峰值信噪比
*/
/************************************************************************/
double PSNR ( IplImage *&img1 , IplImage *&imggest ) //计算PSNR
{
int M = img1->height;
int N = img1->width;
double temp=0;
double temp1=0;
for(int y = 0;y<M;y++)
{
uchar* ptr1 = (uchar*) (img1->imageData+y*img1->widthStep);
uchar* ptrg = (uchar*) (imggest->imageData+y*imggest->widthStep);
for (int x = 0;x<N;x++)
{
temp+=pow((double)(ptr1[x]-ptrg[x]),2);
}
}
temp1=10*log10 (255.0*255*M*N/temp);
return (temp1);
}
/************************************************************************/
/*
计算BPP(bits per pixel),每像素色彩位
*/
/************************************************************************/
double BPP ( vector<grayLevels> &P ,int M , int N , vector<char> &Q ) //计算BPP
{
double b = (double)(Q.size()+40.0*P.size())/(M*N);
return b;
}
/************************************************************************/
/*
显示分割示意图
*/
/************************************************************************/
void showSegmentation(IplImage *img1, vector<couplePoints> &C)
{
//画示意图
cvNamedWindow("分割示意图",CV_WINDOW_AUTOSIZE);
//创建素描图像
IplImage* sketch = cvCreateImage(cvGetSize(img1), IPL_DEPTH_8U,1);
for(int y = 0;y<img1->height;y++)
{
uchar* ptrsketch = (uchar*) (sketch->imageData+y*sketch->widthStep);
for (int x = 0;x<img1->width;x++)
{
ptrsketch[x]=255;
}
}
//素描图像初始化完成
for (int i=0 ; i<C.size();i++)
{
if (C[i].x1==0&&C[i].y1==0)
cvRectangle(sketch,cvPoint(C[i].x1,C[i].y1),cvPoint(C[i].x2,C[i].y2),cvScalar(0x00,0x00,0x00));
else if (C[i].x1==0&&C[i].y1!=0)
cvRectangle(sketch,cvPoint(C[i].x1,C[i].y1-1),cvPoint(C[i].x2,C[i].y2),cvScalar(0x00,0x00,0x00));
else if (C[i].x1!=0&&C[i].y1==0)
cvRectangle(sketch,cvPoint(C[i].x1-1,C[i].y1),cvPoint(C[i].x2,C[i].y2),cvScalar(0x00,0x00,0x00));
else if (C[i].x1!=0&&C[i].y1!=0)
cvRectangle(sketch,cvPoint(C[i].x1-1,C[i].y1-1),cvPoint(C[i].x2,C[i].y2),cvScalar(0x00,0x00,0x00));
}
cvShowImage("分割示意图",sketch);//载入转化后的灰度图像
} | [
"scutmox@foxmail.com"
] | scutmox@foxmail.com |
dfb473fb3db55144f41b8a9b343b5c70a0d8921d | 46fba6660d3f01868398bb4363f9f58c2efc8415 | /GeeksforGeeks/Mathematical/LCM_And_GCD/cpp/main.cpp | 43ac8b01d4014caede6880c18a8ea22508499504 | [] | no_license | is2ei/coding-challenges | 7c5dc56e17ca91d4d9d4ad854cbd1053927d38af | ce0a833ebb3eb9db3963537e3b22ba06cd7dca51 | refs/heads/master | 2020-05-07T13:18:56.185764 | 2019-06-15T06:39:17 | 2019-06-15T06:39:17 | 180,541,213 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 586 | cpp | #include <iostream>
int gcd(long a, long b) {
if (b == 0) {
return a;
}
int t = b;
b = a % b;
a = t;
return gcd(a, b);
}
std::pair<long, long> f(long a, long b) {
std::pair<long, long> p;
p.second = gcd(a, b);
p.first = (a * b) / p.second;
return p;
}
int main() {
int t;
std::cin >> t;
for (int i = 0; i < t; i++) {
int a, b;
std::cin >> a >> b;
std::pair<long, long> result = f(a, b);
std::cout << result.first << " " << result.second << std::endl;
}
return 0;
}
| [
"is2ei.horie@gmail.com"
] | is2ei.horie@gmail.com |
b0d48064b6411de6f565f2e31da18f3fa9acf062 | b7285cb5f964c1e909d5b379546e70ba86808056 | /Device/src/GrabberPluginManager.cpp | e816f9a0fe548972e32e017edf972ee1c91a19a0 | [] | no_license | srgblnch/ImgGrabber | f1d846c4937b79f7cf1c9609f5297c4a5a9559e6 | 8b701278f4980499bbc436d25437137098cf1b51 | refs/heads/master | 2021-06-20T18:45:43.944787 | 2018-04-12T15:09:46 | 2018-04-12T15:09:46 | 43,963,417 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 358 | cpp | /*!
* \file
* \brief Definition of GrabberTask class
* \author Julien Malik - Synchrotron SOLEIL
*/
#include <GrabberPluginManager.h>
namespace GrabAPI
{
std::pair<yat::IPlugInInfo*, yat::IPlugInFactory*>
GrabberPluginManager::load( const std::string &library_file_name )
{
return this->plugin_manager.load(library_file_name);
}
}
| [
"vince_soleil@3b39871e-fe4b-0410-b5db-e82997f68959"
] | vince_soleil@3b39871e-fe4b-0410-b5db-e82997f68959 |
35b91aa32ccb799a646a5ebfbb0420aa19ac216d | aeee81ea549829243660a5d7863217602016f890 | /_src_/Tools/Data/ItemAddOption_bmd/Main.cpp | c897b8d67fbc6355b72eb1ef372f9093c84c62d5 | [
"MIT"
] | permissive | samik3k/MuClientTools | ed7b69ab3f20106c8403aa095ac39c09b3174c46 | 90d8455fe3eb1d60cd1dcd6519425c66bda14c0d | refs/heads/main | 2023-03-26T06:13:21.251149 | 2021-03-30T22:23:52 | 2021-03-30T22:23:52 | 346,051,943 | 2 | 2 | MIT | 2021-03-30T22:23:52 | 2021-03-09T15:25:19 | null | UTF-8 | C++ | false | false | 1,239 | cpp | // This file contains the 'main' function. Program execution begins and ends there.
// Requirement: C++17
#include "Core.h"
#include "ItemAddOptionBmd.h"
using namespace std;
int main(int argc, char** argv)
{
ItemAddOptionBmd opener;
const char* szInputPath = "itemaddoption.bmd";
const char* szOutputPath = nullptr;
if (argc >= 2)
szInputPath = argv[1];
if (argc >= 3)
szOutputPath = argv[2];
if (!szInputPath)
{
cout << "\t Drag&Drop the '.bmd' / '.txt' file \n";
cout << "\t or use console command to execute with the file path. \n";
return EXIT_FAILURE;
}
if (!fs::exists(szInputPath))
{
cout << "Error: Input file does not exist.\n" << endl;
return EXIT_FAILURE;
}
if (fs::is_regular_file(szInputPath))
{
auto ext = fs::path(szInputPath).extension();
if (ext == L".bmd")
{
if (!opener.Unpack(szInputPath, szOutputPath))
{
return EXIT_FAILURE;
}
}
else if (ext == L".txt")
{
if (!opener.Pack(szInputPath, szOutputPath))
{
return EXIT_FAILURE;
}
}
else
{
cout << "Error: File ext is not '.bmd' / '.txt' \n" << endl;
return EXIT_FAILURE;
}
}
else
{
cout << "Error: Invalid file path.\n" << endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
} | [
"vudao1988@gmail.com"
] | vudao1988@gmail.com |
af1d3b93a4c70d0611cf457ef98d9a6668fd31e5 | d0c44dd3da2ef8c0ff835982a437946cbf4d2940 | /cmake-build-debug/programs_tiling/function13915/function13915_schedule_26/function13915_schedule_26_wrapper.cpp | 0741286f60e9252f41822c092fefdd8fb5f8a661 | [] | no_license | IsraMekki/tiramisu_code_generator | 8b3f1d63cff62ba9f5242c019058d5a3119184a3 | 5a259d8e244af452e5301126683fa4320c2047a3 | refs/heads/master | 2020-04-29T17:27:57.987172 | 2019-04-23T16:50:32 | 2019-04-23T16:50:32 | 176,297,755 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,216 | cpp | #include "Halide.h"
#include "function13915_schedule_26_wrapper.h"
#include "tiramisu/utils.h"
#include <cstdlib>
#include <iostream>
#include <time.h>
#include <fstream>
#include <chrono>
#define MAX_RAND 200
int main(int, char **){
Halide::Buffer<int32_t> buf00(128, 64, 128);
Halide::Buffer<int32_t> buf01(128, 64);
Halide::Buffer<int32_t> buf02(128, 64, 128);
Halide::Buffer<int32_t> buf03(128, 128);
Halide::Buffer<int32_t> buf04(64);
Halide::Buffer<int32_t> buf0(128, 64, 64, 128);
init_buffer(buf0, (int32_t)0);
auto t1 = std::chrono::high_resolution_clock::now();
function13915_schedule_26(buf00.raw_buffer(), buf01.raw_buffer(), buf02.raw_buffer(), buf03.raw_buffer(), buf04.raw_buffer(), buf0.raw_buffer());
auto t2 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = t2 - t1;
std::ofstream exec_times_file;
exec_times_file.open("../data/programs/function13915/function13915_schedule_26/exec_times.txt", std::ios_base::app);
if (exec_times_file.is_open()){
exec_times_file << diff.count() * 1000000 << "us" <<std::endl;
exec_times_file.close();
}
return 0;
} | [
"ei_mekki@esi.dz"
] | ei_mekki@esi.dz |
d09926779461f4c153d419c7c9c57e41bb9a7420 | 5ad2f1777daac411b6fd0042f20308720374e4a1 | /26 Game On Checkerboard.cpp | 724a75901e89021d53c9c3312addea820e542b1a | [] | no_license | huanght1997/WHU_ACM | ca87c18a3cb9fc6282ea48633a44e814c5050f8f | 79bd94c87b47f97368910f40abedbe5d7184c86a | refs/heads/master | 2021-07-23T22:15:53.507280 | 2017-10-28T11:49:29 | 2017-10-28T11:49:29 | 108,645,131 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,439 | cpp | #include <iostream>
using namespace std;
int main()
{
int T;
cin >> T;
for (int Ti = 1; Ti <= T; Ti++)
{
int N;
cin >> N;
int **chessboard = new int*[N];
int **dp = new int*[N];
for (int i = 0; i < N; i++)
{
chessboard[i] = new int[N];
dp[i] = new int[N];
for (int j = 0 ; j < N; j++)
{
cin >> chessboard[i][j];
if (i == 0)
dp[i][j] = chessboard[i][j];
}
}
for (int i = 1; i < N; i++)
for (int j = 0; j < N; j++)
{
if (j == 0)
dp[i][j] = max(dp[i-1][j], dp[i-1][j+1]);
else if (j == N-1)
dp[i][j] = max(dp[i-1][j], dp[i-1][j-1]);
else
dp[i][j] = max(max(dp[i-1][j-1], dp[i-1][j]), dp[i-1][j+1]);
dp[i][j] += chessboard[i][j];
}
int result = -1;
cout << "Case " << Ti << ":" << endl;
for (int i = 0; i < N; i++)
{
if (dp[N-1][i] > result)
result = dp[N-1][i];
}
cout << result << endl;
if (Ti != T)
cout << endl;
for (int i = 0; i < N; i++)
{
delete[] dp[i];
delete[] chessboard[i];
}
delete[] dp;
delete[] chessboard;
}
}
| [
"1329635759@qq.com"
] | 1329635759@qq.com |
6b30197d383d3371cdecce17ab21a658dd16cd66 | a4fe18c1ab9199840b21bafc37a803f0875ea7a5 | /sort_exp/program/phi_all_level3.cpp | 306ada502082336775d780d87f8fc6b0ec5527df | [
"Apache-2.0"
] | permissive | puckbee/PhiBench | 87e71723138c6dcd1abfeacc2bde5f996eaf4ab8 | bf2fa1a4459d72f42cf39d772bf49d6965335b78 | refs/heads/master | 2020-12-25T17:36:39.430052 | 2016-08-17T10:12:06 | 2016-08-17T10:12:06 | 40,700,404 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,964 | cpp | /*
* bitonic sort implementation
* rather than sort [A B] B in other direction
* sort A B in the same direction but reverse B in next comparsion first
* a another say to express:
* the input array A,B are sorted in same direction assending or decending order
* so when merge A,B using bitonic way, B should be reversed at first
* But we can consider that A[0] compare with B[n-1] A[1] compare with B[n-2], the same as reversed
*
* */
#include <iostream>
#include <fstream>
#include <algorithm>
//#include <string>
//#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <cmath>
#include <unistd.h>
#include <sys/time.h>
#include <immintrin.h>
#include <memory.h>
#include <assert.h>
//#include <rdtsc.h>
#include <omp.h>
//#include <mpi.h>
#define MICRO_IN_SEC 1000000.00
#define PI acos(-1)
#define eps 1e-9
#define out(x) (cout<<#x<<":"<<x<<" ")
#define outln(x) (cout<<#x<<":"<<x<<endl)
#define outs(x) (cout<<x)
#define outline (cout<<endl)
#define mssleep(time) usleep((time)*(10*1000))
#define FOR_I(begin,end) for (int i=begin;i<end;i++)
#define FOR_J(begin,end) for (int j=begin;j<end;j++)
#define FOR_K(begin,end) for (int k=begin;k<end;k++)
#define FOR_I_J(B1,E1,B2,E2) FOR_I(B1,E1) FOR_J(B2,E2)
#define FOR_I_J_K(B1,E1,B2,E2,B3,E3) FOR_I_J(B1,E1,B2,E2) FOR_K(B3,E3)
#define FOR(begin,end) FOR_I(begin,end)
#define FORN(end) FOR_I(0,end)
#define HERE cout<<"HERE"<<endl
#define THERE cout<<"THERE"<<endl
#define NORM_C (printf("\x1B[0m"))
#define BOLD(x) {printf("\x1B[1m");x;NORM_C;}
#define RED(x) {printf("\x1B[31m");x;NORM_C;}
#define BRED(x) {printf("\x1B[41m");x;NORM_C;}
#define GREEN(x) {printf("\x1B[32m");x;NORM_C;}
#define BGREEN(x) {printf("\x1B[42m");x;NORM_C;}
#define BLUE(x) {printf("\x1B[34m");x;NORM_C;}
#define BBLUE(x) {printf("\x1B[44m");x;NORM_C;}
#define CYAN(x) {printf("\x1B[36m");x;NORM_C;}
#define BCYAN(x) {printf("\x1B[46m");x;NORM_C;}
#define SHINE(x) {printf("\x1B[93m");x;NORM_C;}
using namespace std;
//for mpi
#define MCW MPI_COMM_WORLD
void get_data(FILE* fp, int* data, int nn)
{
int i=0;
int data_item;
while (fscanf(fp,"%d", &data_item) != EOF)
{
if (i>=nn) break;
data[i]=data_item;
i++;
}
printf(" i= %u \n",i);
fclose(fp);
}
double microtime(){
int tv_sec,tv_usec;
double time;
struct timeval tv;
struct timezone tz;
gettimeofday(&tv,&tz);
return tv.tv_sec+tv.tv_usec/MICRO_IN_SEC;
}
template <typename T>
void debug_a(T * data,int begin,int end){
for (int i=begin;i<end;i++) cout<<"["<<i<<"]: "<<data[i]<<"\t";cout<<endl;
}
template <typename T>
void debug_a(T * data,int end){
debug_a(data,0,end);
}
template <typename T>
void debug_a2(T ** data,int end1,int end2){
for (int i=0;i<end1;i++){cout<<"row "<<i<<endl; for (int j=0;j<end2;j++) cout<<"["<<i<<","<<j<<"] "<<data[i][j]<<"\t";cout<<endl;}
}
template <typename T>
void debug_a2(T * data,int n,int m){
cout<<"mn mode"<<endl;
for (int i=0;i<n;i++){cout<<"row "<<i<<endl; for (int j=0;j<m;j++) cout<<"["<<i<<","<<j<<"] "<<data[i*m+j]<<"\t";cout<<endl;}
}
double get_sec(const struct timeval & tval){
return ((double)(tval.tv_sec*1000*1000 + tval.tv_usec))/1000000.0;
}
template <typename T>
T checkmin(T & data,T value){
data = min(data,value);
return data;
}
struct Watch{
timeval begin,end;
void start(){gettimeofday(&begin,NULL);}
double time(){return get_sec(end)-get_sec(begin);}
double stop(){gettimeofday(&end,NULL);return time();}
};
template<typename T>
void show_trends(T *data,int n){
cout<<"["<<0<<"]: "<<data[0]<<"\t";
FOR_I(1,n){
T compare = data[i] - data[i-1];
if (0 == compare)
cout<<"["<<i<<"]: "<<data[i]<<"\t";
else if ( 0 < compare){
GREEN(cout<<"["<<i<<"]: "<<data[i]<<"\t");
}
else if ( compare < 0)
BLUE(cout<<"["<<i<<"]: "<<data[i]<<"\t");
}
cout<<endl<<endl;
}
inline __m512i load(const int* addr){
return _mm512_load_epi32(addr);
}
inline void store(int* addr, const __m512i value){
_mm512_store_epi32(addr,value);
}
inline void show(const __m512i a){
int *buffer=0;
posix_memalign((void **)&buffer,64,16*sizeof(int));
store(buffer,a);
FOR_I(0,16) printf("%d\t",buffer[i]);printf("\n");
}
int key_interval_size;
int interval_size;
int num_keys;
int *data;
int *data2;
int *correct;
int test_arr[16*64] __attribute__ ((aligned(0x100)));
int buffers[8][8][20];
int permute_arr[20];
const _MM_CMPINT_ENUM global_op = _MM_CMPINT_GE;
int nn;
__m512i vconst_sort1,vconst_sort2,vconst_sort3,vconst_sort4;
__m512i vconst_merge1,vconst_merge2,vconst_merge3;
const int SEG_NUM = 512;
void generate_data(int *arr,int n,int MOD){
FOR_I(0,n){
arr[i] = rand() % MOD;
}
}
void check_correctness(int *data1,int *data2,int n){
FOR_I(0,n)
if ( data1[i] != data2[i]){
BCYAN(cout<<"Wrong at "<<i<<" "<<data1[i]<<" <> "<<data2[i]<<endl);
exit(0);
}
}
inline int bsearch(int *data1,int *data2,int n){
int left(0),right(n);
while (left < right){
int mid = (left+right)/2;
if (data1[mid] < data2[mid])
left = mid + 1;
else right = mid;
}
return left;
}
template<bool less_than=false>
inline void vector_swap(__m512i & a, __m512i & b){
__m512i t;
t = a;
if (!less_than){
a = _mm512_min_epi32(a,b);
b = _mm512_max_epi32(t,b);
}
else {
a = _mm512_max_epi32(a,b);
b = _mm512_min_epi32(t,b);
}
}
template<bool reversed=false>
inline void register_sort(__m512i & a){
const int mask1 = reversed? 0xFFFF:0;
const int mask2 = reversed? 0:0xFFFF;
__m512i b;
b = _mm512_shuffle_epi32(a,_MM_PERM_CDAB);
a = _mm512_mask_min_epi32(a,0b0110100110010110^mask1,a,b);
a = _mm512_mask_max_epi32(a,0b0110100110010110^mask2,a,b);
b = _mm512_shuffle_epi32(a,_MM_PERM_BADC);
a = _mm512_mask_min_epi32(a,0b0011110011000011^mask1,a,b);
a = _mm512_mask_max_epi32(a,0b0011110011000011^mask2,a,b);
b = _mm512_shuffle_epi32(a,_MM_PERM_CDAB);
a = _mm512_mask_min_epi32(a,0b0101101010100101^mask1,a,b);
a = _mm512_mask_max_epi32(a,0b0101101010100101^mask2,a,b);
b = _mm512_permute4f128_epi32(a,_MM_PERM_CDAB);
a = _mm512_mask_min_epi32(a,0b0000111111110000^mask1,a,b);
a = _mm512_mask_max_epi32(a,0b0000111111110000^mask2,a,b);
b = _mm512_shuffle_epi32(a,_MM_PERM_BADC);
a = _mm512_mask_min_epi32(a,0b0011001111001100^mask1,a,b);
a = _mm512_mask_max_epi32(a,0b0011001111001100^mask2,a,b);
b = _mm512_shuffle_epi32(a,_MM_PERM_CDAB);
a = _mm512_mask_min_epi32(a,0b0101010110101010^mask1,a,b);
a = _mm512_mask_max_epi32(a,0b0101010110101010^mask2,a,b);
b = _mm512_permute4f128_epi32(a,_MM_PERM_BADC);
a = _mm512_mask_min_epi32(a,0b0000000011111111^mask1,a,b);
a = _mm512_mask_max_epi32(a,0b0000000011111111^mask2,a,b);
b = _mm512_permute4f128_epi32(a,_MM_PERM_CDAB);
a = _mm512_mask_min_epi32(a,0b0000111100001111^mask1,a,b);
a = _mm512_mask_max_epi32(a,0b0000111100001111^mask2,a,b);
b = _mm512_shuffle_epi32(a,_MM_PERM_BADC);
a = _mm512_mask_min_epi32(a,0b0011001100110011^mask1,a,b);
a = _mm512_mask_max_epi32(a,0b0011001100110011^mask2,a,b);
b = _mm512_shuffle_epi32(a,_MM_PERM_CDAB);
a = _mm512_mask_min_epi32(a,0b0101010101010101^mask1,a,b);
a = _mm512_mask_max_epi32(a,0b0101010101010101^mask2,a,b);
}
template<bool reversed = false>
inline void register_merge16(__m512i &a){
const int mask1 = reversed? 0xFFFF:0;
const int mask2 = reversed? 0:0xFFFF;
__m512i b;
b = _mm512_permute4f128_epi32(a,_MM_PERM_BADC);
a = _mm512_mask_min_epi32(a,0b0000000011111111^mask1,a,b);
a = _mm512_mask_max_epi32(a,0b0000000011111111^mask2,a,b);
b = _mm512_permute4f128_epi32(a,_MM_PERM_CDAB);
a = _mm512_mask_min_epi32(a,0b0000111100001111^mask1,a,b);
a = _mm512_mask_max_epi32(a,0b0000111100001111^mask2,a,b);
b = _mm512_shuffle_epi32(a,_MM_PERM_BADC);
a = _mm512_mask_min_epi32(a,0b0011001100110011^mask1,a,b);
a = _mm512_mask_max_epi32(a,0b0011001100110011^mask2,a,b);
b = _mm512_shuffle_epi32(a,_MM_PERM_CDAB);
a = _mm512_mask_min_epi32(a,0b0101010101010101^mask1,a,b);
a = _mm512_mask_max_epi32(a,0b0101010101010101^mask2,a,b);
}
void register_sort(__m512i & a,__m512i & b,bool direction){
/*# of instruction: 77*/
__m512i a2;
a2 = _mm512_mask_min_epi32(a,0b0000000000000000^0xFFFF,a,b);
b = _mm512_mask_max_epi32(b,0b0000000000000000^0xFFFF,a,b);
b = _mm512_shuffle_epi32(b,_MM_PERM_CDAB);
a = _mm512_mask_min_epi32(a2,0b0110011001100110^0xFFFF,a2,b);
a = _mm512_mask_max_epi32(a,0b0110011001100110,a2,b);
b = _mm512_mask_max_epi32(b,0b0110011001100110^0xFFFF,a2,b);
b = _mm512_mask_min_epi32(b,0b0110011001100110,a2,b);
b = _mm512_shuffle_epi32(b,_MM_PERM_CDAB);
a2 = _mm512_mask_min_epi32(a,0b1010101010101010^0xFFFF,a,b);
a2 = _mm512_mask_max_epi32(a2,0b1010101010101010,a,b);
b = _mm512_mask_max_epi32(b,0b1010101010101010^0xFFFF,a,b);
b = _mm512_mask_min_epi32(b,0b1010101010101010,a,b);
b = _mm512_shuffle_epi32(b,_MM_PERM_BADC);
a = _mm512_mask_min_epi32(a2,0b0011110000111100^0xFFFF,a2,b);
a = _mm512_mask_max_epi32(a,0b0011110000111100,a2,b);
b = _mm512_mask_max_epi32(b,0b0011110000111100^0xFFFF,a2,b);
b = _mm512_mask_min_epi32(b,0b0011110000111100,a2,b);
b = _mm512_shuffle_epi32(b,_MM_PERM_ABCD);
a2 = _mm512_mask_min_epi32(a,0b0101101001011010^0xFFFF,a,b);
a2 = _mm512_mask_max_epi32(a2,0b0101101001011010,a,b);
b = _mm512_mask_max_epi32(b,0b0101101001011010^0xFFFF,a,b);
b = _mm512_mask_min_epi32(b,0b0101101001011010,a,b);
b = _mm512_shuffle_epi32(b,_MM_PERM_CDAB);
a = _mm512_mask_min_epi32(a2,0b0110011001100110^0xFFFF,a2,b);
a = _mm512_mask_max_epi32(a,0b0110011001100110,a2,b);
b = _mm512_mask_max_epi32(b,0b0110011001100110^0xFFFF,a2,b);
b = _mm512_mask_min_epi32(b,0b0110011001100110,a2,b);
b = _mm512_permute4f128_epi32(b,_MM_PERM_CDAB);
a2 = _mm512_mask_min_epi32(a,0b0000111111110000^0xFFFF,a,b);
a2 = _mm512_mask_max_epi32(a2,0b0000111111110000,a,b);
b = _mm512_mask_max_epi32(b,0b0000111111110000^0xFFFF,a,b);
b = _mm512_mask_min_epi32(b,0b0000111111110000,a,b);
b = _mm512_permutevar_epi32(vconst_sort1,b);
a = _mm512_mask_min_epi32(a2,0b0011001111001100^0xFFFF,a2,b);
a = _mm512_mask_max_epi32(a,0b0011001111001100,a2,b);
b = _mm512_mask_max_epi32(b,0b0011001111001100^0xFFFF,a2,b);
b = _mm512_mask_min_epi32(b,0b0011001111001100,a2,b);
b = _mm512_shuffle_epi32(b,_MM_PERM_ABCD);
a2 = _mm512_mask_min_epi32(a,0b0101010110101010^0xFFFF,a,b);
a2 = _mm512_mask_max_epi32(a2,0b0101010110101010,a,b);
b = _mm512_mask_max_epi32(b,0b0101010110101010^0xFFFF,a,b);
b = _mm512_mask_min_epi32(b,0b0101010110101010,a,b);
b = _mm512_shuffle_epi32(b,_MM_PERM_CDAB);
a = _mm512_mask_min_epi32(a2,0b1001011010010110^0xFFFF,a2,b);
a = _mm512_mask_max_epi32(a,0b1001011010010110,a2,b);
b = _mm512_mask_max_epi32(b,0b1001011010010110^0xFFFF,a2,b);
b = _mm512_mask_min_epi32(b,0b1001011010010110,a2,b);
b = _mm512_permute4f128_epi32(b,_MM_PERM_BADC);
a2 = _mm512_mask_min_epi32(a,0b1111111100000000^0xFFFF,a,b);
a2 = _mm512_mask_max_epi32(a2,0b1111111100000000,a,b);
b = _mm512_mask_max_epi32(b,0b1111111100000000^0xFFFF,a,b);
b = _mm512_mask_min_epi32(b,0b1111111100000000,a,b);
b = _mm512_permute4f128_epi32(b,_MM_PERM_ABCD);
a = _mm512_mask_min_epi32(a2,0b1111000011110000^0xFFFF,a2,b);
a = _mm512_mask_max_epi32(a,0b1111000011110000,a2,b);
b = _mm512_mask_max_epi32(b,0b1111000011110000^0xFFFF,a2,b);
b = _mm512_mask_min_epi32(b,0b1111000011110000,a2,b);
b = _mm512_permutevar_epi32(vconst_sort2,b);
a2 = _mm512_mask_min_epi32(a,0b1100110011001100^0xFFFF,a,b);
a2 = _mm512_mask_max_epi32(a2,0b1100110011001100,a,b);
b = _mm512_mask_max_epi32(b,0b1100110011001100^0xFFFF,a,b);
b = _mm512_mask_min_epi32(b,0b1100110011001100,a,b);
b = _mm512_shuffle_epi32(b,_MM_PERM_ABCD);
a = _mm512_mask_min_epi32(a2,0b1010101010101010^0xFFFF,a2,b);
a = _mm512_mask_max_epi32(a,0b1010101010101010,a2,b);
b = _mm512_mask_max_epi32(b,0b1010101010101010^0xFFFF,a2,b);
b = _mm512_mask_min_epi32(b,0b1010101010101010,a2,b);
b = _mm512_shuffle_epi32(b,_MM_PERM_CDAB);
a2 = _mm512_mask_min_epi32(a,0b0110100110010110^0xFFFF,a,b);
a2 = _mm512_mask_max_epi32(a2,0b0110100110010110,a,b);
b = _mm512_mask_max_epi32(b,0b0110100110010110^0xFFFF,a,b);
b = _mm512_mask_min_epi32(b,0b0110100110010110,a,b);
b = _mm512_permute4f128_epi32(b,_MM_PERM_BADC);
if (!direction){
a = _mm512_min_epi32(a2,b);
b = _mm512_max_epi32(b,a2);
a = _mm512_permutevar_epi32(vconst_sort3,a);
b = _mm512_permutevar_epi32(vconst_sort3,b);
}
else {
a = _mm512_max_epi32(a2,b);
b = _mm512_min_epi32(b,a2);
a = _mm512_permutevar_epi32(vconst_sort4,a);
b = _mm512_permutevar_epi32(vconst_sort4,b);
}
}
template<bool dir1,bool dir2>
inline void register_merge(__m512i &a, __m512i &b){
/* # of instructions: 2 + 12*2 = 26*/
vector_swap<false>(a,b);
register_merge16<dir1>(a);
register_merge16<dir2>(b);
}
/*
template<bool dir1,bool dir2>
inline void register_merge2(__m512i &a, __m512i &b){
__m512i a2,b2;
a2 = _mm512_mask_min_epi32(a,0b1111111100000000^0xFFFF,a,b);
a2 = _mm512_mask_max_epi32(a2,0b1111111100000000,a,b);
b2 = _mm512_mask_max_epi32(b,0b1111111100000000^0xFFFF,a,b);
b2 = _mm512_mask_min_epi32(b2,0b1111111100000000,a,b);
b2 = _mm512_permute4f128_epi32(b2,_MM_PERM_BADC);
a = _mm512_mask_min_epi32(a2,0b0000111111110000^0xFFFF,a2,b2);
a = _mm512_mask_max_epi32(a,0b0000111111110000,a2,b2);
b = _mm512_mask_max_epi32(b2,0b0000111111110000^0xFFFF,a2,b2);
b = _mm512_mask_min_epi32(b,0b0000111111110000,a2,b2);
b = _mm512_permute4f128_epi32(b,_MM_PERM_CDAB);
a2 = _mm512_mask_min_epi32(a,0b0011110000111100^0xFFFF,a,b);
a2 = _mm512_mask_max_epi32(a2,0b0011110000111100,a,b);
b2 = _mm512_mask_max_epi32(b,0b0011110000111100^0xFFFF,a,b);
b2 = _mm512_mask_min_epi32(b2,0b0011110000111100,a,b);
b2 = _mm512_shuffle_epi32(b2,_MM_PERM_BADC);
a = _mm512_mask_min_epi32(a2,0b0110011001100110^0xFFFF,a2,b2);
a = _mm512_mask_max_epi32(a,0b0110011001100110,a2,b2);
b = _mm512_mask_max_epi32(b2,0b0110011001100110^0xFFFF,a2,b2);
b = _mm512_mask_min_epi32(b,0b0110011001100110,a2,b2);
b = _mm512_shuffle_epi32(b,_MM_PERM_CDAB);
a2 = _mm512_mask_min_epi32(a,0b1010101010101010^0xFFFF,a,b);
a2 = _mm512_mask_max_epi32(a2,0b1010101010101010,a,b);
b2 = _mm512_mask_max_epi32(b,0b1010101010101010^0xFFFF,a,b);
b2 = _mm512_mask_min_epi32(b2,0b1010101010101010,a,b);
b = _mm512_permutevar_epi32(vconst_merge1,b2);
a = _mm512_min_epi32(a2,b);
b = _mm512_max_epi32(b,a2);
if (!dir1)
a = _mm512_permutevar_epi32(vconst_merge2,a);
else a = _mm512_permutevar_epi32(vconst_merge3,a);
if (!dir2)
b = _mm512_permutevar_epi32(vconst_merge2,b);
else b = _mm512_permutevar_epi32(vconst_merge3,b);
}
*/
template<bool direction>
void merge(int *data,int *data_out,int n){
const int kx = direction? -16:16;
int i(0),j(n-16);
int k;
int endk;
if (direction)
k = n-16,endk = 0;
else k=0, endk = n;
__m512i small,large;
int a16,b16;
int compare =0;
small = load(data+i);a16 = data[i+15];
large = load(data+j);b16 = data[j];
while (true){
compare = a16 - b16 ;
if (compare < 0){
register_merge<direction,true>(small,large);
i+=16;
}
else {
register_merge<direction,false>(small,large);
j-=16;
}
store(data_out+k,small);k+=kx;
if (i>=j) break;
if (compare <0){
small = load(data+i);
a16 = data[i+15];
}
else {
small = load(data+j);
b16 = data[j];
}
}//end while
register_merge16<direction>(large);
store(data_out+k,large);
}
template<bool dir>
void basic_sort(int *data){
__m512i a,b;
a = load(data);
register_sort< dir >(a);
b = load(data+16);
register_sort< !dir >(b);
vector_swap<dir>(a,b);
register_merge16<dir>(a);
store(data,a);
register_merge16<dir>(b);
store(data+16,b);
}
void basic_sort(int *data,bool dir){
__m512i a,b,a2,b2;
a = load(data);
b = load(data+16);
register_sort(a,b,dir);
store(data,a);
store(data+16,b);
}
int * one_core_merge_sort(int *data,int *data_out,int n,bool direction){
int len = n>>1;
if ( n<=32 ){
if (direction) basic_sort<true>(data);
else basic_sort<false>(data);
//basic_sort(data,direction);
return data;
}
int *addr1,*addr2;
addr1 = one_core_merge_sort(data,data_out,len,false);
one_core_merge_sort(data+len,data_out+len,len,true);
if (addr1 == data)
addr2 = data_out;
else addr2 = data;
if (direction)
merge<true>(addr1,addr2,n);
else merge<false>(addr1,addr2,n);
return addr2;
}
void first_level(int *data,int *data2,int n){
int seg_len = n / SEG_NUM;
#pragma omp parallel for
FOR_I(0,SEG_NUM){
int a = seg_len*i;
one_core_merge_sort(data+a,data2+a,seg_len,i%2);
}
}
inline __m512i load_unaligned(const int* addr){
#pragma warning( disable : 592 )
__m512i x;
return _mm512_loadunpackhi_epi32(_mm512_loadunpacklo_epi32(x, addr),addr+16);
}
int cut[2500],cut2[2500];
template<bool direction>
void merge_nonealign(int *data,int n1, int * data2,int n2,int *data_out,int n){
const int kx = direction? -16:16;
int i(0),j(n2-16);
int k;
int endk;
if (direction)
k = n-16,endk = 0;
else k=0, endk = n;
__m512i small,large,hill;
__m512i i_second_half,j_first_half;
int part1 = n1 % 16;
hill = load_unaligned(data+n1-part1);
small = load_unaligned(data2-part1);
int mask_hill = ((1<<part1)-1)^0xFFFF ;
hill = _mm512_mask_mov_epi32(hill,mask_hill,small);
int a16,b16;
int compare =0;
small = load_unaligned(data+i);a16 = data[i+15];
large = load_unaligned(data2+j);b16 = data2[j];
if (n1 >=16 && n2 >=16)
while (true){
compare = a16 - b16 ;
if (compare < 0){
register_merge<direction,true>(small,large);
i+=16;
}
else {
register_merge<direction,false>(small,large);
j-=16;
}
store(data_out+k,small);k+=kx;
if ( i >= n1-part1 || j < 0 ) break;
if (compare <0){
small = load_unaligned(data+i);
a16 = data[i+15];
}
else {
small = load_unaligned(data2+j);
b16 = data2[j];
}
}//end while
else {
if ( n1 >= 16 ) large = small;
}
if (0 == part1){
if (i >= n1){
j -= 16;
while (j>=0){
small = load_unaligned(data2+j);
register_merge<direction,false>(small,large);
j -= 16;
store(data_out+k,small);
k+=kx;
}
}
else {
i+=16;
while (i<n1){
small = load_unaligned(data+i);
register_merge<direction,true>(small,large);
i += 16;
store(data_out+k,small);
k+=kx;
}
}
}
else {
if (i >= n1 - part1){
register_merge<direction,false>(hill,large);
store(data_out+k,hill);
k += kx;
j -= 16;
while (j>=0){
small = load_unaligned(data2+j);
register_merge<direction,false>(small,large);
j -= 16;
store(data_out+k,small);
k += kx;
}
}
else {
register_merge<direction,true>(hill,large);
store(data_out+k,hill);
k += kx;
i += 16;
while (i < n1-part1 ){
small = load_unaligned(data+i);
register_merge<direction,true>(small,large);
i += 16;
store(data_out+k,small);
k += kx;
}
}
}
register_merge16<direction>(large);
store(data_out+k,large);
}
int * parallel_merge_sort(int *data,int *data2,int n,bool direction){
int n2;
int seg_len = n / SEG_NUM;
first_level(data,data2,n);
//swap(data,data2);
//show_trends(data,n);
// if SEG_NUM is odd no need to swap
for (int level = 1,n2 = seg_len*2;n2 <= n;n2 <<= 1,level += 1){
int len = n2 >> 1;
int nump = 1 << level;
#pragma omp parallel for
for (int j=0;j<SEG_NUM;j++){
int *addr1,*addr2;
int id = j % nump;
int part_id = j / nump;
/*- parallel merge -*/
addr1 = data + part_id*n2;
addr2 = addr1 + len;
int pos,pos2;
int bsearch_len = (id+1)*seg_len;
if ( id+1 != nump ){
if (id < nump/2){
addr2 += len - bsearch_len;
pos = bsearch(addr1 , addr2 , bsearch_len);
pos2 = bsearch_len - pos;
pos2 = len - pos2;
}
else {
pos = bsearch(addr1 , addr2 , bsearch_len);
bsearch_len = n2-(id+1)*seg_len;
addr1 += len - bsearch_len;
pos = bsearch(addr1 , addr2 , bsearch_len);
pos2 = bsearch_len - pos;
pos += len - bsearch_len;
pos2 = bsearch_len - pos2;
}
cut[j] = pos;
cut2[j] = pos2;
}
}
#pragma omp parallel for
FOR_J(0,SEG_NUM){
//j = 2;
int part_id = j / nump;
int begin1,begin2,end1,end2;
int id = j % nump;
if (0 == id){
begin1 = 0;
end2 = len;
}
else {
begin1 = cut[j-1];
end2 = cut2[j-1];
}
if ( nump == id+1 ){//last one
end1 = len;
begin2 = 0;
}
else {
end1 = cut[j];
begin2 = cut2[j];
}
int size1 = end1 - begin1;
int size2 = end2 - begin2;
int * addr1 = data + part_id*n2 + begin1;
int * addr2 = data + part_id*n2 + len+begin2;
int *addr3;
//cout<<"To merge"<<endl;
//show_trends(addr1,size1);
//show_trends(addr2,size2);
if (part_id % 2 != 0){
addr3 = data2 + (part_id+1)*n2 - (id+1)*seg_len;
merge_nonealign<true>(addr1,size1,addr2,size2,addr3,seg_len);
}
else {
addr3 = data2 + j*seg_len;
merge_nonealign<false>(addr1,size1,addr2,size2,addr3,seg_len);
}
//cout<<"after merge"<<endl;
//show_trends(addr3,seg_len);
}
swap(data2,data);
//cout<<"--------------------------------"<<endl;
//show_trends(data,n);
}
return data;
}
void work(int* data_temp){
int seed =0;
Watch watch;
// srand(seed);
//nn = 4*1024*1024;
//nn = 32*2*16*2;
//nn = 32*4*4*16;
//int mod = 1231328761;
//mod = 123;
//generate_data(data,nn,mod);
//fun0(data);
memcpy(data,data_temp,sizeof(int)*nn);
// posix_memalign((void **)&correct,64,sizeof(int)*nn);
// memcpy(correct,data,sizeof(int)*nn);
memcpy(data2,data,sizeof(int)*nn);
watch.start();
// sort(correct,correct + nn);
double time2 = watch.stop();
double time1;
watch.start();
//show_trends(data,nn);//debug
int * result_pointer = parallel_merge_sort(data,data2,nn,false);
time1 = watch.stop();
// outln(time1);outln(time2);
//show_trends(result_pointer,nn);
//BBLUE(debug_a(correct,nn));//debug
// check_correctness(result_pointer,correct,nn);
//free(correct);
}
void inits(){
vconst_sort1 = _mm512_set_epi32( 9,8,11,10,13,12,15,14,1,0,3,2,5,4,7,6 );
vconst_sort2 = _mm512_set_epi32( 9,8,11,10,13,12,15,14,1,0,3,2,5,4,7,6 );
vconst_sort3 = _mm512_set_epi32( 7,15,14,6,13,5,4,12,11,3,2,10,1,9,8,0 );
vconst_sort4 = _mm512_set_epi32( 0,8,9,1,10,2,3,11,12,4,5,13,6,14,15,7 );
vconst_merge1 = _mm512_set_epi32( 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 );
vconst_merge2 = _mm512_set_epi32( 5,10,11,4,9,6,7,8,13,2,3,12,1,14,15,0 );
vconst_merge3 = _mm512_set_epi32( 0,15,14,1,12,3,2,13,8,7,6,9,4,11,10,5 );
}
int main(int argc, char** argv){
// BRED(cout<<"PROGRAM BEGIN"<<endl);
printf(" Begin \n");
char* ifn = argv[1];
float file_begin=microtime();
inits();
FILE* ifp;
if((ifp=fopen(ifn,"r"))==NULL)
{
printf("%s file open error!\n",ifn);
exit(0);
}
fscanf(ifp,"%d",&nn);
//work(148);return 0;
int * data_temp;
posix_memalign((void **)&data_temp,64,sizeof(int)*nn);
posix_memalign((void **)&data,64,sizeof(int)*nn);
posix_memalign((void **)&data2,64,sizeof(int)*nn);
get_data(ifp,data_temp,nn);
printf(" file reading time is %fs \n", microtime()-file_begin);
double parallel_begin = microtime();
FOR_I(1,100)
work(data_temp);
printf(" parallel time is %fs \n", microtime()-parallel_begin);
free(data_temp);
free(data);
free(data2);
return 0;
}
| [
"puckbee@gmail.com"
] | puckbee@gmail.com |
95412f05c9c164d184ac70f4b25a19dfd70641f2 | cd8addb41043d98e687f8cbac6977b48c126e372 | /step008-matlab/edge.cpp | fc64f40e7413c8a3346ce04f1d41193f84c6faa8 | [
"Apache-2.0"
] | permissive | pedrodiamel/halide-mini-course | ebcd99178005feb7a1124e3d70d00b3e342fb1a1 | 81db2cece84b0d9f156ae3ebd159aca894b81488 | refs/heads/main | 2023-08-05T08:56:45.900918 | 2021-09-10T13:46:55 | 2021-09-10T13:46:55 | 404,375,143 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,594 | cpp | #include "Halide.h"
#include <stdio.h>
using namespace Halide;
using namespace Halide::BoundaryConditions;
class Edge : public Halide::Generator<Edge>
{
public:
Input<Buffer<uint8_t>> input{"input", 2}; // \in [W,H]
Output<Buffer<uint8_t>> output{"output", 2}; // \in [W,H]
void generate()
{
//Func definition
Var x, y;
Func img_pad, img16, gx, gy, g_mag, g_edge;
/* THE ALGORITHM */
img_pad = Halide::BoundaryConditions::repeat_edge( input );
//img_pad = Halide::BoundaryConditions::constant_exterior(input, 0);
//img_pad(x, y) = input(clamp(x, 0, input.width() - 1), clamp(y, 0, input.height() - 1));
//to uin16
img16(x, y) = cast<uint16_t>(img_pad(x, y));
// Magnitud gradient
gx(x, y) = (img16(x + 1, y) - img16(x - 1, y)) / 2;
gy(x, y) = (img16(x, y + 1) - img16(x, y - 1)) / 2;
g_mag(x, y) = gx(x, y) * gx(x, y) + gy(x, y) * gy(x, y);
//to uin8
g_edge(x, y) = cast<uint8_t>(g_mag(x, y));
output(x, y) = g_edge(x, y);
// Estimates (for autoscheduler; ignored otherwise)
{
input.dim(0).set_estimate(0, 4000);
input.dim(1).set_estimate(0, 3000);
output.set_estimate(x, 0, 4000)
.set_estimate(y, 0, 3000);
}
if (!auto_schedule) {
/* THE SCHEDULE */
gx.compute_root();
gy.compute_root();
g_mag.compute_root();
g_edge.compute_root();
}
}
};
HALIDE_REGISTER_GENERATOR(Edge, edge)
| [
"pedrodiamel@gmail.com"
] | pedrodiamel@gmail.com |
e84a190d79b5e5652669de2dd9c4da4ddc45a18f | 2149582d7cd9ace5d07618eebd5be5e4c27bb8c0 | /dipep_analysis/tests/double_test.cpp | e20b7035cacf6a3d87938dbf47c214afb28dbd65 | [] | no_license | graceli/labwork | 855d1fdc926d9b886d78466a72771e1f7f938340 | 6ef7af512a53ebde17eb9bc41410d8f1739827bb | refs/heads/master | 2020-04-15T09:29:23.119514 | 2014-01-22T02:16:16 | 2014-01-22T02:16:16 | 2,140,176 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 137 | cpp | #include <iostream>
int main(){
double a = 9.8995e-25;
double kb = 3.21e-27;
int T = 300;
std::cout<<kb*T<<std::endl;
return 0;
}
| [
"grace@tera"
] | grace@tera |
2a375f5364a4e08524e121d87dd7d327d1a380e6 | 0789ece36e772cd62a66010ed6d995f3310ddf52 | /files/test_driven/Boost.Test Documentation Rewrite/libs/test/doc/src/tutorials/hello_test/3/sut/hello.hpp | a31def4451c09bf0f0b0ccee9b597ca48727214d | [] | no_license | wygos/cppnow_presentations_2014 | 7a03ec4f7644920878a589478a22673e9c879aa7 | e5dc8951ed105357b7b10150dc8f87837de6edf4 | refs/heads/master | 2021-01-21T03:16:04.133038 | 2014-05-19T02:05:49 | 2014-05-19T02:05:49 | 19,926,500 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 146 | hpp | //[ hello_test_sut_hpp3
#if !defined(HELLO_HPP)
#define HELLO_HPP
#include <ostream>
extern void hello_world(std::ostream& stream);
#endif
//]
| [
"rayfix@gmail.com"
] | rayfix@gmail.com |
c1468bee5b82e593688198a8963c25bdcc16ddf0 | 3e7709aad8a8850f5d95f051a70797678b873649 | /PP17/Player.cpp | eef1a27bbdfda3e1c39366b81555d22afa944662 | [] | no_license | OhYouSeok/PP01.HelloSDL.20171200.- | 210998e62c0bbf8db70fe3fa42a1bafb5d7760ae | 43332bed2d3795848064c885a166be8ee28f8af8 | refs/heads/master | 2020-03-28T03:24:05.583773 | 2018-12-04T04:20:35 | 2018-12-04T04:20:35 | 147,642,430 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,486 | cpp | #include "Player.h"
#include "Game.h"
#include "BulletManager.h"
Player::Player(const LoaderParams* pParams) : SDLGameObject(pParams)
{
}
void Player::draw()
{
SDLGameObject::draw(); // we now use SDLGameObject
BulletManager::getInstance()->draw();
}
void Player::update()
{
BulletManager::getInstance()->update();
m_velocity.setX(0);
m_velocity.setY(0);
handleInput(); // add our function
SDLGameObject::update();
}
void Player::clean()
{
BulletManager::getInstance()->clean();
}
void Player::handleInput()
{
Vector2D* target = TheInputHandler::Instance()->getMousePosition();
m_velocity = *target - m_position;
m_velocity /= 50;
//if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_RIGHT))
//{
// m_velocity.setX(2);
//}
//if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_LEFT))
//{
// m_velocity.setX(-2);
//}
//if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_UP))
//{
// m_velocity.setY(-2);
//}
//if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_DOWN))
//{
// m_velocity.setY(2);
//}
//if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_1)) {
// TheGame::Instance()->clean();
//}
//if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_SPACE)) {
// /*m_Bullets.push_back(new Bullet(new LoaderParams(m_position.getX()+50, m_position.getY()+50, 10, 10, "bullet")));*/
// BulletManager::getInstance()->PushBackBullet(new Bullet(new LoaderParams(m_position.getX()+50, m_position.getY()+50, 10, 10, "bullet")));
//}
} | [
"20142355@vision.hoseo.edu"
] | 20142355@vision.hoseo.edu |
e8d7acbb2eb41e7a55580f0385a4d7a4821ed3f6 | ddbbbb86149e85df04ea75f8dbfd125522636b05 | /C language/zeeshanatalib77 - 04 Character type data.cpp | 63dea33098d628c93fb17355898d8de0bce07364 | [] | no_license | zeeshantalib/C-Programming-Language | 01ad1ce7a80d3a309fc38a4ebd82a5a1f283e765 | 7fb0b2de41ad9c0997e3fc305acbb4bd7f7d3a4f | refs/heads/master | 2022-11-20T09:17:12.764300 | 2022-10-25T01:16:49 | 2022-10-25T01:16:49 | 155,690,612 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 360 | cpp | #include<stdio.h>
#include<conio.h>
int main()
{
char ch1,ch2,sum;
// Here character type data is declared with keyword char.
ch1='2';
ch2='6';
sum=ch1+ch2;
printf("sum=%d",sum);
/* the sum of character 2 & 6 should be 104 ,because the ASCII value of
2 is 50 and of 6 is 54.*/
getch();
}
| [
"noreply@github.com"
] | noreply@github.com |
3a3a87745264e1364d155d42c7de17630261ea6c | a92b18defb50c5d1118a11bc364f17b148312028 | /src/prod/src/Reliability/Failover/ra/Infrastructure.EntityExecutionContext.h | 93f5e141a671653fdb9f7a60502c01afaa53827e | [
"MIT"
] | permissive | KDSBest/service-fabric | 34694e150fde662286e25f048fb763c97606382e | fe61c45b15a30fb089ad891c68c893b3a976e404 | refs/heads/master | 2023-01-28T23:19:25.040275 | 2020-11-30T11:11:58 | 2020-11-30T11:11:58 | 301,365,601 | 1 | 0 | MIT | 2020-11-30T11:11:59 | 2020-10-05T10:05:53 | null | UTF-8 | C++ | false | false | 3,984 | h | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#pragma once
namespace Reliability
{
namespace ReconfigurationAgentComponent
{
namespace Infrastructure
{
/*
This object represents some work that is executing on an entity
This allows us to hide away the RA and provide one object that can be transferred around
and allow entities to access different services (hosting, config, clock)
*/
class EntityExecutionContext
{
public:
EntityExecutionContext(
FailoverConfig const & config,
IClock const & clock,
Hosting::HostingAdapter & hosting,
StateMachineActionQueue & queue,
Federation::NodeInstance const & nodeInstance,
UpdateContext & updateContext,
IEntityStateBase const * state) :
config_(&config),
clock_(&clock),
hosting_(&hosting),
nodeInstance_(&nodeInstance),
stateUpdateContext_(queue, updateContext),
assertContext_(state)
{
}
__declspec(property(get = get_Config)) FailoverConfig const & Config;
FailoverConfig const & get_Config() const { return *config_; }
__declspec(property(get = get_Clock)) IClock const & Clock;
IClock const & get_Clock() const { return *clock_; }
__declspec(property(get = get_Queue)) StateMachineActionQueue & Queue;
StateMachineActionQueue & get_Queue() const { return stateUpdateContext_.ActionQueue; }
__declspec(property(get = get_Hosting)) Hosting::HostingAdapter & Hosting;
Hosting::HostingAdapter & get_Hosting() const { return *hosting_; }
__declspec(property(get = get_NodeInstance)) Federation::NodeInstance const & NodeInstance;
Federation::NodeInstance const & get_NodeInstance() const { return *nodeInstance_; }
__declspec(property(get = get_UpdateContextObj)) UpdateContext & UpdateContextObj;
UpdateContext & get_UpdateContextObj() const { return stateUpdateContext_.UpdateContextObj; }
__declspec(property(get = get_StateUpdateContextObj)) StateUpdateContext & StateUpdateContextObj;
StateUpdateContext & get_StateUpdateContextObj() { return stateUpdateContext_; }
__declspec(property(get = get_AssertContext)) EntityAssertContext const & AssertContext;
EntityAssertContext const & get_AssertContext() const { return assertContext_; }
template<typename T>
T & As()
{
return static_cast<T&>(*this);
}
template<typename T>
T const & As() const
{
return static_cast<T const &>(*this);
}
static EntityExecutionContext Create(
ReconfigurationAgent & ra,
StateMachineActionQueue & queue,
UpdateContext & updateContext,
IEntityStateBase const * state);
private:
Hosting::HostingAdapter * hosting_;
FailoverConfig const * config_;
IClock const * clock_;
StateUpdateContext stateUpdateContext_;
Federation::NodeInstance const * nodeInstance_;
EntityAssertContext assertContext_;
};
}
}
}
| [
"noreply-sfteam@microsoft.com"
] | noreply-sfteam@microsoft.com |
d6d8f0785b69b89f0df5231c58b5e9bc91516fb0 | ed997b3a8723cc9e77787c1d868f9300b0097473 | /libs/tti/test/test_mf_has_mem_fun_fail2.cpp | b7386c3b99984118fff95fab6cb12c3cdce9e4fd | [
"BSL-1.0"
] | permissive | juslee/boost-svn | 7ddb99e2046e5153e7cb5680575588a9aa8c79b2 | 6d5a03c1f5ed3e2b23bd0f3ad98d13ff33d4dcbb | refs/heads/master | 2023-04-13T11:00:16.289416 | 2012-11-16T11:14:39 | 2012-11-16T11:14:39 | 6,734,455 | 0 | 0 | BSL-1.0 | 2023-04-03T23:13:08 | 2012-11-17T11:21:17 | C++ | UTF-8 | C++ | false | false | 727 | cpp |
// (C) Copyright Edward Diener 2011
// Use, modification and distribution are subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt).
#include "test_mf_has_mem_fun.hpp"
#include <boost/mpl/assert.hpp>
#include <boost/tti/mf/mf_has_member_function.hpp>
int main()
{
using namespace boost::mpl::placeholders;
// Wrong function signature
BOOST_MPL_ASSERT((boost::tti::mf_has_member_function
<
FunctionReturningInt<_,_>,
boost::mpl::identity<AnotherType>,
short
>
));
return 0;
}
| [
"eldiener@b8fc166d-592f-0410-95f2-cb63ce0dd405"
] | eldiener@b8fc166d-592f-0410-95f2-cb63ce0dd405 |
9a17cfda843d7f4e78a154258f51969db0c23fae | db603264218ae05427128423839afc19e699af89 | /SmedbyCharger/Filter10.h | 6cc3b6446d9b873720a13ec91d1d61cf3d45217e | [] | no_license | itoaa/SmedbyCharger | 451d5548b221724287c1e1fc3bd9e2fe10746de9 | 9a7d5ca21353ae7c04c73b1d7233e9f42c22f9e2 | refs/heads/master | 2021-01-02T22:59:39.354125 | 2017-12-02T15:18:30 | 2017-12-02T15:18:30 | 99,433,663 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,142 | h | /*
* Filter10.h
*
* Created on: 5 aug. 2017
* Author: Ola Andersson
* Filter and buffer class ver 1.0 for Arduino ported to Eclipse and FreeRTOS
*
*/
#ifndef FILTER10_H_
#define FILTER10_H_
#include <Arduino.h>
#define filterSamples 13 // filterSamples should be an odd number, no smaller than 3
class Filter {
private:
int _sensArray1 [filterSamples]; // array for holding raw sensor values for sensor1
int _sensArray1Sort [filterSamples]; // array for holding raw sensor values for sensor2
int _bufferPosition;
int _bufferLength;
public:
Filter(int bufferLength); // BuffesLength = number of samples in buffer.
// virtual ~Filter();
int getValue(int index); // Get valu from buffer. index = position in buffer. (0 = newest value)
int getSortValue(int index); // Get value from sorted buffer. index = position in sorted buffer. (0 = lowes value)
int getFilteredValue(void); // Get filtered and averaged value based on buffer values.
void addValue(int value); // Add one valu to the buffer.
};
#endif /* FILTER10_H_ */
| [
"ola@smedby.net"
] | ola@smedby.net |
99a7f2f68ded18c8bf760f598704f63a5c8de150 | 73cadd555c96c8dadc57c2d69f8485b6bc77e366 | /SudokuGen_nine.h | 3c45fbe3e1f2ad1a14ef3feb9266026c7b723914 | [] | no_license | ol3577600/Sudoku_Game | 08dd2460aceb95eae0e49d95ca250392ff750478 | ba4f95d9fe9a2a2ab0a031f04ccf7f9ecfc3920d | refs/heads/master | 2020-03-09T07:19:02.321131 | 2018-04-08T17:01:25 | 2018-04-08T17:01:25 | 128,661,871 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,008 | h | #define SIZE1 9
#include <vector>
using namespace std;
class SudokuGen_nine
{
public:
SudokuGen_nine();
void generator(); //亂數法產生新棋盤 (初始化時建構子就會呼叫一次)
vector<int > get_board(); //輸出棋盤至vector變數
bool check_rep(vector<int>,int,int); //偵測填入數字是否重複、符合規則,不符合會回傳false值
bool board_put(vector<int>&); //填入數字函式,嘗試失敗超過1000次會回傳false值
void board_dig(vector<int>,int); //挖洞函式
void copy_board(); //複製棋盤函式
vector < vector <int> > All_board ; // 所有棋盤
vector < vector <int> > All_board_ANS ;
private:
int new_board[SIZE1][SIZE1]; //棋盤
int i,j,k,l,a,s; //迴圈用變數
int in_board[SIZE1][SIZE1]; //輸入棋盤
int dig_board[SIZE1][SIZE1]; //輸出棋盤(挖完洞)
int number_seres[SIZE1*SIZE1]; //數字序列
};
| [
"noreply@github.com"
] | noreply@github.com |
357fe502cdaa4b88a498b42c6dd247988e08c303 | 5838cf8f133a62df151ed12a5f928a43c11772ed | /NT/shell/cpls/inetcpl/security.cpp | 04cfce7c62be6f4bbab007422f7b4c7030c62215 | [] | no_license | proaholic/Win2K3 | e5e17b2262f8a2e9590d3fd7a201da19771eb132 | 572f0250d5825e7b80920b6610c22c5b9baaa3aa | refs/heads/master | 2023-07-09T06:15:54.474432 | 2021-08-11T09:09:14 | 2021-08-11T09:09:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 99,007 | cpp | //*********************************************************************
//* Microsoft Windows **
//* Copyright(c) Microsoft Corp., 1995 **
//*********************************************************************
//
// SECURITY.cpp - "Security" Property Sheet
//
// HISTORY:
//
// 6/22/96 t-gpease moved to this file
// 5/14/97 t-ashlm new dialog
#include "inetcplp.h"
#include "inetcpl.h" // for LSDFLAGS
#include "intshcut.h"
#include "permdlg.h" // java permissions
#include "pdlgguid.h" // guids for Java VM permissions dlg
#include "advpub.h"
#include <cryptui.h>
#include <mluisupp.h>
void LaunchSecurityDialogEx(HWND hDlg, DWORD dwZone, BOOL bForceUI, BOOL bDisableAddSites);
//
// Private Functions and Structures
//
INT_PTR CALLBACK SecurityAddSitesDlgProc(HWND hDlg, UINT uMsg, WPARAM wParam,LPARAM lParam);
INT_PTR CALLBACK SecurityCustomSettingsDlgProc(HWND hDlg, UINT uMsg, WPARAM wParam,LPARAM lParam);
INT_PTR CALLBACK SecurityAddSitesIntranetDlgProc(HWND hDlg, UINT uMsg, WPARAM wParam,LPARAM lParam);
void SecurityChanged();
TCHAR *MyIntToStr(TCHAR *pBuf, BYTE iVal);
BOOL SecurityDlgInit(HWND hDlg);
#define WIDETEXT(x) L ## x
#define REGSTR_PATH_SO TEXT("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\SO")
#define REGSTR_PATH_SOIEAK TEXT("Sofwtare\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\SOIEAK")
///////////////////////////////////////////////////////////////////////////////////////
//
// Structures
//
///////////////////////////////////////////////////////////////////////////////////////
typedef struct tagSECURITYZONESETTINGS
{
BOOL dwFlags; // from the ZONEATTRIBUTES struct
DWORD dwZoneIndex; // as defined by ZoneManager
DWORD dwSecLevel; // current level (High, Medium, Low, Custom)
DWORD dwPrevSecLevel;
DWORD dwMinSecLevel; // current min level (High, Medium, Low, Custom)
DWORD dwRecSecLevel; // current recommended level (High, Medium, Low, Custom)
TCHAR szDescription[MAX_ZONE_DESCRIPTION];
TCHAR szDisplayName[MAX_ZONE_PATH];
HICON hicon;
} SECURITYZONESETTINGS, *LPSECURITYZONESETTINGS;
// structure for main security page
typedef struct tagSECURITYPAGE
{
HWND hDlg; // handle to window
LPURLZONEMANAGER pInternetZoneManager; // pointer to InternetZoneManager
IInternetSecurityManager *pInternetSecurityManager; // pointer to InternetSecurityManager
HIMAGELIST himl; // imagelist for Zones combobox
HWND hwndZones; // zones combo box hwnd
LPSECURITYZONESETTINGS pszs; // current settings for displayed zone
INT iZoneSel; // selected zone (as defined by ComboBox)
DWORD dwZoneCount; // number of zones
BOOL fChanged;
BOOL fPendingChange; // to prevent the controls sending multiple sets (for cancel, mostly)
HINSTANCE hinstUrlmon;
BOOL fNoEdit; // hklm lockout of level edit
BOOL fNoAddSites; // hklm lockout of addsites
BOOL fNoZoneMapEdit; // hklm lockout of zone map edits
HFONT hfontBolded; // special bolded font created for the zone title
BOOL fForceUI; // Force every zone to show ui?
BOOL fDisableAddSites; // Automatically diable add sites button?
TCHAR szPageUrl[INTERNET_MAX_URL_LENGTH];
} SECURITYPAGE, *LPSECURITYPAGE;
// structure for Intranet Add Sites
typedef struct tagADDSITESINTRANETINFO {
HWND hDlg; // handle to window
BOOL fUseIntranet; // Use local defined intranet addresses (in reg)
BOOL fUseProxyExclusion; // Use proxy exclusion list
BOOL fUseUNC; // Include UNC in intranet
LPSECURITYPAGE pSec;
} ADDSITESINTRANETINFO, *LPADDSITESINTRANETINFO;
// structure for Add Sites
typedef struct tagADDSITESINFO {
HWND hDlg; // handle to window
BOOL fRequireServerVerification; // Require Server Verification on sites in zone
HWND hwndWebSites; // handle to list
HWND hwndAdd; // handle to edit
TCHAR szWebSite[MAX_ZONE_PATH]; // text in edit control
BOOL fRSVOld;
LPSECURITYPAGE pSec;
} ADDSITESINFO, *LPADDSITESINFO;
// structure for Custom Settings
typedef struct tagCUSTOMSETTINGSINFO {
HWND hDlg; // handle to window
HWND hwndTree;
LPSECURITYPAGE pSec;
HWND hwndCombo;
INT iLevelSel;
IRegTreeOptions *pTO;
BOOL fUseHKLM; // get/set settings from HKLM
DWORD dwJavaPolicy; // Java policy selected
BOOL fChanged;
} CUSTOMSETTINGSINFO, *LPCUSTOMSETTINGSINFO;
BOOL SecurityEnableControls(LPSECURITYPAGE pSec, BOOL fSetFocus);
BOOL SecurityDlgApplyNow(LPSECURITYPAGE pSec, BOOL bPrompt);
void SiteAlreadyInZoneMessage(HWND hwnd, DWORD dwZone);
// global variables
extern DWORD g_dwtlsSecInitFlags;
extern BOOL g_fSecurityChanged; // flag indicating that Active Security has changed.
//////////////////////////////////////////////////////////////////////////////
//
// Main Security Page Helper Functions
//
//////////////////////////////////////////////////////////////////////////////
#define NUM_TEMPLATE_LEVELS 4
TCHAR g_szLevel[3][64];
TCHAR LEVEL_DESCRIPTION0[300];
TCHAR LEVEL_DESCRIPTION1[300];
TCHAR LEVEL_DESCRIPTION2[300];
TCHAR LEVEL_DESCRIPTION3[300];
LPTSTR LEVEL_DESCRIPTION[NUM_TEMPLATE_LEVELS] = {
LEVEL_DESCRIPTION0,
LEVEL_DESCRIPTION1,
LEVEL_DESCRIPTION2,
LEVEL_DESCRIPTION3
};
TCHAR CUSTOM_DESCRIPTION[300];
TCHAR LEVEL_NAME0[30];
TCHAR LEVEL_NAME1[30];
TCHAR LEVEL_NAME2[30];
TCHAR LEVEL_NAME3[30];
LPTSTR LEVEL_NAME[NUM_TEMPLATE_LEVELS] = {
LEVEL_NAME0,
LEVEL_NAME1,
LEVEL_NAME2,
LEVEL_NAME3
};
TCHAR CUSTOM_NAME[30];
// Some accessibility related prototypes.
// Our override of the slider window proc.
LRESULT CALLBACK SliderSubWndProc (HWND hwndSlider, UINT uMsg, WPARAM wParam, LPARAM lParam, WPARAM uID, ULONG_PTR dwRefData );
extern BOOL g_fAttemptedOleAccLoad ;
extern HMODULE g_hOleAcc;
// Can't find value for WM_GETOBJECT in the headers. Need to figure out the right header to include
// here.
#ifndef WM_GETOBJECT
#define WM_GETOBJECT 0x03d
#endif
// Prototype for CreateStdAccessibleProxy.
// A and W versions are available - pClassName can be ANSI or UNICODE
// string. This is a TCHAR-style prototype, but you can do a A or W
// specific one if desired.
typedef HRESULT (WINAPI *PFNCREATESTDACCESSIBLEPROXY) (
HWND hWnd,
LPTSTR pClassName,
LONG idObject,
REFIID riid,
void ** ppvObject
);
/*
* Arguments:
*
* HWND hWnd
* Handle of window to return IAccessible for.
*
* LPTSTR pClassName
* Class name indicating underlying class of the window. For
* example, if "LISTBOX" is used here, the returned object will
* behave appropriately for a listbox, and will expect the given
* hWnd to support listbox messages and styles. This argument
* nearly always reflects the window class from which the control
* is derived.
*
* LONG idObject
* Always OBJID_CLIENT
*
* REFIID riid
* Always IID_IAccessible
*
* void ** ppvObject
* Out pointer used to return an IAccessible to a newly-created
* object which represents the control hWnd as though it were of
* window class pClassName.
*
* If successful,
* returns S_OK, *ppvObject != NULL;
* otherwise returns error HRESULT.
*
*
*/
// Same for LresultFromObject...
typedef LRESULT (WINAPI *PFNLRESULTFROMOBJECT)(
REFIID riid,
WPARAM wParam,
LPUNKNOWN punk
);
PRIVATE PFNCREATESTDACCESSIBLEPROXY s_pfnCreateStdAccessibleProxy = NULL;
PRIVATE PFNLRESULTFROMOBJECT s_pfnLresultFromObject = NULL;
// Simple accessibility wrapper class which returns the right string values
class CSecurityAccessibleWrapper: public CAccessibleWrapper
{
// Want to remember the hwnd of the trackbar...
HWND m_hWnd;
public:
CSecurityAccessibleWrapper( HWND hWnd, IAccessible * pAcc );
~CSecurityAccessibleWrapper();
STDMETHODIMP get_accValue(VARIANT varChild, BSTR* pszValue);
};
// Ctor - pass through the IAccessible we're wrapping to the
// CAccessibleWrapper base class; also remember the trackbar hwnd.
CSecurityAccessibleWrapper::CSecurityAccessibleWrapper( HWND hWnd, IAccessible * pAcc )
: CAccessibleWrapper( pAcc ),
m_hWnd( hWnd )
{
// Do nothing
}
// Nothing to do here - but if we do need to do cleanup, this is the
// place for it.
CSecurityAccessibleWrapper::~CSecurityAccessibleWrapper()
{
// Do nothing
}
// Overridden get_accValue method...
STDMETHODIMP CSecurityAccessibleWrapper::get_accValue(VARIANT varChild, BSTR* pszValue)
{
// varChild.lVal specifies which sub-part of the component
// is being queried.
// CHILDID_SELF (0) specifies the overall component - other
// non-0 values specify a child.
// In a trackbar, CHILDID_SELF refers to the overall trackbar
// (which is what we want), whereas other values refer to the
// sub-components - the actual slider 'thumb', and the 'page
// up/page down' areas to the left/right of it.
if( varChild.vt == VT_I4 && varChild.lVal == CHILDID_SELF )
{
// Get the scrollbar value...
int iPos = (int)SendMessage( m_hWnd, TBM_GETPOS , 0, 0 );
// Check that it's in range...
// (It's possible that we may get this request after the
// trackbar has been created, bu before we've set it to
// a meaningful value.)
if( iPos < 0 || iPos >= NUM_TEMPLATE_LEVELS )
{
TCHAR rgchUndefined[40];
int cch = MLLoadString(IDS_TEMPLATE_NAME_UNDEFINED, rgchUndefined, ARRAYSIZE(rgchUndefined));
if (cch != 0)
{
*pszValue = SysAllocString(rgchUndefined);
}
else
{
// Load String failed, for some reason.
return HRESULT_FROM_WIN32(GetLastError());
}
}
else
{
*pszValue = SysAllocString( LEVEL_NAME[iPos]);
}
// All done!
return S_OK;
}
else
{
// Pass requests about the sub-components to the
// base class (which will forward to the 'original'
// IAccessible for us).
return CAccessibleWrapper::get_accValue(varChild, pszValue);
}
}
// Converting the Security Level DWORD identitifiers to slider levels, and vice versa
int SecLevelToSliderPos(DWORD dwLevel)
{
switch(dwLevel)
{
case URLTEMPLATE_LOW:
return 3;
case URLTEMPLATE_MEDLOW:
return 2;
case URLTEMPLATE_MEDIUM:
return 1;
case URLTEMPLATE_HIGH:
return 0;
case URLTEMPLATE_CUSTOM:
return -1;
default:
return -2;
}
}
DWORD SliderPosToSecLevel(int iPos)
{
switch(iPos)
{
case 3:
return URLTEMPLATE_LOW;
case 2:
return URLTEMPLATE_MEDLOW;
case 1:
return URLTEMPLATE_MEDIUM;
case 0:
return URLTEMPLATE_HIGH;
default:
return URLTEMPLATE_CUSTOM;
}
}
int ZoneIndexToGuiIndex(DWORD dwZoneIndex)
// Product testing asked for the zones in a specific order in the list box;
// This function returns the desired gui position for a given zone
// Unrecognized zones are added to the front
{
int iGuiIndex = -1;
switch(dwZoneIndex)
{
// Intranet: 2nd spot
case 1:
iGuiIndex = 1;
break;
// Internet: 1st spot
case 3:
iGuiIndex = 0;
break;
// Trusted Sites: 3rd Spot
case 2:
iGuiIndex = 2;
break;
// Restricted Sites: 4th Spot
case 4:
iGuiIndex = 3;
break;
// unknown zone
default:
iGuiIndex = -1;
break;
}
return iGuiIndex;
}
// Initialize the global variables (to be destroyed at WM_DESTROY)
// pSec, Urlmon, pSec->pInternetZoneManager, pSec->hIml
// and set up the proper relationships among them
BOOL SecurityInitGlobals(LPSECURITYPAGE * ppSec, HWND hDlg, SECURITYINITFLAGS * psif)
{
DWORD cxIcon;
DWORD cyIcon;
LPSECURITYPAGE pSec = NULL;
*ppSec = (LPSECURITYPAGE)LocalAlloc(LPTR, sizeof(SECURITYPAGE));
pSec = *ppSec;
if (!pSec)
{
return FALSE; // no memory?
}
// make sure Urlmon stays around until we're done with it.
pSec->hinstUrlmon = LoadLibrary(TEXT("URLMON.DLL"));
if(pSec->hinstUrlmon == NULL)
{
return FALSE; // no urlmon?
}
// Get the zone manager
if (FAILED(CoInternetCreateZoneManager(NULL, &(pSec->pInternetZoneManager),0)))
{
return FALSE; // no zone manager?
}
// get our zones hwnd
if (hDlg)
{
pSec->hwndZones = GetDlgItem(hDlg, IDC_LIST_ZONE);
if(! pSec->hwndZones)
{
ASSERT(FALSE);
return FALSE; // no list box?
}
}
// Get the internet secrity manager (for telling if a zone is empty,
// and deciphering the current URL
if(FAILED(CoInternetCreateSecurityManager(NULL, &(pSec->pInternetSecurityManager), 0)))
pSec->pInternetSecurityManager = NULL;
// Store the URL for use by the Add Sites sub-dialog
StrCpyN(pSec->szPageUrl, g_szCurrentURL, ARRAYSIZE(pSec->szPageUrl));
// tell dialog where to get info
if (hDlg)
{
SetWindowLongPtr(hDlg, DWLP_USER, (LONG_PTR)pSec);
}
// save the handle to the page
pSec->hDlg = hDlg;
pSec->fPendingChange = FALSE;
// set dialog options: force ui and disable add sites
if(psif)
{
pSec->fForceUI = psif->fForceUI;
pSec->fDisableAddSites = psif->fDisableAddSites;
}
// create an imagelist for the ListBox
cxIcon = GetSystemMetrics(SM_CXICON);
cyIcon = GetSystemMetrics(SM_CYICON);
#ifndef UNIX
UINT flags = ILC_COLOR32|ILC_MASK;
if(IS_WINDOW_RTL_MIRRORED(hDlg))
{
flags |= ILC_MIRROR;
}
pSec->himl = ImageList_Create(cxIcon, cyIcon, flags, pSec->dwZoneCount, 0);
#else
pSec->himl = ImageList_Create(cxIcon, cyIcon, ILC_COLOR|ILC_MASK, pSec->dwZoneCount, 0);
#endif
if(! pSec->himl)
{
return FALSE; // Image list not created
}
if (hDlg)
{
SendMessage(pSec->hwndZones, LVM_SETIMAGELIST, (WPARAM)LVSIL_NORMAL, (LPARAM)pSec->himl);
}
return TRUE;
}
void FreePszs(SECURITYZONESETTINGS* pszs)
{
if (pszs->hicon)
DestroyIcon(pszs->hicon);
LocalFree((HLOCAL)pszs);
}
void SecurityFreeGlobals(SECURITYPAGE* pSec)
{
if(pSec->hwndZones)
{
for (int iIndex = (int)SendMessage(pSec->hwndZones, LVM_GETITEMCOUNT, 0, 0) - 1;
iIndex >= 0; iIndex--)
{
LV_ITEM lvItem;
// get security zone settings object for this item and release it
lvItem.mask = LVIF_PARAM;
lvItem.iItem = iIndex;
lvItem.iSubItem = 0;
if (SendMessage(pSec->hwndZones, LVM_GETITEM, (WPARAM)0, (LPARAM)&lvItem) == TRUE)
{
LPSECURITYZONESETTINGS pszs = (LPSECURITYZONESETTINGS)lvItem.lParam;
if (pszs)
{
FreePszs(pszs);
pszs = NULL;
}
}
}
}
if(pSec->pInternetZoneManager)
pSec->pInternetZoneManager->Release();
if(pSec->pInternetSecurityManager)
pSec->pInternetSecurityManager->Release();
if(pSec->himl)
ImageList_Destroy(pSec->himl);
if(pSec->hfontBolded)
DeleteObject(pSec->hfontBolded);
// ok, we're done with URLMON
if(pSec->hinstUrlmon)
FreeLibrary(pSec->hinstUrlmon);
LocalFree(pSec);
}
// Set up the variables in pSec about whether the zone settings can be editted
void SecuritySetEdit(LPSECURITYPAGE pSec)
{
// if these calls fail then we'll use the default of zero which means no lockout
DWORD cb;
cb = SIZEOF(pSec->fNoEdit);
SHGetValue(HKEY_LOCAL_MACHINE, REGSTR_PATH_SECURITY_LOCKOUT, REGSTR_VAL_OPTIONS_EDIT,
NULL, &(pSec->fNoEdit), &cb);
// also allow g_restrict to restrict changing settings
pSec->fNoEdit += g_restrict.fSecChangeSettings;
SHGetValue(HKEY_LOCAL_MACHINE, REGSTR_PATH_SECURITY_LOCKOUT, REGSTR_VAL_OPTIONS_EDIT,
NULL, &(pSec->fNoAddSites), &cb);
cb = SIZEOF(pSec->fNoZoneMapEdit);
SHGetValue(HKEY_LOCAL_MACHINE, REGSTR_PATH_SECURITY_LOCKOUT, REGSTR_VAL_ZONES_MAP_EDIT,
NULL, &(pSec->fNoZoneMapEdit), &cb);
// also allow the g_restrict to restrict edit
pSec->fNoAddSites += g_restrict.fSecAddSites;
}
// Fill a zone with information from the zone manager and add it to the
// ordered list going to the listbox
// REturn values:
// S_OK indicates success
// S_FALSE indicates a good state, but the zone was not added (example: flag ZAFLAGS_NO_UI)
// E_OUTOFMEMORY
// E_FAIL - other failure
HRESULT SecurityInitZone(DWORD dwIndex, LPSECURITYPAGE pSec, DWORD dwZoneEnumerator,
LV_ITEM * plviZones, BOOL * pfSpotTaken)
{
DWORD dwZone;
ZONEATTRIBUTES za = {0};
HICON hiconSmall = NULL;
HICON hiconLarge = NULL;
LPSECURITYZONESETTINGS pszs;
WORD iIcon=0;
LPWSTR psz;
TCHAR szIconPath[MAX_PATH];
int iSpot;
LV_ITEM * plvItem;
HRESULT hr = 0;
// get the zone attributes for this zone
za.cbSize = sizeof(ZONEATTRIBUTES);
pSec->pInternetZoneManager->GetZoneAt(dwZoneEnumerator, dwIndex, &dwZone);
hr = pSec->pInternetZoneManager->GetZoneAttributes(dwZone, &za);
if(FAILED(hr))
{
return S_FALSE;
}
// if no ui, then ignore
if ((za.dwFlags & ZAFLAGS_NO_UI) && !pSec->fForceUI)
{
return S_FALSE;
}
// create a structure for zone settings
pszs = (LPSECURITYZONESETTINGS)LocalAlloc(LPTR, sizeof(*pszs));
if (!pszs)
{
return E_OUTOFMEMORY;
}
// store settings for later use
pszs->dwFlags = za.dwFlags;
pszs->dwZoneIndex = dwZone;
pszs->dwSecLevel = za.dwTemplateCurrentLevel;
pszs->dwMinSecLevel = za.dwTemplateMinLevel;
pszs->dwRecSecLevel = za.dwTemplateRecommended;
StrCpyN(pszs->szDescription, za.szDescription, ARRAYSIZE(pszs->szDescription));
StrCpyN(pszs->szDisplayName, za.szDisplayName, ARRAYSIZE(pszs->szDisplayName));
// load the icon
psz = za.szIconPath;
if (*psz)
{
// search for the '#'
while ((psz[0] != WIDETEXT('#')) && (psz[0] != WIDETEXT('\0')))
psz++;
// if we found it, then we have the foo.dll#00001200 format
if (psz[0] == WIDETEXT('#'))
{
psz[0] = WIDETEXT('\0');
StrCpyN(szIconPath, za.szIconPath, ARRAYSIZE(szIconPath));
iIcon = (WORD)StrToIntW(psz+1);
CHAR szPath[MAX_PATH];
SHUnicodeToAnsi(szIconPath, szPath, ARRAYSIZE(szPath));
ExtractIconExA(szPath,(UINT)(-1*iIcon), &hiconLarge, &hiconSmall, 1);
}
else
{
hiconLarge = (HICON)ExtractAssociatedIcon(ghInstance, szIconPath, (LPWORD)&iIcon);
}
}
// no icons?! well, just use the generic icon
if (!hiconSmall && !hiconLarge)
{
hiconLarge = LoadIcon(ghInstance, MAKEINTRESOURCE(IDI_ZONE));
if(! hiconLarge)
{
LocalFree((HLOCAL)pszs);
return S_FALSE; // no icon found for this zone, not even the generic one
}
}
// we want to save the Large icon if possible for use in the subdialogs
pszs->hicon = hiconLarge ? hiconLarge : hiconSmall;
if (plviZones && pfSpotTaken)
{
// Find the proper index for the zone in the listbox (there is a user-preferred order)
iSpot = ZoneIndexToGuiIndex(dwIndex);
if(iSpot == -1)
{
// if not a recognized zone, add it to the end of the list
iSpot = pSec->dwZoneCount - 1;
}
// Make sure there are no collisisons
while(iSpot >= 0 && pfSpotTaken[iSpot] == TRUE)
{
iSpot--;
}
// Don't go past beginning of array
if(iSpot < 0)
{
// It can be proven that it is impossible to get here, unless there is
// something wrong with the function ZoneIndexToGuiIndex
ASSERT(FALSE);
LocalFree((HLOCAL)pszs);
if(hiconSmall)
DestroyIcon(hiconSmall);
if(hiconLarge)
DestroyIcon(hiconLarge);
return E_FAIL;
}
plvItem = &(plviZones[iSpot]);
pfSpotTaken[iSpot] = TRUE;
// init the List Box item and save it for later addition
plvItem->mask = LVIF_TEXT | LVIF_IMAGE | LVIF_PARAM;
plvItem->iItem = iSpot;
plvItem->iSubItem = 0;
// large icons prefered for the icon view (if switch back to report view, prefer small icons)
plvItem->iImage = ImageList_AddIcon(pSec->himl, hiconLarge ? hiconLarge : hiconSmall);
plvItem->pszText = new TCHAR[MAX_PATH];
if(! plvItem->pszText)
{
LocalFree((HLOCAL)pszs);
if(hiconSmall)
DestroyIcon(hiconSmall);
if(hiconLarge)
DestroyIcon(hiconLarge);
return E_OUTOFMEMORY;
}
MLLoadString( IDS_ZONENAME_LOCAL + dwIndex, plvItem->pszText, MAX_PATH);
plvItem->lParam = (LPARAM)pszs; // save the zone settings here
}
else
{
pSec->pszs = pszs;
}
// if we created a small icon, destroy it, since the system does not save the handle
// when it is added to the imagelist (see ImageList_AddIcon in VC help)
// Keep it around if we had to use it in place of the large icon
if (hiconSmall && hiconLarge)
DestroyIcon(hiconSmall);
return S_OK;
}
// Find the current zone from, in order of preference,
// Current URL
// Parameter passed in through dwZone
// Default of internet
void SecurityFindCurrentZone(LPSECURITYPAGE pSec, SECURITYINITFLAGS * psif)
{
INT_PTR iItem;
DWORD dwZone=0;
HRESULT hr = E_FAIL;
// Check for zone selection in psif
if(psif)
{
dwZone = psif->dwZone;
hr = S_OK;
}
// check for current url, and if found, make it's zone the current (overwriting any request from
// psif)
if (g_szCurrentURL[0] && (pSec->pInternetSecurityManager != NULL))
{
LPWSTR pwsz;
#ifndef UNICODE
WCHAR wszCurrentURL[MAX_URL_STRING];
MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, g_szCurrentURL, -1, wszCurrentURL, ARRAYSIZE(wszCurrentURL));
pwsz = wszCurrentURL;
#else
pwsz = g_szCurrentURL;
#endif
hr = pSec->pInternetSecurityManager->MapUrlToZone(pwsz, (LPDWORD)&dwZone, 0);
}
// If there is an active zone, then dwZone now holds the zone's identifier
// if there is no active zone, check to see if there was a zone requested in dwZone
iItem = -1;
if (SUCCEEDED(hr)) // then we have a zone to display
{
ZONEATTRIBUTES za = {0};
LPTSTR pszText;
LV_FINDINFO lvfiName;
za.cbSize = (ULONG) sizeof(ZONEATTRIBUTES);
if(pSec->pInternetZoneManager->GetZoneAttributes(dwZone, &za) != E_FAIL)
{
#ifdef UNICODE
pszText = za.szDisplayName;
#else
CHAR szDisplayName[MAX_ZONE_PATH];
WideCharToMultiByte(CP_ACP, 0, za.szDisplayName, -1, szDisplayName, ARRAYSIZE(szDisplayName), NULL, NULL);
pszText = szDisplayName;
#endif // UNICODE
// Create a find info structure to find the index of the Zone
lvfiName.flags = LVFI_STRING;
lvfiName.psz = pszText;
iItem = SendMessage(pSec->hwndZones, LVM_FINDITEM, (WPARAM)-1, (LPARAM)&lvfiName);
}
}
if (iItem < 0)
{
iItem = 0;
// 0 is the the index (in the listbox) of the "Internet" zone, which we want to come up by default
}
// Sundown: typecast OK since zone values restricted
pSec->iZoneSel = (int) iItem;
}
// To make the slider control accessbile we have to subclass it and over-ride
// the accessiblity object
void SecurityInitSlider(LPSECURITYPAGE pSec)
{
HWND hwndSlider = GetDlgItem(pSec->hDlg, IDC_SLIDER);
ASSERT(hwndSlider != NULL);
// Sub-class the control
BOOL fSucceeded = SetWindowSubclass(hwndSlider, SliderSubWndProc, 0, NULL);
// Shouldn't fail normally. If we fail we will just fall through and use the
// base slider control.
ASSERT(fSucceeded);
// Initialize the slider control (set number of levels, and frequency one tick per level)
SendDlgItemMessage(pSec->hDlg, IDC_SLIDER, TBM_SETRANGE, (WPARAM) (BOOL) FALSE, (LPARAM) MAKELONG(0, NUM_TEMPLATE_LEVELS - 1));
SendDlgItemMessage(pSec->hDlg, IDC_SLIDER, TBM_SETTICFREQ, (WPARAM) 1, (LPARAM) 0);
}
void SecurityInitControls(LPSECURITYPAGE pSec)
{
LV_COLUMN lvCasey;
LV_ITEM lvItem;
// select the item in the listbox
lvItem.mask = LVIF_STATE;
lvItem.stateMask = LVIS_SELECTED;
lvItem.state = LVIS_SELECTED;
SendMessage(pSec->hwndZones, LVM_SETITEMSTATE, (WPARAM)pSec->iZoneSel, (LPARAM)&lvItem);
// get the zone settings for the selected item
lvItem.mask = LVIF_PARAM;
lvItem.iItem = pSec->iZoneSel;
lvItem.iSubItem = 0;
SendMessage(pSec->hwndZones, LVM_GETITEM, (WPARAM)0, (LPARAM)&lvItem);
pSec->pszs = (LPSECURITYZONESETTINGS)lvItem.lParam;
// Initialize the local strings to carry the Level Descriptions
MLLoadString(IDS_TEMPLATE_DESC_HI, LEVEL_DESCRIPTION0, ARRAYSIZE(LEVEL_DESCRIPTION0));
MLLoadString(IDS_TEMPLATE_DESC_MED, LEVEL_DESCRIPTION1, ARRAYSIZE(LEVEL_DESCRIPTION1));
MLLoadString(IDS_TEMPLATE_DESC_MEDLOW, LEVEL_DESCRIPTION2, ARRAYSIZE(LEVEL_DESCRIPTION2));
MLLoadString(IDS_TEMPLATE_DESC_LOW, LEVEL_DESCRIPTION3, ARRAYSIZE(LEVEL_DESCRIPTION3));
MLLoadString(IDS_TEMPLATE_DESC_CUSTOM, CUSTOM_DESCRIPTION, ARRAYSIZE(CUSTOM_DESCRIPTION));
MLLoadString(IDS_TEMPLATE_NAME_HI, LEVEL_NAME0, ARRAYSIZE(LEVEL_NAME0));
MLLoadString(IDS_TEMPLATE_NAME_MED, LEVEL_NAME1, ARRAYSIZE(LEVEL_NAME1));
MLLoadString(IDS_TEMPLATE_NAME_MEDLOW, LEVEL_NAME2, ARRAYSIZE(LEVEL_NAME2));
MLLoadString(IDS_TEMPLATE_NAME_LOW, LEVEL_NAME3, ARRAYSIZE(LEVEL_NAME3));
MLLoadString(IDS_TEMPLATE_NAME_CUSTOM, CUSTOM_NAME, ARRAYSIZE(CUSTOM_NAME));
// Initialize text boxes and icons for the current zone
WCHAR wszBuffer[ MAX_PATH*2];
MLLoadString( IDS_ZONEDESC_LOCAL + pSec->pszs->dwZoneIndex, wszBuffer, ARRAYSIZE(wszBuffer));
SetDlgItemText(pSec->hDlg, IDC_ZONE_DESCRIPTION, wszBuffer);
MLLoadString( IDS_ZONENAME_LOCAL + pSec->pszs->dwZoneIndex, wszBuffer, ARRAYSIZE(wszBuffer));
SetDlgItemText(pSec->hDlg, IDC_ZONELABEL, wszBuffer);
SendDlgItemMessage(pSec->hDlg, IDC_ZONE_ICON, STM_SETIMAGE, (WPARAM)IMAGE_ICON, (LPARAM)pSec->pszs->hicon);
// Initialize the slider control
SecurityInitSlider(pSec);
// Initialize the list view (add column 0 for icon and text, and autosize it)
lvCasey.mask = 0;
SendDlgItemMessage(pSec->hDlg, IDC_LIST_ZONE, LVM_INSERTCOLUMN, (WPARAM) 0, (LPARAM) &lvCasey);
SendDlgItemMessage(pSec->hDlg, IDC_LIST_ZONE, LVM_SETCOLUMNWIDTH, (WPARAM) 0, (LPARAM) MAKELPARAM(LVSCW_AUTOSIZE, 0));
// Set the font of the name to the bold font
pSec->hfontBolded = NULL;
HFONT hfontOrig = (HFONT) SendDlgItemMessage(pSec->hDlg, IDC_STATIC_EMPTY, WM_GETFONT, (WPARAM) 0, (LPARAM) 0);
if(hfontOrig == NULL)
hfontOrig = (HFONT) GetStockObject(SYSTEM_FONT);
// set the zone name and level font to bolded
if(hfontOrig)
{
LOGFONT lfData;
if(GetObject(hfontOrig, SIZEOF(lfData), &lfData) != 0)
{
// The distance from 400 (normal) to 700 (bold)
lfData.lfWeight += 300;
if(lfData.lfWeight > 1000)
lfData.lfWeight = 1000;
pSec->hfontBolded = CreateFontIndirect(&lfData);
if(pSec->hfontBolded)
{
// the zone level and zone name text boxes should have the same font, so this is okat
SendDlgItemMessage(pSec->hDlg, IDC_ZONELABEL, WM_SETFONT, (WPARAM) pSec->hfontBolded, (LPARAM) MAKELPARAM(FALSE, 0));
SendDlgItemMessage(pSec->hDlg, IDC_LEVEL_NAME, WM_SETFONT, (WPARAM) pSec->hfontBolded, (LPARAM) MAKELPARAM(FALSE, 0));
}
}
}
/*
{
// calculate the postions of the static text boxes for the "The current level is:" "<bold>(Level)</bold>" message
TCHAR * pszText = NULL;
LONG lLength = 30;
HDC hdc = NULL;
SIZE size;
RECT rect;
LONG lNameLeftPos = 0;
// Get the text from the "The current level is" box.
lLength = SendDlgItemMessage(pSec->hDlg, IDC_SEC_STATIC_CURRENT_LEVEL, WM_GETTEXTLENGTH,
(WPARAM) 0, (LPARAM) 0);
pszText = new TCHAR[lLength + 1];
if(!pszText)
goto Exit; // E_OUTOFMEMORY
SendDlgItemMessage(pSec->hDlg, IDC_SEC_STATIC_CURRENT_LEVEL, WM_GETTEXT, (WPARAM) lLength,
(LPARAM) pszText);
// get the device context
hdc = GetDC(GetDlgItem(pSec->hDlg, IDC_SEC_STATIC_CURRENT_LEVEL));
if(! hdc)
goto Exit;
// get the length of the text from the device context; assumes the proper font is already in
if(GetTextExtentPoint32(hdc, pszText, lLength, &size) == 0)
goto Exit;
// set the width of the "The current level is" box
GetClientRect(GetDlgItem(pSec->hDlg, IDC_SEC_STATIC_CURRENT_LEVEL), &rect);
rect.right = rect.left + size.cx;
lNameLeftPos = rect.right;
if(MoveWindow(GetDlgItem(pSec->hDlg, IDC_SEC_STATIC_CURRENT_LEVEL), rect.left, rect.top,
rect.right - rect.left, rect.top - rect.bottom, FALSE) == 0)
goto Exit;
// set the x position of the level name box
GetClientRect(GetDlgItem(pSec->hDlg, IDC_LEVEL_NAME), &rect);
rect.left = lNameLeftPos;
if(MoveWindow(GetDlgItem(pSec->hDlg, IDC_LEVEL_NAME), rect.left,
rect.top, rect.right - rect.left, rect.top - rect.bottom, FALSE) == 0)
goto Exit;
Exit:
if(hdc)
ReleaseDC(GetDlgItem(pSec->hDlg, IDC_SEC_STATIC_CURRENT_LEVEL), hdc);
if(pszText)
delete pszText;
}
*/
}
//
// SecurityDlgInit()
//
// Does initalization for Security Dlg.
//
// History:
//
// 6/17/96 t-gpease remove 'gPrefs', cleaned up code
// 6/20/96 t-gpease UI changes
// 5/14/97 t-ashlm UI changes
//
// 7/02/97 t-mattp UI changes (slider, listbox)
//
// hDlg is the handle to the SecurityDialog window
// psif holds initialization parameters. In the case of our entry point
// from shdocvw (ie, double click browser zone icon, view-internetoptions-security, or right click
// on desktop icon), it can be NULL
BOOL SecurityDlgInit(HWND hDlg, SECURITYINITFLAGS * psif)
{
LPSECURITYPAGE pSec = NULL;
UINT iIndex = 0;
HRESULT hr = 0;
DWORD dwZoneEnumerator;
// Initialize globals variables (to be destroyed at WM_DESTROY)
if(SecurityInitGlobals(&pSec, hDlg, psif) == FALSE)
{
EndDialog(hDlg, 0);
return FALSE; // Initialization failed
}
// Get a (local) enumerator for the zones
if (FAILED(pSec->pInternetZoneManager->
CreateZoneEnumerator(&dwZoneEnumerator, &(pSec->dwZoneCount), 0)))
{
EndDialog(hDlg, 0);
return FALSE; // no zone enumerator?
}
// Set up the variables in pSec about whether the zone settings can be editted
SecuritySetEdit(pSec);
// Add the Listbox items for the zones
// The zones have to be added in a particular order
// Array used to order zones for adding
LV_ITEM * plviZones = new LV_ITEM[pSec->dwZoneCount];
BOOL * pfSpotTaken = new BOOL[pSec->dwZoneCount];
// bail out if there were any allocation failures
if ((plviZones == NULL) || (pfSpotTaken == NULL))
{
if (plviZones)
delete [] plviZones;
if (pfSpotTaken)
delete [] pfSpotTaken;
pSec->pInternetZoneManager->DestroyZoneEnumerator(dwZoneEnumerator);
EndDialog(hDlg, 0);
return FALSE;
}
for(iIndex =0; iIndex < pSec->dwZoneCount; iIndex++)
pfSpotTaken[iIndex] = FALSE;
// propogate zone dropdown
for (DWORD dwIndex=0; dwIndex < pSec->dwZoneCount; dwIndex++)
{
if(FAILED(SecurityInitZone(dwIndex, pSec, dwZoneEnumerator, plviZones, pfSpotTaken)))
{
// Delete all memory allocated for any previous zones (which have not yet been added to
// the listbox)
for(iIndex = 0; iIndex < pSec->dwZoneCount; iIndex++)
{
if(pfSpotTaken[iIndex] && (LPSECURITYZONESETTINGS) (plviZones[iIndex].lParam) != NULL)
{
LocalFree((LPSECURITYZONESETTINGS) (plviZones[iIndex].lParam));
plviZones[iIndex].lParam = NULL;
if(plviZones[iIndex].pszText)
delete [] plviZones[iIndex].pszText;
}
}
delete [] plviZones;
delete [] pfSpotTaken;
pSec->pInternetZoneManager->DestroyZoneEnumerator(dwZoneEnumerator);
EndDialog(hDlg, 0);
return FALSE;
}
}
pSec->pInternetZoneManager->DestroyZoneEnumerator(dwZoneEnumerator);
// Add all of the arrayed listitems to the listbox
for(iIndex = 0; iIndex < pSec->dwZoneCount; iIndex++)
{
if(pfSpotTaken[iIndex])
{
SendMessage(pSec->hwndZones, LVM_INSERTITEM, (WPARAM)0, (LPARAM)&(plviZones[iIndex]));
delete [] plviZones[iIndex].pszText;
}
}
delete [] plviZones;
delete [] pfSpotTaken;
SecurityFindCurrentZone(pSec, psif);
SecurityInitControls(pSec);
SecurityEnableControls(pSec, FALSE);
return TRUE;
}
void SecurityChanged()
{
TCHAR szClassName[32];
HWND hwnd = GetTopWindow(GetDesktopWindow());
//
// FEATURE: These should be gotten from some place that is public
// to both MSHTML and INETCPL.
//
while (hwnd) {
GetClassName(hwnd, szClassName, ARRAYSIZE(szClassName));
// notify all "browser" windows that security has changed
if (!StrCmpI(szClassName, TEXT("ExploreWClass")) ||
!StrCmpI(szClassName, TEXT("IEFrame")) ||
!StrCmpI(szClassName, TEXT("CabinetWClass")))
{
// yes... post it a message..
PostMessage(hwnd, CWM_GLOBALSTATECHANGE, CWMF_SECURITY, 0L );
}
hwnd = GetNextWindow(hwnd, GW_HWNDNEXT);
}
}
int SecurityWarning(LPSECURITYPAGE pSec)
{
TCHAR szWarning[64];
TCHAR szBuf[512];
TCHAR szMessage[512];
TCHAR szLevel[64];
// Load "Warning!"
MLLoadShellLangString(IDS_WARNING, szWarning, ARRAYSIZE(szWarning));
// Load "It is not recommended...."
MLLoadShellLangString(IDS_SECURITY_WARNING, szBuf, ARRAYSIZE(szBuf));
// Load level: "High, Medium, Medium Low, Low"
if (pSec->pszs->dwMinSecLevel == URLTEMPLATE_HIGH)
MLLoadShellLangString(IDS_TEMPLATE_NAME_HI, szLevel, ARRAYSIZE(szLevel));
else if (pSec->pszs->dwMinSecLevel == URLTEMPLATE_MEDIUM)
MLLoadShellLangString(IDS_TEMPLATE_NAME_MED, szLevel, ARRAYSIZE(szLevel));
else if (pSec->pszs->dwMinSecLevel == URLTEMPLATE_MEDLOW)
MLLoadShellLangString(IDS_TEMPLATE_NAME_MEDLOW, szLevel, ARRAYSIZE(szLevel));
else
MLLoadShellLangString(IDS_TEMPLATE_NAME_LOW, szLevel, ARRAYSIZE(szLevel));
wnsprintf(szMessage, ARRAYSIZE(szMessage), szBuf, szLevel);
return MessageBox(pSec->hDlg,szMessage,szWarning, MB_ICONWARNING | MB_YESNO | MB_DEFBUTTON2);
}
int RegWriteWarning(HWND hParent)
{
TCHAR szWarning[64];
TCHAR szWriteWarning[128];
// load "Warning!"
MLLoadShellLangString(IDS_WARNING, szWarning, ARRAYSIZE(szWarning));
// Load "You are about to write..."
MLLoadShellLangString(IDS_WRITE_WARNING, szWriteWarning, ARRAYSIZE(szWriteWarning));
return MessageBox(hParent,szWriteWarning, szWarning, MB_ICONWARNING | MB_YESNO | MB_DEFBUTTON2);
}
BOOL SecurityEnableControls(LPSECURITYPAGE pSec, BOOL fSetFocus)
// Duties:
// Make the controls (slider, en/disabled buttons) match the data for the current zone
// Make the views (Level description text) match the data for the current zone
// Set focus (to slider, if enabled, else custom settings button, if enabled, else
// listbox) if fSetFocus is TRUE
// Note: the zone descriptions are not set here; those are handled by the code responsible
// for changing zones
{
int iLevel = -1;
if (pSec && pSec->pszs)
{
HWND hwndSlider = GetDlgItem(pSec->hDlg, IDC_SLIDER);
iLevel = SecLevelToSliderPos(pSec->pszs->dwSecLevel);
ASSERT(iLevel > -2);
// Set the level of the slider to the setting for the current zone
// Show or hide the slider for preset levels/custom
// Set the level description text
if(iLevel >= 0)
{
SendMessage(hwndSlider, TBM_SETPOS, (WPARAM) (BOOL) TRUE, (LPARAM) (LONG) iLevel);
// Make sure the slider is visible
ShowWindow(hwndSlider, SW_SHOW);
ShowWindow(GetDlgItem(pSec->hDlg, IDC_STATIC_SLIDERMOVETEXT), SW_SHOW);
SetDlgItemText(pSec->hDlg, IDC_LEVEL_DESCRIPTION, LEVEL_DESCRIPTION[iLevel]);
SetDlgItemText(pSec->hDlg, IDC_LEVEL_NAME, LEVEL_NAME[iLevel]);
}
else
{
// Hide the slider for custom
ShowWindow(hwndSlider, SW_HIDE);
ShowWindow(GetDlgItem(pSec->hDlg, IDC_STATIC_SLIDERMOVETEXT), SW_HIDE);
SetDlgItemText(pSec->hDlg, IDC_LEVEL_DESCRIPTION, CUSTOM_DESCRIPTION);
SetDlgItemText(pSec->hDlg, IDC_LEVEL_NAME, CUSTOM_NAME);
}
// If the zone is empty, show the "zone is empty" string
// Default is to not show the sting (if something goes wrong)
// Empty zone not possible for internet, intranet, or local zones
if((pSec->pszs->dwZoneIndex != URLZONE_INTRANET &&
pSec->pszs->dwZoneIndex != URLZONE_INTERNET) &&
pSec->pszs->dwZoneIndex != URLZONE_LOCAL_MACHINE &&
(pSec->pInternetSecurityManager != NULL))
{
IEnumString * piesZones = NULL;
LPOLESTR ppszDummy[1];
pSec->pInternetSecurityManager->GetZoneMappings(pSec->pszs->dwZoneIndex, &piesZones, 0);
// If enumerator can not get 1 item, zone is empty (not valid for internet and intranet)
if(piesZones && (piesZones->Next(1, ppszDummy, NULL) == S_FALSE))
{
ShowWindow(GetDlgItem(pSec->hDlg, IDC_STATIC_EMPTY), SW_SHOW);
}
else
{
ShowWindow(GetDlgItem(pSec->hDlg, IDC_STATIC_EMPTY), SW_HIDE);
}
if(piesZones)
piesZones->Release();
}
else
{
ShowWindow(GetDlgItem(pSec->hDlg, IDC_STATIC_EMPTY), SW_HIDE);
}
// If we were told to set focus then move focus to the slider.
if (fSetFocus)
{
if(!pSec->fNoEdit)
{
if(iLevel >= 0)
SetFocus(hwndSlider);
else if(pSec->pszs->dwFlags & ZAFLAGS_CUSTOM_EDIT)
SetFocus(GetDlgItem(pSec->hDlg, IDC_BUTTON_SETTINGS));
else
SetFocus(GetDlgItem(pSec->hDlg, IDC_LIST_ZONE));
}
else // No focus is allowed, set focus to the list box
{
SetFocus(GetDlgItem(pSec->hDlg, IDC_LIST_ZONE));
}
}
BOOL fEdit = !(pSec->fNoEdit || (IEHardened() && !IsNTAdmin(0, NULL)));
EnableWindow(hwndSlider, (iLevel >= 0) && fEdit);
EnableWindow(GetDlgItem(pSec->hDlg, IDC_ZONE_RESET),
fEdit && (pSec->pszs->dwSecLevel != pSec->pszs->dwRecSecLevel));
EnableWindow(GetDlgItem(pSec->hDlg, IDC_BUTTON_SETTINGS),
(pSec->pszs->dwFlags & ZAFLAGS_CUSTOM_EDIT) && fEdit);
EnableWindow(GetDlgItem(pSec->hDlg, IDC_BUTTON_ADD_SITES),
(pSec->pszs->dwFlags & ZAFLAGS_ADD_SITES) && !pSec->fDisableAddSites);
return TRUE;
}
return FALSE;
}
void SecuritySetLevel(DWORD dwLevel, LPSECURITYPAGE pSec)
{
// All calls to this function are requests to change the security
// level for the current zone
// dwLevel = requested level template (URLTEMPLATE_???)
int iPos = SecLevelToSliderPos(dwLevel);
ASSERT(iPos != -2);
BOOL bCanceled = FALSE;
// Do nothing if the requested level is equal to the current level
if(dwLevel != pSec->pszs->dwSecLevel)
{
// Pop up warning box if under recommended min level and lowering security (custom N/A)
if((pSec->pszs->dwMinSecLevel > dwLevel) && (pSec->pszs->dwSecLevel > dwLevel)
&& (dwLevel != URLTEMPLATE_CUSTOM))
{
if(SecurityWarning(pSec) == IDNO)
{
bCanceled = TRUE;
}
}
if(! bCanceled)
{
// Set the level
pSec->pszs->dwPrevSecLevel = pSec->pszs->dwSecLevel;
pSec->pszs->dwSecLevel = dwLevel;
ENABLEAPPLY(pSec->hDlg);
//Tell apply and ok that settings have been changed
pSec->fChanged = TRUE;
}
// Sync the controls to the new level (or back to the old if cancelled)
SecurityEnableControls(pSec, TRUE);
}
// Record that the change request has been handled
pSec->fPendingChange = FALSE;
}
//
// SecurityDlgApplyNow()
//
// Retrieves the user's choices in dlg ctls,
// and saves them through SecurityManager interfaces
// If bSaveAll is true, the data for all zones is saved,
// if false, only the current
// Return value is whether the changes were okayed
//
BOOL SecurityDlgApplyNow(LPSECURITYPAGE pSec, BOOL bSaveAll)
{
if (pSec->fChanged)
{
for (int iIndex = (int)SendMessage(pSec->hwndZones, LVM_GETITEMCOUNT, 0, 0) - 1;
iIndex >= 0; iIndex--)
{
if(!((bSaveAll) || (iIndex == pSec->iZoneSel)))
continue;
LV_ITEM lvItem = {0};
ZONEATTRIBUTES za = {0};
LPSECURITYZONESETTINGS pszs;
// get the item settings
lvItem.mask = LVIF_PARAM;
lvItem.iItem = iIndex;
lvItem.iSubItem = 0;
if(SendMessage(pSec->hwndZones, LVM_GETITEM, (WPARAM)0, (LPARAM)&lvItem))
{
pszs = (LPSECURITYZONESETTINGS)lvItem.lParam;
za.cbSize = sizeof(ZONEATTRIBUTES);
pSec->pInternetZoneManager->GetZoneAttributes(pszs->dwZoneIndex, &za);
za.dwTemplateCurrentLevel = pszs->dwSecLevel;
pSec->pInternetZoneManager->SetZoneAttributes(pszs->dwZoneIndex, &za);
// Custom settings are saved on exit from the Custom Settings window
}
}
UpdateAllWindows();
SecurityChanged();
if (bSaveAll)
{
// if bSaveAll is false, that means we're saving the info for one zone, but not
// the others. This happens when you have custom settings for a particular zone
// However, other zones may have been changed to only one of the standard settings
// We need to ensure that those settings also get saved when the user clicks OK/Apply.
pSec->fChanged = FALSE;
}
}
return TRUE;
}
//
// SecurityOnCommand()
//
// Handles Security Dialog's window messages
//
// History:
//
// 6/17/96 t-gpease created
// 5/14/97 t-ashlm ui changes
//
void SecurityOnCommand(LPSECURITYPAGE pSec, UINT id, UINT nCmd)
{
switch (id)
{
case IDC_BUTTON_ADD_SITES:
{
if (pSec->pszs->dwZoneIndex == URLZONE_INTRANET && !IEHardened())
{
DialogBoxParam(MLGetHinst(), MAKEINTRESOURCE(IDD_SECURITY_INTRANET), pSec->hDlg,
SecurityAddSitesIntranetDlgProc, (LPARAM)pSec);
}
else
{
DialogBoxParam(MLGetHinst(), MAKEINTRESOURCE(IDD_SECURITY_ADD_SITES), pSec->hDlg,
SecurityAddSitesDlgProc, (LPARAM)pSec);
}
// Resynch controls (in case the "zone is empty" message needs to be updated)
SecurityEnableControls(pSec, FALSE);
}
break;
case IDC_BUTTON_SETTINGS:
{
// Note: messages to change the level from preset to custom as a result of this call
// are sent by the CustomSettings dialog
DialogBoxParam(MLGetHinst(), MAKEINTRESOURCE(IDD_SECURITY_CUSTOM_SETTINGS), pSec->hDlg,
SecurityCustomSettingsDlgProc, (LPARAM)pSec);
break;
}
case IDC_ZONE_RESET:
if(!pSec->fPendingChange && pSec->pszs->dwSecLevel != pSec->pszs->dwRecSecLevel)
{
pSec->fPendingChange = TRUE;
PostMessage(pSec->hDlg, WM_APP, (WPARAM) 0, (LPARAM) pSec->pszs->dwRecSecLevel);
}
break;
case IDOK:
SecurityDlgApplyNow(pSec, TRUE);
EndDialog(pSec->hDlg, IDOK);
break;
case IDCANCEL:
EndDialog(pSec->hDlg, IDCANCEL);
break;
case IDC_SLIDER:
{
// Get the current slider position
// Sundown: forced typecast to int, slider positions are restricted
int iPos = (int) SendDlgItemMessage(pSec->hDlg, IDC_SLIDER, TBM_GETPOS, (WPARAM) 0, (LPARAM) 0);
if(nCmd == TB_THUMBTRACK)
{
// on Mouse Move, change the level description only
SetDlgItemText(pSec->hDlg, IDC_LEVEL_DESCRIPTION, LEVEL_DESCRIPTION[iPos]);
SetDlgItemText(pSec->hDlg, IDC_LEVEL_NAME, LEVEL_NAME[iPos]);
}
else
{
// Request that the current zone's security level be set to the corresponding level
DWORD_PTR dwLevel = SliderPosToSecLevel(iPos);
if(! pSec->fPendingChange)
{
pSec->fPendingChange = TRUE;
PostMessage(pSec->hDlg, WM_APP, (WPARAM) 0, (LPARAM) dwLevel);
}
}
}
break;
case IDC_LIST_ZONE:
{
// Sundown: coercion to int-- selection is range-restricted
int iNewSelection = (int) SendMessage(pSec->hwndZones, LVM_GETNEXTITEM, (WPARAM)-1,
MAKELPARAM(LVNI_SELECTED, 0));
if ((iNewSelection != pSec->iZoneSel) && (iNewSelection != -1))
{
LV_ITEM lvItem;
lvItem.iItem = iNewSelection;
lvItem.iSubItem = 0;
lvItem.mask = LVIF_PARAM;
SendMessage(pSec->hwndZones, LVM_GETITEM, (WPARAM)0, (LPARAM)&lvItem);
pSec->pszs = (LPSECURITYZONESETTINGS)lvItem.lParam;
pSec->iZoneSel = iNewSelection;
WCHAR wszBuffer[ MAX_PATH*2];
MLLoadString( IDS_ZONEDESC_LOCAL + pSec->pszs->dwZoneIndex, wszBuffer, ARRAYSIZE(wszBuffer));
SetDlgItemText(pSec->hDlg, IDC_ZONE_DESCRIPTION, wszBuffer);
MLLoadString( IDS_ZONENAME_LOCAL + pSec->pszs->dwZoneIndex, wszBuffer, ARRAYSIZE(wszBuffer));
SetDlgItemText(pSec->hDlg, IDC_ZONELABEL, wszBuffer);
SendDlgItemMessage(pSec->hDlg, IDC_ZONE_ICON, STM_SETIMAGE, (WPARAM)IMAGE_ICON, (LPARAM)pSec->pszs->hicon);
SecurityEnableControls(pSec, FALSE);
}
break;
}
}
} // SecurityOnCommand()
//
// SecurityDlgProc()
//
// Handles Security Dialog's window messages
//
// History:
//
// 6/17/96 t-gpease created
// 5/14/97 t-ashlm ui changes
//
INT_PTR CALLBACK SecurityDlgProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
LPSECURITYPAGE pSec;
if (uMsg == WM_INITDIALOG)
{
// A hack forced by PropertyPage:
// PropertyPage creates this dialog in mainwnd.cpp when the dialog is entered from
// the desktop e's properties, the browser's menu view-internetoptions-security, or
// right clicking on the browser's zone icon.
// In the property page case, lParam (our only route to get initialization information
// in) is a pointer to a PROPERTYSHEETHEADER, more or less, and of entirely no use to us.
// However, when called from our exported function LaunchSecurityDialogEx, using
// CreateDialogParamWrapW, we want to pass useful information in. The only way to make sure
// we our dealing with useful information is to make the passed in pointer be to a
// structure we know and love, and hence could not possibly be pointed to by PropertyPage.
// We use a ThreadLocalStorage object, as our information reference
SECURITYINITFLAGS * psif = NULL;
if(g_dwtlsSecInitFlags != (DWORD) -1)
psif = (SECURITYINITFLAGS *) TlsGetValue(g_dwtlsSecInitFlags);
if((SECURITYINITFLAGS *) lParam != psif)
psif = NULL;
return SecurityDlgInit(hDlg, psif);
}
pSec = (LPSECURITYPAGE)GetWindowLongPtr(hDlg, DWLP_USER);
if (!pSec)
return FALSE;
switch (uMsg)
{
case WM_COMMAND:
SecurityOnCommand(pSec, LOWORD(wParam), HIWORD(wParam));
return TRUE;
case WM_NOTIFY:
{
NMHDR *lpnm = (NMHDR *) lParam;
ASSERT(lpnm);
// List Box Messages
if(lpnm->idFrom == IDC_LIST_ZONE)
{
NM_LISTVIEW * lplvnm = (NM_LISTVIEW *) lParam;
if(lplvnm->hdr.code == LVN_ITEMCHANGED)
{
// If an item's state has changed, and it is now selected
if(((lplvnm->uChanged & LVIF_STATE) != 0) && ((lplvnm->uNewState & LVIS_SELECTED) != 0))
{
SecurityOnCommand(pSec, IDC_LIST_ZONE, LVN_ITEMCHANGED);
}
}
}
else
{
switch (lpnm->code)
{
case PSN_QUERYCANCEL:
case PSN_KILLACTIVE:
case PSN_RESET:
SetWindowLongPtr(pSec->hDlg, DWLP_MSGRESULT, FALSE);
return TRUE;
case PSN_APPLY:
// Hitting the apply button runs this code
SecurityDlgApplyNow(pSec, TRUE);
break;
}
}
}
break;
case WM_HELP: // F1
ResWinHelp( (HWND)((LPHELPINFO)lParam)->hItemHandle, IDS_HELPFILE,
HELP_WM_HELP, (DWORD_PTR)(LPSTR)mapIDCsToIDHs);
break;
case WM_APP:
// A message needs to be posted, because the set tools sometimes send two messages
// hence we need delayed action and a pending change boolean
// lParam is the level to set for this message
// wParam is not used
SecuritySetLevel((DWORD) lParam, pSec);
break;
case WM_VSCROLL:
// Slider Messages
SecurityOnCommand(pSec, IDC_SLIDER, LOWORD(wParam));
return TRUE;
case WM_CONTEXTMENU: // right mouse click
ResWinHelp( (HWND) wParam, IDS_HELPFILE,
HELP_CONTEXTMENU, (DWORD_PTR)(LPSTR)mapIDCsToIDHs);
break;
case WM_DESTROY:
if(! pSec)
break;
SecurityFreeGlobals(pSec);
SetWindowLongPtr(hDlg, DWLP_USER, (LONG_PTR)NULL);
break;
}
return FALSE;
}
// Subclassed window proc for the slider. This is used to take over the
// accessibility wrapper for the class so we can return the right zone
// string ( i.e. High, Medium, Low, etc). Just trap WM_GETOBJECT and pass
// in our override of the accessibility wrapper.
LRESULT CALLBACK SliderSubWndProc (HWND hwndSlider, UINT uMsg, WPARAM wParam, LPARAM lParam, WPARAM uID, ULONG_PTR dwRefData)
{
ASSERT(uID == 0);
ASSERT(dwRefData == 0);
switch (uMsg)
{
case WM_GETOBJECT:
if ( lParam == OBJID_CLIENT )
{
// At this point we will try to load oleacc and get the functions
// we need.
if (!g_fAttemptedOleAccLoad)
{
g_fAttemptedOleAccLoad = TRUE;
ASSERT(s_pfnCreateStdAccessibleProxy == NULL);
ASSERT(s_pfnLresultFromObject == NULL);
g_hOleAcc = LoadLibrary(TEXT("OLEACC"));
if (g_hOleAcc != NULL)
{
#ifdef UNICODE
s_pfnCreateStdAccessibleProxy = (PFNCREATESTDACCESSIBLEPROXY)
GetProcAddress(g_hOleAcc, "CreateStdAccessibleProxyW");
#else
s_pfnCreateStdAccessibleProxy = (PFNCREATESTDACCESSIBLEPROXY)
GetProcAddress(g_hOleAcc, "CreateStdAccessibleProxyA");
#endif
s_pfnLresultFromObject = (PFNLRESULTFROMOBJECT)
GetProcAddress(g_hOleAcc, "LresultFromObject");
}
if (s_pfnLresultFromObject == NULL || s_pfnCreateStdAccessibleProxy == NULL)
{
// No point holding on to Oleacc since we can't use it.
FreeLibrary(g_hOleAcc);
g_hOleAcc = NULL;
s_pfnLresultFromObject = NULL;
s_pfnCreateStdAccessibleProxy = NULL;
}
}
if (g_hOleAcc && s_pfnCreateStdAccessibleProxy && s_pfnLresultFromObject)
{
IAccessible *pAcc = NULL;
HRESULT hr;
// Create default slider proxy.
hr = s_pfnCreateStdAccessibleProxy(
hwndSlider,
TEXT("msctls_trackbar32"),
OBJID_CLIENT,
IID_IAccessible,
(void **)&pAcc
);
if (SUCCEEDED(hr) && pAcc)
{
// now wrap it up in our customized wrapper...
IAccessible * pWrapAcc = new CSecurityAccessibleWrapper( hwndSlider, pAcc );
// Release our ref to proxy (wrapper has its own addref'd ptr)...
pAcc->Release();
if (pWrapAcc != NULL)
{
// ...and return the wrapper via LresultFromObject...
LRESULT lr = s_pfnLresultFromObject( IID_IAccessible, wParam, pWrapAcc );
// Release our interface pointer - OLEACC has its own addref to the object
pWrapAcc->Release();
// Return the lresult, which 'contains' a reference to our wrapper object.
return lr;
// All done!
}
// If it didn't work, fall through to default behavior instead.
}
}
}
break;
case WM_DESTROY:
RemoveWindowSubclass(hwndSlider, SliderSubWndProc, uID);
break;
} /* end switch */
return DefSubclassProc(hwndSlider, uMsg, wParam, lParam);
}
// In Urlmon.dll
HRESULT __stdcall GetAddSitesFileUrl(LPWSTR /* [in, out] */ pszUrl);
HRESULT _GetAddSitesDisplayUrl(LPCWSTR pszUrl, LPWSTR pszUrlDisplay, DWORD cchUrlDisplay)
{
HRESULT hr;
LPWSTR pszSecUrl;
hr = CoInternetGetSecurityUrl(pszUrl, &pszSecUrl, PSU_DEFAULT, 0);
if (SUCCEEDED(hr))
{
LPCWSTR pszColon = StrChr(pszSecUrl, L':');
//Special case about Urls so we don't munge them.
if (pszColon && (pszColon - pszSecUrl != 5 || StrCmpNI(pszSecUrl, L"about", 5) != 0))
{
DWORD bufferUsed = min(cchUrlDisplay, (DWORD)(pszColon - pszSecUrl) + 2);
StrCpyN(pszUrlDisplay, pszSecUrl, bufferUsed);
//Don't add // if the security url already has it
if (StrCmpNI(pszColon + 1, L"//", 2) != 0)
{
StrCatBuff(pszUrlDisplay, L"//", cchUrlDisplay - bufferUsed);
StrCatBuff(pszUrlDisplay, pszColon + 1, cchUrlDisplay - bufferUsed - 2);
}
else
{
StrCatBuff(pszUrlDisplay, pszColon + 1, cchUrlDisplay - bufferUsed);
}
}
else
{
StrCpyN(pszUrlDisplay, pszSecUrl, cchUrlDisplay);
}
CoTaskMemFree(pszSecUrl);
}
else
{
StrCpyN(pszUrlDisplay, pszUrl, cchUrlDisplay);
hr = S_OK;
}
if (SUCCEEDED (hr))
// Transform file:// URLs to a file://UNC format if necessary:
hr = GetAddSitesFileUrl(pszUrlDisplay);
return hr;
}
BOOL __cdecl _FormatMessage(LPCWSTR szTemplate, LPWSTR szBuf, UINT cchBuf, ...)
{
BOOL fRet;
va_list ArgList;
va_start(ArgList, cchBuf);
fRet = FormatMessage(FORMAT_MESSAGE_FROM_STRING, szTemplate, 0, 0, szBuf, cchBuf, &ArgList);
va_end(ArgList);
return fRet;
}
HRESULT _AddSite(LPADDSITESINFO pasi)
{
HRESULT hr = S_OK;
LPWSTR psz;
SendMessage(pasi->hwndAdd, WM_GETTEXT, MAX_ZONE_PATH, (LPARAM)pasi->szWebSite);
#ifndef UNICODE
WCHAR wszMapping[MAX_ZONE_PATH];
MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, pasi->szWebSite, sizeof(pasi->szWebSite), wszMapping, ARRAYSIZE(wszMapping));
psz = wszMapping;
#else
psz = pasi->szWebSite;
#endif
if (*psz)
{
pasi->fRSVOld = pasi->fRequireServerVerification;
pasi->fRequireServerVerification = IsDlgButtonChecked(pasi->hDlg, IDC_CHECK_REQUIRE_SERVER_VERIFICATION);
// if the state of RequireServerVer has changed, then do a SetZoneAttr so we'll get the correct error codes
if (pasi->fRSVOld != pasi->fRequireServerVerification)
{
ZONEATTRIBUTES za;
za.cbSize = sizeof(ZONEATTRIBUTES);
pasi->pSec->pInternetZoneManager->GetZoneAttributes(pasi->pSec->pszs->dwZoneIndex, &za);
if (pasi->fRequireServerVerification)
za.dwFlags |= ZAFLAGS_REQUIRE_VERIFICATION;
else
za.dwFlags &= ~ZAFLAGS_REQUIRE_VERIFICATION;
pasi->pSec->pInternetZoneManager->SetZoneAttributes(pasi->pSec->pszs->dwZoneIndex, &za);
}
hr = pasi->pSec->pInternetSecurityManager->SetZoneMapping(pasi->pSec->pszs->dwZoneIndex,
psz, SZM_CREATE);
if (FAILED(hr))
{
UINT id = IDS_MAPPINGFAIL;
if (hr == URL_E_INVALID_SYNTAX)
{
id = IDS_INVALIDURL;
}
else if (hr == E_INVALIDARG)
{
id = IDS_INVALIDWILDCARD;
}
else if (hr == E_ACCESSDENIED)
{
id = IDS_HTTPSREQ;
}
else if (hr == HRESULT_FROM_WIN32(ERROR_FILE_EXISTS))
{
id = IDS_SITEEXISTS;
}
DWORD dwOldZone;
if (id == IDS_SITEEXISTS && SUCCEEDED(pasi->pSec->pInternetSecurityManager->MapUrlToZone(psz, &dwOldZone, 0)))
{
if (dwOldZone == pasi->pSec->pszs->dwZoneIndex)
{
// Nothing to do except inform the user
SiteAlreadyInZoneMessage(pasi->hDlg, dwOldZone);
}
else if (dwOldZone == URLZONE_UNTRUSTED)
{
// Do not allow moving a site from the restricted zone to any other zone.
WCHAR szMessage[200];
WCHAR szZone[100];
if (MLLoadString(IDS_CANNOT_MOVE_FROM_RESTRICTED, szMessage, ARRAYSIZE(szMessage)) &&
MLLoadString(IDS_ZONENAME_LOCAL + URLZONE_UNTRUSTED, szZone, ARRAYSIZE(szZone)))
{
MLShellMessageBox(pasi->hDlg, szMessage, szZone, MB_ICONINFORMATION | MB_OK);
}
}
else
{
// The site exists in another zone
WCHAR szNewZone[100];
MLLoadString(IDS_ZONENAME_LOCAL + pasi->pSec->pszs->dwZoneIndex, szNewZone, ARRAYSIZE(szNewZone));
WCHAR szOldZone[100];
MLLoadString(IDS_ZONENAME_LOCAL + dwOldZone, szOldZone, ARRAYSIZE(szOldZone));
WCHAR szFormat[200];
MLLoadString(IDS_ADDSITEREPLACE, szFormat, ARRAYSIZE(szFormat));
WCHAR szText[400];
_FormatMessage(szFormat, szText, ARRAYSIZE(szText), szOldZone, szNewZone);
if (IDYES == MLShellMessageBox(pasi->hDlg, szText, NULL, MB_ICONQUESTION | MB_YESNO))
{
pasi->pSec->pInternetSecurityManager->SetZoneMapping(dwOldZone, psz, SZM_DELETE);
hr = _AddSite(pasi);
}
}
}
else
{
MLShellMessageBox(pasi->hDlg, MAKEINTRESOURCEW(id), NULL, MB_ICONSTOP|MB_OK);
Edit_SetSel(pasi->hwndAdd, 0, -1);
}
}
else
{
WCHAR szUrl[MAX_ZONE_PATH];
_GetAddSitesDisplayUrl(pasi->szWebSite, szUrl, ARRAYSIZE(szUrl));
SendMessage(pasi->hwndWebSites, LB_ADDSTRING, (WPARAM)0, (LPARAM)szUrl);
SendMessage(pasi->hwndAdd, WM_SETTEXT, (WPARAM)0, (LPARAM)NULL);
SetFocus(pasi->hwndAdd);
}
}
return hr;
}
INT_PTR CALLBACK SecurityAddSitesDlgProc(HWND hDlg, UINT uMsg, WPARAM wParam,LPARAM lParam)
{
LPADDSITESINFO pasi;
if (uMsg == WM_INITDIALOG)
{
pasi = (LPADDSITESINFO)LocalAlloc(LPTR, sizeof(*pasi));
if (!pasi)
{
EndDialog(hDlg, IDCANCEL);
return FALSE;
}
// tell dialog where to get info
SetWindowLongPtr(hDlg, DWLP_USER, (LONG_PTR)pasi);
// save the handle to the page
pasi->hDlg = hDlg;
pasi->pSec = (LPSECURITYPAGE)lParam;
pasi->hwndWebSites = GetDlgItem(hDlg, IDC_LIST_WEBSITES);
pasi->hwndAdd = GetDlgItem(hDlg, IDC_EDIT_ADD_SITE);
// cross-lang platform support
SHSetDefaultDialogFont(hDlg, IDC_EDIT_ADD_SITE);
// limit the text so it will fit
SendMessage(pasi->hwndAdd, EM_SETLIMITTEXT, (WPARAM)sizeof(pasi->szWebSite), (LPARAM)0);
pasi->fRequireServerVerification = pasi->pSec->pszs->dwFlags & ZAFLAGS_REQUIRE_VERIFICATION;
CheckDlgButton(hDlg, IDC_CHECK_REQUIRE_SERVER_VERIFICATION, pasi->fRequireServerVerification);
// hide the checkbox if it doesn't support server verification
if (!(pasi->pSec->pszs->dwFlags & ZAFLAGS_SUPPORTS_VERIFICATION))
ShowWindow(GetDlgItem(hDlg, IDC_CHECK_REQUIRE_SERVER_VERIFICATION), SW_HIDE);
SendMessage(hDlg, WM_SETTEXT, (WPARAM)0, (LPARAM)pasi->pSec->pszs->szDisplayName);
SetDlgItemText(hDlg, IDC_ADDSITES_GROUPBOX,(LPTSTR)pasi->pSec->pszs->szDisplayName);
SendDlgItemMessage(hDlg, IDC_ZONE_ICON, STM_SETIMAGE, (WPARAM)IMAGE_ICON, (LPARAM)pasi->pSec->pszs->hicon);
EnableWindow(GetDlgItem(hDlg, IDC_BUTTON_REMOVE), FALSE);
if (pasi->pSec->pInternetSecurityManager || SUCCEEDED(CoInternetCreateSecurityManager(NULL, &(pasi->pSec->pInternetSecurityManager), 0)))
{
IEnumString *pEnum;
if (SUCCEEDED(pasi->pSec->pInternetSecurityManager->GetZoneMappings(pasi->pSec->pszs->dwZoneIndex, &pEnum, 0)))
{
LPOLESTR pszMapping;
#ifndef UNICODE
CHAR szMapping[MAX_URL_STRING];
#endif
LPTSTR psz;
while (pEnum->Next(1, &pszMapping, NULL) == S_OK)
{
#ifndef UNICODE
WideCharToMultiByte(CP_ACP, 0, pszMapping, -1, szMapping, ARRAYSIZE(szMapping), NULL, NULL);
psz = szMapping;
#else
psz = pszMapping;
#endif // UNICODE
SendMessage(pasi->hwndWebSites, LB_INSERTSTRING, (WPARAM)-1, (LPARAM)psz);
CoTaskMemFree(pszMapping);
}
pEnum->Release();
}
}
BOOL fUseHKLM = FALSE;
DWORD cb = SIZEOF(fUseHKLM);
SHGetValue( HKEY_LOCAL_MACHINE,
REGSTR_PATH_SECURITY_LOCKOUT,
REGSTR_VAL_HKLM_ONLY,
NULL,
&fUseHKLM,
&cb);
if (pasi->pSec->fNoAddSites || pasi->pSec->fNoZoneMapEdit || (fUseHKLM && !IsNTAdmin(0, NULL)))
{
EnableDlgItem(hDlg, IDC_EDIT_ADD_SITE, FALSE);
EnableDlgItem(hDlg, IDC_BUTTON_REMOVE, FALSE);
}
else if (pasi->pSec->szPageUrl[0])
{
// Security manager should have been created above
if (pasi->pSec->pInternetSecurityManager)
{
DWORD dwZone;
if (SUCCEEDED(pasi->pSec->pInternetSecurityManager->MapUrlToZone(pasi->pSec->szPageUrl, &dwZone, 0)))
{
// If a site is already restricted, we don't want to auto-suggest.
// If a site is already trusted, we can't add it to either list anyway.
// So we only need to check for Intranet and Internet.
if ((dwZone == URLZONE_INTERNET) ||
(pasi->pSec->pszs->dwZoneIndex == URLZONE_INTRANET && dwZone == URLZONE_TRUSTED) ||
(pasi->pSec->pszs->dwZoneIndex == URLZONE_TRUSTED && dwZone == URLZONE_INTRANET))
{
WCHAR szUrl[MAX_ZONE_PATH];
if (SUCCEEDED(_GetAddSitesDisplayUrl(pasi->pSec->szPageUrl, szUrl, ARRAYSIZE(szUrl))))
{
SetWindowText(pasi->hwndAdd, szUrl);
SetFocus(GetDlgItem(hDlg, IDC_BUTTON_ADD));
}
}
}
}
}
if (pasi->pSec->fNoZoneMapEdit)
{
EnableDlgItem(hDlg, IDC_CHECK_REQUIRE_SERVER_VERIFICATION, FALSE);
EnableDlgItem(hDlg, IDS_STATIC_ADDSITE, FALSE);
}
SHAutoComplete(GetDlgItem(hDlg, IDC_EDIT_ADD_SITE), SHACF_DEFAULT);
}
else
pasi = (LPADDSITESINFO)GetWindowLongPtr(hDlg, DWLP_USER);
if (!pasi)
return FALSE;
switch (uMsg)
{
case WM_COMMAND:
switch (LOWORD(wParam))
{
case IDCANCEL: //Close
{
ZONEATTRIBUTES za;
pasi->fRequireServerVerification = IsDlgButtonChecked(hDlg, IDC_CHECK_REQUIRE_SERVER_VERIFICATION);
if (pasi->fRequireServerVerification)
pasi->pSec->pszs->dwFlags |= ZAFLAGS_REQUIRE_VERIFICATION;
else
pasi->pSec->pszs->dwFlags &= ~ZAFLAGS_REQUIRE_VERIFICATION;
za.cbSize = sizeof(ZONEATTRIBUTES);
pasi->pSec->pInternetZoneManager->GetZoneAttributes(pasi->pSec->pszs->dwZoneIndex, &za);
za.dwFlags = pasi->pSec->pszs->dwFlags;
pasi->pSec->pInternetZoneManager->SetZoneAttributes(pasi->pSec->pszs->dwZoneIndex, &za);
SecurityChanged();
EndDialog(hDlg, IDOK);
break;
}
case IDC_LIST_WEBSITES:
switch (HIWORD(wParam))
{
case LBN_SELCHANGE:
case LBN_SELCANCEL:
if (!pasi->pSec->fNoAddSites && !pasi->pSec->fNoZoneMapEdit)
EnableWindow(GetDlgItem(hDlg, IDC_BUTTON_REMOVE), SendDlgItemMessage(hDlg, IDC_LIST_WEBSITES, LB_GETCURSEL, 0, 0) != -1);
break;
}
break;
case IDC_EDIT_ADD_SITE:
switch(HIWORD(wParam))
{
case EN_CHANGE:
BOOL fEnable = GetWindowTextLength(GetDlgItem(hDlg, IDC_EDIT_ADD_SITE)) ? TRUE:FALSE;
EnableWindow(GetDlgItem(hDlg,IDC_BUTTON_ADD), fEnable);
SendMessage(hDlg, DM_SETDEFID, fEnable ? IDC_BUTTON_ADD : IDOK, 0);
break;
}
break;
case IDC_BUTTON_ADD:
_AddSite(pasi);
break;
case IDC_BUTTON_REMOVE:
{
TCHAR szMapping[MAX_ZONE_PATH];
LPWSTR psz;
INT_PTR iSel = SendMessage(pasi->hwndWebSites, LB_GETCURSEL, 0, 0);
if (iSel != -1)
{
SendMessage(pasi->hwndWebSites, LB_GETTEXT, (WPARAM)iSel, (LPARAM)szMapping);
#ifndef UNICODE
WCHAR wszMapping[MAX_ZONE_PATH];
MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, szMapping, sizeof(szMapping), wszMapping, ARRAYSIZE(wszMapping));
psz = wszMapping;
#else
psz = szMapping;
#endif
SendMessage(pasi->hwndWebSites, LB_DELETESTRING, iSel , 0);
SendMessage(pasi->hwndWebSites, LB_SETCURSEL, iSel-1, 0);
if (!pasi->pSec->fNoAddSites && !pasi->pSec->fNoZoneMapEdit)
EnableWindow(GetDlgItem(hDlg, IDC_BUTTON_REMOVE), SendDlgItemMessage(hDlg, IDC_LIST_WEBSITES, LB_GETCURSEL, 0, 0) != -1);
pasi->pSec->pInternetSecurityManager->SetZoneMapping(pasi->pSec->pszs->dwZoneIndex,
psz, SZM_DELETE);
}
break;
}
default:
return FALSE;
}
return TRUE;
break;
case WM_HELP: // F1
ResWinHelp( (HWND)((LPHELPINFO)lParam)->hItemHandle, IDS_HELPFILE,
HELP_WM_HELP, (DWORD_PTR)(LPSTR)mapIDCsToIDHs);
break;
case WM_CONTEXTMENU: // right mouse click
ResWinHelp( (HWND) wParam, IDS_HELPFILE,
HELP_CONTEXTMENU, (DWORD_PTR)(LPSTR)mapIDCsToIDHs);
break;
case WM_DESTROY:
SHRemoveDefaultDialogFont(hDlg);
if (pasi)
{
LocalFree(pasi);
SetWindowLongPtr(hDlg, DWLP_USER, (LONG_PTR)NULL);
}
break;
}
return FALSE;
}
INT_PTR CALLBACK SecurityAddSitesIntranetDlgProc(HWND hDlg, UINT uMsg, WPARAM wParam,LPARAM lParam)
{
LPADDSITESINTRANETINFO pasii;
if (uMsg == WM_INITDIALOG)
{
pasii = (LPADDSITESINTRANETINFO)LocalAlloc(LPTR, sizeof(*pasii));
if (!pasii)
{
EndDialog(hDlg, IDCANCEL);
return FALSE;
}
// tell dialog where to get info
SetWindowLongPtr(hDlg, DWLP_USER, (LONG_PTR)pasii);
// save the handle to the page
pasii->hDlg = hDlg;
pasii->pSec = (LPSECURITYPAGE)lParam;
SendMessage(hDlg, WM_SETTEXT, (WPARAM)0, (LPARAM)pasii->pSec->pszs->szDisplayName);
CheckDlgButton(hDlg, IDC_CHECK_USEINTRANET, pasii->pSec->pszs->dwFlags & ZAFLAGS_INCLUDE_INTRANET_SITES);
CheckDlgButton(hDlg, IDC_CHECK_PROXY, pasii->pSec->pszs->dwFlags & ZAFLAGS_INCLUDE_PROXY_OVERRIDE);
CheckDlgButton(hDlg, IDC_CHECK_UNC, pasii->pSec->pszs->dwFlags & ZAFLAGS_UNC_AS_INTRANET);
SendDlgItemMessage(hDlg, IDC_ZONE_ICON, STM_SETIMAGE, (WPARAM)IMAGE_ICON, (LPARAM)pasii->pSec->pszs->hicon);
BOOL fHarden = IEHardened();
if (pasii->pSec->fNoAddSites || pasii->pSec->fNoZoneMapEdit || fHarden)
{
EnableDlgItem(hDlg, IDC_CHECK_USEINTRANET, FALSE);
EnableDlgItem(hDlg, IDC_CHECK_PROXY, FALSE);
}
if (pasii->pSec->fNoZoneMapEdit || fHarden)
{
EnableDlgItem(hDlg, IDC_CHECK_UNC, FALSE);
}
return TRUE;
}
else
pasii = (LPADDSITESINTRANETINFO)GetWindowLongPtr(hDlg, DWLP_USER);
if (!pasii)
return FALSE;
switch (uMsg) {
case WM_COMMAND:
switch (LOWORD(wParam))
{
case IDOK:
{
ZONEATTRIBUTES za;
pasii->fUseIntranet = IsDlgButtonChecked(hDlg, IDC_CHECK_USEINTRANET);
pasii->fUseProxyExclusion = IsDlgButtonChecked(hDlg, IDC_CHECK_PROXY);
pasii->fUseUNC = IsDlgButtonChecked(hDlg, IDC_CHECK_UNC);
if (pasii->fUseIntranet)
pasii->pSec->pszs->dwFlags |= ZAFLAGS_INCLUDE_INTRANET_SITES;
else
pasii->pSec->pszs->dwFlags &= ~ZAFLAGS_INCLUDE_INTRANET_SITES;
if (pasii->fUseProxyExclusion)
pasii->pSec->pszs->dwFlags |= ZAFLAGS_INCLUDE_PROXY_OVERRIDE;
else
pasii->pSec->pszs->dwFlags &= ~ZAFLAGS_INCLUDE_PROXY_OVERRIDE;
if (pasii->fUseUNC)
pasii->pSec->pszs->dwFlags |= ZAFLAGS_UNC_AS_INTRANET;
else
pasii->pSec->pszs->dwFlags &= ~ZAFLAGS_UNC_AS_INTRANET;
za.cbSize = sizeof(ZONEATTRIBUTES);
pasii->pSec->pInternetZoneManager->GetZoneAttributes(pasii->pSec->pszs->dwZoneIndex, &za);
za.dwFlags = pasii->pSec->pszs->dwFlags;
pasii->pSec->pInternetZoneManager->SetZoneAttributes(pasii->pSec->pszs->dwZoneIndex, &za);
SecurityChanged();
EndDialog(hDlg, IDOK);
break;
}
case IDCANCEL:
EndDialog(hDlg, IDCANCEL);
break;
case IDC_INTRANET_ADVANCED:
DialogBoxParam(MLGetHinst(), MAKEINTRESOURCE(IDD_SECURITY_ADD_SITES), hDlg,
SecurityAddSitesDlgProc, (LPARAM)pasii->pSec);
break;
default:
return FALSE;
}
return TRUE;
break;
case WM_HELP: // F1
ResWinHelp( (HWND)((LPHELPINFO)lParam)->hItemHandle, IDS_HELPFILE,
HELP_WM_HELP, (DWORD_PTR)(LPSTR)mapIDCsToIDHs);
break;
case WM_CONTEXTMENU: // right mouse click
ResWinHelp( (HWND) wParam, IDS_HELPFILE,
HELP_CONTEXTMENU, (DWORD_PTR)(LPSTR)mapIDCsToIDHs);
break;
case WM_DESTROY:
if (pasii)
{
LocalFree(pasii);
SetWindowLongPtr(hDlg, DWLP_USER, (LONG_PTR)NULL);
}
break;
}
return FALSE;
}
VOID ShowJavaZonePermissionsDialog (HWND hdlg, LPCUSTOMSETTINGSINFO pcsi)
{
HRESULT hr;
IJavaZonePermissionEditor *zoneeditor;
hr = CoCreateInstance(
CLSID_JavaRuntimeConfiguration,
NULL,
CLSCTX_INPROC_SERVER | CLSCTX_INPROC_HANDLER | CLSCTX_LOCAL_SERVER,
IID_IJavaZonePermissionEditor,
(PVOID*)&zoneeditor
);
if (SUCCEEDED(hr))
{
hr = zoneeditor->ShowUI(
hdlg,
0,
0,
pcsi->fUseHKLM ? URLZONEREG_HKLM : URLZONEREG_DEFAULT,
pcsi->pSec->pszs->dwZoneIndex,
pcsi->dwJavaPolicy | URLACTION_JAVA_PERMISSIONS,
pcsi->pSec->pInternetZoneManager
);
zoneeditor->Release();
}
}
void ShowCustom(LPCUSTOMSETTINGSINFO pcsi, HTREEITEM hti)
{
TV_ITEM tvi;
tvi.hItem = hti;
tvi.mask = TVIF_HANDLE | TVIF_PARAM | TVIF_IMAGE;
TreeView_GetItem( pcsi->hwndTree, &tvi );
// If it's not selected don't bother.
if (tvi.iImage != IDRADIOON)
return;
TCHAR szValName[64];
DWORD cb = SIZEOF(szValName);
DWORD dwChecked;
if (SHRegQueryUSValue((HUSKEY)tvi.lParam,
TEXT("ValueName"),
NULL,
(LPBYTE)szValName,
&cb,
pcsi->fUseHKLM,
NULL,
0) == ERROR_SUCCESS)
{
if (!(StrCmp(szValName, TEXT("1C00"))))
{
cb = SIZEOF(dwChecked);
if (SHRegQueryUSValue((HUSKEY)tvi.lParam,
TEXT("CheckedValue"),
NULL,
(LPBYTE)&dwChecked,
&cb,
pcsi->fUseHKLM,
NULL,
0) == ERROR_SUCCESS)
{
#ifndef UNIX
HWND hCtl = GetDlgItem(pcsi->hDlg, IDC_JAVACUSTOM);
ShowWindow(hCtl,
(dwChecked == URLPOLICY_JAVA_CUSTOM) && (tvi.iImage == IDRADIOON) ? SW_SHOWNA : SW_HIDE);
EnableWindow(hCtl, dwChecked==URLPOLICY_JAVA_CUSTOM ? TRUE : FALSE);
pcsi->dwJavaPolicy = dwChecked;
#endif
}
}
}
}
void _FindCustomRecursive(
LPCUSTOMSETTINGSINFO pcsi,
HTREEITEM htvi
)
{
HTREEITEM hctvi; // child
// step through the children
hctvi = TreeView_GetChild( pcsi->hwndTree, htvi );
while ( hctvi )
{
_FindCustomRecursive(pcsi,hctvi);
hctvi = TreeView_GetNextSibling( pcsi->hwndTree, hctvi );
}
ShowCustom(pcsi, htvi);
}
void _FindCustom(
LPCUSTOMSETTINGSINFO pcsi
)
{
HTREEITEM hti = TreeView_GetRoot( pcsi->hwndTree );
// and walk the list of other roots
while (hti)
{
// recurse through its children
_FindCustomRecursive(pcsi, hti);
// get the next root
hti = TreeView_GetNextSibling(pcsi->hwndTree, hti );
}
}
BOOL SecurityCustomSettingsInitDialog(HWND hDlg, LPARAM lParam)
{
LPCUSTOMSETTINGSINFO pcsi = (LPCUSTOMSETTINGSINFO)LocalAlloc(LPTR, sizeof(*pcsi));
HRESULT hr;
if (!pcsi)
{
EndDialog(hDlg, IDCANCEL);
return FALSE;
}
// tell dialog where to get info
SetWindowLongPtr(hDlg, DWLP_USER, (LONG_PTR)pcsi);
// save the handle to the page
pcsi->hDlg = hDlg;
pcsi->pSec = (LPSECURITYPAGE)lParam;
// save dialog handle
pcsi->hwndTree = GetDlgItem(pcsi->hDlg, IDC_TREE_SECURITY_SETTINGS);
CoInitialize(0);
hr = CoCreateInstance(CLSID_CRegTreeOptions, NULL, CLSCTX_INPROC_SERVER,
IID_IRegTreeOptions, (LPVOID *)&(pcsi->pTO));
DWORD cb = SIZEOF(pcsi->fUseHKLM);
SHGetValue(HKEY_LOCAL_MACHINE,
REGSTR_PATH_SECURITY_LOCKOUT,
REGSTR_VAL_HKLM_ONLY,
NULL,
&(pcsi->fUseHKLM),
&cb);
// if this fails, we'll just use the default of fUseHKLM == 0
if (SUCCEEDED(hr))
{
CHAR szZone[32];
wnsprintfA(szZone, ARRAYSIZE(szZone), "%ld", pcsi->pSec->pszs->dwZoneIndex);
// use the SOHKLM tree when fUseHKLM==TRUE for IEAK
hr = pcsi->pTO->InitTree(pcsi->hwndTree, HKEY_LOCAL_MACHINE,
pcsi->fUseHKLM ?
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\SOIEAK" :
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\SO",
szZone);
}
// find the first root and make sure that it is visible
TreeView_EnsureVisible( pcsi->hwndTree, TreeView_GetRoot( pcsi->hwndTree ) );
pcsi->hwndCombo = GetDlgItem(hDlg, IDC_COMBO_RESETLEVEL);
SendMessage(pcsi->hwndCombo, CB_INSERTSTRING, (WPARAM)0, (LPARAM)LEVEL_NAME[3]);
SendMessage(pcsi->hwndCombo, CB_INSERTSTRING, (WPARAM)0, (LPARAM)LEVEL_NAME[2]);
SendMessage(pcsi->hwndCombo, CB_INSERTSTRING, (WPARAM)0, (LPARAM)LEVEL_NAME[1]);
SendMessage(pcsi->hwndCombo, CB_INSERTSTRING, (WPARAM)0, (LPARAM)LEVEL_NAME[0]);
switch (pcsi->pSec->pszs->dwRecSecLevel)
{
case URLTEMPLATE_LOW:
pcsi->iLevelSel = 3;
break;
case URLTEMPLATE_MEDLOW:
pcsi->iLevelSel = 2;
break;
case URLTEMPLATE_MEDIUM:
pcsi->iLevelSel = 1;
break;
case URLTEMPLATE_HIGH:
pcsi->iLevelSel = 0;
break;
default:
pcsi->iLevelSel = 0;
break;
}
_FindCustom(pcsi);
SendMessage(pcsi->hwndCombo, CB_SETCURSEL, (WPARAM)pcsi->iLevelSel, (LPARAM)0);
if (pcsi->pSec->fNoEdit)
{
EnableDlgItem(hDlg, IDC_COMBO_RESETLEVEL, FALSE);
EnableDlgItem(hDlg, IDC_BUTTON_APPLY, FALSE);
}
pcsi->fChanged = FALSE;
return TRUE;
}
INT_PTR CALLBACK SecurityCustomSettingsDlgProc(HWND hDlg, UINT uMsg, WPARAM wParam,LPARAM lParam)
{
LPCUSTOMSETTINGSINFO pcsi;
if (uMsg == WM_INITDIALOG)
return SecurityCustomSettingsInitDialog(hDlg, lParam);
else
pcsi = (LPCUSTOMSETTINGSINFO)GetWindowLongPtr(hDlg, DWLP_USER);
if (!pcsi)
return FALSE;
switch (uMsg) {
case WM_NOTIFY:
{
LPNMHDR psn = (LPNMHDR)lParam;
switch( psn->code )
{
case TVN_KEYDOWN:
{
TV_KEYDOWN *pnm = (TV_KEYDOWN*)psn;
if (pnm->wVKey == VK_SPACE) {
if (!pcsi->pSec->fNoEdit)
{
HTREEITEM hti = (HTREEITEM)SendMessage(pcsi->hwndTree, TVM_GETNEXTITEM, TVGN_CARET, NULL);
pcsi->pTO->ToggleItem(hti);
ShowCustom(pcsi, hti);
pcsi->fChanged = TRUE;
EnableWindow(GetDlgItem(hDlg, IDC_BUTTON_APPLY),TRUE);
SetWindowLongPtr(hDlg, DWLP_MSGRESULT, TRUE); // eat the key
return TRUE;
}
}
break;
}
case NM_CLICK:
case NM_DBLCLK:
{ // is this click in our tree?
if ( psn->idFrom == IDC_TREE_SECURITY_SETTINGS )
{ // yes...
TV_HITTESTINFO ht;
HTREEITEM hti;
if (!pcsi->pSec->fNoEdit)
{
GetCursorPos( &ht.pt ); // get where we were hit
ScreenToClient( pcsi->hwndTree, &ht.pt ); // translate it to our window
// retrieve the item hit
hti = TreeView_HitTest( pcsi->hwndTree, &ht);
pcsi->pTO->ToggleItem(hti);
pcsi->fChanged = TRUE;
ShowCustom(pcsi, hti);
EnableWindow(GetDlgItem(hDlg, IDC_BUTTON_APPLY),TRUE);
}
}
}
break;
}
}
break;
case WM_COMMAND:
switch (LOWORD(wParam))
{
case IDOK:
if(pcsi->pSec->fPendingChange)
break;
if(pcsi->fChanged && RegWriteWarning(pcsi->pSec->hDlg) == IDNO)
break;
// we use send message instead of post because there is no chance of this button
// receiving multiple signals at one click, and we need the change level message to be
// processed before the apply message below
pcsi->pSec->fPendingChange = TRUE;
SendMessage(pcsi->pSec->hDlg, WM_APP, (WPARAM) 0, (LPARAM) URLTEMPLATE_CUSTOM);
if(pcsi->fChanged)
{
pcsi->pTO->WalkTree( WALK_TREE_SAVE );
}
// Saves custom to registry and Handles updateallwindows
// and securitychanged calls
// APPCOMPAT: Force a call to SetZoneAttributes when anything in custom changes.
// This forces the security manager to flush any caches it has for that zone.
pcsi->pSec->fChanged = TRUE;
SecurityDlgApplyNow(pcsi->pSec, FALSE);
EndDialog(hDlg, IDOK);
break;
case IDCANCEL:
EndDialog(hDlg, IDCANCEL);
break;
case IDC_COMBO_RESETLEVEL:
switch (HIWORD(wParam))
{
case CBN_SELCHANGE:
{
// Sundown: coercion to integer since cursor selection is 32b
int iNewSelection = (int) SendMessage(pcsi->hwndCombo, CB_GETCURSEL, (WPARAM)0, (LPARAM)0);
if (iNewSelection != pcsi->iLevelSel)
{
pcsi->iLevelSel = iNewSelection;
EnableWindow(GetDlgItem(hDlg, IDC_BUTTON_APPLY),TRUE);
}
break;
}
}
break;
case IDC_JAVACUSTOM:
ShowJavaZonePermissionsDialog(hDlg, pcsi);
break;
case IDC_BUTTON_APPLY:
{
TCHAR szLevel[64];
ZONEATTRIBUTES za;
if(pcsi->pSec->fPendingChange == TRUE)
break;
if(RegWriteWarning(hDlg) == IDNO)
{
break;
}
pcsi->pSec->fPendingChange = TRUE;
SendMessage(pcsi->hwndCombo, WM_GETTEXT, (WPARAM)ARRAYSIZE(szLevel), (LPARAM)szLevel);
za.cbSize = sizeof(ZONEATTRIBUTES);
pcsi->pSec->pInternetZoneManager->GetZoneAttributes(pcsi->pSec->pszs->dwZoneIndex, &za);
if (!StrCmp(szLevel, LEVEL_NAME[3]))
za.dwTemplateCurrentLevel = URLTEMPLATE_LOW;
else if (!StrCmp(szLevel, LEVEL_NAME[2]))
za.dwTemplateCurrentLevel = URLTEMPLATE_MEDLOW;
else if (!StrCmp(szLevel, LEVEL_NAME[1]))
za.dwTemplateCurrentLevel = URLTEMPLATE_MEDIUM;
else if (!StrCmp(szLevel, LEVEL_NAME[0]))
za.dwTemplateCurrentLevel = URLTEMPLATE_HIGH;
else
za.dwTemplateCurrentLevel = URLTEMPLATE_CUSTOM;
pcsi->pSec->pInternetZoneManager->SetZoneAttributes(pcsi->pSec->pszs->dwZoneIndex, &za);
pcsi->pTO->WalkTree(WALK_TREE_REFRESH);
// find the first root and make sure that it is visible
TreeView_EnsureVisible( pcsi->hwndTree, TreeView_GetRoot( pcsi->hwndTree ) );
EnableWindow(GetDlgItem(hDlg, IDC_BUTTON_APPLY), FALSE);
SendMessage(hDlg, DM_SETDEFID, IDOK, 0);
SetFocus(GetDlgItem(hDlg, IDOK)); // since we grayout the reset button, might have keyboard
// focus, so we should set focus somewhere else
_FindCustom(pcsi);
// BUG #57358. We tell the Zone Manager to change to [High/Med/Low] level because we want
// the policy values for those, but we don't want it to change the level from
// custom. So, after it changes the setting from Custom, we change it back.
// Save the level as custom
// we use send message instead of post because there is no chance of this button
// receiving multiple signals at one click, and we need the change level message to be
// processed before the apply message below
SendMessage(pcsi->pSec->hDlg, WM_APP, (WPARAM) 0, (LPARAM) URLTEMPLATE_CUSTOM);
// Saves custom to registry and Handles updateallwindows
// and securitychanged calls
// APPCOMPAT: Force a call to SetZoneAttributes when anything in custom changes.
// This forces the security manager to flush any caches it has for that zone.
pcsi->pSec->fChanged = TRUE;
SecurityDlgApplyNow(pcsi->pSec, TRUE);
pcsi->fChanged = FALSE;
break;
}
default:
return FALSE;
}
return TRUE;
break;
case WM_HELP: // F1
{
LPHELPINFO lphelpinfo;
lphelpinfo = (LPHELPINFO)lParam;
TV_HITTESTINFO ht;
HTREEITEM hItem;
// If this help is invoked through the F1 key.
if (GetAsyncKeyState(VK_F1) < 0)
{
// Yes we need to give help for the currently selected item.
hItem = TreeView_GetSelection(pcsi->hwndTree);
}
else
{
// Else we need to give help for the item at current cursor position
ht.pt =((LPHELPINFO)lParam)->MousePos;
ScreenToClient(pcsi->hwndTree, &ht.pt); // Translate it to our window
hItem = TreeView_HitTest(pcsi->hwndTree, &ht);
}
if (FAILED(pcsi->pTO->ShowHelp(hItem , HELP_WM_HELP)))
{
ResWinHelp( (HWND)((LPHELPINFO)lParam)->hItemHandle, IDS_HELPFILE,
HELP_WM_HELP, (DWORD_PTR)(LPSTR)mapIDCsToIDHs);
}
break;
}
case WM_CONTEXTMENU: // right mouse click
{
TV_HITTESTINFO ht;
GetCursorPos( &ht.pt ); // get where we were hit
ScreenToClient( pcsi->hwndTree, &ht.pt ); // translate it to our window
// retrieve the item hit
if (FAILED(pcsi->pTO->ShowHelp(TreeView_HitTest( pcsi->hwndTree, &ht),HELP_CONTEXTMENU)))
{
ResWinHelp( (HWND) wParam, IDS_HELPFILE,
HELP_CONTEXTMENU, (DWORD_PTR)(LPSTR)mapIDCsToIDHs);
}
break;
}
case WM_DESTROY:
if (pcsi)
{
if (pcsi->pTO)
{
pcsi->pTO->WalkTree( WALK_TREE_DELETE );
pcsi->pTO->Release();
pcsi->pTO=NULL;
}
LocalFree(pcsi);
SetWindowLongPtr(hDlg, DWLP_USER, (LONG_PTR)NULL);
CoUninitialize();
}
break;
}
return FALSE;
}
#ifdef UNIX
extern "C"
#endif
BOOL LaunchSecurityDialogEx(HWND hDlg, DWORD dwZone, DWORD dwFlags)
{
INITCOMMONCONTROLSEX icex;
SECURITYINITFLAGS * psif = NULL;
icex.dwSize = sizeof(INITCOMMONCONTROLSEX);
icex.dwICC = ICC_USEREX_CLASSES|ICC_NATIVEFNTCTL_CLASS;
InitCommonControlsEx(&icex);
if(g_dwtlsSecInitFlags != (DWORD) -1)
psif = (SECURITYINITFLAGS *) TlsGetValue(g_dwtlsSecInitFlags);
if(psif)
{
psif->fForceUI = dwFlags & LSDFLAG_FORCEUI;
psif->fDisableAddSites = dwFlags & LSDFLAG_NOADDSITES;
psif->dwZone = dwZone;
}
// passing in a NULL psif is okay
DialogBoxParam(MLGetHinst(), MAKEINTRESOURCE(IDD_SECSTANDALONE), hDlg,
SecurityDlgProc, (LPARAM) psif);
return TRUE;
}
// backwards compatability
#ifdef UNIX
extern "C"
#endif
void LaunchSecurityDialog(HWND hDlg, DWORD dwZone)
{
LaunchSecurityDialogEx(hDlg, dwZone, LSDFLAG_DEFAULT);
}
#ifdef UNIX
extern "C"
#endif
void LaunchSiteCertDialog(HWND hDlg)
{
CRYPTUI_CERT_MGR_STRUCT ccm = {0};
ccm.dwSize = sizeof(ccm);
ccm.hwndParent = hDlg;
CryptUIDlgCertMgr(&ccm);
}
BOOL SiteAlreadyInZone(LPCWSTR pszUrl, DWORD dwZone, SECURITYPAGE* pSec)
{
BOOL fRet = FALSE;
if (pSec->pInternetSecurityManager || SUCCEEDED(CoInternetCreateSecurityManager(NULL, &(pSec->pInternetSecurityManager), 0)))
{
DWORD dwMappedZone;
if (SUCCEEDED(pSec->pInternetSecurityManager->MapUrlToZone(pszUrl, &dwMappedZone, 0)))
{
fRet = (dwZone == dwMappedZone);
}
}
return fRet;
}
void SiteAlreadyInZoneMessage(HWND hwnd, DWORD dwZone)
{
WCHAR szFormat[200];
WCHAR szZone[100];
if (MLLoadString(IDS_SITEALREADYINZONE, szFormat, ARRAYSIZE(szFormat)) &&
MLLoadString(IDS_ZONENAME_LOCAL + dwZone, szZone, ARRAYSIZE(szZone)))
{
WCHAR szText[300];
wnsprintf(szText, ARRAYSIZE(szText), szFormat, szZone);
MLShellMessageBox(hwnd, szText, szZone, MB_ICONINFORMATION | MB_OK);
}
}
BOOL ShowAddSitesDialog(HWND hwnd, DWORD dwZone, LPCWSTR pszUrl)
{
BOOL fRet = FALSE;
SECURITYPAGE* pSec = NULL;
if (SecurityInitGlobals(&pSec, NULL, NULL))
{
DWORD dwEnum;
if (SUCCEEDED(pSec->pInternetZoneManager->CreateZoneEnumerator(&dwEnum, &(pSec->dwZoneCount), 0)))
{
if (S_OK == (SecurityInitZone(dwZone, pSec, dwEnum, NULL, NULL)))
{
if (!SiteAlreadyInZone(pszUrl, dwZone, pSec))
{
StrCpyN(pSec->szPageUrl, pszUrl, ARRAYSIZE(pSec->szPageUrl));
DialogBoxParam(MLGetHinst(), MAKEINTRESOURCE(IDD_SECURITY_ADD_SITES), hwnd, SecurityAddSitesDlgProc, (LPARAM)pSec);
fRet = TRUE;
FreePszs(pSec->pszs);
}
else
{
SiteAlreadyInZoneMessage(hwnd, dwZone);
}
}
pSec->pInternetZoneManager->DestroyZoneEnumerator(dwEnum);
}
SecurityFreeGlobals(pSec);
}
return fRet;
}
| [
"blindtiger@foxmail.com"
] | blindtiger@foxmail.com |
b5de86cb9e218e7d7fa277e56da06fb22e1c66ca | da9d2fb0cfe3d92b45d52615e8d95d8192ca67ad | /Fast_Power.cpp | 4f562cf902b98f58c3ebaf12f41ba2af01ae08a6 | [] | no_license | Hack-sham/CODING-BLOCKS-COMPETITIVE-CODING-COURSE | dde7fc17586efbb381ba7aef862b96a9bb3fce16 | 1703495f71c545371d1326b8b9e13edb0fb01b36 | refs/heads/main | 2023-06-04T23:10:36.426639 | 2021-06-22T10:04:47 | 2021-06-22T10:04:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 370 | cpp | #include <iostream>
using namespace std;
int fast_power(int a,int n)
{ if(n==0) return 1;
int sub_ans=fast_power(a,n/2);
sub_ans*=sub_ans;
if(n&1)
return sub_ans*a;
else
return sub_ans;
}
int main()
{ int a=2,n=5;
cout<<fast_power(a,n);
}
| [
"noreply@github.com"
] | noreply@github.com |
c88bb58fdfe4c82349b704cee5dfee7f0d849ffe | 805cd1baa255d889f5c5127598b668987e2ee14c | /GameFramework/GameFramework/Graphic/GraphicEffectManager/BehaviorScheduler/Behavior/Flash.h | 5d857f7514350e2d4b1408e0c5db880029c7497e | [] | no_license | human-osaka-game-2018/GameFramework | e93e67c3fd9ca1dc48c72967e54a6de57ad30d9d | b20bf9e885c8327ee2941fe2bf69d82989650b76 | refs/heads/master | 2020-04-26T04:15:33.295642 | 2019-06-12T08:31:04 | 2019-06-12T08:33:55 | 173,295,756 | 0 | 0 | null | 2019-06-12T08:33:57 | 2019-03-01T12:06:42 | C++ | UTF-8 | C++ | false | false | 988 | h | #ifndef FLASH_H
#define FLASH_H
#include <Window.h>
#include "Vertices.h"
#include "Behavior.h"
#include "WindowParam/WindowParam.h"
#include "Algorithm.h"
/// <summary>
/// 基礎構築に関するものをまとめた名前空間
/// </summary>
namespace gameframework
{
/// <summary>
/// 点滅
/// </summary>
class Flash :public Behavior
{
public:
/// <param name="flashFrameMax">点滅にかかるカウント数</param>
/// <param name="alphaMin">点滅のアルファ値の最大値</param>
/// <param name="alphaMax">点滅のアルファ値の最小値</param>
Flash(int flashFrameMax, BYTE alphaMin, BYTE alphaMax);
virtual ~Flash();
/// <summary>
/// 引数の矩形クラスに属性を付与する
/// </summary>
/// <param name="pVertices">矩形クラスのポインタ</param>
virtual void Impart(Vertices* pVertices)override;
protected:
int m_flashFrameMax = 0;
BYTE m_alphaMin = 0;
BYTE m_alphaMax = 0;
};
}
#endif //!FLASH_H
| [
"glaca986@outlook.jp"
] | glaca986@outlook.jp |
d46da6203034a8d648e3414def2322e74bd8beb5 | 8650da0f2b3c8e1312a102b6e8fcee3c3647e7cf | /Source/Project4/Public/Interactables/SkillDropActor.h | 216a3ef8dc35a7c99eeaa82ecd50f7ba818bbfcf | [] | no_license | ElliotCouvignou/Project4 | 706c377c15a0cf3ebb3d4a7e1a421e12c3d57cc8 | 13b7b5063f2cc1f6a0dbcfedaf5dfd0a86e86735 | refs/heads/master | 2023-06-20T10:16:38.207895 | 2021-07-21T00:30:45 | 2021-07-21T00:30:45 | 263,475,979 | 0 | 0 | null | 2020-10-01T00:27:43 | 2020-05-12T23:30:41 | C++ | UTF-8 | C++ | false | false | 857 | h | // Project4 Copyright (Elliot Couvignou) Dont steal this mayne :(
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "Interactables/P4Interactable.h"
#include "SkillDropActor.generated.h"
UCLASS()
class PROJECT4_API ASkillDropActor : public AP4Interactable
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
ASkillDropActor();
/* if true, thios actor doesnt get destroyed after interaction */
UPROPERTY(BlueprintReadWrite, EditDefaultsOnly)
bool bIsTestActor = false;
virtual void OnInteract(const AP4PlayerCharacterBase* SourceActor) override;
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
UPROPERTY()
TArray<APlayerController*> SeenPlayers;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
};
| [
"ecouvignou@gmail.com"
] | ecouvignou@gmail.com |
47ceee7c091e948c25ea17795f64575605b02094 | 3a78fcd2c9a66789f995513d9beba219c8a45fe8 | /Hardware/krnl_cornertracker.build/link/vivado/vpl/prj/prj.srcs/sources_1/bd/zcu104_base/ip/zcu104_base_m04_regslice_0/sim/zcu104_base_m04_regslice_0_sc.h | f9adfdf4fd8bbccaf5b8c87590830ab646fe5342 | [] | no_license | msimpsonbbx/test_fast | d25a36e3c067a75c1bae7163ece026879f1cb2aa | 01b00070b2d4165c7796726f5a32be93bfee8482 | refs/heads/main | 2023-03-26T00:04:16.541544 | 2021-03-25T16:15:28 | 2021-03-25T16:15:28 | 351,492,336 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,373 | h | #ifndef IP_ZCU104_BASE_M04_REGSLICE_0_SC_H_
#define IP_ZCU104_BASE_M04_REGSLICE_0_SC_H_
// (c) Copyright 1995-2021 Xilinx, Inc. All rights reserved.
//
// This file contains confidential and proprietary information
// of Xilinx, Inc. and is protected under U.S. and
// international copyright and other intellectual property
// laws.
//
// DISCLAIMER
// This disclaimer is not a license and does not grant any
// rights to the materials distributed herewith. Except as
// otherwise provided in a valid license issued to you by
// Xilinx, and to the maximum extent permitted by applicable
// law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
// WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
// AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
// BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
// INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
// (2) Xilinx shall not be liable (whether in contract or tort,
// including negligence, or under any other theory of
// liability) for any loss or damage of any kind or nature
// related to, arising under or in connection with these
// materials, including for any direct, or any indirect,
// special, incidental, or consequential loss or damage
// (including loss of data, profits, goodwill, or any type of
// loss or damage suffered as a result of any action brought
// by a third party) even if such damage or loss was
// reasonably foreseeable or Xilinx had been advised of the
// possibility of the same.
//
// CRITICAL APPLICATIONS
// Xilinx products are not designed or intended to be fail-
// safe, or for use in any application requiring fail-safe
// performance, such as life-support or safety devices or
// systems, Class III medical devices, nuclear facilities,
// applications related to the deployment of airbags, or any
// other applications that could lead to death, personal
// injury, or severe property or environmental damage
// (individually and collectively, "Critical
// Applications"). Customer assumes the sole risk and
// liability of any use of Xilinx products in Critical
// Applications, subject only to applicable laws and
// regulations governing limitations on product liability.
//
// THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
// PART OF THIS FILE AT ALL TIMES.
//
// DO NOT MODIFY THIS FILE.
#ifndef XTLM
#include "xtlm.h"
#endif
#ifndef SYSTEMC_INCLUDED
#include <systemc>
#endif
#if defined(_MSC_VER)
#define DllExport __declspec(dllexport)
#elif defined(__GNUC__)
#define DllExport __attribute__ ((visibility("default")))
#else
#define DllExport
#endif
class axi_register_slice;
class DllExport zcu104_base_m04_regslice_0_sc : public sc_core::sc_module
{
public:
zcu104_base_m04_regslice_0_sc(const sc_core::sc_module_name& nm);
virtual ~zcu104_base_m04_regslice_0_sc();
public: // module socket-to-socket TLM interface
xtlm::xtlm_aximm_initiator_socket* M_INITIATOR_rd_socket;
xtlm::xtlm_aximm_initiator_socket* M_INITIATOR_wr_socket;
xtlm::xtlm_aximm_target_socket* S_TARGET_rd_socket;
xtlm::xtlm_aximm_target_socket* S_TARGET_wr_socket;
protected:
axi_register_slice* mp_impl;
private:
zcu104_base_m04_regslice_0_sc(const zcu104_base_m04_regslice_0_sc&);
const zcu104_base_m04_regslice_0_sc& operator=(const zcu104_base_m04_regslice_0_sc&);
};
#endif // IP_ZCU104_BASE_M04_REGSLICE_0_SC_H_
| [
"m.simpson@beetlebox.org"
] | m.simpson@beetlebox.org |
23b4b4184866f0448ded851321e11d7d49f9f1cf | 1d6a9741b6297e45438ecec81563f56dd5d7fab7 | /src/query_operations/broad_combined_gvcf.cc | babf0c2317c03001a71e7c63161675e5a9cdad7f | [
"MIT"
] | permissive | pearofducks/GenomicsDB | e1255072b70e30cb7c531fd9c74f551edc13f2aa | 15bfe1f614c484a3cfa24c9d88699768179045d0 | refs/heads/master | 2023-09-01T14:07:00.747285 | 2016-04-06T18:17:59 | 2016-04-06T18:17:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,594 | cc | /**
* The MIT License (MIT)
* Copyright (c) 2016 Intel Corporation
*
* 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.
*/
#ifdef HTSDIR
#include "broad_combined_gvcf.h"
//INFO fields
#define MAKE_BCF_INFO_TUPLE(enum_idx, variant_type_enum, bcf_type) \
INFO_tuple_type(enum_idx, variant_type_enum, bcf_type)
#define BCF_INFO_GET_KNOWN_FIELD_ENUM(X) (std::get<0>(X))
#define BCF_INFO_GET_VARIANT_FIELD_TYPE_ENUM(X) (std::get<1>(X))
#define BCF_INFO_GET_BCF_HT_TYPE(X) (std::get<2>(X))
//FORMAT fields
#define MAKE_BCF_FORMAT_TUPLE(enum_idx, variant_type_enum, bcf_type) \
FORMAT_tuple_type(enum_idx, variant_type_enum, bcf_type)
#define BCF_FORMAT_GET_KNOWN_FIELD_ENUM(X) (std::get<0>(X))
#define BCF_FORMAT_GET_VARIANT_FIELD_TYPE_ENUM(X) (std::get<1>(X))
#define BCF_FORMAT_GET_BCF_HT_TYPE(X) (std::get<2>(X))
//Static member
const std::unordered_set<char> BroadCombinedGVCFOperator::m_legal_bases({'A', 'T', 'G', 'C'});
BroadCombinedGVCFOperator::BroadCombinedGVCFOperator(VCFAdapter& vcf_adapter, const VidMapper& id_mapper,
const VariantQueryConfig& query_config)
: GA4GHOperator(query_config)
{
clear();
if(!id_mapper.is_initialized())
throw BroadCombinedGVCFException("Id mapper is not initialized");
m_query_config = &query_config;
//Initialize VCF structs
m_vcf_adapter = &vcf_adapter;
m_vid_mapper = &id_mapper;
m_vcf_hdr = vcf_adapter.get_vcf_header();
m_bcf_out = bcf_init();
//vector of char*, to avoid frequent reallocs()
m_alleles_pointer_buffer.resize(100u);
//INFO fields
m_INFO_fields_vec = std::move(std::vector<INFO_tuple_type>
{
MAKE_BCF_INFO_TUPLE(GVCF_BASEQRANKSUM_IDX, VARIANT_FIELD_FLOAT, BCF_HT_REAL),
MAKE_BCF_INFO_TUPLE(GVCF_CLIPPINGRANKSUM_IDX, VARIANT_FIELD_FLOAT, BCF_HT_REAL),
MAKE_BCF_INFO_TUPLE(GVCF_MQRANKSUM_IDX, VARIANT_FIELD_FLOAT, BCF_HT_REAL),
MAKE_BCF_INFO_TUPLE(GVCF_READPOSRANKSUM_IDX, VARIANT_FIELD_FLOAT, BCF_HT_REAL),
MAKE_BCF_INFO_TUPLE(GVCF_MQ_IDX, VARIANT_FIELD_FLOAT, BCF_HT_REAL),
MAKE_BCF_INFO_TUPLE(GVCF_RAW_MQ_IDX, VARIANT_FIELD_FLOAT, BCF_HT_REAL),
MAKE_BCF_INFO_TUPLE(GVCF_MQ0_IDX, VARIANT_FIELD_INT, BCF_HT_INT)
});
m_FORMAT_fields_vec = std::move(std::vector<FORMAT_tuple_type>
{
MAKE_BCF_FORMAT_TUPLE(GVCF_GT_IDX, VARIANT_FIELD_INT, BCF_HT_INT),
MAKE_BCF_FORMAT_TUPLE(GVCF_GQ_IDX, VARIANT_FIELD_INT, BCF_HT_INT),
MAKE_BCF_FORMAT_TUPLE(GVCF_SB_IDX, VARIANT_FIELD_INT, BCF_HT_INT),
MAKE_BCF_FORMAT_TUPLE(GVCF_AD_IDX, VARIANT_FIELD_INT, BCF_HT_INT),
MAKE_BCF_FORMAT_TUPLE(GVCF_PL_IDX, VARIANT_FIELD_INT, BCF_HT_INT),
MAKE_BCF_FORMAT_TUPLE(GVCF_PGT_IDX, VARIANT_FIELD_CHAR, BCF_HT_STR),
MAKE_BCF_FORMAT_TUPLE(GVCF_PID_IDX, VARIANT_FIELD_CHAR, BCF_HT_STR),
MAKE_BCF_FORMAT_TUPLE(GVCF_MIN_DP_IDX, VARIANT_FIELD_INT, BCF_HT_INT),
MAKE_BCF_FORMAT_TUPLE(GVCF_DP_FORMAT_IDX, VARIANT_FIELD_INT, BCF_HT_INT),
MAKE_BCF_FORMAT_TUPLE(GVCF_DP_IDX, VARIANT_FIELD_INT, BCF_HT_INT) //always last field, read DP not DP_FORMAT field
});
//Last field should always be DP
if(BCF_FORMAT_GET_KNOWN_FIELD_ENUM(m_FORMAT_fields_vec[m_FORMAT_fields_vec.size()-1u]) != GVCF_DP_IDX)
throw BroadCombinedGVCFException("Last queried FORMAT field should be DP, instead it is "
+g_known_variant_field_names[BCF_FORMAT_GET_KNOWN_FIELD_ENUM(m_FORMAT_fields_vec[m_FORMAT_fields_vec.size()-1u])]);
//Discard fields not part of the query
auto last_valid_idx = 0u;
for(auto i=0u;i<m_INFO_fields_vec.size();++i)
{
auto& tuple = m_INFO_fields_vec[i];
if(query_config.is_defined_query_idx_for_known_field_enum((BCF_INFO_GET_KNOWN_FIELD_ENUM(tuple))))
m_INFO_fields_vec[last_valid_idx++] = tuple;
}
m_INFO_fields_vec.resize(last_valid_idx);
//Same for FORMAT
last_valid_idx = 0u;
for(auto i=0u;i<m_FORMAT_fields_vec.size();++i)
{
auto& tuple = m_FORMAT_fields_vec[i];
if(query_config.is_defined_query_idx_for_known_field_enum((BCF_FORMAT_GET_KNOWN_FIELD_ENUM(tuple))))
m_FORMAT_fields_vec[last_valid_idx++] = tuple;
}
m_FORMAT_fields_vec.resize(last_valid_idx);
//Add missing contig names to template header
for(auto i=0u;i<m_vid_mapper->get_num_contigs();++i)
{
auto& contig_info = m_vid_mapper->get_contig_info(i);
auto& contig_name = contig_info.m_name;
if(bcf_hdr_name2id(m_vcf_hdr, contig_name.c_str()) < 0)
{
std::string contig_vcf_line = std::string("##contig=<ID=")+contig_name+",length="
+std::to_string(contig_info.m_length)+">";
int line_length = 0;
auto hrec = bcf_hdr_parse_line(m_vcf_hdr, contig_vcf_line.c_str(), &line_length);
bcf_hdr_add_hrec(m_vcf_hdr, hrec);
bcf_hdr_sync(m_vcf_hdr);
}
}
//Get contig info for position 0, store curr contig in next_contig and call switch_contig function to do all the setup
auto curr_contig_flag = m_vid_mapper->get_next_contig_location(-1ll, m_next_contig_name, m_next_contig_begin_position);
assert(curr_contig_flag);
switch_contig();
//Add samples to template header
std::string callset_name;
for(auto i=0ull;i<query_config.get_num_rows_to_query();++i)
{
auto row_idx = query_config.get_array_row_idx_for_query_row_idx(i);
auto status = m_vid_mapper->get_callset_name(row_idx, callset_name);
assert(status);
bcf_hdr_add_sample(m_vcf_hdr, callset_name.c_str());
}
bcf_hdr_sync(m_vcf_hdr);
m_vcf_adapter->print_header();
//vector of field pointers used for handling remapped fields when dealing with spanning deletions
//Individual pointers will be allocated later
m_spanning_deletions_remapped_fields.resize(m_remapped_fields_query_idxs.size());
}
void BroadCombinedGVCFOperator::clear()
{
m_curr_contig_name.clear();
m_next_contig_name.clear();
m_alleles_pointer_buffer.clear();
m_INFO_fields_vec.clear();
m_FORMAT_fields_vec.clear();
m_MIN_DP_vector.clear();
m_DP_FORMAT_vector.clear();
m_spanning_deletions_remapped_fields.clear();
}
void BroadCombinedGVCFOperator::handle_INFO_fields(const Variant& variant)
{
//interval variant, add END tag
if(m_remapped_variant.get_column_end() > m_remapped_variant.get_column_begin())
{
int vcf_end_pos = m_remapped_variant.get_column_end() - m_curr_contig_begin_position + 1; //vcf END is 1 based
bcf_update_info_int32(m_vcf_hdr, m_bcf_out, "END", &vcf_end_pos, 1);
}
//Compute median for all INFO fields except RAW_MQ
for(auto i=0u;i<m_INFO_fields_vec.size();++i)
{
auto& curr_tuple = m_INFO_fields_vec[i];
auto known_field_enum = BCF_INFO_GET_KNOWN_FIELD_ENUM(curr_tuple);
assert(known_field_enum < g_known_variant_field_names.size());
auto variant_type_enum = BCF_INFO_GET_VARIANT_FIELD_TYPE_ENUM(curr_tuple);
//valid field handler
assert(variant_type_enum < m_field_handlers.size() && m_field_handlers[variant_type_enum].get());
if(known_field_enum != GVCF_RAW_MQ_IDX)
{
//Just need a 4-byte value, the contents could be a float or int (determined by the templated median function)
int32_t median;
auto valid_median_found = m_field_handlers[variant_type_enum]->get_valid_median(variant, *m_query_config,
m_query_config->get_query_idx_for_known_field_enum(known_field_enum), reinterpret_cast<void*>(&median));
if(valid_median_found)
bcf_update_info(m_vcf_hdr, m_bcf_out, g_known_variant_field_names[known_field_enum].c_str(), &median, 1, BCF_INFO_GET_BCF_HT_TYPE(curr_tuple));
}
else
{
//RAW_MQ - was element wise sum initially
//auto num_elements = KnownFieldInfo::get_num_elements_for_known_field_enum(GVCF_RAW_MQ_IDX, 0u, 0u);
//auto result_vector = std::move(std::vector<int>(num_elements, 0u));
//auto valid_sum_found = m_field_handlers[variant_type_enum]->compute_valid_element_wise_sum(variant, *m_query_config,
//m_query_config->get_query_idx_for_known_field_enum(known_field_enum), reinterpret_cast<void*>(&(result_vector[0])), num_elements);
//Just need a 4-byte value, the contents could be a float or int (determined by the templated sum function)
int32_t sum;
auto valid_sum_found = m_field_handlers[variant_type_enum]->get_valid_sum(variant, *m_query_config,
m_query_config->get_query_idx_for_known_field_enum(known_field_enum), reinterpret_cast<void*>(&sum));
if(valid_sum_found)
bcf_update_info(m_vcf_hdr, m_bcf_out, g_known_variant_field_names[known_field_enum].c_str(), &sum, 1, BCF_INFO_GET_BCF_HT_TYPE(curr_tuple));
//bcf_update_info(m_vcf_hdr, m_bcf_out, g_known_variant_field_names[known_field_enum].c_str(), &(result_vector[0]), num_elements,
//BCF_INFO_GET_BCF_HT_TYPE(curr_tuple));
}
}
}
void BroadCombinedGVCFOperator::handle_FORMAT_fields(const Variant& variant)
{
//For weird DP field handling
auto valid_DP_found = false;
auto valid_MIN_DP_found = false;
m_MIN_DP_vector.resize(m_remapped_variant.get_num_calls()); //will do nothing after the first resize
auto valid_DP_FORMAT_found = false;
m_DP_FORMAT_vector.resize(m_remapped_variant.get_num_calls());
//Pointer to extended vector inside field handler object
const void* ptr = 0;
auto num_elements = 0u;
int* int_vec = 0; //will point to same address as ptr, but as int*
//Handle all fields - simply need to extend to the largest size
for(auto i=0u;i<m_FORMAT_fields_vec.size();++i)
{
auto& curr_tuple = m_FORMAT_fields_vec[i];
auto known_field_enum = BCF_FORMAT_GET_KNOWN_FIELD_ENUM(curr_tuple);
assert(known_field_enum < g_known_variant_field_names.size());
auto variant_type_enum = BCF_FORMAT_GET_VARIANT_FIELD_TYPE_ENUM(curr_tuple);
//valid field handler
assert(variant_type_enum < m_field_handlers.size() && m_field_handlers[variant_type_enum].get());
//Check if this is a field that was remapped - for remapped fields, we must use field objects from m_remapped_variant
//else we should use field objects from the original variant
auto query_field_idx = m_query_config->get_query_idx_for_known_field_enum(known_field_enum);
auto& src_variant = (KnownFieldInfo::is_length_allele_dependent(known_field_enum)) ? m_remapped_variant : variant;
auto valid_field_found = m_field_handlers[variant_type_enum]->collect_and_extend_fields(src_variant, *m_query_config,
query_field_idx, &ptr, num_elements);
if(valid_field_found)
{
auto j=0u;
auto do_insert = true; //by default, insert into VCF record
switch(known_field_enum)
{
case GVCF_GT_IDX: //GT field is a pita
int_vec = const_cast<int*>(reinterpret_cast<const int*>(ptr));
//CombineGVCF sets GT field to missing
for(j=0u;j<num_elements;++j)
int_vec[j] = bcf_gt_missing;
//int_vec[j] = (int_vec[j] == get_bcf_missing_value<int>()) ? bcf_gt_missing : bcf_gt_unphased(int_vec[j]);
break;
case GVCF_GQ_IDX:
do_insert = m_should_add_GQ_field;
break;
case GVCF_MIN_DP_IDX: //simply copy over min-dp values
memcpy(&(m_MIN_DP_vector[0]), ptr, m_remapped_variant.get_num_calls()*sizeof(int));
valid_MIN_DP_found = true;
break;
case GVCF_DP_FORMAT_IDX:
memcpy(&(m_DP_FORMAT_vector[0]), ptr, m_remapped_variant.get_num_calls()*sizeof(int));
valid_DP_FORMAT_found = true;
do_insert = false; //Do not insert DP_FORMAT, wait till DP is read
break;
case GVCF_DP_IDX:
int_vec = const_cast<int*>(reinterpret_cast<const int*>(ptr));
valid_DP_found = true;
do_insert = false; //Do not insert DP, handle DP related garbage at the end
break;
default:
break;
}
if(do_insert)
bcf_update_format(m_vcf_hdr, m_bcf_out, g_known_variant_field_names[known_field_enum].c_str(), ptr, num_elements,
BCF_FORMAT_GET_BCF_HT_TYPE(curr_tuple));
}
}
//Update DP fields
if(valid_DP_found || valid_DP_FORMAT_found)
{
int sum_INFO_DP = 0;
auto found_one_valid_DP_FORMAT = false;
for(auto j=0ull;j<m_remapped_variant.get_num_calls();++j)
{
int dp_info_val = valid_DP_found ? int_vec[j] : get_bcf_missing_value<int>();
int dp_format_val = valid_DP_FORMAT_found ? m_DP_FORMAT_vector[j] : get_bcf_missing_value<int>();
assert(is_bcf_valid_value<int>(dp_format_val) || dp_format_val == get_bcf_missing_value<int>());
assert(is_bcf_valid_value<int>(dp_info_val) || dp_info_val == get_bcf_missing_value<int>());
//If DP_FORMAT is invalid, use dp_info value for DP_FORMAT
//dp_format_val = is_bcf_valid_value<int>(dp_format_val) ? dp_format_val : dp_info_val;
if(!is_bcf_valid_value<int>(dp_info_val)) //no valid DP info value found
{
//MIN_DP gets higher priority
if(valid_MIN_DP_found && is_bcf_valid_value<int>(m_MIN_DP_vector[j]))
dp_info_val = m_MIN_DP_vector[j];
else //else DP_FORMAT
dp_info_val = dp_format_val;
}
m_DP_FORMAT_vector[j] = dp_format_val;
found_one_valid_DP_FORMAT = is_bcf_valid_value<int>(dp_format_val) || found_one_valid_DP_FORMAT;
sum_INFO_DP += (is_bcf_valid_value<int>(dp_info_val) ? dp_info_val : 0);
}
if(found_one_valid_DP_FORMAT)
bcf_update_format_int32(m_vcf_hdr, m_bcf_out, "DP", &(m_DP_FORMAT_vector[0]), m_DP_FORMAT_vector.size()); //add DP FORMAT field
//If valid DP INFO field found, add to INFO list
if(valid_DP_found)
bcf_update_info_int32(m_vcf_hdr, m_bcf_out, "DP", &sum_INFO_DP, 1);
}
}
void BroadCombinedGVCFOperator::operate(Variant& variant, const VariantQueryConfig& query_config)
{
//Handle spanning deletions - change ALT alleles in calls with deletions to *, <NON_REF>
handle_deletions(variant, query_config);
GA4GHOperator::operate(variant, query_config);
//Moved to new contig
if(static_cast<int64_t>(m_remapped_variant.get_column_begin()) >= m_next_contig_begin_position)
{
std::string contig_name;
int64_t contig_position;
auto status = m_vid_mapper->get_contig_location(m_remapped_variant.get_column_begin(), contig_name, contig_position);
if(status)
{
int64_t contig_begin_position = m_remapped_variant.get_column_begin() - contig_position;
if(contig_begin_position != m_next_contig_begin_position)
{
m_next_contig_name = std::move(contig_name);
m_next_contig_begin_position = contig_begin_position;
}
}
else
throw BroadCombinedGVCFException("Unknown contig for position "+std::to_string(m_remapped_variant.get_column_begin()));
switch_contig();
}
//clear out
bcf_clear(m_bcf_out);
//If no valid FORMAT fields exist, this value is never set
m_bcf_out->n_sample = bcf_hdr_nsamples(m_vcf_hdr);
//position
m_bcf_out->rid = m_curr_contig_hdr_idx;
m_bcf_out->pos = m_remapped_variant.get_column_begin() - m_curr_contig_begin_position;
//GATK combined GVCF does not care about QUAL value
m_bcf_out->qual = get_bcf_missing_value<float>();
//Update alleles
auto& ref_allele = dynamic_cast<VariantFieldString*>(m_remapped_variant.get_common_field(0u).get())->get();
if(ref_allele.length() == 1u && ref_allele[0] == 'N')
{
ref_allele[0] = m_vcf_adapter->get_reference_base_at_position(m_curr_contig_name.c_str(), m_bcf_out->pos);
if(BroadCombinedGVCFOperator::m_legal_bases.find(ref_allele[0]) == BroadCombinedGVCFOperator::m_legal_bases.end())
ref_allele[0] = 'N';
}
const auto& alt_alleles = dynamic_cast<VariantFieldALTData*>(m_remapped_variant.get_common_field(1u).get())->get();
auto total_num_merged_alleles = alt_alleles.size() + 1u; //+1 for REF
if(total_num_merged_alleles > m_alleles_pointer_buffer.size())
m_alleles_pointer_buffer.resize(total_num_merged_alleles);
//REF
m_alleles_pointer_buffer[0] = ref_allele.c_str();
//ALT
for(auto i=1u;i<total_num_merged_alleles;++i)
m_alleles_pointer_buffer[i] = alt_alleles[i-1u].c_str();
bcf_update_alleles(m_vcf_hdr, m_bcf_out, &(m_alleles_pointer_buffer[0]), total_num_merged_alleles);
//Flag that determines when to add GQ field - only when <NON_REF> is the only alternate allele
//m_should_add_GQ_field = (m_NON_REF_exists && alt_alleles.size() == 1u);
m_should_add_GQ_field = true; //always added in new version of CombineGVCFs
//INFO fields
handle_INFO_fields(variant);
//FORMAT fields
handle_FORMAT_fields(variant);
m_vcf_adapter->handoff_output_bcf_line(m_bcf_out);
}
void BroadCombinedGVCFOperator::switch_contig()
{
m_curr_contig_name = std::move(m_next_contig_name);
m_curr_contig_begin_position = m_next_contig_begin_position;
m_curr_contig_hdr_idx = bcf_hdr_id2int(m_vcf_hdr, BCF_DT_CTG, m_curr_contig_name.c_str());
m_vid_mapper->get_next_contig_location(m_next_contig_begin_position, m_next_contig_name, m_next_contig_begin_position);
}
//Modifies original Variant object
void BroadCombinedGVCFOperator::handle_deletions(Variant& variant, const VariantQueryConfig& query_config)
{
m_reduced_alleles_LUT.resize_luts_if_needed(variant.get_num_calls(), 10u); //will not have more than 3 alleles anyway
m_reduced_alleles_LUT.reset_luts();
for(auto iter=variant.begin(), e=variant.end();iter != e;++iter)
{
auto& curr_call = *iter;
auto curr_call_idx_in_variant = iter.get_call_idx_in_variant();
//Deletion and not handled as spanning deletion
//So replace the ALT with *,<NON_REF> and REF with "N"
//Remap PL, AD fields
if(curr_call.contains_deletion() && variant.get_column_begin() > curr_call.get_column_begin())
{
auto& ref_allele = get_known_field<VariantFieldString, true>(curr_call, query_config, GVCF_REF_IDX)->get();
auto& alt_alleles = get_known_field<VariantFieldALTData, true>(curr_call, query_config, GVCF_ALT_IDX)->get();
assert(alt_alleles.size() > 0u);
//Already handled as a spanning deletion, nothing to do
if(alt_alleles[0u] == g_vcf_SPANNING_DELETION)
continue;
//Reduced allele list will be REF="N", ALT="*, <NON_REF>"
m_reduced_alleles_LUT.add_input_merged_idx_pair(curr_call_idx_in_variant, 0, 0); //REF-REF mapping
//Need to find deletion allele with lowest PL value - this deletion allele is mapped to "*" allele
auto lowest_deletion_allele_idx = -1;
int lowest_PL_value = INT_MAX;
auto PL_field_ptr = get_known_field_if_queried<VariantFieldPrimitiveVectorData<int>, true>(curr_call, query_config, GVCF_PL_IDX);
auto has_NON_REF = false;
//PL field exists
if(PL_field_ptr)
{
auto& PL_vector = PL_field_ptr->get();
for(auto i=0u;i<alt_alleles.size();++i)
{
auto allele_idx = i+1; //+1 for REF
if(VariantUtils::is_deletion(ref_allele, alt_alleles[i]))
{
unsigned gt_idx = bcf_alleles2gt(allele_idx, allele_idx);
assert(gt_idx < PL_vector.size());
if(PL_vector[gt_idx] < lowest_PL_value)
{
lowest_PL_value = PL_vector[gt_idx];
lowest_deletion_allele_idx = allele_idx;
}
}
else
if(IS_NON_REF_ALLELE(alt_alleles[i]))
{
m_reduced_alleles_LUT.add_input_merged_idx_pair(curr_call_idx_in_variant, allele_idx, 2);
has_NON_REF = true;
}
}
}
else //PL field is not queried, simply use the first ALT allele
lowest_deletion_allele_idx = 1;
assert(lowest_deletion_allele_idx >= 1); //should be an ALT allele
//first ALT allele in reduced list is *
m_reduced_alleles_LUT.add_input_merged_idx_pair(curr_call_idx_in_variant, lowest_deletion_allele_idx, 1);
if(has_NON_REF)
{
alt_alleles.resize(2u);
alt_alleles[1u] = TILEDB_NON_REF_VARIANT_REPRESENTATION;
}
else
alt_alleles.resize(1u); //only spanning deletion
ref_allele = "N"; //set to unknown REF for now
alt_alleles[0u] = g_vcf_SPANNING_DELETION;
unsigned num_reduced_alleles = alt_alleles.size() + 1u; //+1 for REF
//Remap fields that need to be remapped
for(auto i=0u;i<m_remapped_fields_query_idxs.size();++i)
{
auto query_field_idx = m_remapped_fields_query_idxs[i];
//is known field?
assert(query_config.is_defined_known_field_enum_for_query_idx(query_field_idx));
const auto* info_ptr = query_config.get_info_for_query_idx(query_field_idx);
//known field whose length is dependent on #alleles
assert(info_ptr && info_ptr->is_length_allele_dependent());
unsigned num_reduced_elements = info_ptr->get_num_elements_for_known_field_enum(num_reduced_alleles-1u, 0u); //#alt alleles
//Remapper for variant
RemappedVariant remapper_variant(variant, query_field_idx);
auto& curr_field = curr_call.get_field(query_field_idx);
if(curr_field.get() && curr_field->is_valid()) //Not null
{
//Copy field to pass to remap function
assert(i < m_spanning_deletions_remapped_fields.size());
copy_field(m_spanning_deletions_remapped_fields[i], curr_field);
curr_field->resize(num_reduced_elements);
//Get handler for current type
auto& handler = get_handler_for_type(curr_field->get_element_type());
assert(handler.get());
//Call remap function
handler->remap_vector_data(
m_spanning_deletions_remapped_fields[i], curr_call_idx_in_variant,
m_reduced_alleles_LUT, num_reduced_alleles, has_NON_REF,
info_ptr->get_length_descriptor(), num_reduced_elements, remapper_variant);
}
}
//Broad's CombineGVCF ignores GT field anyway - set missing
if(m_GT_query_idx != UNDEFINED_ATTRIBUTE_IDX_VALUE)
{
auto& GT_vector = get_known_field<VariantFieldPrimitiveVectorData<int>, true>(curr_call, query_config, GVCF_GT_IDX)->get();
for(auto i=0u;i<GT_vector.size();++i)
GT_vector[i] = get_tiledb_null_value<int>();
}
//Invalidate INFO fields
for(const auto& tuple : m_INFO_fields_vec)
{
assert(query_config.is_defined_query_idx_for_known_field_enum(BCF_INFO_GET_KNOWN_FIELD_ENUM(tuple)));
auto query_idx = query_config.get_query_idx_for_known_field_enum(BCF_INFO_GET_KNOWN_FIELD_ENUM(tuple));
auto& field = curr_call.get_field(query_idx);
if(field.get())
field->set_valid(false);
}
}
}
}
#endif //ifdef HTSDIR
| [
"karthik.gururaj@intel.com"
] | karthik.gururaj@intel.com |
919f7984c3e85871e7564edb7c2e6febb8f61549 | aecf4944523b50424831f8af3debef67e3163b97 | /net.ssa/xr_3da/xrGame/AI/Idol/ai_idol.cpp | 59ee233078b13e4b97252e9f94eb7ffafaeaadda | [] | no_license | xrLil-Batya/gitxray | bc8c905444e40c4da5d77f69d03b41d5b9cec378 | 58aaa5185f7a682b8cf5f5f376a2e5b6ca16fed4 | refs/heads/main | 2023-03-31T07:43:57.500002 | 2020-12-12T21:12:25 | 2020-12-12T21:12:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,185 | cpp | ////////////////////////////////////////////////////////////////////////////
// Module : ai_crow.cpp
// Created : 13.05.2002
// Modified : 13.05.2002
// Author : Dmitriy Iassenev
// Description : AI Behaviour for monster "Crow"
////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "ai_idol.h"
#include "../../inventory.h"
#include "../../phmovementcontrol.h"
#include "../../xrserver_objects_alife_monsters.h"
#include "../../../skeletonanimated.h"
CAI_Idol::CAI_Idol ()
{
m_tpCurrentBlend = 0;
m_bPlaying = false;
m_dwCurrentAnimationIndex = 0;
m_PhysicMovementControl->AllocateCharacterObject(CPHMovementControl::CharacterType::ai);
}
CAI_Idol::~CAI_Idol ()
{
}
void CAI_Idol::Load (LPCSTR section)
{
setEnabled (false);
inherited::Load (section);
}
BOOL CAI_Idol::net_Spawn (LPVOID DC)
{
CSE_Abstract *e = (CSE_Abstract*)(DC);
CSE_ALifeObjectIdol *tpIdol = smart_cast<CSE_ALifeObjectIdol*>(e);
R_ASSERT (tpIdol);
if (!inherited::net_Spawn(DC)) return FALSE;
m_dwAnyPlayType = tpIdol->m_dwAniPlayType;
m_tpaAnims.clear ();
m_body.current.yaw = m_body.target.yaw = -tpIdol->o_Angle.y;
m_body.current.pitch = m_body.target.pitch = 0;
u32 N = _GetItemCount(*tpIdol->m_caAnimations);
string32 I;
for (u32 i=0; i<N; ++i)
m_tpaAnims.push_back (smart_cast<CSkeletonAnimated*>(Visual())->ID_Cycle(_GetItem(*tpIdol->m_caAnimations,i,I)));
return TRUE;
}
void CAI_Idol::SelectAnimation (const Fvector& /**_view/**/, const Fvector& /**_move/**/, float /**speed/**/)
{
//R_ASSERT (!m_tpaAnims.empty());
if (m_tpaAnims.empty())
return;
if (g_Alive()) {
switch (m_dwAnyPlayType) {
case 0 : {
if (!m_bPlaying) {
m_tpCurrentBlend = smart_cast<CSkeletonAnimated*>(Visual())->PlayCycle (m_tpaAnims[::Random.randI((int)m_tpaAnims.size())],TRUE,AnimCallback,this);
m_bPlaying = true;
}
break;
}
case 1 : {
if (!m_bPlaying) {
m_tpCurrentBlend = smart_cast<CSkeletonAnimated*>(Visual())->PlayCycle (m_tpaAnims[m_dwCurrentAnimationIndex],TRUE,AnimCallback,this);
m_bPlaying = true;
m_dwCurrentAnimationIndex = (m_dwCurrentAnimationIndex + 1) % m_tpaAnims.size();
}
break;
}
case 2 : {
if (!m_bPlaying) {
m_tpCurrentBlend = smart_cast<CSkeletonAnimated*>(Visual())->PlayCycle (m_tpaAnims[m_dwCurrentAnimationIndex],TRUE,AnimCallback,this);
m_bPlaying = true;
if (m_dwCurrentAnimationIndex < m_tpaAnims.size() - 1)
++m_dwCurrentAnimationIndex;
}
break;
}
default : NODEFAULT;
}
}
}
IC BOOL BE (BOOL A, BOOL B)
{
bool a = !!A;
bool b = !!B;
return a==b;
}
void CAI_Idol::OnEvent (NET_Packet& P, u16 type)
{
inherited::OnEvent (P,type);
u16 id;
switch (type)
{
case GE_OWNERSHIP_TAKE:
{
P.r_u16 (id);
CObject* O = Level().Objects.net_Find (id);
if (bDebug) Log("Trying to take - ", *O->cName());
if(g_Alive() && inventory().Take(smart_cast<CGameObject*>(O), false, false)) {
O->H_SetParent(this);
if (bDebug) Log("TAKE - ", *O->cName());
}
}
break;
case GE_OWNERSHIP_REJECT:
{
P.r_u16 (id);
CObject* O = Level().Objects.net_Find (id);
if(inventory().Drop(smart_cast<CGameObject*>(O))) {
O->H_SetParent(0);
feel_touch_deny(O,2000);
}
}
break;
case GE_TRANSFER_AMMO:
{
}
break;
}
}
void CAI_Idol::feel_touch_new (CObject* O)
{
if (!g_Alive()) return;
if (Remote()) return;
// Now, test for game specific logical objects to minimize traffic
CInventoryItem *I = smart_cast<CInventoryItem*> (O);
if (I && I->useful_for_NPC()) {
Msg("Taking item %s!",*I->cName());
NET_Packet P;
u_EventGen (P,GE_OWNERSHIP_TAKE,ID());
P.w_u16 (u16(I->ID()));
u_EventSend (P);
}
}
void CAI_Idol::DropItemSendMessage(CObject *O)
{
if (!O || !O->H_Parent() || (this != O->H_Parent()))
return;
Msg("Dropping item!");
// We doesn't have similar weapon - pick up it
NET_Packet P;
u_EventGen (P,GE_OWNERSHIP_REJECT,ID());
P.w_u16 (u16(O->ID()));
u_EventSend (P);
}
void CAI_Idol::shedule_Update(u32 dt)
{
inherited::shedule_Update(dt);
}
void CAI_Idol::g_WeaponBones (int &L, int &R1, int &R2)
{
if (g_Alive() && inventory().ActiveItem()) {
CKinematics *V = smart_cast<CKinematics*>(Visual());
R1 = V->LL_BoneID("bip01_r_hand");
R2 = V->LL_BoneID("bip01_r_finger2");
L = V->LL_BoneID("bip01_l_finger1");
}
}
void CAI_Idol::renderable_Render ()
{
inherited::renderable_Render ();
if(inventory().ActiveItem())
inventory().ActiveItem()->renderable_Render();
}
void CAI_Idol::g_fireParams(const CHudItem* pHudItem, Fvector& P, Fvector& D)
{
if (g_Alive() && inventory().ActiveItem()) {
Center(P);
D.setHP(0,0);
D.normalize_safe();
}
}
void CAI_Idol::AnimCallback (CBlend* B)
{
CAI_Idol *tpIdol = (CAI_Idol*)B->CallbackParam;
tpIdol->m_bPlaying = false;
}
| [
"admin@localhost"
] | admin@localhost |
752bfab3d58a51074ef1231600f274e576689b89 | d0448333c6b9df7d8da49ded311910bc58d42f95 | /include/backend/ChannelsHandler.hpp | 7ad206832454f5c368ee9ccf31f6c8fe75970d09 | [
"MIT"
] | permissive | skydiveuas/fm-client-sdk-cpp | 88d635c6451efe09b49d36c2b3fe06d8390a8e69 | 2ce252b7692b4eb0f09758dac18ece74468f7531 | refs/heads/master | 2020-04-15T06:50:58.753610 | 2019-05-12T20:36:46 | 2019-05-12T20:36:46 | 164,475,815 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,334 | hpp | #ifndef FM_BACKEND_CHANNELSHANDLER_HPP
#define FM_BACKEND_CHANNELSHANDLER_HPP
#include "traffic/ChannelImpl.hpp"
#include "common/channel_management.pb.h"
#include <boost/asio/ssl.hpp>
#include <boost/log/trivial.hpp>
#include <memory>
#include <vector>
#include <unordered_map>
namespace fm
{
namespace backend
{
class ClientBackend;
/**
* Created by: Bartosz Nawrot
* Date: 2018-12-16
* Description:
*/
class ChannelsHandler
{
public:
ChannelsHandler(ClientBackend&);
std::vector<traffic::IChannel*> getChannels();
std::vector<traffic::IChannel*> getChannels(const std::vector<long>&);
std::vector<long> getChannelsIds();
std::vector<traffic::IChannel*> validateChannels(const std::vector<com::fleetmgr::interfaces::ChannelResponse>&);
void closeChannels(const std::vector<long>&);
void closeAllChannels();
void setOwned(const std::vector<long>&);
void setOwned(long, bool);
private:
ClientBackend& backend;
boost::asio::ssl::context sslContext;
std::unordered_map<long, traffic::ChannelImpl> channels;
void log(const boost::log::trivial::severity_level&, const std::string&);
std::shared_ptr<traffic::socket::ISocket> buildSocket(const com::fleetmgr::interfaces::ChannelResponse&);
};
} // backend
} // fm
#endif // FM_BACKEND_CHANNELSHANDLER_HPP
| [
"nawbar23@gmail.com"
] | nawbar23@gmail.com |
3aeb4ac1eae8ecef45f7be5df25743316986a877 | 6d688b229c25594887966cd3f18c17132d685f3c | /PhoneBook/test.cpp | 9c33853ed17d02798584eba2cd24e5c17d7b8293 | [] | no_license | makisto/STP2 | bfe3bfff3751589d742461917e3e12b05f55a0b3 | 8d3b8d7d1266f25312b69dbb65c20b5a95e0f3ee | refs/heads/main | 2023-04-10T00:41:33.638800 | 2021-04-22T13:20:52 | 2021-04-22T13:20:52 | 360,524,438 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,380 | cpp | #include "test.h"
#include "phoneb.h"
#include <QtTest/QTest>
test::test(QObject *parent) : QObject(parent) {}
void test::add()
{
phoneB p;
p.add("ivan", "+1234567890");
QMultiMap<QString, QString> res;
res.insert("ivan", "+1234567890");
QCOMPARE(res, p.getPhoneBook());
res.insert("iv", "+1234567890");
bool check = res == p.getPhoneBook();
QCOMPARE(false, check);
}
void test::del() {
phoneB p;
p.add("ivan", "+1234567890");
p.add("ivan1", "+1234567890");
int res = 2;
QCOMPARE(res, p.getPhoneBook().size());
p.del("ivan");
res = 1;
QCOMPARE(res, p.getPhoneBook().size());
}
void test::clear()
{
phoneB p;
p.add("ivan", "+1234567890");
p.add("ivan1", "+1234567890");
bool res = true;
p.clear();
QCOMPARE(res, p.getPhoneBook().isEmpty());
}
void test::isUniqueName()
{
phoneB p;
p.add("ivan", "+1234567890");
p.add("ivan1", "+1234567890");
bool res = true;
QCOMPARE(res, p.isUniqueName("ivan"));
res = false;
QCOMPARE(res, p.isUniqueName("petr"));
}
void test::find()
{
phoneB p;
p.add("petr", "+242342323423");
p.add("ivan1", "+1234567890");
p.add("ivan", "+1234567890");
int index = 2;
QCOMPARE(index, p.find("petr"));
index = 0;
QCOMPARE(index, p.find("ivan"));
index = -1;
QCOMPARE(index, p.find("iv"));
}
| [
"TJAYYM@yandex.ru"
] | TJAYYM@yandex.ru |
3bfa393fe35987042c4e7b4f1cd119097edf85ab | 785f542387f302225a8a95af820eaccb50d39467 | /codeforces/448-A/448-A-7126769.cpp | 9b11f07950852f97ae4ad1d74cfb69a0f959a15d | [] | no_license | anveshi/Competitive-Programming | ce33b3f0356beda80b50fee48b0c7b0f42c44b0c | 9a719ea3a631320dfa84c60300f45e370694b378 | refs/heads/master | 2016-08-12T04:27:13.078738 | 2015-01-19T17:30:00 | 2016-03-08T17:44:36 | 51,570,689 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 702 | cpp | /*
Thursday 17th July 2014
By ++Anveshi Shukla
*/
#include<bits/stdc++.h>
#define sz(a) int((a).size())
#define pb push_back
#define all(c) (c).begin(),(c).end()
#define tr(c,i) for(typeof((c).begin() i=(c).begin() ;i!=c.end();i++)
#define present(c,x) ((c).find(x)!=(c).end())
#define cpresent(c,x) (find(all(c),x)!=(c).end())
using namespace std;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef pair<int,int> ii;
int main()
{
// code starts here
int a1,a2,a3,b1,b2,b3,n;
scanf("%d %d %d",&a1,&a2,&a3); //cups
scanf("%d %d %d",&b1,&b2,&b3); // medals
scanf("%d",&n);
int x,y;
x=(a1+a2+a3+4)/5;
y=(b1+b2+b3+9)/10;
if(x+y<=n)printf("YES\n");
else printf("NO\n");
return 0;
} | [
"anveshishukla@gmail.com"
] | anveshishukla@gmail.com |
e7bbb755f35c97c423649dbdbc82282055779d4b | f3866e1a2c0919ff464acc7c916beb4c4ffd68e8 | /benchmarks/deretta-coroutine/libs/coroutine/test/test_meta.cpp | 3dcf1fd3e0a71923fd7f48466ed97d42a2dc243e | [] | no_license | bombela/CxxCoroutine | 2f2f68ad76db103abd2fe7e896db32805fac9922 | dee6aac5b1436cef359f17447248641bcc52bbc2 | refs/heads/master | 2021-01-15T21:44:20.486195 | 2011-10-18T07:00:53 | 2011-10-18T07:00:53 | 1,563,956 | 13 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 2,208 | cpp | // Copyright (c) 2006, Giovanni P. Deretta
//
// This code may be used under either of the following two licences:
//
// 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. OF SUCH DAMAGE.
//
// Or:
//
// 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)
#include <iostream>
#include <boost/mpl/assert.hpp>
#include <boost/coroutine/detail/is_callable.hpp>
namespace coroutines = boost::coroutines;
struct test_is_function_pointer {
template<typename T>
test_is_function_pointer(T) {
BOOST_MPL_ASSERT((coroutines::detail::is_function_pointer<T>));
}
};
struct test_is_functor {
template<typename T>
test_is_functor(T) {
BOOST_MPL_ASSERT((coroutines::detail::is_functor<T>));
}
};
struct test_is_callable {
template<typename T>
test_is_callable(T) {
BOOST_MPL_ASSERT((coroutines::detail::is_callable<T>));
}
};
void foo() {}
struct bar {
typedef void result_type;
} a_bar;
int main() {
test_is_function_pointer t1 (foo);
test_is_functor t2 (a_bar);
test_is_callable t3 (foo);
test_is_callable t4 (a_bar);
}
| [
"bombela@gmail.com"
] | bombela@gmail.com |
33abca17227bdbcf15f3fa8915b31c5cff2a399b | e711b9e143b1c94e3358365923f13e5ff1caf313 | /apps/editors/backup/ModelEditor/GenerateTiles.cpp | 106b8971d3191463a79ab02ba53abbb7102ecdcf | [] | no_license | galapaegos/old-engine | adf25cc62eb4295dab9c85ec4d96ac446a4a3d6d | ed2086c0ba0d1fbefc254ffde8785e33a6cfbe2a | refs/heads/master | 2020-07-10T03:33:58.835462 | 2019-08-24T12:56:48 | 2019-08-24T12:56:48 | 204,156,406 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,706 | cpp | #include "GenerateTiles.h"
GenerateTiles::GenerateTiles (const int &x, const int &y, const int &w, const int &h) : gswin::gswindow (0,
"GenerateTiles", "Generate Tiles", WS_OVERLAPPEDWINDOW, x, y, w, h)
{
gswin::gsdescription *pWidthDesc = new gswin::gsdescription ("Number of width tiles:", 5, 5, 120, 25, this);
m_pWidth = new gswin::gstextbox ("", WS_CHILD|ES_LEFT, 130, 5, 50, 25, this);
gswin::gsdescription *pHeightDesc = new gswin::gsdescription ("Number of height tiles:", 5, 35, 120, 25, this);
m_pHeight = new gswin::gstextbox ("", WS_CHILD|ES_LEFT, 130, 35, 50, 25, this);
m_pOk = new gswin::gsbutton ("Ok", BS_PUSHBUTTON|WS_CHILD, 5, 70, w/2 - 10, 25, this);
m_pCancel = new gswin::gsbutton ("Cancel", BS_PUSHBUTTON|WS_CHILD, w/2 + 5, 70, w/2 - 10, 25, this);
}
GenerateTiles::~GenerateTiles ()
{
}
void GenerateTiles::onClose ()
{
delete this;
}
void GenerateTiles::onCommand (void *wParam, void *lParam)
{
WPARAM wp = (WPARAM)wParam;
LPARAM lp = (LPARAM)lParam;
if ((HWND)lp == m_pOk->getHandle ())
{
int w = atoi (m_pWidth->getText ().str ());
int h = atoi (m_pHeight->getText ().str ());
if (w == 0 || h == 0)
return;
gsgeom::gsscene *s = TileConfig::get ()->m_pScene;
s->m_Geometry->m_mutex.lock ();
gsutil::gsarray <gsgeom::gsvec3f> temp;
temp.resize (w*h);
for (int x = 0; x < w; x++)
for (int y = 0; y < h; y++)
temp.add (gsgeom::gsvec3f ((float)x, 0, (float)y));
for (int x = 0; x < w - 1; x++)
{
for (int y = 0; y < h - 1; y++)
{
gsgeom::gsscene *child = new gsgeom::gsscene;
s->m_ChildNodes.add (child);
gsgeom::gseffect *effect = new gsgeom::gseffect;
effect->setLineSettings (true);
effect->setLineWidth (3.f);
child->m_pEffect = effect;
gsgeom::gsgeometryinfo *g = new gsgeom::gsgeometryinfo;
child->m_Geometry = g;
g->m_vPoints.add (temp[w*x + y]);
g->m_vPoints.add (temp[w*x + y + 1]);
g->m_vPoints.add (temp[w*(x + 1) + y + 1]);
g->m_vPoints.add (temp[w*(x + 1) + y]);
g->m_vColors.add (gsgeom::gscolor (1, 1, 1, 1));
g->m_vColors.add (gsgeom::gscolor (1, 1, 1, 1));
g->m_vColors.add (gsgeom::gscolor (1, 1, 1, 1));
g->m_vColors.add (gsgeom::gscolor (1, 1, 1, 1));
gsgeom::gsgeometryinfo::IndexType *i = new gsgeom::gsgeometryinfo::IndexType;
g->m_vIndices.add (i);
i->indexType = gsgeom::gsgeometryinfo::GS_TRIANGLE;
i->m_vIndices.add (0);
i->m_vIndices.add (1);
i->m_vIndices.add (2);
i->m_vIndices.add (2);
i->m_vIndices.add (3);
i->m_vIndices.add (0);
}
}
s->m_Geometry->m_mutex.unlock ();
temp.clear ();
delete this;
}
else if ((HWND)lp == m_pCancel->getHandle ())
{
delete this;
}
}
| [
"bhittle@osc.edu"
] | bhittle@osc.edu |
a850c09899a14cb051674350beb6cdf660026533 | 6aab87375568c398181acfc378c128acb8e8528a | /NEPS/SDK/Vector.h | 15063cc165abd9f3b10cbd5391e5d7aaac1ef38b | [
"BSD-3-Clause",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | CrackerCat/NEPS | 011f8402672b3305f63c11f3160ed352f000f838 | 4f3dc9223fcde3c1af6fea3d5fa359f2e2fa247e | refs/heads/master | 2023-07-13T07:12:38.686911 | 2021-08-22T16:26:38 | 2021-08-22T16:26:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,644 | h | #pragma once
#include <cmath>
#include "../lib/Helpers.hpp"
class Matrix3x4;
struct Vector
{
constexpr auto notNull() const noexcept
{
return x || y || z;
}
constexpr auto operator==(const Vector &v) const noexcept
{
return x == v.x && y == v.y && z == v.z;
}
constexpr auto operator>=(const Vector &v) const noexcept
{
return x >= v.x && y >= v.y && z >= v.z;
}
constexpr auto operator<=(const Vector &v) const noexcept
{
return x <= v.x && y <= v.y && z <= v.z;
}
constexpr auto operator>(const Vector &v) const noexcept
{
return x > v.x && y > v.y && z > v.z;
}
constexpr auto operator<(const Vector &v) const noexcept
{
return x < v.x &&y < v.y &&z < v.z;
}
constexpr auto operator!=(const Vector &v) const noexcept
{
return !(*this == v);
}
constexpr Vector &operator=(const float array[3]) noexcept
{
x = array[0];
y = array[1];
z = array[2];
return *this;
}
constexpr Vector &operator+=(const Vector &v) noexcept
{
x += v.x;
y += v.y;
z += v.z;
return *this;
}
constexpr Vector &operator+=(float f) noexcept
{
x += f;
y += f;
z += f;
return *this;
}
constexpr Vector &operator-=(const Vector &v) noexcept
{
x -= v.x;
y -= v.y;
z -= v.z;
return *this;
}
constexpr Vector &operator-=(float f) noexcept
{
x -= f;
y -= f;
z -= f;
return *this;
}
constexpr auto operator-(const Vector &v) const noexcept
{
return Vector{x - v.x, y - v.y, z - v.z};
}
constexpr auto operator+(const Vector &v) const noexcept
{
return Vector{x + v.x, y + v.y, z + v.z};
}
constexpr auto operator*(const Vector &v) const noexcept
{
return Vector{x * v.x, y * v.y, z * v.z};
}
constexpr Vector &operator/=(float div) noexcept
{
x /= div;
y /= div;
z /= div;
return *this;
}
constexpr Vector &operator*=(float mul) noexcept
{
x *= mul;
y *= mul;
z *= mul;
return *this;
}
constexpr auto operator*(float mul) const noexcept
{
return Vector{x * mul, y * mul, z * mul};
}
constexpr auto operator/(float div) const noexcept
{
return Vector{x / div, y / div, z / div};
}
constexpr auto operator-(float sub) const noexcept
{
return Vector{x - sub, y - sub, z - sub};
}
constexpr auto operator+(float add) const noexcept
{
return Vector{x + add, y + add, z + add};
}
constexpr auto operator-() const noexcept
{
return Vector{-x, -y, -z};
}
Vector &normalize() noexcept
{
x = Helpers::normalizeDeg(x);
y = Helpers::normalizeDeg(y);
z = 0.0f;
return *this;
}
auto length() const noexcept
{
return std::sqrt(x * x + y * y + z * z);
}
auto length2D() const noexcept
{
return std::sqrt(x * x + y * y);
}
constexpr auto lengthSquared() const noexcept
{
return x * x + y * y + z * z;
}
constexpr auto lengthSquared2D() const noexcept
{
return x * x + y * y;
}
constexpr auto dotProduct(const Vector &v) const noexcept
{
return x * v.x + y * v.y + z * v.z;
}
constexpr auto dotProduct2D(const Vector &v) const noexcept
{
return x * v.x + y * v.y;
}
constexpr auto crossProduct(const Vector &v) const noexcept
{
return Vector{y * v.z - z * v.y, z * v.x - x * v.z, x * v.y - y * v.x};
}
auto rotate(const Vector &axis, float angle) const noexcept
{
const auto cos = std::cos(Helpers::degreesToRadians(angle));
const auto sin = std::sin(Helpers::degreesToRadians(angle));
return *this * cos + axis.crossProduct(*this) * sin + axis * axis.dotProduct(*this) * (1.0f - cos);
}
constexpr auto transform(const Matrix3x4 &mat) const noexcept;
auto distTo(const Vector &v) const noexcept
{
return (*this - v).length();
}
auto distToSquared(const Vector &v) const noexcept
{
return (*this - v).lengthSquared();
}
auto toAngle() const noexcept
{
return Vector{Helpers::radiansToDegrees(std::atan2f(-z, std::hypot(x, y))),
Helpers::radiansToDegrees(std::atan2f(y, x)),
0.0f};
}
auto toAngle2D() const noexcept
{
return Helpers::radiansToDegrees(std::atan2f(y, x));
}
auto snapTo4() const noexcept
{
const float l = length2D();
bool xp = x >= 0.0f;
bool yp = y >= 0.0f;
bool xy = std::fabsf(x) >= std::fabsf(y);
if (xp && xy)
return Vector{l, 0.0f, 0.0f};
if (!xp && xy)
return Vector{-l, 0.0f, 0.0f};
if (yp && !xy)
return Vector{0.0f, l, 0.0f};
if (!yp && !xy)
return Vector{0.0f, -l, 0.0f};
return Vector{};
}
static auto fromAngle(const Vector &angle) noexcept
{
return Vector{std::cos(Helpers::degreesToRadians(angle.x)) * std::cos(Helpers::degreesToRadians(angle.y)),
std::cos(Helpers::degreesToRadians(angle.x)) * std::sin(Helpers::degreesToRadians(angle.y)),
-std::sin(Helpers::degreesToRadians(angle.x))};
}
static auto fromAngle2D(float angle) noexcept
{
return Vector{std::cos(Helpers::degreesToRadians(angle)),
std::sin(Helpers::degreesToRadians(angle)),
0.0f};
}
static auto up() noexcept
{
return Vector{0.0f, 0.0f, 1.0f};
}
static auto down() noexcept
{
return Vector{0.0f, 0.0f, -1.0f};
}
static auto forward() noexcept
{
return Vector{1.0f, 0.0f, 0.0f};
}
static auto back() noexcept
{
return Vector{-1.0f, 0.0f, 0.0f};
}
static auto left() noexcept
{
return Vector{0.0f, 1.0f, 0.0f};
}
static auto right() noexcept
{
return Vector{0.0f, -1.0f, 0.0f};
}
float x, y, z;
};
#include "Matrix3x4.h"
constexpr auto Vector::transform(const Matrix3x4 &mat) const noexcept
{
return Vector{dotProduct({ mat[0][0], mat[0][1], mat[0][2] }) + mat[0][3],
dotProduct({ mat[1][0], mat[1][1], mat[1][2] }) + mat[1][3],
dotProduct({ mat[2][0], mat[2][1], mat[2][2] }) + mat[2][3]};
}
| [
"65950527+degeneratehyperbola@users.noreply.github.com"
] | 65950527+degeneratehyperbola@users.noreply.github.com |
aabd40852dd4e266f583a5a3afc78215904a7ac9 | d61f48bf6b230f81ecc57b31647454408290f97d | /16_External_searching/16.03_B_trees/examples/ex_16_3.cpp | e1f916d464c738d8d799f2e82e0ed95bd99b51db | [] | no_license | RomantsovS/Sadgewick | 30da7538e38b2c66e2d5b0eb1f896d82013224f2 | 606f331e5394f92d42b7d246758a49c2554449a6 | refs/heads/master | 2022-07-23T21:08:32.150269 | 2022-07-22T08:00:04 | 2022-07-22T08:00:04 | 179,793,767 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,328 | cpp | #include <cassert>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
const std::string red_str("\033[0;31m");
std::string reset_str("\033[0m");
using Key = int;
Key maxKey = 1000;
#include <Item.h>
const size_t M = 6;
template <class Item, class Key>
struct entry {
Key key;
Item item;
struct node *next;
};
struct node {
size_t m;
entry<Item, Key> b[M];
node() { m = 0; }
};
using link = node *;
template <typename Item, typename Key>
class BTREE {
private:
Item nullItem;
size_t N;
size_t HT;
link head;
Item searchR(link h, Key v, int ht) {
size_t j;
if (ht == 0)
for (j = 0; j < h->m; j++) {
if (v == h->b[j].key) return h->b[j].item;
}
else
for (j = 0; j < h->m; j++)
if ((j + 1 == h->m) || (v < h->b[j + 1].key))
return searchR(h->b[j].next, v, ht - 1);
return nullItem;
}
link split(link h) {
link t = new node;
for (size_t j = 0; j < M / 2; j++) t->b[j] = h->b[M / 2 + j];
h->m = M / 2;
t->m = M / 2;
return t;
}
link insertR(link h, Item x, int ht) {
size_t i, j;
Key v = x.key();
entry<Item, Key> t;
t.key = v;
t.item = x;
if (ht == 0)
for (j = 0; j < h->m; j++) {
if (v < h->b[j].key) break;
}
else
for (j = 0; j < h->m; j++)
if ((j + 1 == h->m) || (v < h->b[j + 1].key)) {
link u;
u = insertR(h->b[j++].next, x, ht - 1);
if (u == 0) return 0;
t.key = u->b[0].key;
t.next = u;
break;
}
for (i = h->m; i > j; i--) h->b[i] = h->b[i - 1];
h->b[j] = t;
if (++h->m < M)
return 0;
else
return split(h);
}
void printR(link h, int ht, Key key = maxKey) {
if (ht == 0) {
for (size_t j = 0; j < h->m; j++) {
cout << string(5 * (HT - ht), ' ')
<< (h->b[j].item.key() == key ? red_str : reset_str)
<< to_string(h->b[j].item.key()) << reset_str << endl;
}
cout << string(5 * (HT - ht), ' ') << "_____\n";
} else {
for (size_t j = 0; j < h->m; j++) {
printR(h->b[j].next, ht - 1, key);
if (j == h->m / 2) {
for (size_t k = 0; k < h->m; k++) {
cout << string(5 * (HT - ht), ' ') << to_string(h->b[k].key) << endl;
}
}
}
}
}
public:
BTREE() {
N = 0;
HT = 0;
head = new node;
}
Item search(Key v) { return searchR(head, v, HT); }
void insert(Item item) {
link u = insertR(head, item, HT);
if (u == 0) return;
link t = new node();
t->m = 2;
t->b[0].key = head->b[0].key;
t->b[1].key = u->b[0].key;
t->b[0].next = head;
t->b[1].next = u;
head = t;
HT++;
}
std::size_t replace_all(std::string &inout, std::string_view what, std::string_view with) {
std::size_t count{};
for (std::string::size_type pos{};
inout.npos != (pos = inout.find(what.data(), pos, what.length()));
pos += with.length(), ++count) {
inout.replace(pos, what.length(), with.data(), with.length());
}
return count;
}
void print(Key key = maxKey) { printR(head, HT, key); }
};
int main([[maybe_unused]] int argc, [[maybe_unused]] char *argv[]) {
BTREE<Item, Key> btree;
vector<int> svec = {706, 176, 601, 153, 513, 773, 742, 373, 527, 766, 275,
737, 574, 434, 641, 207, 111, 227, 61, 736, 526 , 562, 17, 107, 147};
for (size_t i = 0; i < svec.size(); ++i) {
btree.insert(svec[i]);
for (size_t j = 0; j <= i; ++j) {
assert(btree.search(svec[i]).key() == svec[i]);
}
btree.print(svec[i]);
cout << "===============\n";
}
assert(btree.search(0).null());
cout << "ok\n";
} | [
"romantsov_s@rusklimat.ru"
] | romantsov_s@rusklimat.ru |
f9c524495b528c3d6f82d30354d4c04a2fd0f7eb | 89f8073f32c5e76c36d7e3072002015a5646119f | /common files/WOW Factor.cpp | 5e20b6b6994eea9bf925af839df146b1f15d5022 | [] | no_license | PulockDas/Competitive-Programming-Algorithms | f19b8eab081e73c01b4a8ba8673c9df752ff3646 | 2b3774a34170f10e81ec5b3479f4a49bc138e938 | refs/heads/main | 2023-06-11T20:59:57.458069 | 2021-06-29T19:54:05 | 2021-06-29T19:54:05 | 308,912,300 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,048 | cpp | #include <bits/stdc++.h>
using namespace std;
#define ll long long
int main ()
{
string s;
cin >> s;
ll l = s.length();
ll check[l];
memset(check, 0, sizeof(check));
ll sum = 0;
for(ll i=0; i<l; i++){
if(s[i] == 'v'){
for(i=i+1; i<l; i++){
if(s[i] == 'v'){
sum++;
check[i] = sum;
}
else break;
}
}
}
ll ans = 0;
for(ll i=1; i<l; i++){
if(s[i] == 'o'){
ll j = i-1;
while(check[j] == 0){
j--;
if(j < 0)
break;
}
if(j < 0)
continue;
ll bam = check[j];
for(j=l-1; j>i; j--){
if(check[j] > 0)
break;
}
if(check[j] == 0)
continue;
ll right = check[j] - bam;
ans += right*bam;
}
}
cout << ans;
return 0;
}
| [
"pulock46@student.sust.edu"
] | pulock46@student.sust.edu |
a603a2008e444def6f1dca06364c2d7f1734b2d7 | 3feb39edb55c50373bc4cb78b5c8aaeb126133b1 | /system/source/libraries/spoon/storage/File.cpp | 59516a635c36c481bb86b0e062d56fe5f20b2a7a | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | blanham/spoon | bec6305f991d214b7f85e1074ddf97beb1d1909e | a2b5babab160da0791170f36c0d0def6e214f33c | refs/heads/master | 2020-04-06T07:01:57.307234 | 2013-12-13T03:54:24 | 2013-12-13T03:54:24 | 15,154,254 | 7 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 5,118 | cpp | #include <types.h>
#include <stdlib.h>
#include <string.h>
#include <spoon/sysmsg.h>
#include <spoon/ipc/Message.h>
#include <spoon/ipc/Messenger.h>
#include <spoon/storage/File.h>
#include <spoon/storage/StorageDefs.h>
File::File( const char *node )
: _fd(-1)
{
_node = strdup(node);
}
File::~File()
{
if ( _fd >= 0 ) Close();
if ( _node != NULL ) free( _node );
}
// ---------------------------------------------------------
int File::Create( const char *node )
{
Message *reply = NULL;
Message *msg = new Message( CREATE );
msg->AddString( "node", node );
reply = Messenger::SendReceiveMessage( "vfs_server", 0, msg );
delete msg;
if ( reply == NULL ) return -1;
int ok = reply->what;
delete reply;
return ok;
}
int File::Delete( const char *node )
{
Message *reply = NULL;
Message *msg = new Message( DELETE );
msg->AddString( "node", node );
reply = Messenger::SendReceiveMessage( "vfs_server", 0, msg );
delete msg;
if ( reply == NULL ) return -1;
int ok = reply->what;
delete reply;
return ok;
}
bool File::Exists( const char *node )
{
File *file = new File( node );
bool exists = ((file->Open() >= 0 ));
if ( exists == true ) file->Close();
delete file;
return exists;
}
// ---------------------------------------------------------
int File::Open()
{
Message *reply = NULL;
Message *msg = new Message( OPEN );
msg->AddString( "node", _node );
reply = Messenger::SendReceiveMessage( "vfs_server", 0, msg );
delete msg;
if ( reply == NULL ) return -1;
if ( reply->FindInt32("_fd", &_fd ) != 0 ) _fd = -1;
delete reply;
return _fd;
}
int File::Read( void *data, int len )
{
if ( _fd < 0 ) return -1;
Message *msg = new Message(READ);
msg->AddInt32("_fd", _fd);
msg->AddInt32("_len", len );
Message *reply = Messenger::SendReceiveMessage( "vfs_server", 0, msg );
delete msg;
if ( reply == NULL ) return -1;
int rc;
if ( reply->FindInt32("_rc", &rc) != 0 )
{
delete reply;
return -1;
}
if ( rc == 0 )
{
delete reply;
return 0;
}
void *newd;
int news;
if ( reply->FindData( "_data", RAW_TYPE,
(const void**)&newd, &news) != 0 )
{
delete reply;
return rc;
}
if ( news > len )
{
delete reply;
return -1; // weird. Given more data than requested.
}
memcpy( data, newd, news );
delete reply;
return news;
}
int File::Write( const void *data, int len )
{
if ( _fd < 0 ) return -1;
Message *msg = new Message(WRITE);
msg->AddInt32("_fd", _fd);
msg->AddInt32("_len", len );
msg->AddData( "_data", RAW_TYPE, data, len );
Message *reply = Messenger::SendReceiveMessage( "vfs_server", 0, msg );
delete msg;
if ( reply == NULL ) return -1;
int rc;
if ( reply->FindInt32("_rc", &rc) != 0 )
{
delete reply;
return -1;
}
delete reply;
return rc;
}
int File::Stat( struct stat *st )
{
Message *reply = NULL;
Message *msg = new Message(STAT);
msg->AddInt32("_fd", _fd );
reply = Messenger::SendReceiveMessage( "gui_server", 0, msg );
delete msg;
if ( reply == NULL ) return -1;
if ( reply->what != OK )
{
delete reply;
return -1;
}
void *newst;
int size;
if ( reply->FindData( "_stat", RAW_TYPE,
(const void**)&newst, &size) != 0 )
{
delete reply;
return -1;
}
memcpy( st, newst, sizeof( struct stat ) );
delete reply;
return 0;
}
int File::Close()
{
/// \todo convert to message.
Messenger::SendPulse( "vfs_server", 0, CLOSE, _fd );
_fd = -1;
return 0;
}
int64 File::Seek( int64 pos )
{
Message *reply = NULL;
Message *msg = new Message(SEEK);
msg->AddInt32("_fd", _fd );
msg->AddInt64("_seek", pos );
reply = Messenger::SendReceiveMessage( "vfs_server", 0, msg );
delete msg;
if ( reply == NULL ) return -1;
int rc = -1;
if ( reply->FindInt32("_rc", &rc ) != 0 )
{
delete reply;
return -1;
}
if ( rc != 0 ) return -1;
return pos;
}
// ****************************************************
int64 File::Size()
{
struct stat st;
if ( Stat( &st ) != 0 ) return -1;
return st.st_size;
}
//*****************************************************
bool File::Eject()
{
Message *reply = NULL;
Message *msg = new Message(EJECT);
msg->AddInt32("_fd", _fd );
reply = Messenger::SendReceiveMessage( "vfs_server", 0, msg );
delete msg;
if ( reply == NULL ) return false;
int rc = reply->what;
delete reply;
if ( rc != 0 ) return false;
return true;
}
bool File::Loaded()
{
Message *reply = NULL;
Message *msg = new Message(LOADED);
msg->AddInt32("_fd", _fd );
reply = Messenger::SendReceiveMessage( "vfs_server", 0, msg );
delete msg;
if ( reply == NULL ) return false;
int rc = reply->what;
delete reply;
if ( rc != 0 ) return false;
return true;
}
| [
"blanham@gmail.com"
] | blanham@gmail.com |
26f3172322216d8d50f4f3c7dfe00843453f32a9 | e2e3cf2edf60eeb6dd45adaa8a58e110bdef92d9 | /Portable/zoolib/UUID.h | f89ee30e44551c3da4582c193ff5a2a3e25af4b9 | [
"MIT"
] | permissive | zoolib/zoolib_cxx | 0ae57b83d8b3d8c688ee718b236e678b128c0ac7 | b415ef23476afdad89d61a003543570270a85844 | refs/heads/master | 2023-03-22T20:53:40.334006 | 2023-03-11T23:44:22 | 2023-03-11T23:44:22 | 3,355,296 | 17 | 5 | MIT | 2023-03-11T23:44:23 | 2012-02-04T20:54:08 | C++ | UTF-8 | C++ | false | false | 486 | h | // Copyright (c) 2021 Andrew Green. MIT License. http://www.zoolib.org
#ifndef __ZooLib_UUID_h__
#define __ZooLib_UUID_h__ 1
#include "zconfig.h"
#include "zoolib/StdInt.h" // For byte
#include "zoolib/TagVal.h"
#include <array>
namespace ZooLib {
// =================================================================================================
#pragma mark - UUID
typedef TagVal<std::array<byte,16>, struct Tag_UUID> UUID;
} // namespace ZooLib
#endif // __ZooLib_UUID_h__
| [
"ag@em.net"
] | ag@em.net |
8c783a4a7fba54f49abf9e4dc55e6ec5aa201534 | 5c875539b7a294aed1750ab46ae5d3f9dd54516c | /ota_test2/lib/thirdparty/BLE/src/BLERemoteCharacteristic.cpp | c733c1d14a808dd5db805503e1f5e0ee0249e6f4 | [] | no_license | TimUntersberger/Diplomarbeit | 8f0fae394ebb589f3cbbdc38fb4e865ee0e48238 | bdc946edb6a96808f145917781a675bfaaa4365c | refs/heads/master | 2022-04-25T12:23:29.826968 | 2020-04-21T12:48:35 | 2020-04-21T12:48:35 | 223,121,269 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,868 | cpp | /*
* BLERemoteCharacteristic.cpp
*
* Created on: Jul 8, 2017
* Author: kolban
*/
#include "BLERemoteCharacteristic.h"
#include "sdkconfig.h"
#if defined(CONFIG_BT_ENABLED)
#include <esp_gattc_api.h>
#include <esp_err.h>
#include <sstream>
#include "BLEExceptions.h"
#include "BLEUtils.h"
#include "GeneralUtils.h"
#include "BLERemoteDescriptor.h"
#include "esp32-hal-log.h"
/**
* @brief Constructor.
* @param [in] handle The BLE server side handle of this characteristic.
* @param [in] uuid The UUID of this characteristic.
* @param [in] charProp The properties of this characteristic.
* @param [in] pRemoteService A reference to the remote service to which this remote characteristic pertains.
*/
BLERemoteCharacteristic::BLERemoteCharacteristic(
uint16_t handle,
BLEUUID uuid,
esp_gatt_char_prop_t charProp,
BLERemoteService* pRemoteService) {
log_v(">> BLERemoteCharacteristic: handle: %d 0x%d, uuid: %s", handle, handle, uuid.toString().c_str());
m_handle = handle;
m_uuid = uuid;
m_charProp = charProp;
m_pRemoteService = pRemoteService;
m_notifyCallback = nullptr;
retrieveDescriptors(); // Get the descriptors for this characteristic
log_v("<< BLERemoteCharacteristic");
} // BLERemoteCharacteristic
/**
*@brief Destructor.
*/
BLERemoteCharacteristic::~BLERemoteCharacteristic() {
removeDescriptors(); // Release resources for any descriptor information we may have allocated.
} // ~BLERemoteCharacteristic
/**
* @brief Does the characteristic support broadcasting?
* @return True if the characteristic supports broadcasting.
*/
bool BLERemoteCharacteristic::canBroadcast() {
return (m_charProp & ESP_GATT_CHAR_PROP_BIT_BROADCAST) != 0;
} // canBroadcast
/**
* @brief Does the characteristic support indications?
* @return True if the characteristic supports indications.
*/
bool BLERemoteCharacteristic::canIndicate() {
return (m_charProp & ESP_GATT_CHAR_PROP_BIT_INDICATE) != 0;
} // canIndicate
/**
* @brief Does the characteristic support notifications?
* @return True if the characteristic supports notifications.
*/
bool BLERemoteCharacteristic::canNotify() {
return (m_charProp & ESP_GATT_CHAR_PROP_BIT_NOTIFY) != 0;
} // canNotify
/**
* @brief Does the characteristic support reading?
* @return True if the characteristic supports reading.
*/
bool BLERemoteCharacteristic::canRead() {
return (m_charProp & ESP_GATT_CHAR_PROP_BIT_READ) != 0;
} // canRead
/**
* @brief Does the characteristic support writing?
* @return True if the characteristic supports writing.
*/
bool BLERemoteCharacteristic::canWrite() {
return (m_charProp & ESP_GATT_CHAR_PROP_BIT_WRITE) != 0;
} // canWrite
/**
* @brief Does the characteristic support writing with no response?
* @return True if the characteristic supports writing with no response.
*/
bool BLERemoteCharacteristic::canWriteNoResponse() {
return (m_charProp & ESP_GATT_CHAR_PROP_BIT_WRITE_NR) != 0;
} // canWriteNoResponse
/*
static bool compareSrvcId(esp_gatt_srvc_id_t id1, esp_gatt_srvc_id_t id2) {
if (id1.id.inst_id != id2.id.inst_id) {
return false;
}
if (!BLEUUID(id1.id.uuid).equals(BLEUUID(id2.id.uuid))) {
return false;
}
return true;
} // compareSrvcId
*/
/*
static bool compareGattId(esp_gatt_id_t id1, esp_gatt_id_t id2) {
if (id1.inst_id != id2.inst_id) {
return false;
}
if (!BLEUUID(id1.uuid).equals(BLEUUID(id2.uuid))) {
return false;
}
return true;
} // compareCharId
*/
/**
* @brief Handle GATT Client events.
* When an event arrives for a GATT client we give this characteristic the opportunity to
* take a look at it to see if there is interest in it.
* @param [in] event The type of event.
* @param [in] gattc_if The interface on which the event was received.
* @param [in] evtParam Payload data for the event.
* @returns N/A
*/
void BLERemoteCharacteristic::gattClientEventHandler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t* evtParam) {
switch(event) {
// ESP_GATTC_NOTIFY_EVT
//
// notify
// - uint16_t conn_id - The connection identifier of the server.
// - esp_bd_addr_t remote_bda - The device address of the BLE server.
// - uint16_t handle - The handle of the characteristic for which the event is being received.
// - uint16_t value_len - The length of the received data.
// - uint8_t* value - The received data.
// - bool is_notify - True if this is a notify, false if it is an indicate.
//
// We have received a notification event which means that the server wishes us to know about a notification
// piece of data. What we must now do is find the characteristic with the associated handle and then
// invoke its notification callback (if it has one).
case ESP_GATTC_NOTIFY_EVT: {
if (evtParam->notify.handle != getHandle()) break;
if (m_notifyCallback != nullptr) {
log_d("Invoking callback for notification on characteristic %s", toString().c_str());
m_notifyCallback(this, evtParam->notify.value, evtParam->notify.value_len, evtParam->notify.is_notify);
} // End we have a callback function ...
break;
} // ESP_GATTC_NOTIFY_EVT
// ESP_GATTC_READ_CHAR_EVT
// This event indicates that the server has responded to the read request.
//
// read:
// - esp_gatt_status_t status
// - uint16_t conn_id
// - uint16_t handle
// - uint8_t* value
// - uint16_t value_len
case ESP_GATTC_READ_CHAR_EVT: {
// If this event is not for us, then nothing further to do.
if (evtParam->read.handle != getHandle()) break;
// At this point, we have determined that the event is for us, so now we save the value
// and unlock the semaphore to ensure that the requestor of the data can continue.
if (evtParam->read.status == ESP_GATT_OK) {
m_value = std::string((char*) evtParam->read.value, evtParam->read.value_len);
if(m_rawData != nullptr) free(m_rawData);
m_rawData = (uint8_t*) calloc(evtParam->read.value_len, sizeof(uint8_t));
memcpy(m_rawData, evtParam->read.value, evtParam->read.value_len);
} else {
m_value = "";
}
m_semaphoreReadCharEvt.give();
break;
} // ESP_GATTC_READ_CHAR_EVT
// ESP_GATTC_REG_FOR_NOTIFY_EVT
//
// reg_for_notify:
// - esp_gatt_status_t status
// - uint16_t handle
case ESP_GATTC_REG_FOR_NOTIFY_EVT: {
// If the request is not for this BLERemoteCharacteristic then move on to the next.
if (evtParam->reg_for_notify.handle != getHandle()) break;
// We have processed the notify registration and can unlock the semaphore.
m_semaphoreRegForNotifyEvt.give();
break;
} // ESP_GATTC_REG_FOR_NOTIFY_EVT
// ESP_GATTC_UNREG_FOR_NOTIFY_EVT
//
// unreg_for_notify:
// - esp_gatt_status_t status
// - uint16_t handle
case ESP_GATTC_UNREG_FOR_NOTIFY_EVT: {
if (evtParam->unreg_for_notify.handle != getHandle()) break;
// We have processed the notify un-registration and can unlock the semaphore.
m_semaphoreRegForNotifyEvt.give();
break;
} // ESP_GATTC_UNREG_FOR_NOTIFY_EVT:
// ESP_GATTC_WRITE_CHAR_EVT
//
// write:
// - esp_gatt_status_t status
// - uint16_t conn_id
// - uint16_t handle
case ESP_GATTC_WRITE_CHAR_EVT: {
// Determine if this event is for us and, if not, pass onwards.
if (evtParam->write.handle != getHandle()) break;
// There is nothing further we need to do here. This is merely an indication
// that the write has completed and we can unlock the caller.
m_semaphoreWriteCharEvt.give();
break;
} // ESP_GATTC_WRITE_CHAR_EVT
default:
break;
} // End switch
}; // gattClientEventHandler
/**
* @brief Populate the descriptors (if any) for this characteristic.
*/
void BLERemoteCharacteristic::retrieveDescriptors() {
log_v(">> retrieveDescriptors() for characteristic: %s", getUUID().toString().c_str());
removeDescriptors(); // Remove any existing descriptors.
// Loop over each of the descriptors within the service associated with this characteristic.
// For each descriptor we find, create a BLERemoteDescriptor instance.
uint16_t offset = 0;
esp_gattc_descr_elem_t result;
while(true) {
uint16_t count = 10;
esp_gatt_status_t status = ::esp_ble_gattc_get_all_descr(
getRemoteService()->getClient()->getGattcIf(),
getRemoteService()->getClient()->getConnId(),
getHandle(),
&result,
&count,
offset
);
if (status == ESP_GATT_INVALID_OFFSET) { // We have reached the end of the entries.
break;
}
if (status != ESP_GATT_OK) {
log_e("esp_ble_gattc_get_all_descr: %s", BLEUtils::gattStatusToString(status).c_str());
break;
}
if (count == 0) break;
log_d("Found a descriptor: Handle: %d, UUID: %s", result.handle, BLEUUID(result.uuid).toString().c_str());
// We now have a new characteristic ... let us add that to our set of known characteristics
BLERemoteDescriptor* pNewRemoteDescriptor = new BLERemoteDescriptor(
result.handle,
BLEUUID(result.uuid),
this
);
m_descriptorMap.insert(std::pair<std::string, BLERemoteDescriptor*>(pNewRemoteDescriptor->getUUID().toString(), pNewRemoteDescriptor));
offset++;
} // while true
//m_haveCharacteristics = true; // Remember that we have received the characteristics.
log_v("<< retrieveDescriptors(): Found %d descriptors.", offset);
} // getDescriptors
/**
* @brief Retrieve the map of descriptors keyed by UUID.
*/
std::map<std::string, BLERemoteDescriptor*>* BLERemoteCharacteristic::getDescriptors() {
return &m_descriptorMap;
} // getDescriptors
/**
* @brief Get the handle for this characteristic.
* @return The handle for this characteristic.
*/
uint16_t BLERemoteCharacteristic::getHandle() {
//log_v(">> getHandle: Characteristic: %s", getUUID().toString().c_str());
//log_v("<< getHandle: %d 0x%.2x", m_handle, m_handle);
return m_handle;
} // getHandle
/**
* @brief Get the descriptor instance with the given UUID that belongs to this characteristic.
* @param [in] uuid The UUID of the descriptor to find.
* @return The Remote descriptor (if present) or null if not present.
*/
BLERemoteDescriptor* BLERemoteCharacteristic::getDescriptor(BLEUUID uuid) {
log_v(">> getDescriptor: uuid: %s", uuid.toString().c_str());
std::string v = uuid.toString();
for (auto &myPair : m_descriptorMap) {
if (myPair.first == v) {
log_v("<< getDescriptor: found");
return myPair.second;
}
}
log_v("<< getDescriptor: Not found");
return nullptr;
} // getDescriptor
/**
* @brief Get the remote service associated with this characteristic.
* @return The remote service associated with this characteristic.
*/
BLERemoteService* BLERemoteCharacteristic::getRemoteService() {
return m_pRemoteService;
} // getRemoteService
/**
* @brief Get the UUID for this characteristic.
* @return The UUID for this characteristic.
*/
BLEUUID BLERemoteCharacteristic::getUUID() {
return m_uuid;
} // getUUID
/**
* @brief Read an unsigned 16 bit value
* @return The unsigned 16 bit value.
*/
uint16_t BLERemoteCharacteristic::readUInt16() {
std::string value = readValue();
if (value.length() >= 2) {
return *(uint16_t*)(value.data());
}
return 0;
} // readUInt16
/**
* @brief Read an unsigned 32 bit value.
* @return the unsigned 32 bit value.
*/
uint32_t BLERemoteCharacteristic::readUInt32() {
std::string value = readValue();
if (value.length() >= 4) {
return *(uint32_t*)(value.data());
}
return 0;
} // readUInt32
/**
* @brief Read a byte value
* @return The value as a byte
*/
uint8_t BLERemoteCharacteristic::readUInt8() {
std::string value = readValue();
if (value.length() >= 1) {
return (uint8_t)value[0];
}
return 0;
} // readUInt8
/**
* @brief Read the value of the remote characteristic.
* @return The value of the remote characteristic.
*/
std::string BLERemoteCharacteristic::readValue() {
log_v(">> readValue(): uuid: %s, handle: %d 0x%.2x", getUUID().toString().c_str(), getHandle(), getHandle());
// Check to see that we are connected.
if (!getRemoteService()->getClient()->isConnected()) {
log_e("Disconnected");
throw BLEDisconnectedException();
}
m_semaphoreReadCharEvt.take("readValue");
// Ask the BLE subsystem to retrieve the value for the remote hosted characteristic.
// This is an asynchronous request which means that we must block waiting for the response
// to become available.
esp_err_t errRc = ::esp_ble_gattc_read_char(
m_pRemoteService->getClient()->getGattcIf(),
m_pRemoteService->getClient()->getConnId(), // The connection ID to the BLE server
getHandle(), // The handle of this characteristic
ESP_GATT_AUTH_REQ_NONE); // Security
if (errRc != ESP_OK) {
log_e("esp_ble_gattc_read_char: rc=%d %s", errRc, GeneralUtils::errorToString(errRc));
return "";
}
// Block waiting for the event that indicates that the read has completed. When it has, the std::string found
// in m_value will contain our data.
m_semaphoreReadCharEvt.wait("readValue");
log_v("<< readValue(): length: %d", m_value.length());
return m_value;
} // readValue
/**
* @brief Register for notifications.
* @param [in] notifyCallback A callback to be invoked for a notification. If NULL is provided then we are
* unregistering a notification.
* @return N/A.
*/
void BLERemoteCharacteristic::registerForNotify(notify_callback notifyCallback, bool notifications) {
log_v(">> registerForNotify(): %s", toString().c_str());
m_notifyCallback = notifyCallback; // Save the notification callback.
m_semaphoreRegForNotifyEvt.take("registerForNotify");
if (notifyCallback != nullptr) { // If we have a callback function, then this is a registration.
esp_err_t errRc = ::esp_ble_gattc_register_for_notify(
m_pRemoteService->getClient()->getGattcIf(),
*m_pRemoteService->getClient()->getPeerAddress().getNative(),
getHandle()
);
if (errRc != ESP_OK) {
log_e("esp_ble_gattc_register_for_notify: rc=%d %s", errRc, GeneralUtils::errorToString(errRc));
}
uint8_t val[] = {0x01, 0x00};
if(!notifications) val[0] = 0x02;
BLERemoteDescriptor* desc = getDescriptor(BLEUUID((uint16_t)0x2902));
desc->writeValue(val, 2);
} // End Register
else { // If we weren't passed a callback function, then this is an unregistration.
esp_err_t errRc = ::esp_ble_gattc_unregister_for_notify(
m_pRemoteService->getClient()->getGattcIf(),
*m_pRemoteService->getClient()->getPeerAddress().getNative(),
getHandle()
);
if (errRc != ESP_OK) {
log_e("esp_ble_gattc_unregister_for_notify: rc=%d %s", errRc, GeneralUtils::errorToString(errRc));
}
uint8_t val[] = {0x00, 0x00};
BLERemoteDescriptor* desc = getDescriptor((uint16_t)0x2902);
desc->writeValue(val, 2);
} // End Unregister
m_semaphoreRegForNotifyEvt.wait("registerForNotify");
log_v("<< registerForNotify()");
} // registerForNotify
/**
* @brief Delete the descriptors in the descriptor map.
* We maintain a map called m_descriptorMap that contains pointers to BLERemoteDescriptors
* object references. Since we allocated these in this class, we are also responsible for deleteing
* them. This method does just that.
* @return N/A.
*/
void BLERemoteCharacteristic::removeDescriptors() {
// Iterate through all the descriptors releasing their storage and erasing them from the map.
for (auto &myPair : m_descriptorMap) {
m_descriptorMap.erase(myPair.first);
delete myPair.second;
}
m_descriptorMap.clear(); // Technically not neeeded, but just to be sure.
} // removeCharacteristics
/**
* @brief Convert a BLERemoteCharacteristic to a string representation;
* @return a String representation.
*/
std::string BLERemoteCharacteristic::toString() {
std::ostringstream ss;
ss << "Characteristic: uuid: " << m_uuid.toString() <<
", handle: " << getHandle() << " 0x" << std::hex << getHandle() <<
", props: " << BLEUtils::characteristicPropertiesToString(m_charProp);
return ss.str();
} // toString
/**
* @brief Write the new value for the characteristic.
* @param [in] newValue The new value to write.
* @param [in] response Do we expect a response?
* @return N/A.
*/
void BLERemoteCharacteristic::writeValue(std::string newValue, bool response) {
writeValue((uint8_t*)newValue.c_str(), strlen(newValue.c_str()), response);
} // writeValue
/**
* @brief Write the new value for the characteristic.
*
* This is a convenience function. Many BLE characteristics are a single byte of data.
* @param [in] newValue The new byte value to write.
* @param [in] response Whether we require a response from the write.
* @return N/A.
*/
void BLERemoteCharacteristic::writeValue(uint8_t newValue, bool response) {
writeValue(&newValue, 1, response);
} // writeValue
/**
* @brief Write the new value for the characteristic from a data buffer.
* @param [in] data A pointer to a data buffer.
* @param [in] length The length of the data in the data buffer.
* @param [in] response Whether we require a response from the write.
*/
void BLERemoteCharacteristic::writeValue(uint8_t* data, size_t length, bool response) {
// writeValue(std::string((char*)data, length), response);
log_v(">> writeValue(), length: %d", length);
// Check to see that we are connected.
if (!getRemoteService()->getClient()->isConnected()) {
log_e("Disconnected");
throw BLEDisconnectedException();
}
m_semaphoreWriteCharEvt.take("writeValue");
// Invoke the ESP-IDF API to perform the write.
esp_err_t errRc = ::esp_ble_gattc_write_char(
m_pRemoteService->getClient()->getGattcIf(),
m_pRemoteService->getClient()->getConnId(),
getHandle(),
length,
data,
response?ESP_GATT_WRITE_TYPE_RSP:ESP_GATT_WRITE_TYPE_NO_RSP,
ESP_GATT_AUTH_REQ_NONE
);
if (errRc != ESP_OK) {
log_e("esp_ble_gattc_write_char: rc=%d %s", errRc, GeneralUtils::errorToString(errRc));
return;
}
m_semaphoreWriteCharEvt.wait("writeValue");
log_v("<< writeValue");
} // writeValue
/**
* @brief Read raw data from remote characteristic as hex bytes
* @return return pointer data read
*/
uint8_t* BLERemoteCharacteristic::readRawData() {
return m_rawData;
}
#endif /* CONFIG_BT_ENABLED */
| [
"waldl.stefan@gmail.com"
] | waldl.stefan@gmail.com |
4658fc82320f15382330f8fa140bc1d3bd889ae0 | a316b25d78becd64d29af3c698207bb4e93e4791 | /baekjoon/1956.cpp | e3b5fd13a542e61262117d4fa14e6a339db3e268 | [] | no_license | gnueskob/PS | 0aa96ce6a9eb3935905d652f4400c184e3f79b9b | 2a2e9c331e2f2290c3f4ff0a64b0b0ece9da9b75 | refs/heads/master | 2021-06-09T03:37:44.032216 | 2021-05-08T03:10:28 | 2021-05-08T03:10:28 | 172,658,184 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,089 | cpp | // https://www.acmicpc.net/problem/1956
// #플로이드와셜
#ifdef GNUES_INPUT
#include "plugin/fiostream.hpp"
#include "_fileRead.hpp"
GNUES::FileRead f("1956.txt");
#endif
#include <iostream>
#include <vector>
int main()
{
auto [V, E] = GNUES::readInts<int, int>();
int inf = std::numeric_limits<int>::max();
std::vector<std::vector<long long>> graph(V+1, std::vector<long long>(V+1, inf));
while (E--)
{
auto [a, b, c] = GNUES::readInts<int, int, long long>();
graph[a][b] = std::min(graph[a][b], c);
}
// 플로이드와셜을 통해 모든 노드간 최단거리 갱신
// graph[v][v] 자기 자신으로 되돌아 올 수 있다면 사이클
for (int v=1; v<=V; ++v)
{
for (int s=1; s<=V; ++s)
{
for (int e=1; e<=V; ++e)
{
graph[s][e] = std::min(graph[s][e], graph[s][v] + graph[v][e]);
}
}
}
long long ans = inf;
for (int v=1; v<=V; ++v)
ans = std::min(ans, graph[v][v]);
GNUES::writeInt((ans >= inf ? -1 : ans));
} | [
"gnueskob@gmail.com"
] | gnueskob@gmail.com |
9eb26fc4417704d46fc28087605364b11f3eeb36 | 75bed69010bd373b7803f3cb51b565a783f36397 | /componente.cpp | 12253754bf538b9fb17d4105ee69fcf1faecd285 | [] | no_license | joseSalazar4/SimuladorRestaurante | b87a30dd8cb8c53c96390dab9bdb581c26cea9d2 | 06db5b63d63cae70d61e27d0ccd5abb6dc15d310 | refs/heads/master | 2022-03-10T10:02:23.702397 | 2019-10-01T03:45:11 | 2019-10-01T03:45:11 | 208,942,401 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 55 | cpp | #include "componente.h"
Componente::Componente()
{
}
| [
"jsalazarg48@gmail.com"
] | jsalazarg48@gmail.com |
eadd8203b93bc2564e6f8ccb345280a0e26d7eda | ae25bffa378345c49e5ef5a0347f2c121c7a0f31 | /ns-2.1b8a/emulate/net-ip.cc | 7fbc28eae6e2180a2f58bf4aeb526e2dd5039e49 | [] | no_license | smilemare/NS-2.1b8a-MacOS | 49a00733c4aee95e86324d595bb7e85d98259be9 | b556e49bf6ff88df0bdd983baaae68a809676f88 | refs/heads/master | 2020-12-24T15:22:53.671307 | 2014-10-31T10:04:37 | 2014-10-31T10:04:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,904 | cc | /*-
* Copyright (c) 1993-1994, 1998
* The Regents of the University of California.
* 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 acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and the Network Research Group at
* Lawrence Berkeley Laboratory.
* 4. Neither the name of the University nor of the Laboratory may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#ifndef lint
static const char rcsid[] =
"@(#) $Header: /nfs/jade/vint/CVSROOT/ns-2/emulate/net-ip.cc,v 1.18 2000/11/06 19:29:44 haoboy Exp $ (LBL)";
#endif
#include <stdio.h>
#ifndef WIN32
#include <unistd.h>
#endif
#include <time.h>
#include <errno.h>
#include <string.h>
#ifdef WIN32
#include <io.h>
#define close closesocket
#else
#include <sys/param.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
typedef int Socket;
#endif
#if defined(sun) && defined(__svr4__)
#include <sys/systeminfo.h>
#endif
#include "config.h"
#include "net.h"
#include "inet.h"
#include "tclcl.h"
#include "scheduler.h"
//#define NIPDEBUG 1
#ifdef NIPDEBUG
#define NIDEBUG(x) { if (NIPDEBUG) fprintf(stderr, (x)); }
#define NIDEBUG2(x,y) { if (NIPDEBUG) fprintf(stderr, (x), (y)); }
#define NIDEBUG3(x,y,z) { if (NIPDEBUG) fprintf(stderr, (x), (y), (z)); }
#define NIDEBUG4(w,x,y,z) { if (NIPDEBUG) fprintf(stderr, (w), (x), (y), (z)); }
#define NIDEBUG5(v,w,x,y,z) { if (NIPDEBUG) fprintf(stderr, (v), (w), (x), (y), (z)); }
#else
#define NIDEBUG(x) { }
#define NIDEBUG2(x,y) { }
#define NIDEBUG3(x,y,z) { }
#define NIDEBUG4(w,x,y,z) { }
#define NIDEBUG5(v,w,x,y,z) { }
#endif
/*
* Net-ip.cc: this file defines the IP and IP/UDP network
* objects. IP provides a raw IP interface and support functions
* [such as setting multicast parameters]. IP/UDP provides a standard
* UDP datagram interface.
*/
//
// IPNetwork: a low-level (raw) IP network object
//
class IPNetwork : public Network {
public:
IPNetwork();
inline int ttl() const { return (mttl_); } // current mcast ttl
inline int noloopback_broken() { // no loopback filter?
return (noloopback_broken_);
}
int setmttl(Socket, int); // set mcast ttl
int setmloop(Socket, int); // set mcast loopback
int command(int argc, const char*const* argv); // virtual in Network
inline Socket rchannel() { return(rsock_); } // virtual in Network
inline Socket schannel() { return(ssock_); } // virtual in Network
int send(u_char* buf, int len); // virtual in Network
int recv(u_char* buf, int len, sockaddr& from, double& ); // virtual in Network
inline in_addr& laddr() { return (localaddr_); }
inline in_addr& dstaddr() { return (destaddr_); }
int add_membership(Socket, in_addr& grp); // join mcast
int drop_membership(Socket, in_addr& grp); // leave mcast
/* generally useful routines */
static int bindsock(Socket, in_addr&, u_int16_t, sockaddr_in&);
static int connectsock(Socket, in_addr&, u_int16_t, sockaddr_in&);
static int rbufsize(Socket, int);
static int sbufsize(Socket, int);
protected:
in_addr destaddr_; // remote side, if set (network order)
in_addr localaddr_; // local side (network order)
int mttl_; // multicast ttl to use
Socket rsock_; // socket to receive on
Socket ssock_; // socket to send on
int noloopback_broken_; // couldn't turn (off) mcast loopback
int loop_; // do we want loopbacks?
// (system usually assumes yes)
void reset(int reconfigure); // reset + reconfig?
virtual int open(int mode); // open sockets/endpoints
virtual void reconfigure(); // restore state after reset
int close();
time_t last_reset_;
};
class UDPIPNetwork : public IPNetwork {
public:
UDPIPNetwork();
int send(u_char*, int);
int recv(u_char*, int, sockaddr&, double&);
int open(int mode); // mode only
int command(int argc, const char*const* argv);
void reconfigure();
void add_membership(Socket, in_addr&, u_int16_t); // udp version
protected:
int bind(in_addr&, u_int16_t port); // bind to addr/port, mcast ok
int connect(in_addr& remoteaddr, u_int16_t port); // connect()
u_int16_t lport_; // local port (network order)
u_int16_t port_; // remote (dst) port (network order)
};
static class IPNetworkClass : public TclClass {
public:
IPNetworkClass() : TclClass("Network/IP") {}
TclObject* create(int, const char*const*) {
return (new IPNetwork);
}
} nm_ip;
static class UDPIPNetworkClass : public TclClass {
public:
UDPIPNetworkClass() : TclClass("Network/IP/UDP") {}
TclObject* create(int, const char*const*) {
return (new UDPIPNetwork);
}
} nm_ip_udp;
IPNetwork::IPNetwork() :
mttl_(0),
rsock_(-1),
ssock_(-1),
noloopback_broken_(0),
loop_(1)
{
localaddr_.s_addr = 0L;
destaddr_.s_addr = 0L;
NIDEBUG("IPNetwork: ctor\n");
}
UDPIPNetwork::UDPIPNetwork() :
lport_(htons(0)),
port_(htons(0))
{
NIDEBUG("UDPIPNetwork: ctor\n");
}
/*
* UDPIP::send -- send "len" bytes in buffer "buf" out the sending
* channel.
*
* returns the number of bytes written
*/
int
UDPIPNetwork::send(u_char* buf, int len)
{
int cc = ::send(schannel(), (char*)buf, len, 0);
NIDEBUG5("UDPIPNetwork(%s): ::send(%d, buf, %d) returned %d\n",
name(), schannel(), len, cc);
if (cc < 0) {
switch (errno) {
case ECONNREFUSED:
/* no one listening at some site - ignore */
#if defined(__osf__) || defined(_AIX) || defined(__FreeBSD__)
/*
* Here's an old comment...
*
* Due to a bug in kern/uipc_socket.c, on several
* systems, datagram sockets incorrectly persist
* in an error state on receipt of an ICMP
* port-unreachable. This causes unicast connection
* rendezvous problems, and worse, multicast
* transmission problems because several systems
* incorrectly send port unreachables for
* multicast destinations. Our work around
* is to simply close and reopen the socket
* (by calling reset() below).
*
* This bug originated at CSRG in Berkeley
* and was present in the BSD Reno networking
* code release. It has since been fixed
* in 4.4BSD and OSF-3.x. It is known to remain
* in AIX-4.1.3.
*
* A fix is to change the following lines from
* kern/uipc_socket.c:
*
* if (so_serror)
* snderr(so->so_error);
*
* to:
*
* if (so->so_error) {
* error = so->so_error;
* so->so_error = 0;
* splx(s);
* goto release;
* }
*
*/
reset(1);
#endif
break;
case ENETUNREACH:
case EHOSTUNREACH:
/*
* These "errors" are totally meaningless.
* There is some broken host sending
* icmp unreachables for multicast destinations.
* UDP probably aborted the send because of them --
* try exactly once more. E.g., the send we
* just did cleared the errno for the previous
* icmp unreachable, so we should be able to
* send now.
*/
cc = ::send(schannel(), (char*)buf, len, 0);
break;
default:
fprintf(stderr, "UDPIPNetwork(%s): send failed: %s\n",
name(), strerror(errno));
return (-1);
}
}
return cc; // bytes sent
}
int
UDPIPNetwork::recv(u_char* buf, int len, sockaddr& from, double& ts)
{
sockaddr_in sfrom;
int fromlen = sizeof(sfrom);
int cc = ::recvfrom(rsock_, (char*)buf, len, 0,
(sockaddr*)&sfrom, (socklen_t*)&fromlen);
NIDEBUG5("UDPIPNetwork(%s): ::recvfrom(%d, buf, %d) returned %d\n",
name(), rsock_, len, cc);
if (cc < 0) {
if (errno != EWOULDBLOCK) {
fprintf(stderr,
"UDPIPNetwork(%s): recvfrom failed: %s\n",
name(), strerror(errno));
}
return (-1);
}
from = *((sockaddr*)&sfrom);
/*
* if we received multicast data and we don't want the look,
* there is a chance it is
* what we sent if "noloopback_broken_" is set.
* If so, filter out the stuff we don't want right here.
*/
if (!loop_ && noloopback_broken_ &&
sfrom.sin_addr.s_addr == localaddr_.s_addr &&
sfrom.sin_port == lport_) {
NIDEBUG2("UDPIPNetwork(%s): filtered out our own pkt\n", name());
return (0); // empty
}
ts = Scheduler::instance().clock();
return (cc); // number of bytes received
}
int
UDPIPNetwork::open(int mode)
{
if (mode == O_RDONLY || mode == O_RDWR) {
rsock_ = socket(AF_INET, SOCK_DGRAM, 0);
if (rsock_ < 0) {
fprintf(stderr,
"UDPIPNetwork(%s): open: couldn't open rcv sock\n",
name());
}
nonblock(rsock_);
int on = 1;
if (::setsockopt(rsock_, SOL_SOCKET, SO_REUSEADDR, (char *)&on,
sizeof(on)) < 0) {
fprintf(stderr,
"UDPIPNetwork(%s): open: warning: unable set REUSEADDR: %s\n",
name(), strerror(errno));
}
#ifdef SO_REUSEPORT
on = 1;
if (::setsockopt(rsock_, SOL_SOCKET, SO_REUSEPORT, (char *)&on,
sizeof(on)) < 0) {
fprintf(stderr,
"UDPIPNetwork(%s): open: warning: unable set REUSEPORT: %s\n",
name(), strerror(errno));
}
#endif
/*
* XXX don't need this for the session socket.
*/
if (rbufsize(rsock_, 80*1024) < 0) {
if (rbufsize(rsock_, 32*1024) < 0) {
fprintf(stderr,
"UDPIPNetwork(%s): open: unable to set r bufsize to %d: %s\n",
name(), 32*1024, strerror(errno));
}
}
}
if (mode == O_WRONLY || mode == O_RDWR) {
ssock_ = socket(AF_INET, SOCK_DGRAM, 0);
if (ssock_ < 0) {
fprintf(stderr,
"UDPIPNetwork(%s): open: couldn't open snd sock\n",
name());
}
nonblock(ssock_);
int firsttry = 80 * 1024;
int secondtry = 48 * 1024;
if (sbufsize(ssock_, firsttry) < 0) {
if (sbufsize(ssock_, secondtry) < 0) {
fprintf(stderr,
"UDPIPNetwork(%s): open: cannot set send sockbuf size to %d bytes, using default\n",
name(), secondtry);
}
}
}
mode_ = mode;
NIDEBUG5("UDPIPNetwork(%s): opened network w/mode %d, ssock:%d, rsock:%d\n",
name(), mode_, rsock_, ssock_);
return (0);
}
//
// IP/UDP version of add_membership: try binding
//
void
UDPIPNetwork::add_membership(Socket sock, in_addr& addr, u_int16_t port)
{
int failure = 0;
sockaddr_in sin;
if (bindsock(sock, addr, port, sin) < 0)
failure = 1;
if (failure) {
in_addr addr2 = addr;
addr2.s_addr = INADDR_ANY;
if (bindsock(sock, addr2, port, sin) < 0)
failure = 1;
else
failure = 0;
}
if (IPNetwork::add_membership(sock, addr) < 0)
failure = 1;
if (failure) {
fprintf(stderr,
"UDPIPNetwork(%s): add_membership: failed bind on mcast addr %s and INADDR_ANY\n",
name(), inet_ntoa(addr));
}
}
//
// server-side bind (or mcast subscription)
//
int
UDPIPNetwork::bind(in_addr& addr, u_int16_t port)
{
NIDEBUG4("UDPIPNetwork(%s): attempt to bind to addr %s, port %d [net order]\n",
name(), inet_ntoa(addr), ntohs(port));
if (rsock_ < 0) {
fprintf(stderr,
"UDPIPNetwork(%s): bind/listen called before net is open\n",
name());
return (-1);
}
if (mode_ == O_WRONLY) {
fprintf(stderr,
"UDPIPNetwork(%s): attempted bind/listen but net is write-only\n",
name());
return (-1);
}
#ifdef IP_ADD_MEMBERSHIP
if (IN_CLASSD(ntohl(addr.s_addr))) {
// MULTICAST case, call UDPIP vers of add_membership
add_membership(rsock_, addr, port);
} else
#endif
{
// UNICAST case
sockaddr_in sin;
if (bindsock(rsock_, addr, port, sin) < 0) {
port = ntohs(port);
fprintf(stderr,
"UDPIPNetwork(%s): bind: unable to bind %s [port:%hu]: %s\n",
name(), inet_ntoa(addr),
port, strerror(errno));
return (-1);
}
/*
* MS Windows currently doesn't compy with the Internet Host
* Requirements standard (RFC-1122) and won't let us include
* the source address in the receive socket demux state.
*/
#ifndef WIN32
/*
* (try to) connect the foreign host's address to this socket.
*/
(void)connectsock(rsock_, addr, 0, sin);
#endif
}
localaddr_ = addr;
lport_ = port;
return (0);
}
//
// client-side connect
//
int
UDPIPNetwork::connect(in_addr& addr, u_int16_t port)
{
sockaddr_in sin;
if (ssock_ < 0) {
fprintf(stderr,
"UDPIPNetwork(%s): connect called before net is open\n",
name());
return (-1);
}
if (mode_ == O_RDONLY) {
fprintf(stderr,
"UDPIPNetwork(%s): attempted connect but net is read-only\n",
name());
return (-1);
}
int rval = connectsock(ssock_, addr, port, sin);
if (rval < 0)
return (rval);
destaddr_ = addr;
port_ = port;
last_reset_ = 0;
return(rval);
}
int
UDPIPNetwork::command(int argc, const char*const* argv)
{
Tcl& tcl = Tcl::instance();
if (argc == 2) {
// $udpip port
if (strcmp(argv[1], "port") == 0) {
tcl.resultf("%d", ntohs(port_));
return (TCL_OK);
}
// $udpip lport
if (strcmp(argv[1], "lport") == 0) {
tcl.resultf("%d", ntohs(lport_));
return (TCL_OK);
}
} else if (argc == 4) {
// $udpip listen addr port
// $udpip bind addr port
if (strcmp(argv[1], "listen") == 0 ||
strcmp(argv[1], "bind") == 0) {
in_addr addr;
if (strcmp(argv[2], "any") == 0)
addr.s_addr = INADDR_ANY;
else
addr.s_addr = LookupHostAddr(argv[2]);
u_int16_t port = htons(atoi(argv[3]));
if (bind(addr, port) < 0) {
tcl.resultf("%s %hu",
inet_ntoa(addr), port);
} else {
tcl.result("0");
}
return (TCL_OK);
}
// $udpip connect addr port
if (strcmp(argv[1], "connect") == 0) {
in_addr addr;
addr.s_addr = LookupHostAddr(argv[2]);
u_int16_t port = htons(atoi(argv[3]));
if (connect(addr, port) < 0) {
tcl.resultf("%s %hu",
inet_ntoa(addr), port);
} else {
tcl.result("0");
}
return (TCL_OK);
}
}
return (IPNetwork::command(argc, argv));
}
//
// raw IP network recv()
//
int
IPNetwork::recv(u_char* buf, int len, sockaddr& sa, double& ts)
{
if (mode_ == O_WRONLY) {
fprintf(stderr,
"IPNetwork(%s) recv while in writeonly mode!\n",
name());
abort();
}
int fromlen = sizeof(sa);
int cc = ::recvfrom(rsock_, (char*)buf, len, 0, &sa, (socklen_t*)&fromlen);
if (cc < 0) {
if (errno != EWOULDBLOCK)
perror("recvfrom");
return (-1);
}
ts = Scheduler::instance().clock();
return (cc);
}
//
// we are given a "raw" IP datagram.
// the raw interface appears to want the len and off fields
// in *host* order, so make it this way here
// note also, that it will compute the cksum "for" us... :(
//
int
IPNetwork::send(u_char* buf, int len)
{
struct ip *ip = (struct ip*) buf;
ip->ip_len = ntohs(ip->ip_len);
ip->ip_off = ntohs(ip->ip_off);
return (::send(ssock_, (char*)buf, len, 0));
}
int IPNetwork::command(int argc, const char*const* argv)
{
Tcl& tcl = Tcl::instance();
if (argc == 2) {
if (strcmp(argv[1], "close") == 0) {
close();
return (TCL_OK);
}
char* cp = tcl.result();
if (strcmp(argv[1], "destaddr") == 0) {
strcpy(cp, inet_ntoa(destaddr_));
return (TCL_OK);
}
if (strcmp(argv[1], "localaddr") == 0) {
strcpy(cp, inet_ntoa(localaddr_));
return (TCL_OK);
}
if (strcmp(argv[1], "mttl") == 0) {
tcl.resultf("%d", mttl_);
return (TCL_OK);
}
/* for backward compatability */
if (strcmp(argv[1], "ismulticast") == 0) {
tcl.result(IN_CLASSD(ntohl(destaddr_.s_addr)) ?
"1" : "0");
return (TCL_OK);
}
if (strcmp(argv[1], "addr") == 0) {
strcpy(cp, inet_ntoa(destaddr_));
return (TCL_OK);
}
if (strcmp(argv[1], "ttl") == 0) {
tcl.resultf("%d", mttl_);
return (TCL_OK);
}
if (strcmp(argv[1], "interface") == 0) {
strcpy(cp, inet_ntoa(localaddr_));
return (TCL_OK);
}
} else if (argc == 3) {
if (strcmp(argv[1], "open") == 0) {
int mode = parsemode(argv[2]);
if (open(mode) < 0)
return (TCL_ERROR);
return (TCL_OK);
}
if (strcmp(argv[1], "add-membership") == 0) {
in_addr addr;
addr.s_addr = LookupHostAddr(argv[2]);
if (add_membership(rchannel(), addr) < 0)
tcl.result("0");
else
tcl.result("1");
return (TCL_OK);
}
if (strcmp(argv[1], "drop-membership") == 0) {
in_addr addr;
addr.s_addr = LookupHostAddr(argv[2]);
if (drop_membership(rchannel(), addr) < 0)
tcl.result("0");
else
tcl.result("1");
return (TCL_OK);
}
if (strcmp(argv[1], "loopback") == 0) {
int val = atoi(argv[2]);
if (strcmp(argv[2], "true") == 0)
val = 1;
else if (strcmp(argv[2], "false") == 0)
val = 0;
if (setmloop(schannel(), val) < 0)
tcl.result("0");
else
tcl.result("1");
return (TCL_OK);
}
}
return (Network::command(argc, argv));
}
int
IPNetwork::setmttl(Socket s, int ttl)
{
/* set the multicast TTL */
#ifdef WIN32
u_int t = ttl;
#else
u_char t = ttl;
#endif
t = (ttl > 255) ? 255 : (ttl < 0) ? 0 : ttl;
if (::setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL,
(char*)&t, sizeof(t)) < 0) {
fprintf(stderr,
"IPNetwork(%s): couldn't set multicast ttl to %d\n",
name(), t);
return (-1);
}
return (0);
}
/*
* open a RAW IP socket (will require privilege).
* turn on HDRINCL, specifying that we will be writing the raw IP header
*/
int
IPNetwork::open(int mode)
{
// obtain a raw socket we can use to send ip datagrams
Socket fd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
if (fd < 0) {
perror("socket(RAW)");
if (::getuid() != 0 && ::geteuid() != 0) {
fprintf(stderr,
"IPNetwork(%s): open: use of the Network/IP object requires super-user privs\n",
name());
}
return (-1);
}
// turn on HDRINCL option (we will be writing IP header)
// in FreeBSD 2.2.5 (and possibly others), the IP id field
// is set by the kernel routine rip_output()
// only if it is non-zero, so we should be ok.
int one = 1;
if (::setsockopt(fd, IPPROTO_IP, IP_HDRINCL, &one, sizeof(one)) < 0) {
fprintf(stderr,
"IPNetwork(%s): open: unable to turn on IP_HDRINCL: %s\n",
name(), strerror(errno));
return (-1);
}
// sort of curious, but do a connect() even though we have
// HDRINCL on. Otherwise, we get ENOTCONN when doing a send()
sockaddr_in sin;
in_addr ia = { INADDR_ANY };
if (connectsock(fd, ia, 0, sin) < 0) {
fprintf(stderr,
"IPNetwork(%s): open: unable to connect : %s\n",
name(), strerror(errno));
}
rsock_ = ssock_ = fd;
mode_ = mode;
NIDEBUG5("IPNetwork(%s): opened with mode %d, rsock_:%d, ssock_:%d\n",
name(), mode_, rsock_, ssock_);
return 0;
}
/*
* close both sending and receiving sockets
*/
int
IPNetwork::close()
{
if (ssock_ >= 0) {
(void)::close(ssock_);
ssock_ = -1;
}
if (rsock_ >= 0) {
(void)::close(rsock_);
rsock_ = -1;
}
return (0);
}
/*
* add multicast group membership on the socket
*/
int
IPNetwork::add_membership(Socket fd, in_addr& addr)
{
#if defined(IP_ADD_MEMBERSHIP)
if (IN_CLASSD(ntohl(addr.s_addr))) {
#ifdef notdef
/*
* Try to bind the multicast address as the socket
* dest address. On many systems this won't work
* so fall back to a destination of INADDR_ANY if
* the first bind fails.
*/
sockaddr_in sin;
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr = addr;
if (::bind(fd, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
sin.sin_addr.s_addr = INADDR_ANY;
if (::bind(fd, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
fprintf(stderr,
"IPNetwork(%s): add_membership: unable to bind to addr %s: %s\n",
name(), inet_ntoa(sin.sin_addr),
strerror(errno));
return (-1);
}
}
#endif
/*
* XXX This is bogus multicast setup that really
* shouldn't have to be done (group membership should be
* implicit in the IP class D address, route should contain
* ttl & no loopback flag, etc.). Steve Deering has promised
* to fix this for the 4.4bsd release. We're all waiting
* with bated breath.
*/
struct ip_mreq mr;
mr.imr_multiaddr = addr;
mr.imr_interface.s_addr = INADDR_ANY;
if (::setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
(char *)&mr, sizeof(mr)) < 0) {
fprintf(stderr, "IPNetwork(%s): add_membership: unable to add membership for addr %s: %s\n",
name(), inet_ntoa(addr), strerror(errno));
return (-1);
}
NIDEBUG3("IPNetwork(%s): add_membership for grp %s done\n",
name(), inet_ntoa(addr));
return (0);
}
#else
fprintf(stderr, "IPNetwork(%s): add_membership: host does not support IP multicast\n",
name());
#endif
NIDEBUG3("IPNetwork(%s): add_membership for grp %s failed\n",
name(), inet_ntoa(addr));
return (-1);
}
/*
* drop membership from the specified group on the specified socket
*/
int
IPNetwork::drop_membership(Socket fd, in_addr& addr)
{
#if defined(IP_DROP_MEMBERSHIP)
if (IN_CLASSD(ntohl(addr.s_addr))) {
struct ip_mreq mr;
mr.imr_multiaddr = addr;
mr.imr_interface.s_addr = INADDR_ANY;
if (::setsockopt(fd, IPPROTO_IP, IP_DROP_MEMBERSHIP,
(char *)&mr, sizeof(mr)) < 0) {
fprintf(stderr, "IPNetwork(%s): drop_membership: unable to drop membership for addr %s: %s\n",
name(), inet_ntoa(addr), strerror(errno));
return (-1);
}
NIDEBUG3("IPNetwork(%s): drop_membership for grp %s done\n",
name(), inet_ntoa(addr));
return (0);
}
#else
fprintf(stderr, "IPNetwork(%s): drop_membership: host does not support IP multicast\n",
name());
#endif
NIDEBUG3("IPNetwork(%s): drop_membership for grp %s failed\n",
name(), inet_ntoa(addr));
return (-1);
}
int
IPNetwork::bindsock(Socket s, in_addr& addr, u_int16_t port, sockaddr_in& sin)
{
memset((char *)&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_port = port;
sin.sin_addr = addr;
return(::bind(s, (struct sockaddr *)&sin, sizeof(sin)));
}
int
IPNetwork::connectsock(Socket s, in_addr& addr, u_int16_t port, sockaddr_in& sin)
{
memset((char *)&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_port = port;
sin.sin_addr = addr;
return(::connect(s, (struct sockaddr *)&sin, sizeof(sin)));
}
int
IPNetwork::sbufsize(Socket s, int cnt)
{
return(::setsockopt(s, SOL_SOCKET, SO_SNDBUF, (char *)&cnt, sizeof(cnt)));
}
int
IPNetwork::rbufsize(Socket s, int cnt)
{
return(::setsockopt(s, SOL_SOCKET, SO_RCVBUF, (char *)&cnt, sizeof(cnt)));
}
int
IPNetwork::setmloop(Socket s, int loop)
{
#ifdef IP_MULTICAST_LOOP
u_char c = loop;
if (::setsockopt(s, IPPROTO_IP, IP_MULTICAST_LOOP, &c, sizeof(c)) < 0) {
/*
* If we cannot turn off loopback (Like on the
* Microsoft TCP/IP stack), then declare this
* option broken so that our packets can be
* filtered on the recv path.
*/
if (c != loop) {
noloopback_broken_ = 1;
loop_ = c;
}
return (-1);
}
noloopback_broken_ = 0;
#else
fprintf(stderr, "IPNetwork(%s): msetloop: host does not support IP multicast\n",
name());
#endif
loop_ = c;
return (0);
}
void
IPNetwork::reset(int restart)
{
time_t t = time(0);
int d = int(t - last_reset_);
NIDEBUG2("IPNetwork(%s): reset\n", name());
if (d > 3) { // Steve: why?
last_reset_ = t;
if (ssock_ >= 0)
(void)::close(ssock_);
if (rsock_ >= 0)
(void)::close(rsock_);
if (open(mode_) < 0) {
fprintf(stderr,
"IPNetwork(%s): couldn't reset\n",
name());
mode_ = -1;
return;
}
if (restart)
(void) reconfigure();
}
}
/*
* after a reset, we may want to re-establish our state
* [set up addressing, etc]. Do this here
*/
void
IPNetwork::reconfigure()
{
}
void
UDPIPNetwork::reconfigure()
{
}
| [
"smilemare@foxmail.com"
] | smilemare@foxmail.com |
b3717b3eefead7bf88602293c117b93a712ebab2 | 11a246743073e9d2cb550f9144f59b95afebf195 | /acmsgu/538.cpp | 26b974fd691520480c8fea102b5ad7e3d0261683 | [] | no_license | ankitpriyarup/online-judge | b5b779c26439369cedc05c045af5511cbc3c980f | 8a00ec141142c129bfa13a68dbf704091eae9588 | refs/heads/master | 2020-09-05T02:46:56.377213 | 2019-10-27T20:12:25 | 2019-10-27T20:12:25 | 219,959,932 | 0 | 1 | null | 2019-11-06T09:30:58 | 2019-11-06T09:30:57 | null | UTF-8 | C++ | false | false | 1,327 | cpp | #include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
#include <fstream>
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <utility>
#include <vector>
#include <queue>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <complex>
using namespace std;
using ll = long long;
using ld = long double;
using pii = pair<int, int>;
bool latinspace(char c) {
if (c == ' ') return true;
if ('a' <= c and c <= 'z') return true;
if ('A' <= c and c <= 'Z') return true;
return false;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
string s;
getline(cin, s);
int n = s.size();
int ans = 0;
vector<int> stk;
for (int i = 0; i < n; ++i) {
if (s[i] == '(') {
stk.push_back(i);
} else if (s[i] == ')') {
if (!stk.empty()) {
stk.pop_back();
ans += stk.size();
stk.clear();
} else {
++ans;
}
} else if (!latinspace(s[i])) {
ans += stk.size();
stk.clear();
}
}
ans += stk.size();
printf("%d\n", ans);
return 0;
}
| [
"arnavsastry@gmail.com"
] | arnavsastry@gmail.com |
9414607a9086ef07e88c8e940a771c8d32bda7ae | 1095cfe2e29ddf4e4c5e12d713bd12f45c9b6f7d | /ext/systemc/src/sysc/kernel/sc_simcontext.cpp | 104f7c984e7d55db8ab077c95dcb25c23e445d67 | [
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license",
"LGPL-2.0-or-later",
"MIT"
] | permissive | gem5/gem5 | 9ec715ae036c2e08807b5919f114e1d38d189bce | 48a40cf2f5182a82de360b7efa497d82e06b1631 | refs/heads/stable | 2023-09-03T15:56:25.819189 | 2023-08-31T05:53:03 | 2023-08-31T05:53:03 | 27,425,638 | 1,185 | 1,177 | BSD-3-Clause | 2023-09-14T08:29:31 | 2014-12-02T09:46:00 | C++ | UTF-8 | C++ | false | false | 70,506 | cpp | /*****************************************************************************
Licensed to Accellera Systems Initiative Inc. (Accellera) under one or
more contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright ownership.
Accellera licenses this file to you under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with the
License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
*****************************************************************************/
/*****************************************************************************
sc_simcontext.cpp -- Provides a simulation context for use with multiple
simulations.
Original Author: Stan Y. Liao, Synopsys, Inc.
Martin Janssen, Synopsys, Inc.
CHANGE LOG AT THE END OF THE FILE
*****************************************************************************/
#include <algorithm>
#define SC_DISABLE_API_VERSION_CHECK // for in-library sc_ver.h inclusion
#include "sysc/kernel/sc_cor_fiber.h"
#include "sysc/kernel/sc_cor_pthread.h"
#include "sysc/kernel/sc_cor_qt.h"
#include "sysc/kernel/sc_event.h"
#include "sysc/kernel/sc_kernel_ids.h"
#include "sysc/kernel/sc_module.h"
#include "sysc/kernel/sc_module_registry.h"
#include "sysc/kernel/sc_name_gen.h"
#include "sysc/kernel/sc_object_manager.h"
#include "sysc/kernel/sc_cthread_process.h"
#include "sysc/kernel/sc_method_process.h"
#include "sysc/kernel/sc_thread_process.h"
#include "sysc/kernel/sc_process_handle.h"
#include "sysc/kernel/sc_simcontext.h"
#include "sysc/kernel/sc_simcontext_int.h"
#include "sysc/kernel/sc_reset.h"
#include "sysc/kernel/sc_ver.h"
#include "sysc/kernel/sc_boost.h"
#include "sysc/kernel/sc_spawn.h"
#include "sysc/kernel/sc_phase_callback_registry.h"
#include "sysc/communication/sc_port.h"
#include "sysc/communication/sc_export.h"
#include "sysc/communication/sc_prim_channel.h"
#include "sysc/tracing/sc_trace.h"
#include "sysc/utils/sc_mempool.h"
#include "sysc/utils/sc_list.h"
#include "sysc/utils/sc_utils_ids.h"
// DEBUGGING MACROS:
//
// DEBUG_MSG(NAME,P,MSG)
// MSG = message to print
// NAME = name that must match the process for the message to print, or
// null if the message should be printed unconditionally.
// P = pointer to process message is for, or NULL in which case the
// message will not print.
#if 0
# define DEBUG_NAME ""
# define DEBUG_MSG(NAME,P,MSG) \
{ \
if ( P && ( (strlen(NAME)==0) || !strcmp(NAME,P->name())) ) \
std::cout << "**** " << sc_time_stamp() << " (" \
<< sc_get_current_process_name() << "): " << MSG \
<< " - " << P->name() << std::endl; \
}
#else
# define DEBUG_MSG(NAME,P,MSG)
#endif
#if SC_HAS_PHASE_CALLBACKS_
# define SC_DO_PHASE_CALLBACK_( Kind ) \
m_phase_cb_registry->Kind()
#else
# define SC_DO_PHASE_CALLBACK_( Kind ) \
((void)0) /* do nothing */
#endif
#if defined( SC_ENABLE_SIMULATION_PHASE_CALLBACKS_TRACING )
// use callback based tracing
# define SC_SIMCONTEXT_TRACING_ 0
#else
// enable tracing via explicit trace_cycle calls from simulator loop
# define SC_SIMCONTEXT_TRACING_ 1
#endif
namespace sc_core {
sc_stop_mode stop_mode = SC_STOP_FINISH_DELTA;
// ----------------------------------------------------------------------------
// CLASS : sc_process_table
//
// Container class that keeps track of all method processes,
// (c)thread processes.
// ----------------------------------------------------------------------------
class sc_process_table
{
public:
sc_process_table();
~sc_process_table();
void push_front( sc_method_handle );
void push_front( sc_thread_handle );
sc_method_handle method_q_head();
sc_method_handle remove( sc_method_handle );
sc_thread_handle thread_q_head();
sc_thread_handle remove( sc_thread_handle );
private:
sc_method_handle m_method_q; // Queue of existing method processes.
sc_thread_handle m_thread_q; // Queue of existing thread processes.
};
// IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII
sc_process_table::sc_process_table() : m_method_q(0), m_thread_q(0)
{}
sc_process_table::~sc_process_table()
{
sc_method_handle method_next_p; // Next method to delete.
sc_method_handle method_now_p; // Method now deleting.
for( method_now_p = m_method_q; method_now_p; method_now_p = method_next_p )
{
method_next_p = method_now_p->next_exist();
delete method_now_p;
}
if ( m_thread_q )
{
::std::cout << ::std::endl
<< "WATCH OUT!! In sc_process_table destructor. "
<< "Threads and cthreads are not actually getting deleted here. "
<< "Some memory may leak. Look at the comments here in "
<< "kernel/sc_simcontext.cpp for more details."
<< ::std::endl;
}
// don't delete threads and cthreads. If a (c)thread
// has died, then it has already been deleted. Only (c)threads created
// before simulation-start are in this table. Due to performance
// reasons, we don't look up the dying thread in the process table
// and remove it from there. simcontext::reset and ~simcontext invoke this
// destructor. At present none of these routines are ever invoked.
// We can delete threads and cthreads here if a dying thread figured out
// it was created before simulation-start and took itself off the
// process_table.
#if 0
sc_thread_handle thread_next_p; // Next thread to delete.
sc_thread_handle thread_now_p; // Thread now deleting.
for( thread_now_p=m_thread_q; thread_now_p; thread_now_p=thread_next_p )
{
thread_next_p = thread_now_p->next_exist();
delete thread_now_p;
}
#endif // 0
}
inline
sc_method_handle
sc_process_table::method_q_head()
{
return m_method_q;
}
inline
void
sc_process_table::push_front( sc_method_handle handle_ )
{
handle_->set_next_exist(m_method_q);
m_method_q = handle_;
}
inline
void
sc_process_table::push_front( sc_thread_handle handle_ )
{
handle_->set_next_exist(m_thread_q);
m_thread_q = handle_;
}
sc_method_handle
sc_process_table::remove( sc_method_handle handle_ )
{
sc_method_handle now_p; // Entry now examining.
sc_method_handle prior_p; // Entry prior to one now examining.
prior_p = 0;
for ( now_p = m_method_q; now_p; now_p = now_p->next_exist() )
{
if ( now_p == handle_ )
{
if ( prior_p )
prior_p->set_next_exist( now_p->next_exist() );
else
m_method_q = now_p->next_exist();
return handle_;
}
}
return 0;
}
sc_thread_handle
sc_process_table::remove( sc_thread_handle handle_ )
{
sc_thread_handle now_p; // Entry now examining.
sc_thread_handle prior_p; // Entry prior to one now examining.
prior_p = 0;
for ( now_p = m_thread_q; now_p; now_p = now_p->next_exist() )
{
if ( now_p == handle_ )
{
if ( prior_p )
prior_p->set_next_exist( now_p->next_exist() );
else
m_thread_q = now_p->next_exist();
return handle_;
}
}
return 0;
}
inline
sc_thread_handle
sc_process_table::thread_q_head()
{
return m_thread_q;
}
int
sc_notify_time_compare( const void* p1, const void* p2 )
{
const sc_event_timed* et1 = static_cast<const sc_event_timed*>( p1 );
const sc_event_timed* et2 = static_cast<const sc_event_timed*>( p2 );
const sc_time& t1 = et1->notify_time();
const sc_time& t2 = et2->notify_time();
if( t1 < t2 ) {
return 1;
} else if( t1 > t2 ) {
return -1;
} else {
return 0;
}
}
// +============================================================================
// | CLASS sc_invoke_method - class to invoke sc_method's to support
// | sc_simcontext::preempt_with().
// +============================================================================
SC_MODULE(sc_invoke_method)
{
SC_CTOR(sc_invoke_method)
{
// remove from object hierarchy
detach();
}
virtual ~sc_invoke_method()
{
m_invokers.resize(0);
}
// Method to call to execute a method's semantics.
void invoke_method( sc_method_handle method_h )
{
sc_process_handle invoker_h; // handle for invocation thread to use.
std::vector<sc_process_handle>::size_type invokers_n; // number of invocation threads available.
m_method = method_h;
// There is not an invocation thread to use, so allocate one.
invokers_n = m_invokers.size();
if ( invokers_n == 0 )
{
sc_spawn_options options;
options.dont_initialize();
options.set_stack_size(0x100000);
options.set_sensitivity(&m_dummy);
invoker_h = sc_spawn(sc_bind(&sc_invoke_method::invoker,this),
sc_gen_unique_name("invoker"), &options);
((sc_process_b*)invoker_h)->detach();
}
// There is an invocation thread to use, use the last one on the list.
else
{
invoker_h = m_invokers[invokers_n-1];
m_invokers.pop_back();
}
// Fire off the invocation thread to invoke the method's semantics,
// When it blocks put it onto the list of invocation threads that
// are available.
sc_get_curr_simcontext()->preempt_with( (sc_thread_handle)invoker_h );
DEBUG_MSG( DEBUG_NAME, m_method, "back from preemption" );
m_invokers.push_back(invoker_h);
}
// Thread to call method from:
void invoker()
{
sc_simcontext* csc_p = sc_get_curr_simcontext();
sc_process_b* me = sc_get_current_process_b();
DEBUG_MSG( DEBUG_NAME, me, "invoker initialization" );
for (;; )
{
DEBUG_MSG( DEBUG_NAME, m_method, "invoker executing method" );
csc_p->set_curr_proc( (sc_process_b*)m_method );
csc_p->get_active_invokers().push_back((sc_thread_handle)me);
m_method->run_process();
csc_p->set_curr_proc( me );
csc_p->get_active_invokers().pop_back();
DEBUG_MSG( DEBUG_NAME, m_method, "back from executing method" );
wait();
}
}
sc_event m_dummy; // dummy event to wait on.
sc_method_handle m_method; // method to be invoked.
std::vector<sc_process_handle> m_invokers; // list of invoking threads.
};
// ----------------------------------------------------------------------------
// CLASS : sc_simcontext
//
// The simulation context.
// ----------------------------------------------------------------------------
void
sc_simcontext::init()
{
// ALLOCATE VARIOUS MANAGERS AND REGISTRIES:
m_object_manager = new sc_object_manager;
m_module_registry = new sc_module_registry( *this );
m_port_registry = new sc_port_registry( *this );
m_export_registry = new sc_export_registry( *this );
m_prim_channel_registry = new sc_prim_channel_registry( *this );
m_phase_cb_registry = new sc_phase_callback_registry( *this );
m_name_gen = new sc_name_gen;
m_process_table = new sc_process_table;
m_current_writer = 0;
// CHECK FOR ENVIRONMENT VARIABLES THAT MODIFY SIMULATOR EXECUTION:
const char* write_check = std::getenv("SC_SIGNAL_WRITE_CHECK");
m_write_check = ( (write_check==0) || strcmp(write_check,"DISABLE") ) ?
true : false;
// FINISH INITIALIZATIONS:
reset_curr_proc();
m_next_proc_id = -1;
m_timed_events = new sc_ppq<sc_event_timed*>( 128, sc_notify_time_compare );
m_something_to_trace = false;
m_runnable = new sc_runnable;
m_collectable = new sc_process_list;
m_time_params = new sc_time_params;
m_curr_time = SC_ZERO_TIME;
m_max_time = SC_ZERO_TIME;
m_change_stamp = 0;
m_delta_count = 0;
m_forced_stop = false;
m_paused = false;
m_ready_to_simulate = false;
m_elaboration_done = false;
m_execution_phase = phase_initialize;
m_error = NULL;
m_cor_pkg = 0;
m_method_invoker_p = NULL;
m_cor = 0;
m_in_simulator_control = false;
m_start_of_simulation_called = false;
m_end_of_simulation_called = false;
m_simulation_status = SC_ELABORATION;
}
void
sc_simcontext::clean()
{
delete m_object_manager;
delete m_module_registry;
delete m_port_registry;
delete m_export_registry;
delete m_prim_channel_registry;
delete m_phase_cb_registry;
delete m_name_gen;
delete m_process_table;
m_child_objects.resize(0);
m_delta_events.resize(0);
delete m_timed_events;
for( int i = m_trace_files.size() - 1; i >= 0; -- i ) {
delete m_trace_files[i];
}
m_trace_files.resize(0);
delete m_runnable;
delete m_collectable;
delete m_time_params;
delete m_cor_pkg;
delete m_error;
}
sc_simcontext::sc_simcontext() :
m_object_manager(0), m_module_registry(0), m_port_registry(0),
m_export_registry(0), m_prim_channel_registry(0),
m_phase_cb_registry(0), m_name_gen(0),
m_process_table(0), m_curr_proc_info(), m_current_writer(0),
m_write_check(false), m_next_proc_id(-1), m_child_events(),
m_child_objects(), m_delta_events(), m_timed_events(0), m_trace_files(),
m_something_to_trace(false), m_runnable(0), m_collectable(0),
m_time_params(), m_curr_time(SC_ZERO_TIME), m_max_time(SC_ZERO_TIME),
m_change_stamp(0), m_delta_count(0), m_forced_stop(false), m_paused(false),
m_ready_to_simulate(false), m_elaboration_done(false),
m_execution_phase(phase_initialize), m_error(0),
m_in_simulator_control(false), m_end_of_simulation_called(false),
m_simulation_status(SC_ELABORATION), m_start_of_simulation_called(false),
m_cor_pkg(0), m_cor(0)
{
init();
}
sc_simcontext::~sc_simcontext()
{
clean();
}
// +----------------------------------------------------------------------------
// |"sc_simcontext::active_object"
// |
// | This method returns the currently active object with respect to
// | additions to the hierarchy. It will be the top of the object hierarchy
// | stack if it is non-empty, or it will be the active process, or NULL
// | if there is no active process.
// +----------------------------------------------------------------------------
sc_object*
sc_simcontext::active_object()
{
sc_object* result_p; // pointer to return.
result_p = m_object_manager->hierarchy_curr();
if ( !result_p )
result_p = (sc_object*)get_curr_proc_info()->process_handle;
return result_p;
}
// +----------------------------------------------------------------------------
// |"sc_simcontext::crunch"
// |
// | This method implements the simulator's execution of processes. It performs
// | one or more "delta" cycles. Each delta cycle consists of an evaluation,
// | an update phase, and a notification phase. During the evaluation phase any
// | processes that are ready to run are executed. After all the processes have
// | been executed the update phase is entered. During the update phase the
// | values of any signals that have changed are updated. After the updates
// | have been performed the notification phase is entered. During that phase
// | any notifications that need to occur because of of signal values changes
// | are performed. This will result in the queueing of processes for execution
// | that are sensitive to those notifications. At that point a delta cycle
// | is complete, and the process is started again unless 'once' is true.
// |
// | Arguments:
// | once = true if only one delta cycle is to be performed.
// +----------------------------------------------------------------------------
inline void
sc_simcontext::crunch( bool once )
{
#ifdef DEBUG_SYSTEMC
int num_deltas = 0; // number of delta cycles
#endif
while ( true )
{
// EVALUATE PHASE
m_execution_phase = phase_evaluate;
bool empty_eval_phase = true;
while( true )
{
// execute method processes
m_runnable->toggle_methods();
sc_method_handle method_h = pop_runnable_method();
while( method_h != 0 ) {
empty_eval_phase = false;
if ( !method_h->run_process() )
{
goto out;
}
method_h = pop_runnable_method();
}
// execute (c)thread processes
m_runnable->toggle_threads();
sc_thread_handle thread_h = pop_runnable_thread();
while( thread_h != 0 ) {
if ( thread_h->m_cor_p != NULL ) break;
thread_h = pop_runnable_thread();
}
if( thread_h != 0 ) {
empty_eval_phase = false;
m_cor_pkg->yield( thread_h->m_cor_p );
}
if( m_error ) {
goto out;
}
// check for call(s) to sc_stop
if( m_forced_stop ) {
if ( stop_mode == SC_STOP_IMMEDIATE ) goto out;
}
// no more runnable processes
if( m_runnable->is_empty() ) {
break;
}
}
// remove finally dead zombies:
while( ! m_collectable->empty() )
{
sc_process_b* del_p = m_collectable->front();
m_collectable->pop_front();
del_p->reference_decrement();
}
// UPDATE PHASE
//
// The change stamp must be updated first so that event_occurred()
// will work.
m_execution_phase = phase_update;
if ( !empty_eval_phase )
{
// SC_DO_PHASE_CALLBACK_(evaluation_done);
m_change_stamp++;
m_delta_count ++;
}
m_prim_channel_registry->perform_update();
SC_DO_PHASE_CALLBACK_(update_done);
m_execution_phase = phase_notify;
#if SC_SIMCONTEXT_TRACING_
if( m_something_to_trace ) {
trace_cycle( /* delta cycle? */ true );
}
#endif
// check for call(s) to sc_stop
if( m_forced_stop ) {
break;
}
#ifdef DEBUG_SYSTEMC
// check for possible infinite loops
if( ++ num_deltas > SC_MAX_NUM_DELTA_CYCLES ) {
::std::cerr << "SystemC warning: "
<< "the number of delta cycles exceeds the limit of "
<< SC_MAX_NUM_DELTA_CYCLES
<< ", defined in sc_constants.h.\n"
<< "This is a possible sign of an infinite loop.\n"
<< "Increase the limit if this warning is invalid.\n";
break;
}
#endif
// NOTIFICATION PHASE:
//
// Process delta notifications which will queue processes for
// subsequent execution.
int size = m_delta_events.size();
if ( size != 0 )
{
sc_event** l_events = &m_delta_events[0];
int i = size - 1;
do {
l_events[i]->trigger();
} while( -- i >= 0 );
m_delta_events.resize(0);
}
if( m_runnable->is_empty() ) {
// no more runnable processes
break;
}
// if sc_pause() was called we are done.
if ( m_paused ) break;
// IF ONLY DOING ONE CYCLE, WE ARE DONE. OTHERWISE EXECUTE NEW CALLBACKS
if ( once ) break;
}
// When this point is reached the processing of delta cycles is complete,
// if the completion was because of an error throw the exception specified
// by '*m_error'.
out:
this->reset_curr_proc();
if( m_error ) throw *m_error; // re-throw propagated error
}
inline
void
sc_simcontext::cycle( const sc_time& t)
{
sc_time next_event_time;
m_in_simulator_control = true;
crunch();
SC_DO_PHASE_CALLBACK_(before_timestep);
#if SC_SIMCONTEXT_TRACING_
if( m_something_to_trace ) {
trace_cycle( /* delta cycle? */ false );
}
#endif
m_curr_time += t;
if ( next_time(next_event_time) && next_event_time <= m_curr_time) {
SC_REPORT_WARNING(SC_ID_CYCLE_MISSES_EVENTS_, "");
}
m_in_simulator_control = false;
SC_DO_PHASE_CALLBACK_(simulation_paused);
}
void
sc_simcontext::elaborate()
{
if( m_elaboration_done || sim_status() != SC_SIM_OK ) {
return;
}
// Instantiate the method invocation module
// (not added to public object hierarchy)
m_method_invoker_p =
new sc_invoke_method("$$$$kernel_module$$$$_invoke_method" );
m_simulation_status = SC_BEFORE_END_OF_ELABORATION;
for( int cd = 0; cd != 4; /* empty */ )
{
cd = m_port_registry->construction_done();
cd += m_export_registry->construction_done();
cd += m_prim_channel_registry->construction_done();
cd += m_module_registry->construction_done();
// check for call(s) to sc_stop
if( m_forced_stop ) {
do_sc_stop_action();
return;
}
}
SC_DO_PHASE_CALLBACK_(construction_done);
// SIGNAL THAT ELABORATION IS DONE
//
// We set the switch before the calls in case someone creates a process
// in an end_of_elaboration callback. We need the information to flag
// the process as being dynamic.
m_elaboration_done = true;
m_simulation_status = SC_END_OF_ELABORATION;
m_port_registry->elaboration_done();
m_export_registry->elaboration_done();
m_prim_channel_registry->elaboration_done();
m_module_registry->elaboration_done();
SC_DO_PHASE_CALLBACK_(elaboration_done);
sc_reset::reconcile_resets();
// check for call(s) to sc_stop
if( m_forced_stop ) {
do_sc_stop_action();
return;
}
}
void
sc_simcontext::prepare_to_simulate()
{
sc_method_handle method_p; // Pointer to method process accessing.
sc_thread_handle thread_p; // Pointer to thread process accessing.
if( m_ready_to_simulate || sim_status() != SC_SIM_OK ) {
return;
}
// instantiate the coroutine package
m_cor_pkg = new sc_cor_pkg_t( this );
m_cor = m_cor_pkg->get_main();
// NOTIFY ALL OBJECTS THAT SIMULATION IS ABOUT TO START:
m_simulation_status = SC_START_OF_SIMULATION;
m_port_registry->start_simulation();
m_export_registry->start_simulation();
m_prim_channel_registry->start_simulation();
m_module_registry->start_simulation();
SC_DO_PHASE_CALLBACK_(start_simulation);
m_start_of_simulation_called = true;
// CHECK FOR CALL(S) TO sc_stop
if( m_forced_stop ) {
do_sc_stop_action();
return;
}
// PREPARE ALL (C)THREAD PROCESSES FOR SIMULATION:
for ( thread_p = m_process_table->thread_q_head();
thread_p; thread_p = thread_p->next_exist() )
{
thread_p->prepare_for_simulation();
}
m_simulation_status = SC_RUNNING;
m_ready_to_simulate = true;
m_runnable->init();
// update phase
m_execution_phase = phase_update;
m_prim_channel_registry->perform_update();
m_execution_phase = phase_notify;
int size;
// make all method processes runnable
for ( method_p = m_process_table->method_q_head();
method_p; method_p = method_p->next_exist() )
{
if ( ((method_p->m_state & sc_process_b::ps_bit_disabled) != 0) ||
method_p->dont_initialize() )
{
if ( method_p->m_static_events.size() == 0 )
{
SC_REPORT_WARNING( SC_ID_DISABLE_WILL_ORPHAN_PROCESS_,
method_p->name() );
}
}
else if ( (method_p->m_state & sc_process_b::ps_bit_suspended) == 0)
{
push_runnable_method_front( method_p );
}
else
{
method_p->m_state |= sc_process_b::ps_bit_ready_to_run;
}
}
// make thread processes runnable
// (cthread processes always have the dont_initialize flag set)
for ( thread_p = m_process_table->thread_q_head();
thread_p; thread_p = thread_p->next_exist() )
{
if ( ((thread_p->m_state & sc_process_b::ps_bit_disabled) != 0) ||
thread_p->dont_initialize() )
{
if ( thread_p->m_static_events.size() == 0 )
{
SC_REPORT_WARNING( SC_ID_DISABLE_WILL_ORPHAN_PROCESS_,
thread_p->name() );
}
}
else if ( (thread_p->m_state & sc_process_b::ps_bit_suspended) == 0)
{
push_runnable_thread_front( thread_p );
}
else
{
thread_p->m_state |= sc_process_b::ps_bit_ready_to_run;
}
}
// process delta notifications
if( ( size = m_delta_events.size() ) != 0 ) {
sc_event** l_delta_events = &m_delta_events[0];
int i = size - 1;
do {
l_delta_events[i]->trigger();
} while( -- i >= 0 );
m_delta_events.resize(0);
}
SC_DO_PHASE_CALLBACK_(initialization_done);
}
void
sc_simcontext::initial_crunch( bool no_crunch )
{
if( no_crunch || m_runnable->is_empty() ) {
return;
}
// run the delta cycle loop
crunch();
if( m_error ) {
return;
}
#if SC_SIMCONTEXT_TRACING_
if( m_something_to_trace ) {
trace_cycle( false );
}
#endif
// check for call(s) to sc_stop
if( m_forced_stop ) {
do_sc_stop_action();
}
}
void
sc_simcontext::initialize( bool no_crunch )
{
m_in_simulator_control = true;
elaborate();
prepare_to_simulate();
initial_crunch(no_crunch);
m_in_simulator_control = false;
}
// +----------------------------------------------------------------------------
// |"sc_simcontext::simulate"
// |
// | This method runs the simulation for the specified amount of time.
// |
// | Notes:
// | (1) This code always run with an SC_EXIT_ON_STARVATION starvation policy,
// | so the simulation time on return will be the minimum of the
// | simulation on entry plus the duration, and the maximum time of any
// | event present in the simulation. If the simulation policy is
// | SC_RUN_TO_TIME starvation it is implemented by the caller of this
// | method, e.g., sc_start(), by artificially setting the simulation
// | time forward after this method completes.
// |
// | Arguments:
// | duration = amount of time to simulate.
// +----------------------------------------------------------------------------
void
sc_simcontext::simulate( const sc_time& duration )
{
initialize( true );
if (sim_status() != SC_SIM_OK) {
return;
}
sc_time non_overflow_time = sc_max_time() - m_curr_time;
if ( duration > non_overflow_time )
{
SC_REPORT_ERROR(SC_ID_SIMULATION_TIME_OVERFLOW_, "");
return;
}
else if ( duration < SC_ZERO_TIME )
{
SC_REPORT_ERROR(SC_ID_NEGATIVE_SIMULATION_TIME_,"");
}
m_in_simulator_control = true;
m_paused = false;
sc_time until_t = m_curr_time + duration;
sc_time t; // current simulaton time.
// IF DURATION WAS ZERO WE ONLY CRUNCH ONCE:
//
// We duplicate the code so that we don't add the overhead of the
// check to each loop in the do below.
if ( duration == SC_ZERO_TIME )
{
m_in_simulator_control = true;
crunch( true );
if( m_error ) {
m_in_simulator_control = false;
return;
}
#if SC_SIMCONTEXT_TRACING_
if( m_something_to_trace )
trace_cycle( /* delta cycle? */ false );
#endif
if( m_forced_stop ) {
do_sc_stop_action();
return;
}
// return via implicit pause
goto exit_pause;
}
// NON-ZERO DURATION: EXECUTE UP TO THAT TIME, OR UNTIL EVENT STARVATION:
do {
crunch();
if( m_error ) {
m_in_simulator_control = false;
return;
}
#if SC_SIMCONTEXT_TRACING_
if( m_something_to_trace ) {
trace_cycle( false );
}
#endif
// check for call(s) to sc_stop() or sc_pause().
if( m_forced_stop ) {
do_sc_stop_action();
return;
}
if( m_paused ) goto exit_pause; // return explicit pause
t = m_curr_time;
do {
// See note 1 above:
if ( !next_time(t) || (t > until_t ) ) goto exit_time;
if ( t > m_curr_time )
{
SC_DO_PHASE_CALLBACK_(before_timestep);
m_curr_time = t;
m_change_stamp++;
}
// PROCESS TIMED NOTIFICATIONS AT THE CURRENT TIME
do {
sc_event_timed* et = m_timed_events->extract_top();
sc_event* e = et->event();
delete et;
if( e != 0 ) {
e->trigger();
}
} while( m_timed_events->size() &&
m_timed_events->top()->notify_time() == t );
} while( m_runnable->is_empty() );
} while ( t < until_t ); // hold off on the delta for the until_t time.
exit_time: // final simulation time update, if needed
if ( t > m_curr_time && t <= until_t )
{
SC_DO_PHASE_CALLBACK_(before_timestep);
m_curr_time = t;
m_change_stamp++;
}
exit_pause: // call pause callback upon implicit or explicit pause
m_execution_phase = phase_evaluate;
m_in_simulator_control = false;
SC_DO_PHASE_CALLBACK_(simulation_paused);
}
void
sc_simcontext::do_sc_stop_action()
{
SC_REPORT_INFO("/OSCI/SystemC","Simulation stopped by user.");
if (m_start_of_simulation_called) {
end();
m_in_simulator_control = false;
}
m_simulation_status = SC_STOPPED;
SC_DO_PHASE_CALLBACK_(simulation_stopped);
}
void
sc_simcontext::mark_to_collect_process( sc_process_b* zombie )
{
m_collectable->push_back( zombie );
}
//------------------------------------------------------------------------------
//"sc_simcontext::stop"
//
// This method stops the simulator after some amount of further processing.
// How much processing is done depends upon the value of the global variable
// stop_mode:
// SC_STOP_IMMEDIATE - aborts the execution phase of the current delta
// cycle and performs whatever updates are pending.
// SC_STOP_FINISH_DELTA - finishes the current delta cycle - both execution
// and updates.
// If sc_stop is called outside of the purview of the simulator kernel
// (e.g., directly from sc_main), the end of simulation notifications
// are performed. From within the purview of the simulator kernel, these
// will be performed at a later time.
//------------------------------------------------------------------------------
void
sc_simcontext::stop()
{
static bool stop_warning_issued = false;
if (m_forced_stop)
{
if ( !stop_warning_issued )
{
stop_warning_issued = true; // This must be before the WARNING!!!
SC_REPORT_WARNING(SC_ID_SIMULATION_STOP_CALLED_TWICE_, "");
}
return;
}
if ( stop_mode == SC_STOP_IMMEDIATE ) m_runnable->init();
m_forced_stop = true;
if ( !m_in_simulator_control )
{
do_sc_stop_action();
}
}
void
sc_simcontext::reset()
{
clean();
init();
}
void
sc_simcontext::end()
{
m_simulation_status = SC_END_OF_SIMULATION;
m_ready_to_simulate = false;
m_port_registry->simulation_done();
m_export_registry->simulation_done();
m_prim_channel_registry->simulation_done();
m_module_registry->simulation_done();
SC_DO_PHASE_CALLBACK_(simulation_done);
m_end_of_simulation_called = true;
}
void
sc_simcontext::hierarchy_push( sc_module* mod )
{
m_object_manager->hierarchy_push( mod );
}
sc_module*
sc_simcontext::hierarchy_pop()
{
return static_cast<sc_module*>( m_object_manager->hierarchy_pop() );
}
sc_module*
sc_simcontext::hierarchy_curr() const
{
return static_cast<sc_module*>( m_object_manager->hierarchy_curr() );
}
sc_object*
sc_simcontext::first_object()
{
return m_object_manager->first_object();
}
sc_object*
sc_simcontext::next_object()
{
return m_object_manager->next_object();
}
sc_object*
sc_simcontext::find_object( const char* name )
{
static bool warn_find_object=true;
if ( warn_find_object )
{
warn_find_object = false;
SC_REPORT_INFO(SC_ID_IEEE_1666_DEPRECATION_,
"sc_simcontext::find_object() is deprecated,\n" \
" use sc_find_object()" );
}
return m_object_manager->find_object( name );
}
// to generate unique names for objects in an MT-Safe way
const char*
sc_simcontext::gen_unique_name( const char* basename_, bool preserve_first )
{
return m_name_gen->gen_unique_name( basename_, preserve_first );
}
sc_process_handle
sc_simcontext::create_cthread_process(
const char* name_p, bool free_host, SC_ENTRY_FUNC method_p,
sc_process_host* host_p, const sc_spawn_options* opt_p )
{
sc_thread_handle handle =
new sc_cthread_process(name_p, free_host, method_p, host_p, opt_p);
if ( m_ready_to_simulate )
{
handle->prepare_for_simulation();
} else {
m_process_table->push_front( handle );
}
return sc_process_handle(handle);
}
sc_process_handle
sc_simcontext::create_method_process(
const char* name_p, bool free_host, SC_ENTRY_FUNC method_p,
sc_process_host* host_p, const sc_spawn_options* opt_p )
{
sc_method_handle handle =
new sc_method_process(name_p, free_host, method_p, host_p, opt_p);
if ( m_ready_to_simulate ) { // dynamic process
if ( !handle->dont_initialize() )
{
#ifdef SC_HAS_PHASE_CALLBACKS_
if( SC_UNLIKELY_( m_simulation_status
& (SC_END_OF_UPDATE|SC_BEFORE_TIMESTEP) ) )
{
std::stringstream msg;
msg << m_simulation_status
<< ":\n\t immediate method spawning of "
"`" << handle->name() << "' ignored";
SC_REPORT_WARNING( SC_ID_PHASE_CALLBACK_FORBIDDEN_
, msg.str().c_str() );
}
else
#endif // SC_HAS_PHASE_CALLBACKS_
{
push_runnable_method( handle );
}
}
else if ( handle->m_static_events.size() == 0 )
{
SC_REPORT_WARNING( SC_ID_DISABLE_WILL_ORPHAN_PROCESS_,
handle->name() );
}
} else {
m_process_table->push_front( handle );
}
return sc_process_handle(handle);
}
sc_process_handle
sc_simcontext::create_thread_process(
const char* name_p, bool free_host, SC_ENTRY_FUNC method_p,
sc_process_host* host_p, const sc_spawn_options* opt_p )
{
sc_thread_handle handle =
new sc_thread_process(name_p, free_host, method_p, host_p, opt_p);
if ( m_ready_to_simulate ) { // dynamic process
handle->prepare_for_simulation();
if ( !handle->dont_initialize() )
{
#ifdef SC_HAS_PHASE_CALLBACKS_
if( SC_UNLIKELY_( m_simulation_status
& (SC_END_OF_UPDATE|SC_BEFORE_TIMESTEP) ) )
{
std::stringstream msg;
msg << m_simulation_status
<< ":\n\t immediate thread spawning of "
"`" << handle->name() << "' ignored";
SC_REPORT_WARNING( SC_ID_PHASE_CALLBACK_FORBIDDEN_
, msg.str().c_str() );
}
else
#endif // SC_HAS_PHASE_CALLBACKS_
{
push_runnable_thread( handle );
}
}
else if ( handle->m_static_events.size() == 0 )
{
SC_REPORT_WARNING( SC_ID_DISABLE_WILL_ORPHAN_PROCESS_,
handle->name() );
}
} else {
m_process_table->push_front( handle );
}
return sc_process_handle(handle);
}
void
sc_simcontext::add_trace_file( sc_trace_file* tf )
{
m_trace_files.push_back( tf );
m_something_to_trace = true;
}
void
sc_simcontext::remove_trace_file( sc_trace_file* tf )
{
m_trace_files.erase(
std::remove( m_trace_files.begin(), m_trace_files.end(), tf )
);
m_something_to_trace = ( m_trace_files.size() > 0 );
}
sc_cor*
sc_simcontext::next_cor()
{
if( m_error ) {
return m_cor;
}
sc_thread_handle thread_h = pop_runnable_thread();
while( thread_h != 0 ) {
if ( thread_h->m_cor_p != NULL ) break;
thread_h = pop_runnable_thread();
}
if( thread_h != 0 ) {
return thread_h->m_cor_p;
} else {
return m_cor;
}
}
const ::std::vector<sc_object*>&
sc_simcontext::get_child_objects() const
{
static bool warn_get_child_objects=true;
if ( warn_get_child_objects )
{
warn_get_child_objects = false;
SC_REPORT_INFO(SC_ID_IEEE_1666_DEPRECATION_,
"sc_simcontext::get_child_objects() is deprecated,\n" \
" use sc_get_top_level_objects()" );
}
return m_child_objects;
}
void
sc_simcontext::add_child_event( sc_event* event_ )
{
// no check if object_ is already in the set
m_child_events.push_back( event_ );
}
void
sc_simcontext::add_child_object( sc_object* object_ )
{
// no check if object_ is already in the set
m_child_objects.push_back( object_ );
}
void
sc_simcontext::remove_child_event( sc_event* event_ )
{
int size = m_child_events.size();
for( int i = 0; i < size; ++ i ) {
if( event_ == m_child_events[i] ) {
m_child_events[i] = m_child_events[size - 1];
m_child_events.resize(size-1);
return;
}
}
// no check if event_ is really in the set
}
void
sc_simcontext::remove_child_object( sc_object* object_ )
{
int size = m_child_objects.size();
for( int i = 0; i < size; ++ i ) {
if( object_ == m_child_objects[i] ) {
m_child_objects[i] = m_child_objects[size - 1];
m_child_objects.resize(size-1);
return;
}
}
// no check if object_ is really in the set
}
sc_dt::uint64
sc_simcontext::delta_count() const
{
static bool warn_delta_count=true;
if ( warn_delta_count )
{
warn_delta_count = false;
SC_REPORT_INFO(SC_ID_IEEE_1666_DEPRECATION_,
"sc_simcontext::delta_count() is deprecated, use sc_delta_count()" );
}
return m_delta_count;
}
bool
sc_simcontext::is_running() const
{
static bool warn_is_running=true;
if ( warn_is_running )
{
warn_is_running = false;
SC_REPORT_INFO(SC_ID_IEEE_1666_DEPRECATION_,
"sc_simcontext::is_running() is deprecated, use sc_is_running()" );
}
return m_ready_to_simulate;
}
// +----------------------------------------------------------------------------
// |"sc_simcontext::next_time"
// |
// | This method returns the time of the next event. If there are no events
// | it returns false.
// |
// | Arguments:
// | result = where to place time of the next event, if no event is
// | found this value will not be changed.
// | Result is true if an event is found, false if not.
// +----------------------------------------------------------------------------
bool
sc_simcontext::next_time( sc_time& result ) const
{
while( m_timed_events->size() ) {
sc_event_timed* et = m_timed_events->top();
if( et->event() != 0 ) {
result = et->notify_time();
return true;
}
delete m_timed_events->extract_top();
}
return false;
}
void
sc_simcontext::remove_delta_event( sc_event* e )
{
int i = e->m_delta_event_index;
int j = m_delta_events.size() - 1;
assert( i >= 0 && i <= j );
if( i != j ) {
sc_event** l_delta_events = &m_delta_events[0];
l_delta_events[i] = l_delta_events[j];
l_delta_events[i]->m_delta_event_index = i;
}
m_delta_events.resize(m_delta_events.size()-1);
e->m_delta_event_index = -1;
}
// +----------------------------------------------------------------------------
// |"sc_simcontext::preempt_with"
// |
// | This method executes the supplied method immediately, suspending the
// | caller. After executing the supplied method the caller's execution will
// | be restored. It is used to allow a method to immediately throw an
// | exception, e.g., when the method's kill_process() method was called.
// | There are three cases to consider:
// | (1) The caller is a method, e.g., murder by method.
// | (2) The caller is a thread instance, e.g., murder by thread.
// | (3) The caller is this method instance, e.g., suicide.
// |
// | Arguments:
// | method_h -> method to be executed.
// +----------------------------------------------------------------------------
void
sc_simcontext::preempt_with( sc_method_handle method_h )
{
sc_curr_proc_info caller_info; // process info for caller.
sc_method_handle active_method_h; // active method or null.
sc_thread_handle active_thread_h; // active thread or null.
// Determine the active process and take the thread to be run off the
// run queue, if its there, since we will be explicitly causing its
// execution.
active_method_h = DCAST<sc_method_handle>(sc_get_current_process_b());
active_thread_h = DCAST<sc_thread_handle>(sc_get_current_process_b());
if ( method_h->next_runnable() != NULL )
remove_runnable_method( method_h );
// CALLER IS THE METHOD TO BE RUN:
//
// Should never get here, ignore it unless we are debugging.
if ( method_h == active_method_h )
{
DEBUG_MSG(DEBUG_NAME,method_h,"self preemption of active method");
}
// THE CALLER IS A METHOD:
//
// (a) Set the current process information to our method.
// (b) Invoke our method directly by-passing the run queue.
// (c) Restore the process info to the caller.
// (d) Check to see if the calling method should throw an exception
// because of activity that occurred during the preemption.
else if ( active_method_h != NULL )
{
caller_info = m_curr_proc_info;
DEBUG_MSG( DEBUG_NAME, method_h,
"preempting active method with method" );
sc_get_curr_simcontext()->set_curr_proc( (sc_process_b*)method_h );
method_h->run_process();
sc_get_curr_simcontext()->set_curr_proc((sc_process_b*)active_method_h);
active_method_h->check_for_throws();
}
// CALLER IS A THREAD:
//
// (a) Use an invocation thread to execute the method.
else if ( active_thread_h != NULL )
{
DEBUG_MSG( DEBUG_NAME, method_h,
"preempting active thread with method" );
m_method_invoker_p->invoke_method(method_h);
}
// CALLER IS THE SIMULATOR:
//
// That is not allowed.
else
{
caller_info = m_curr_proc_info;
DEBUG_MSG( DEBUG_NAME, method_h,
"preempting no active process with method" );
sc_get_curr_simcontext()->set_curr_proc( (sc_process_b*)method_h );
method_h->run_process();
m_curr_proc_info = caller_info;
}
}
//------------------------------------------------------------------------------
//"sc_simcontext::requeue_current_process"
//
// This method requeues the current process at the beginning of the run queue
// if it is a thread. This is called by sc_process_handle::throw_it() to assure
// that a thread that is issuing a throw will execute immediately after the
// processes it notifies via the throw.
//------------------------------------------------------------------------------
void sc_simcontext::requeue_current_process()
{
sc_thread_handle thread_p;
thread_p = DCAST<sc_thread_handle>(get_curr_proc_info()->process_handle);
if ( thread_p )
{
execute_thread_next( thread_p );
}
}
//------------------------------------------------------------------------------
//"sc_simcontext::suspend_current_process"
//
// This method suspends the current process if it is a thread. This is called
// by sc_process_handle::throw_it() to allow the processes that have received
// a throw to execute.
//------------------------------------------------------------------------------
void sc_simcontext::suspend_current_process()
{
sc_thread_handle thread_p;
thread_p = DCAST<sc_thread_handle>(get_curr_proc_info()->process_handle);
if ( thread_p )
{
thread_p->suspend_me();
}
}
void
sc_simcontext::trace_cycle( bool delta_cycle )
{
int size;
if( ( size = m_trace_files.size() ) != 0 ) {
sc_trace_file** l_trace_files = &m_trace_files[0];
int i = size - 1;
do {
l_trace_files[i]->cycle( delta_cycle );
} while( -- i >= 0 );
}
}
// ----------------------------------------------------------------------------
#if 1
#ifdef PURIFY
static sc_simcontext sc_default_global_context;
sc_simcontext* sc_curr_simcontext = &sc_default_global_context;
#else
sc_simcontext* sc_curr_simcontext = 0;
sc_simcontext* sc_default_global_context = 0;
#endif
#else
// Not MT-safe!
static sc_simcontext* sc_curr_simcontext = 0;
sc_simcontext*
sc_get_curr_simcontext()
{
if( sc_curr_simcontext == 0 ) {
#ifdef PURIFY
static sc_simcontext sc_default_global_context;
sc_curr_simcontext = &sc_default_global_context;
#else
static sc_simcontext* sc_default_global_context = new sc_simcontext;
sc_curr_simcontext = sc_default_global_context;
#endif
}
return sc_curr_simcontext;
}
#endif // 0
// Generates unique names within each module.
const char*
sc_gen_unique_name( const char* basename_, bool preserve_first )
{
sc_simcontext* simc = sc_get_curr_simcontext();
sc_module* curr_module = simc->hierarchy_curr();
if( curr_module != 0 ) {
return curr_module->gen_unique_name( basename_, preserve_first );
} else {
sc_process_b* curr_proc_p = sc_get_current_process_b();
if ( curr_proc_p )
{
return curr_proc_p->gen_unique_name( basename_, preserve_first );
}
else
{
return simc->gen_unique_name( basename_, preserve_first );
}
}
}
// Get a handle for the current process
//
// Note that this method should not be called if the current process is
// in the act of being deleted, it will mess up the reference count management
// of sc_process_b instance the handle represents. Instead, use the a
// pointer to the raw sc_process_b instance, which may be acquired via
// sc_get_current_process_b().
sc_process_handle
sc_get_current_process_handle()
{
return ( sc_is_running() ) ?
sc_process_handle(sc_get_current_process_b()) :
sc_get_last_created_process_handle();
}
// THE FOLLOWING FUNCTION IS DEPRECATED IN 2.1
sc_process_b*
sc_get_curr_process_handle()
{
static bool warn=true;
if ( warn )
{
warn = false;
SC_REPORT_INFO(SC_ID_IEEE_1666_DEPRECATION_,
"sc_get_curr_process_handle deprecated use sc_get_current_process_handle"
);
}
return sc_get_curr_simcontext()->get_curr_proc_info()->process_handle;
}
// Return indication if there are more processes to execute in this delta phase
bool
sc_simcontext::pending_activity_at_current_time() const
{
return ( m_delta_events.size() != 0) ||
( m_runnable->is_initialized() && !m_runnable->is_empty() ) ||
m_prim_channel_registry->pending_updates();
}
// Return time of next activity.
sc_time sc_time_to_pending_activity( const sc_simcontext* simc_p )
{
// If there is an activity pending at the current time
// return a delta of zero.
sc_time result=SC_ZERO_TIME; // time of pending activity.
if ( simc_p->pending_activity_at_current_time() )
{
return result;
}
// Any activity will take place in the future pick up the next event's time.
else
{
result = simc_p->max_time();
simc_p->next_time(result);
result -= sc_time_stamp();
}
return result;
}
// Set the random seed for controlled randomization -- not yet implemented
void
sc_set_random_seed( unsigned int )
{
SC_REPORT_WARNING( SC_ID_NOT_IMPLEMENTED_,
"void sc_set_random_seed( unsigned int )" );
}
// +----------------------------------------------------------------------------
// |"sc_start"
// |
// | This function starts, or restarts, the execution of the simulator.
// |
// | Arguments:
// | duration = the amount of time the simulator should execute.
// | p = event starvation policy.
// +----------------------------------------------------------------------------
void
sc_start( const sc_time& duration, sc_starvation_policy p )
{
sc_simcontext* context_p; // current simulation context.
sc_time entry_time; // simulation time upon entry.
sc_time exit_time; // simulation time to set upon exit.
sc_dt::uint64 starting_delta; // delta count upon entry.
int status; // current simulation status.
// Set up based on the arguments passed to us:
context_p = sc_get_curr_simcontext();
starting_delta = sc_delta_count();
entry_time = context_p->m_curr_time;
if ( p == SC_RUN_TO_TIME )
exit_time = context_p->m_curr_time + duration;
// called with duration = SC_ZERO_TIME for the first time
static bool init_delta_or_pending_updates =
( starting_delta == 0 && exit_time == SC_ZERO_TIME );
// If the simulation status is bad issue the appropriate message:
status = context_p->sim_status();
if( status != SC_SIM_OK )
{
if ( status == SC_SIM_USER_STOP )
SC_REPORT_ERROR(SC_ID_SIMULATION_START_AFTER_STOP_, "");
if ( status == SC_SIM_ERROR )
SC_REPORT_ERROR(SC_ID_SIMULATION_START_AFTER_ERROR_, "");
return;
}
if ( context_p->m_prim_channel_registry->pending_updates() )
init_delta_or_pending_updates = true;
// If the simulation status is good perform the simulation:
context_p->simulate( duration );
// Re-check the status:
status = context_p->sim_status();
// Update the current time to the exit time if that is the starvation
// policy:
if ( p == SC_RUN_TO_TIME && !context_p->m_paused && status == SC_SIM_OK )
{
context_p->m_curr_time = exit_time;
}
// If there was no activity and the simulation clock did not move warn
// the user, except if we're in a first sc_start(SC_ZERO_TIME) for
// initialisation (only) or there have been pending updates:
if ( !init_delta_or_pending_updates &&
starting_delta == sc_delta_count() &&
context_p->m_curr_time == entry_time &&
status == SC_SIM_OK )
{
SC_REPORT_WARNING(SC_ID_NO_SC_START_ACTIVITY_, "");
}
// reset init/update flag for subsequent calls
init_delta_or_pending_updates = false;
}
void
sc_start()
{
sc_start( sc_max_time() - sc_time_stamp(),
SC_EXIT_ON_STARVATION );
}
// for backward compatibility with 1.0
#if 0
void
sc_start( double duration ) // in default time units
{
static bool warn_sc_start=true;
if ( warn_sc_start )
{
warn_sc_start = false;
SC_REPORT_INFO(SC_ID_IEEE_1666_DEPRECATION_,
"sc_start(double) deprecated, use sc_start(sc_time) or sc_start()");
}
if( duration == -1 ) // simulate forever
{
sc_start(
sc_time(~sc_dt::UINT64_ZERO, false) - sc_time_stamp() );
}
else
{
sc_start( sc_time( duration, true ) );
}
}
#endif //
void
sc_stop()
{
sc_get_curr_simcontext()->stop();
}
// The following function is deprecated in favor of sc_start(SC_ZERO_TIME):
void
sc_initialize()
{
static bool warning_initialize = true;
if ( warning_initialize )
{
warning_initialize = false;
SC_REPORT_INFO(SC_ID_IEEE_1666_DEPRECATION_,
"sc_initialize() is deprecated: use sc_start(SC_ZERO_TIME)" );
}
sc_get_curr_simcontext()->initialize();
}
// The following function has been deprecated in favor of sc_start(duration):
void
sc_cycle( const sc_time& duration )
{
static bool warning_cycle = true;
if ( warning_cycle )
{
warning_cycle = false;
SC_REPORT_INFO(SC_ID_IEEE_1666_DEPRECATION_,
"sc_cycle is deprecated: use sc_start(sc_time)" );
}
sc_get_curr_simcontext()->cycle( duration );
}
sc_event* sc_find_event( const char* name )
{
return sc_get_curr_simcontext()->get_object_manager()->find_event( name );
}
sc_object* sc_find_object( const char* name )
{
return sc_get_curr_simcontext()->get_object_manager()->find_object( name );
}
const sc_time&
sc_max_time()
{
return sc_get_curr_simcontext()->max_time();
}
const sc_time&
sc_time_stamp()
{
return sc_get_curr_simcontext()->time_stamp();
}
double
sc_simulation_time()
{
static bool warn_simulation_time=true;
if ( warn_simulation_time )
{
warn_simulation_time=false;
SC_REPORT_INFO(SC_ID_IEEE_1666_DEPRECATION_,
"sc_simulation_time() is deprecated use sc_time_stamp()" );
}
return sc_get_curr_simcontext()->time_stamp().to_default_time_units();
}
void
sc_defunct_process_function( sc_module* )
{
// This function is pointed to by defunct sc_thread_process'es and
// sc_cthread_process'es. In a correctly constructed world, this
// function should never be called; hence the assert.
assert( false );
}
//------------------------------------------------------------------------------
//"sc_set_stop_mode"
//
// This function sets the mode of operation when sc_stop() is called.
// mode = SC_STOP_IMMEDIATE or SC_STOP_FINISH_DELTA.
//------------------------------------------------------------------------------
void sc_set_stop_mode(sc_stop_mode mode)
{
if ( sc_is_running() )
{
SC_REPORT_ERROR(SC_ID_STOP_MODE_AFTER_START_,"");
}
else
{
switch( mode )
{
case SC_STOP_IMMEDIATE:
case SC_STOP_FINISH_DELTA:
stop_mode = mode;
break;
default:
break;
}
}
}
sc_stop_mode
sc_get_stop_mode()
{
return stop_mode;
}
bool sc_is_unwinding()
{
return sc_get_current_process_handle().is_unwinding();
}
// The IEEE 1666 Standard for 2011 designates that the treatment of
// certain process control interactions as being "implementation dependent".
// These interactions are:
// (1) What happens when a resume() call is performed on a disabled,
// suspended process.
// (2) What happens when sync_reset_on() or sync_reset_off() is called
// on a suspended process.
// (3) What happens when the value specified in a reset_signal_is()
// call changes value while a process is suspended.
//
// By default this Proof of Concept implementation reports an error
// for these interactions. However, the implementation also provides
// a non-error treatment. The non-error treatment for the interactions is:
// (1) A resume() call performed on a disabled, suspended process will
// mark the process as no longer suspended, and if it is capable
// of execution (not waiting on any events) it will be placed on
// the queue of runnable processes. See the state diagram below.
// (2) A call to sync_reset_on() or sync_reset_off() will set or clear
// the synchronous reset flag. Whether the process is in reset or
// not will be determined when the process actually executes by
// looking at the flag's value at that time.
// (3) If a suspended process has a reset_signal_is() specification
// the value of the reset variable at the time of its next execution
// will determine whether it is in reset or not.
//
// TO GET THE NON-ERROR BEHAVIOR SET THE VARIABLE BELOW TO TRUE.
//
// This can be done in this source before you build the library, or you
// can use an assignment as the first statement in your sc_main() function:
// sc_core::sc_allow_process_control_corners = true;
bool sc_allow_process_control_corners = false;
// The state transition diagram for the interaction of disable and suspend
// when sc_allow_process_control_corners is true is shown below:
//
// ......................................................................
// . ENABLED . DISABLED .
// . . .
// . +----------+ disable +----------+ .
// . +------------>| |-------.-------->| | .
// . | | runnable | . | runnable | .
// . | +-------| |<------.---------| |------+ .
// . | | +----------+ enable +----------+ | .
// . | | | ^ . | ^ | .
// . | | suspend | | resume . suspend | | resume | .
// . | | V | . V | | .
// . | | +----------+ disable +----------+ | .
// . | | | suspend |-------.-------->| suspend | | .
// . t | r | | | . | | | r .
// . r | u | | ready |<------.---------| ready | | u .
// . i | n | +----------+ enable +----------+ | n .
// . g | / | ^ . | / .
// . g | w | trigger| . | w .
// . e | a | | . | a .
// . r | i | +----------+ disable +----------+ | i .
// . | t | | suspend |-------.-------->| suspend | | t .
// . | | | | . | | | .
// . | | | waiting |<------.---------| waiting | | .
// . | | +----------+ enable +----------+ | .
// . | | | ^ . | ^ | .
// . | | suspend | | resume . suspend | | resume | .
// . | | V | . V | | .
// . | | +----------+ disable +----------+ | .
// . | +------>| |-------.-------->| | | .
// . | | waiting | . | waiting | | .
// . +-------------| |<------.---------| |<-----+ .
// . +----------+ enable +----------+ .
// . . .
// ......................................................................
// ----------------------------------------------------------------------------
static std::ostream&
print_status_expression( std::ostream& os, sc_status s );
// utility helper to print a simulation status
std::ostream& operator << ( std::ostream& os, sc_status s )
{
// print primitive values
switch(s)
{
# define PRINT_STATUS( Status ) \
case Status: { os << #Status; } break
PRINT_STATUS( SC_UNITIALIZED );
PRINT_STATUS( SC_ELABORATION );
PRINT_STATUS( SC_BEFORE_END_OF_ELABORATION );
PRINT_STATUS( SC_END_OF_ELABORATION );
PRINT_STATUS( SC_START_OF_SIMULATION );
PRINT_STATUS( SC_RUNNING );
PRINT_STATUS( SC_PAUSED );
PRINT_STATUS( SC_STOPPED );
PRINT_STATUS( SC_END_OF_SIMULATION );
PRINT_STATUS( SC_END_OF_INITIALIZATION );
// PRINT_STATUS( SC_END_OF_EVALUATION );
PRINT_STATUS( SC_END_OF_UPDATE );
PRINT_STATUS( SC_BEFORE_TIMESTEP );
PRINT_STATUS( SC_STATUS_ANY );
# undef PRINT_STATUS
default:
if( s & SC_STATUS_ANY ) // combination of status bits
print_status_expression( os, s );
else // invalid number, print hex value
os << "0x" << std::hex << +s;
}
return os;
}
// pretty-print a combination of sc_status bits (i.e. a callback mask)
static std::ostream&
print_status_expression( std::ostream& os, sc_status s )
{
std::vector<sc_status> bits;
unsigned is_set = SC_ELABORATION;
// collect bits
while( is_set <= SC_STATUS_LAST )
{
if( s & is_set )
bits.push_back( (sc_status)is_set );
is_set <<= 1;
}
if( s & ~SC_STATUS_ANY ) // remaining bits
bits.push_back( (sc_status)( s & ~SC_STATUS_ANY ) );
// print expression
std::vector<sc_status>::size_type i=0, n=bits.size();
if ( n>1 )
os << "(";
for( ; i<n-1; ++i )
os << bits[i] << "|";
os << bits[i];
if ( n>1 )
os << ")";
return os;
}
} // namespace sc_core
/*****************************************************************************
MODIFICATION LOG - modifiers, enter your name, affiliation, date and
changes you are making here.
Name, Affiliation, Date: Ali Dasdan, Synopsys, Inc.
Description of Modification: - Added sc_stop() detection into initial_crunch
and crunch. This makes it possible to exit out
of a combinational loop using sc_stop().
Name, Affiliation, Date: Andy Goodrich, Forte Design Systems 20 May 2003
Description of Modification: - sc_stop mode
- phase callbacks
Name, Affiliation, Date: Bishnupriya Bhattacharya, Cadence Design Systems,
25 August 2003
Description of Modification: - support for dynamic process
- support for sc export registry
- new member methods elaborate(),
prepare_to_simulate(), and initial_crunch()
that are invoked by initialize() in that order
- implement sc_get_last_created_process_handle() for use
before simulation starts
- remove "set_curr_proc(handle)" from
register_method_process and
register_thread_process - led to bugs
Name, Affiliation, Date: Andy Goodrich, Forte Design Systems 04 Sep 2003
Description of Modification: - changed process existence structures to
linked lists to eliminate exponential
execution problem with using sc_pvector.
*****************************************************************************/
// $Log: sc_simcontext.cpp,v $
// Revision 1.37 2011/08/29 18:04:32 acg
// Philipp A. Hartmann: miscellaneous clean ups.
//
// Revision 1.36 2011/08/26 20:46:10 acg
// Andy Goodrich: moved the modification log to the end of the file to
// eliminate source line number skew when check-ins are done.
//
// Revision 1.35 2011/08/24 22:05:51 acg
// Torsten Maehne: initialization changes to remove warnings.
//
// Revision 1.34 2011/08/04 17:15:28 acg
// Andy Goodrich: added documentation to crunch() routine.
//
// Revision 1.32 2011/07/24 11:16:36 acg
// Philipp A. Hartmann: fix reference counting on deferred deletions of
// processes.
//
// Revision 1.31 2011/07/01 18:49:07 acg
// Andy Goodrich: moved pln() from sc_simcontext.cpp to sc_ver.cpp.
//
// Revision 1.30 2011/05/09 04:07:49 acg
// Philipp A. Hartmann:
// (1) Restore hierarchy in all phase callbacks.
// (2) Ensure calls to before_end_of_elaboration.
//
// Revision 1.29 2011/04/08 22:39:09 acg
// Andy Goodrich: moved method invocation code to sc_method.h so that the
// details are hidden from sc_simcontext.
//
// Revision 1.28 2011/04/05 20:50:57 acg
// Andy Goodrich:
// (1) changes to make sure that event(), posedge() and negedge() only
// return true if the clock has not moved.
// (2) fixes for method self-resumes.
// (3) added SC_PRERELEASE_VERSION
// (4) removed kernel events from the object hierarchy, added
// sc_hierarchy_name_exists().
//
// Revision 1.27 2011/04/05 06:14:15 acg
// Andy Goodrich: fix typo.
//
// Revision 1.26 2011/04/05 06:03:32 acg
// Philipp A. Hartmann: added code to set ready to run bit for a suspended
// process that does not have dont_initialize specified at simulation
// start up.
//
// Revision 1.25 2011/04/01 21:31:55 acg
// Andy Goodrich: make sure processes suspended before the start of execution
// don't get scheduled for initial execution.
//
// Revision 1.24 2011/03/28 13:02:52 acg
// Andy Goodrich: Changes for disable() interactions.
//
// Revision 1.23 2011/03/12 21:07:51 acg
// Andy Goodrich: changes to kernel generated event support.
//
// Revision 1.22 2011/03/07 17:38:43 acg
// Andy Goodrich: tightening up of checks for undefined interaction between
// synchronous reset and suspend.
//
// Revision 1.21 2011/03/06 19:57:11 acg
// Andy Goodrich: refinements for the illegal suspend - synchronous reset
// interaction.
//
// Revision 1.20 2011/03/06 15:58:50 acg
// Andy Goodrich: added escape to turn off process control corner case
// checks.
//
// Revision 1.19 2011/03/05 04:45:16 acg
// Andy Goodrich: moved active process calculation to the sc_simcontext class.
//
// Revision 1.18 2011/03/05 01:39:21 acg
// Andy Goodrich: changes for named events.
//
// Revision 1.17 2011/02/18 20:27:14 acg
// Andy Goodrich: Updated Copyrights.
//
// Revision 1.16 2011/02/17 19:53:28 acg
// Andy Goodrich: eliminated use of ready_to_run() as part of process control
// simplification.
//
// Revision 1.15 2011/02/13 21:47:38 acg
// Andy Goodrich: update copyright notice.
//
// Revision 1.14 2011/02/11 13:25:24 acg
// Andy Goodrich: Philipp A. Hartmann's changes:
// (1) Removal of SC_CTHREAD method overloads.
// (2) New exception processing code.
//
// Revision 1.13 2011/02/08 08:42:50 acg
// Andy Goodrich: fix ordering of check for stopped versus paused.
//
// Revision 1.12 2011/02/07 19:17:20 acg
// Andy Goodrich: changes for IEEE 1666 compatibility.
//
// Revision 1.11 2011/02/02 07:18:11 acg
// Andy Goodrich: removed toggle() calls for the new crunch() toggle usage.
//
// Revision 1.10 2011/02/01 23:01:53 acg
// Andy Goodrich: removed dead code.
//
// Revision 1.9 2011/02/01 21:11:59 acg
// Andy Goodrich:
// (1) Use of new toggle_methods() and toggle_threads() run queue methods
// to make sure the thread run queue does not execute when allow preempt_me()
// is called from an SC_METHOD.
// (2) Use of execute_thread_next() to allow thread execution in the current
// delta cycle() rather than push_runnable_thread_front which executed
// in the following cycle.
//
// Revision 1.8 2011/01/25 20:50:37 acg
// Andy Goodrich: changes for IEEE 1666 2011.
//
// Revision 1.7 2011/01/19 23:21:50 acg
// Andy Goodrich: changes for IEEE 1666 2011
//
// Revision 1.6 2011/01/18 20:10:45 acg
// Andy Goodrich: changes for IEEE1666_2011 semantics.
//
// Revision 1.5 2010/11/20 17:10:57 acg
// Andy Goodrich: reset processing changes for new IEEE 1666 standard.
//
// Revision 1.4 2010/07/22 20:02:33 acg
// Andy Goodrich: bug fixes.
//
// Revision 1.3 2008/05/22 17:06:26 acg
// Andy Goodrich: updated copyright notice to include 2008.
//
// Revision 1.2 2007/09/20 20:32:35 acg
// Andy Goodrich: changes to the semantics of throw_it() to match the
// specification. A call to throw_it() will immediately suspend the calling
// thread until all the throwees have executed. At that point the calling
// thread will be restarted before the execution of any other threads.
//
// Revision 1.1.1.1 2006/12/15 20:20:05 acg
// SystemC 2.3
//
// Revision 1.21 2006/08/29 23:37:13 acg
// Andy Goodrich: Added check for negative time.
//
// Revision 1.20 2006/05/26 20:33:16 acg
// Andy Goodrich: changes required by additional platform compilers (i.e.,
// Microsoft VC++, Sun Forte, HP aCC).
//
// Revision 1.19 2006/05/08 17:59:52 acg
// Andy Goodrich: added a check before m_curr_time is set to make sure it
// is not set to a time before its current value. This will treat
// sc_event.notify( ) calls with negative times as calls with a zero time.
//
// Revision 1.18 2006/04/20 17:08:17 acg
// Andy Goodrich: 3.0 style process changes.
//
// Revision 1.17 2006/04/11 23:13:21 acg
// Andy Goodrich: Changes for reduced reset support that only includes
// sc_cthread, but has preliminary hooks for expanding to method and thread
// processes also.
//
// Revision 1.16 2006/03/21 00:00:34 acg
// Andy Goodrich: changed name of sc_get_current_process_base() to be
// sc_get_current_process_b() since its returning an sc_process_b instance.
//
// Revision 1.15 2006/03/13 20:26:50 acg
// Andy Goodrich: Addition of forward class declarations, e.g.,
// sc_reset, to keep gcc 4.x happy.
//
// Revision 1.14 2006/02/02 23:42:41 acg
// Andy Goodrich: implemented a much better fix to the sc_event_finder
// proliferation problem. This new version allocates only a single event
// finder for each port for each type of event, e.g., pos(), neg(), and
// value_change(). The event finder persists as long as the port does,
// which is what the LRM dictates. Because only a single instance is
// allocated for each event type per port there is not a potential
// explosion of storage as was true in the 2.0.1/2.1 versions.
//
// Revision 1.13 2006/02/02 21:29:10 acg
// Andy Goodrich: removed the call to sc_event_finder::free_instances() that
// was in end_of_elaboration(), leaving only the call in clean(). This is
// because the LRM states that sc_event_finder instances are persistent as
// long as the sc_module hierarchy is valid.
//
// Revision 1.12 2006/02/02 21:09:50 acg
// Andy Goodrich: added call to sc_event_finder::free_instances in the clean()
// method.
//
// Revision 1.11 2006/02/02 20:43:14 acg
// Andy Goodrich: Added an existence linked list to sc_event_finder so that
// the dynamically allocated instances can be freed after port binding
// completes. This replaces the individual deletions in ~sc_bind_ef, as these
// caused an exception if an sc_event_finder instance was used more than
// once, due to a double freeing of the instance.
//
// Revision 1.10 2006/01/31 21:43:26 acg
// Andy Goodrich: added comments in constructor to highlight environmental
// overrides section.
//
// Revision 1.9 2006/01/26 21:04:54 acg
// Andy Goodrich: deprecation message changes and additional messages.
//
// Revision 1.8 2006/01/25 00:31:19 acg
// Andy Goodrich: Changed over to use a standard message id of
// SC_ID_IEEE_1666_DEPRECATION for all deprecation messages.
//
// Revision 1.7 2006/01/24 20:49:05 acg
// Andy Goodrich: changes to remove the use of deprecated features within the
// simulator, and to issue warning messages when deprecated features are used.
//
// Revision 1.6 2006/01/19 00:29:52 acg
// Andy Goodrich: Yet another implementation for signal write checking. This
// one uses an environment variable SC_SIGNAL_WRITE_CHECK, that when set to
// DISABLE will disable write checking on signals.
//
// Revision 1.5 2006/01/13 18:44:30 acg
// Added $Log to record CVS changes into the source.
//
// Revision 1.4 2006/01/03 23:18:44 acg
// Changed copyright to include 2006.
//
// Revision 1.3 2005/12/20 22:11:10 acg
// Fixed $Log lines.
//
// Revision 1.2 2005/12/20 22:02:30 acg
// Changed where delta cycles are incremented to match IEEE 1666. Added the
// event_occurred() method to hide how delta cycle comparisions are done within
// sc_simcontext. Changed the boolean update_phase to an enum that shows all
// the phases.
// Taf!
| [
"jungma@eit.uni-kl.de"
] | jungma@eit.uni-kl.de |
f0f82bc9596471142e50d9e1526156fe4baf147c | 6b40e9dccf2edc767c44df3acd9b626fcd586b4d | /NT/inetsrv/iis/setup/osrc/mdkey.h | f631156e1cf9a6c766f16f5fb931737b1306c3aa | [] | no_license | jjzhang166/WinNT5_src_20201004 | 712894fcf94fb82c49e5cd09d719da00740e0436 | b2db264153b80fbb91ef5fc9f57b387e223dbfc2 | refs/heads/Win2K3 | 2023-08-12T01:31:59.670176 | 2021-10-14T15:14:37 | 2021-10-14T15:14:37 | 586,134,273 | 1 | 0 | null | 2023-01-07T03:47:45 | 2023-01-07T03:47:44 | null | UTF-8 | C++ | false | false | 5,978 | h | #ifndef _MDKEY_H_
#define _MDKEY_H_
class CMDValue
{
protected:
DWORD m_dwId;
DWORD m_dwAttributes;
DWORD m_dwUserType;
DWORD m_dwDataType;
DWORD m_cbDataLen;
BUFFER m_bufData;
public:
CMDValue();
~CMDValue();
DWORD SetValue(DWORD dwId,
DWORD dwAttributes,
DWORD dwUserType,
DWORD dwDataType,
DWORD dwDataLen,
LPVOID pbData);
DWORD SetValue(DWORD dwId,
DWORD dwAttributes,
DWORD dwUserType,
DWORD dwDataType,
DWORD dwDataLen,
LPTSTR szDataString);
DWORD SetValue(DWORD dwId,
DWORD dwAttributes,
DWORD dwUserType,
DWORD dwValue);
DWORD GetId() { return m_dwId; }
DWORD GetAttributes() { return m_dwAttributes; }
DWORD GetUserType() { return m_dwUserType; }
DWORD GetDataType() { return m_dwDataType; }
DWORD GetDataLen() { return m_cbDataLen; }
PVOID GetData() { return m_bufData.QueryPtr(); }
void SetAttributes(DWORD dwAttrib) { m_dwAttributes = dwAttrib; }
BOOL IsEqual(DWORD dwDataType, DWORD cbDataLen, LPVOID pbData);
BOOL IsEqual(DWORD dwDataType, DWORD cbDataLen, DWORD dwData);
};
class CMDKey : public CObject
{
protected:
IMSAdminBase * m_pcCom;
METADATA_HANDLE m_hKey;
LPTSTR pszFailedAPI;
public:
CMDKey();
~CMDKey();
TCHAR m_szCurrentNodeName[_MAX_PATH];
// allow CMDKey to be used where type METADATA_HANDLE is required
operator METADATA_HANDLE () {return m_hKey;}
METADATA_HANDLE GetMDKeyHandle() {return m_hKey;}
IMSAdminBase *GetMDKeyICOM() {return m_pcCom;}
// open an existing MD key
HRESULT OpenNode(LPCTSTR pchSubKeyPath, BOOL bSupressErrorMessage = FALSE);
// to open an existing MD key, or create one if doesn't exist
HRESULT CreateNode(METADATA_HANDLE hKeyBase, LPCTSTR pchSubKeyPath);
// close node opened/created by OpenNode() or CreateNode()
HRESULT Close();
// Add a node
HRESULT AddNode( LPWSTR szNodeName );
HRESULT ForceWriteMetabaseToDisk();
HRESULT DeleteNode(LPCTSTR pchSubKeyPath);
BOOL IsEmpty( PWCHAR pszSubString = L"" );
int GetNumberOfSubKeys( PWCHAR pszSubString = L"" );
// get all the sub keys that have a certain property on them and return the
// sub-paths in a cstring list object. The cstring list should be instantiated
// by the caller and deleted by the same.
HRESULT GetDataPaths(
DWORD dwMDIdentifier,
DWORD dwMDDataType,
CStringList& szPathList,
PWCHAR pszSubString = L"" );
HRESULT GetMultiSzAsStringList (
DWORD dwMDIdentifier,
DWORD *uType,
DWORD *attributes,
CStringList& szStrList,
LPCWSTR pszSubString = L"" );
HRESULT SetMultiSzAsStringList (
DWORD dwMDIdentifier,
DWORD uType,
DWORD attributes,
CStringList& szStrList,
PWCHAR pszSubString = L"" );
HRESULT GetStringAsCString (
DWORD dwMDIdentifier,
DWORD uType,
DWORD attributes,
CString& szStrList,
PWCHAR pszSubString = L"",
int iStringType = 0);
HRESULT SetCStringAsString (
DWORD dwMDIdentifier,
DWORD uType,
DWORD attributes,
CString& szStrList,
PWCHAR pszSubString = L"",
int iStringType = 0);
HRESULT GetDword(
DWORD dwMDIdentifier,
DWORD uType,
DWORD attributes,
DWORD& MyDword,
PWCHAR pszSubString = L"");
HRESULT SetData(
DWORD id,
DWORD attr,
DWORD uType,
DWORD dType,
DWORD cbLen,
LPBYTE pbData,
PWCHAR pszSubString = L"" );
BOOL GetData(DWORD id,
DWORD *pdwAttr,
DWORD *pdwUType,
DWORD *pdwDType,
DWORD *pcbLen,
LPBYTE pbData,
DWORD BufSize,
LPCWSTR pszSubString = L"" );
BOOL GetData(DWORD id,
DWORD *pdwAttr,
DWORD *pdwUType,
DWORD *pdwDType,
DWORD *pcbLen,
LPBYTE pbData,
DWORD BufSize,
DWORD dwAttributes,
DWORD dwUType,
DWORD dwDType,
LPCWSTR pszSubString = L"" );
BOOL EnumKeys( LPWSTR pchMDName,
DWORD dwIndex,
LPTSTR pszSubKeyPath = _T("") );
HRESULT DeleteData(DWORD id, DWORD dType, PWCHAR pszSubString = L"" );
HRESULT RenameNode(LPCTSTR pszMDPath,LPCTSTR pszMDNewName);
BOOL GetData(CMDValue &Value,
DWORD id,
LPCWSTR pszSubString = L"" );
BOOL SetData(CMDValue &Value,
DWORD id,
PWCHAR pszSubString = L"" );
static BOOL Backup( LPWSTR szBackupName,
DWORD dwVersion,
DWORD dwFlags );
static BOOL DeleteBackup( LPWSTR szBackupName,
DWORD dwVersion = MD_BACKUP_HIGHEST_VERSION );
private:
HRESULT DoCoInitEx();
void DoCoUnInit();
static HRESULT CreateABO( IMSAdminBase **ppcABO );
static void CloseABO( IMSAdminBase *pcABO );
// a count of the calls to coinit
INT m_cCoInits;
};
class CMDKeyIter : public CObject
{
protected:
IMSAdminBase * m_pcCom;
METADATA_HANDLE m_hKey;
LPWSTR m_pBuffer;
DWORD m_dwBuffer;
public:
CMDKeyIter(CMDKey &cmdKey);
~CMDKeyIter();
LONG Next(CString *pcsName, PWCHAR pwcsSubString = L"");
void Reset() {m_index = 0;}
DWORD m_index;
};
#endif // _MDKEY_H_
| [
"seta7D5@protonmail.com"
] | seta7D5@protonmail.com |
8b5506a08a216878aeaaf54ec3b830a37edd36d4 | 119c5b266a22d57a1b6a20a73d45e21b6c0447d1 | /Shapes/Ball.cpp | b659ee68165f79b44991c3fd8df4692223000658 | [] | no_license | LePtitDev/prog3d-opengl | 6b6e13a4cdb92292f9a311ec32b059a45220c146 | eb97f516bc8c6826fea417cae748827fe2f50af8 | refs/heads/master | 2021-01-21T11:18:42.181319 | 2017-07-11T13:24:31 | 2017-07-11T13:24:31 | 83,551,176 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,647 | cpp | #include "Ball.hpp"
Ball::Ball() :
p(Point()), r(1)
{
this->surface = Ball::SurfaceByBall(*this, 20, 20);
}
Ball::Ball(const Point & p, double r, long n, long m) :
p(p), r(r)
{
this->surface = Ball::SurfaceByBall(*this, n, m);
}
Ball::Ball(const Ball & b) :
p(b.p), r(b.r), surface(b.surface)
{
}
Surface Ball::SurfaceByBall(const Ball & b, long n, long m) {
Surface surface;
double teta, phi;
for (int i = 0; i < m; i++) {
phi = ((double)i / (double)(m - 1)) * M_PI;
for (int j = 0; j < n; j++) {
teta = ((double)j / (double)(n - 2)) * 2.0 * M_PI;
surface[i][j] = Point(b.r * sin(phi) * cos(teta) + b.p.x, b.r * cos(phi) + b.p.y, b.r * sin(phi) * sin(teta) + b.p.z);
}
}
return surface;
}
bool Ball::Inside(double x, double y, double z) {
return (Segment(Point(x, y, z), this->p).GetLength() <= r);
}
void Ball::Draw() {
this->surface.Draw();
}
Mesh Ball::GetMesh(unsigned int n) {
Mesh mesh;
double teta, phi;
for (unsigned int i = 1; i < n - 1; i++) {
phi = ((double)i / (double)(n - 1)) * M_PI;
for (unsigned int j = 0; j < n - 1; j++) {
teta = ((double)j / (double)(n - 1)) * 2.0 * M_PI;
mesh.PushPoint(Point(this->r * sin(phi) * cos(teta) + this->p.x, this->r * cos(phi) + this->p.y, this->r * sin(phi) * sin(teta) + this->p.z));
}
}
mesh.PushPoint(this->p + Vecteur(0, 1, 0) * this->r);
mesh.PushPoint(this->p + Vecteur(0, -1, 0) * this->r);
for (unsigned int i = 1; i < n - 2; i++) {
for (unsigned int j = 0; j < n - 2; j++) {
unsigned int vertex[4] = {
(i - 1) * (n - 1) + j,
(i - 1) * (n - 1) + j + 1,
i * (n - 1) + j,
i * (n - 1) + j + 1
};
mesh.PushTriangle(vertex[0], vertex[1], vertex[2]);
mesh.PushTriangle(vertex[1], vertex[3], vertex[2]);
}
mesh.PushTriangle(i * (n - 1) - 1, (i - 1) * (n - 1), (i + 1) * (n - 1) - 1);
mesh.PushTriangle((i - 1) * (n - 1), i * (n - 1), (i + 1) * (n - 1) - 1);
}
unsigned int pos_center_1 = mesh.PointNumber() - 2, pos_last_circle = pos_center_1 - n + 1;
for (unsigned int i = 1; i < n - 1; i++) {
mesh.PushTriangle(pos_center_1, i, i - 1);
mesh.PushTriangle(pos_center_1 + 1, pos_last_circle + i - 1, pos_last_circle + i);
}
mesh.PushTriangle(pos_center_1, 0, n - 2);
mesh.PushTriangle(pos_center_1 + 1, pos_center_1 - 1, pos_last_circle);
return mesh;
} | [
"arthur.ferre@etu.umontpellier.fr"
] | arthur.ferre@etu.umontpellier.fr |
8f03e235e3306f9b3a7ed977b426709dd407fbb3 | e7f3c7db44e7aa54bc88a5629f3c0fb517701ed3 | /judges/uva/Happy_Number/10591.cpp | 27d3ee740004593a0305d188570816bc8460e876 | [
"MIT"
] | permissive | ednunes/competitive-programming | f699ef9a176277e18b7f017876efac95ad3cd643 | 0f6bdc573b4d03d1ed20a2b77ec5388dca1ee47b | refs/heads/master | 2022-09-08T09:19:08.225422 | 2019-10-03T17:03:50 | 2019-10-03T17:03:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 618 | cpp | #include <bits/stdc++.h>
using namespace std;
int main (){
string a;
int cont = 0;
int q;
cin >> q;
while(cont < q){
cin >> a;
int aux = stoull(a);
long long unsigned soma = 0;
do{
soma = 0;
int v;
for(long long unsigned i = 0; i < a.length(); i++){
v = a[i] - '0';
soma += pow(v*1.0, 2);
}
if(soma == 4){
break;
}
a = to_string(soma);
}while(soma != aux && soma != 1);
cont++;
if(soma == 1){
printf("Case #%d: %llu is a Happy number.\n", cont, aux);
}else{
printf("Case #%d: %llu is an Unhappy number.\n", cont, aux);
}
}
return 0;
} | [
"eduardonunes2525@gmail.com"
] | eduardonunes2525@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.