code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
from . import Cl, conformalize
layout_orig, blades_orig = Cl(3)
layout, blades, stuff = conformalize(layout_orig)
locals().update(blades)
locals().update(stuff)
# for shorter reprs
layout.__name__ = 'layout'
layout.__module__ = __name__
| arsenovic/clifford | clifford/g3c.py | Python | bsd-3-clause | 240 |
using System;
using Renci.SshNet.Messages.Connection;
namespace Renci.SshNet.Channels
{
internal abstract class ServerChannel : Channel
{
internal void Initialize(Session session, uint localWindowSize, uint localPacketSize, uint remoteChannelNumber, uint remoteWindowSize, uint remotePacketSize)
{
Initialize(session, localWindowSize, localPacketSize);
InitializeRemoteInfo(remoteChannelNumber, remoteWindowSize, remotePacketSize);
//Session.ChannelOpenReceived += OnChannelOpen;
}
//private void OnChannelOpen(object sender, MessageEventArgs<ChannelOpenMessage> e)
//{
// var channelOpenMessage = e.Message;
// if (channelOpenMessage.LocalChannelNumber == LocalChannelNumber)
// {
// _remoteChannelNumber = channelOpenMessage.LocalChannelNumber;
// RemoteWindowSize = channelOpenMessage.InitialWindowSize;
// _remotePacketSize = channelOpenMessage.MaximumPacketSize;
// OnOpen(e.Message.Info);
// }
//}
protected void SendMessage(ChannelOpenConfirmationMessage message)
{
// No need to check whether channel is open when trying to open a channel
Session.SendMessage(message);
// When we act as server, consider the channel open when we've sent the
// confirmation message to the peer
IsOpen = true;
}
///// <summary>
///// Called when channel need to be open on the client.
///// </summary>
///// <param name="info">Channel open information.</param>
//protected virtual void OnOpen(ChannelOpenInfo info)
//{
//}
protected override void Dispose(bool disposing)
{
if (disposing)
{
var session = Session;
if (session != null)
{
//session.ChannelOpenReceived -= OnChannelOpen;
}
}
base.Dispose(disposing);
}
}
}
| EddyBeaupre/Renci.SshNet | Channels/ServerChannel.cs | C# | bsd-3-clause | 2,118 |
<?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model app\models\ShopGoodsCategory */
$this->title = Yii::t('app', 'Create Shop Goods Category');
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Shop Goods Categories'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="shop-goods-category-create">
<?= $this->render('_form', [
'model' => $model,
]) ?>
</div>
| xiangpingeasy/yii2_fbg_shop | backend/views/shop-goods-category/create.php | PHP | bsd-3-clause | 446 |
// 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/chromeos/login/login_utils.h"
#include <algorithm>
#include <set>
#include <vector>
#include "base/bind.h"
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/location.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/singleton.h"
#include "base/memory/weak_ptr.h"
#include "base/path_service.h"
#include "base/prefs/pref_member.h"
#include "base/prefs/pref_registry_simple.h"
#include "base/prefs/pref_service.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/synchronization/lock.h"
#include "base/sys_info.h"
#include "base/task_runner_util.h"
#include "base/threading/worker_pool.h"
#include "base/time/time.h"
#include "chrome/browser/about_flags.h"
#include "chrome/browser/app_mode/app_mode_utils.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_shutdown.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/chromeos/boot_times_loader.h"
#include "chrome/browser/chromeos/input_method/input_method_util.h"
#include "chrome/browser/chromeos/login/chrome_restart_request.h"
#include "chrome/browser/chromeos/login/demo_mode/demo_app_launcher.h"
#include "chrome/browser/chromeos/login/input_events_blocker.h"
#include "chrome/browser/chromeos/login/login_display_host.h"
#include "chrome/browser/chromeos/login/oauth2_login_manager.h"
#include "chrome/browser/chromeos/login/oauth2_login_manager_factory.h"
#include "chrome/browser/chromeos/login/parallel_authenticator.h"
#include "chrome/browser/chromeos/login/profile_auth_data.h"
#include "chrome/browser/chromeos/login/saml/saml_offline_signin_limiter.h"
#include "chrome/browser/chromeos/login/saml/saml_offline_signin_limiter_factory.h"
#include "chrome/browser/chromeos/login/screen_locker.h"
#include "chrome/browser/chromeos/login/startup_utils.h"
#include "chrome/browser/chromeos/login/supervised_user_manager.h"
#include "chrome/browser/chromeos/login/user.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/chromeos/settings/cros_settings.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/first_run/first_run.h"
#include "chrome/browser/google/google_util_chromeos.h"
#include "chrome/browser/lifetime/application_lifetime.h"
#include "chrome/browser/pref_service_flags_storage.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/rlz/rlz.h"
#include "chrome/browser/signin/signin_manager.h"
#include "chrome/browser/signin/signin_manager_factory.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/sync/profile_sync_service_factory.h"
#include "chrome/browser/ui/app_list/start_page_service.h"
#include "chrome/browser/ui/startup/startup_browser_creator.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/logging_chrome.h"
#include "chrome/common/pref_names.h"
#include "chromeos/chromeos_switches.h"
#include "chromeos/cryptohome/cryptohome_util.h"
#include "chromeos/dbus/cryptohome_client.h"
#include "chromeos/dbus/dbus_method_call_status.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "chromeos/dbus/session_manager_client.h"
#include "chromeos/ime/input_method_manager.h"
#include "chromeos/settings/cros_settings_names.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_service.h"
#include "google_apis/gaia/gaia_auth_consumer.h"
#include "net/base/network_change_notifier.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h"
#include "url/gurl.h"
using content::BrowserThread;
namespace chromeos {
namespace {
#if defined(ENABLE_RLZ)
// Flag file that disables RLZ tracking, when present.
const base::FilePath::CharType kRLZDisabledFlagName[] =
FILE_PATH_LITERAL(".rlz_disabled");
base::FilePath GetRlzDisabledFlagPath() {
return base::GetHomeDir().Append(kRLZDisabledFlagName);
}
#endif
} // namespace
struct DoBrowserLaunchOnLocaleLoadedData;
class LoginUtilsImpl
: public LoginUtils,
public OAuth2LoginManager::Observer,
public net::NetworkChangeNotifier::ConnectionTypeObserver,
public base::SupportsWeakPtr<LoginUtilsImpl> {
public:
LoginUtilsImpl()
: has_web_auth_cookies_(false),
delegate_(NULL),
exit_after_session_restore_(false),
session_restore_strategy_(
OAuth2LoginManager::RESTORE_FROM_SAVED_OAUTH2_REFRESH_TOKEN) {
net::NetworkChangeNotifier::AddConnectionTypeObserver(this);
}
virtual ~LoginUtilsImpl() {
net::NetworkChangeNotifier::RemoveConnectionTypeObserver(this);
}
// LoginUtils implementation:
virtual void DoBrowserLaunch(Profile* profile,
LoginDisplayHost* login_host) OVERRIDE;
virtual void PrepareProfile(
const UserContext& user_context,
const std::string& display_email,
bool has_cookies,
bool has_active_session,
LoginUtils::Delegate* delegate) OVERRIDE;
virtual void DelegateDeleted(LoginUtils::Delegate* delegate) OVERRIDE;
virtual void CompleteOffTheRecordLogin(const GURL& start_url) OVERRIDE;
virtual void SetFirstLoginPrefs(PrefService* prefs) OVERRIDE;
virtual scoped_refptr<Authenticator> CreateAuthenticator(
LoginStatusConsumer* consumer) OVERRIDE;
virtual void RestoreAuthenticationSession(Profile* profile) OVERRIDE;
virtual void InitRlzDelayed(Profile* user_profile) OVERRIDE;
// OAuth2LoginManager::Observer overrides.
virtual void OnSessionRestoreStateChanged(
Profile* user_profile,
OAuth2LoginManager::SessionRestoreState state) OVERRIDE;
virtual void OnNewRefreshTokenAvaiable(Profile* user_profile) OVERRIDE;
// net::NetworkChangeNotifier::ConnectionTypeObserver overrides.
virtual void OnConnectionTypeChanged(
net::NetworkChangeNotifier::ConnectionType type) OVERRIDE;
private:
typedef std::set<std::string> SessionRestoreStateSet;
// DoBrowserLaunch is split into two parts.
// This one is called after anynchronous locale switch.
void DoBrowserLaunchOnLocaleLoadedImpl(Profile* profile,
LoginDisplayHost* login_host);
// Callback for locale_util::SwitchLanguage().
static void DoBrowserLaunchOnLocaleLoaded(
scoped_ptr<DoBrowserLaunchOnLocaleLoadedData> context,
const std::string& locale,
const std::string& loaded_locale,
const bool success);
// Restarts OAuth session authentication check.
void KickStartAuthentication(Profile* profile);
// Callback for Profile::CREATE_STATUS_CREATED profile state.
// Initializes basic preferences for newly created profile. Any other
// early profile initialization that needs to happen before
// ProfileManager::DoFinalInit() gets called is done here.
void InitProfilePreferences(Profile* user_profile,
const std::string& email);
// Callback for asynchronous profile creation.
void OnProfileCreated(const std::string& email,
Profile* profile,
Profile::CreateStatus status);
// Callback for asynchronous off the record profile creation.
void OnOTRProfileCreated(const std::string& email,
Profile* profile,
Profile::CreateStatus status);
// Callback for Profile::CREATE_STATUS_INITIALIZED profile state.
// Profile is created, extensions and promo resources are initialized.
void UserProfileInitialized(Profile* user_profile);
// Callback for Profile::CREATE_STATUS_INITIALIZED profile state for an OTR
// login.
void OTRProfileInitialized(Profile* user_profile);
// Callback to resume profile creation after transferring auth data from
// the authentication profile.
void CompleteProfileCreate(Profile* user_profile);
// Finalized profile preparation.
void FinalizePrepareProfile(Profile* user_profile);
// Initializes member variables needed for session restore process via
// OAuthLoginManager.
void InitSessionRestoreStrategy();
// Restores GAIA auth cookies for the created user profile from OAuth2 token.
void RestoreAuthSession(Profile* user_profile,
bool restore_from_auth_cookies);
// Initializes RLZ. If |disabled| is true, RLZ pings are disabled.
void InitRlz(Profile* user_profile, bool disabled);
// Attempts restarting the browser process and esures that this does
// not happen while we are still fetching new OAuth refresh tokens.
void AttemptRestart(Profile* profile);
UserContext user_context_;
// True if the authentication profile's cookie jar should contain
// authentication cookies from the authentication extension log in flow.
bool has_web_auth_cookies_;
// Has to be scoped_refptr, see comment for CreateAuthenticator(...).
scoped_refptr<Authenticator> authenticator_;
// Delegate to be fired when the profile will be prepared.
LoginUtils::Delegate* delegate_;
// Set of user_id for those users that we should restore authentication
// session when notified about online state change.
SessionRestoreStateSet pending_restore_sessions_;
// True if we should restart chrome right after session restore.
bool exit_after_session_restore_;
// Sesion restore strategy.
OAuth2LoginManager::SessionRestoreStrategy session_restore_strategy_;
// OAuth2 refresh token for session restore.
std::string oauth2_refresh_token_;
DISALLOW_COPY_AND_ASSIGN(LoginUtilsImpl);
};
class LoginUtilsWrapper {
public:
static LoginUtilsWrapper* GetInstance() {
return Singleton<LoginUtilsWrapper>::get();
}
LoginUtils* get() {
base::AutoLock create(create_lock_);
if (!ptr_.get())
reset(new LoginUtilsImpl);
return ptr_.get();
}
void reset(LoginUtils* ptr) {
ptr_.reset(ptr);
}
private:
friend struct DefaultSingletonTraits<LoginUtilsWrapper>;
LoginUtilsWrapper() {}
base::Lock create_lock_;
scoped_ptr<LoginUtils> ptr_;
DISALLOW_COPY_AND_ASSIGN(LoginUtilsWrapper);
};
struct DoBrowserLaunchOnLocaleLoadedData {
DoBrowserLaunchOnLocaleLoadedData(LoginUtilsImpl* login_utils_impl,
Profile* profile,
LoginDisplayHost* display_host)
: login_utils_impl(login_utils_impl),
profile(profile),
display_host(display_host) {}
LoginUtilsImpl* login_utils_impl;
Profile* profile;
chromeos::LoginDisplayHost* display_host;
// Block UI events untill ResourceBundle is reloaded.
InputEventsBlocker input_events_blocker;
};
// static
void LoginUtilsImpl::DoBrowserLaunchOnLocaleLoaded(
scoped_ptr<DoBrowserLaunchOnLocaleLoadedData> context,
const std::string& /* locale */,
const std::string& /* loaded_locale */,
const bool /* success */) {
context->login_utils_impl->DoBrowserLaunchOnLocaleLoadedImpl(
context->profile, context->display_host);
}
// Called from DoBrowserLaunch() or from
// DoBrowserLaunchOnLocaleLoaded() depending on
// if locale switch was needed.
void LoginUtilsImpl::DoBrowserLaunchOnLocaleLoadedImpl(
Profile* profile,
LoginDisplayHost* login_host) {
if (!UserManager::Get()->GetCurrentUserFlow()->ShouldLaunchBrowser()) {
UserManager::Get()->GetCurrentUserFlow()->LaunchExtraSteps(profile);
return;
}
CommandLine user_flags(CommandLine::NO_PROGRAM);
about_flags::PrefServiceFlagsStorage flags_storage_(profile->GetPrefs());
about_flags::ConvertFlagsToSwitches(&flags_storage_, &user_flags,
about_flags::kAddSentinels);
// Only restart if needed and if not going into managed mode.
// Don't restart browser if it is not first profile in session.
if (UserManager::Get()->GetLoggedInUsers().size() == 1 &&
!UserManager::Get()->IsLoggedInAsLocallyManagedUser() &&
!about_flags::AreSwitchesIdenticalToCurrentCommandLine(
user_flags, *CommandLine::ForCurrentProcess())) {
CommandLine::StringVector flags;
// argv[0] is the program name |CommandLine::NO_PROGRAM|.
flags.assign(user_flags.argv().begin() + 1, user_flags.argv().end());
VLOG(1) << "Restarting to apply per-session flags...";
DBusThreadManager::Get()->GetSessionManagerClient()->SetFlagsForUser(
UserManager::Get()->GetActiveUser()->email(), flags);
AttemptRestart(profile);
return;
}
if (login_host) {
login_host->SetStatusAreaVisible(true);
login_host->BeforeSessionStart();
}
BootTimesLoader::Get()->AddLoginTimeMarker("BrowserLaunched", false);
VLOG(1) << "Launching browser...";
StartupBrowserCreator browser_creator;
int return_code;
chrome::startup::IsFirstRun first_run = first_run::IsChromeFirstRun() ?
chrome::startup::IS_FIRST_RUN : chrome::startup::IS_NOT_FIRST_RUN;
browser_creator.LaunchBrowser(*CommandLine::ForCurrentProcess(),
profile,
base::FilePath(),
chrome::startup::IS_PROCESS_STARTUP,
first_run,
&return_code);
// Triggers app launcher start page service to load start page web contents.
app_list::StartPageService::Get(profile);
// Mark login host for deletion after browser starts. This
// guarantees that the message loop will be referenced by the
// browser before it is dereferenced by the login host.
if (login_host)
login_host->Finalize();
UserManager::Get()->SessionStarted();
}
void LoginUtilsImpl::DoBrowserLaunch(Profile* profile,
LoginDisplayHost* login_host) {
if (browser_shutdown::IsTryingToQuit())
return;
User* const user = UserManager::Get()->GetUserByProfile(profile);
scoped_ptr<DoBrowserLaunchOnLocaleLoadedData> data(
new DoBrowserLaunchOnLocaleLoadedData(this, profile, login_host));
scoped_ptr<locale_util::SwitchLanguageCallback> callback(
new locale_util::SwitchLanguageCallback(
base::Bind(&LoginUtilsImpl::DoBrowserLaunchOnLocaleLoaded,
base::Passed(data.Pass()))));
if (!UserManager::Get()->
RespectLocalePreference(profile, user, callback.Pass())) {
DoBrowserLaunchOnLocaleLoadedImpl(profile, login_host);
}
}
void LoginUtilsImpl::PrepareProfile(
const UserContext& user_context,
const std::string& display_email,
bool has_cookies,
bool has_active_session,
LoginUtils::Delegate* delegate) {
BootTimesLoader* btl = BootTimesLoader::Get();
VLOG(1) << "Completing login for " << user_context.username;
if (!has_active_session) {
btl->AddLoginTimeMarker("StartSession-Start", false);
DBusThreadManager::Get()->GetSessionManagerClient()->StartSession(
user_context.username);
btl->AddLoginTimeMarker("StartSession-End", false);
}
btl->AddLoginTimeMarker("UserLoggedIn-Start", false);
UserManager* user_manager = UserManager::Get();
user_manager->UserLoggedIn(user_context.username,
user_context.username_hash,
false);
btl->AddLoginTimeMarker("UserLoggedIn-End", false);
// Switch log file as soon as possible.
if (base::SysInfo::IsRunningOnChromeOS())
logging::RedirectChromeLogging(*(CommandLine::ForCurrentProcess()));
// Update user's displayed email.
if (!display_email.empty())
user_manager->SaveUserDisplayEmail(user_context.username, display_email);
user_context_ = user_context;
has_web_auth_cookies_ = has_cookies;
delegate_ = delegate;
InitSessionRestoreStrategy();
if (DemoAppLauncher::IsDemoAppSession(user_context.username)) {
g_browser_process->profile_manager()->CreateProfileAsync(
user_manager->GetUserProfileDir(user_context.username),
base::Bind(&LoginUtilsImpl::OnOTRProfileCreated, AsWeakPtr(),
user_context.username),
base::string16(), base::string16(), std::string());
} else {
// Can't use display_email because it is empty when existing user logs in
// using sing-in pod on login screen (i.e. user didn't type email).
g_browser_process->profile_manager()->CreateProfileAsync(
user_manager->GetUserProfileDir(user_context.username),
base::Bind(&LoginUtilsImpl::OnProfileCreated, AsWeakPtr(),
user_context.username),
base::string16(), base::string16(), std::string());
}
}
void LoginUtilsImpl::DelegateDeleted(LoginUtils::Delegate* delegate) {
if (delegate_ == delegate)
delegate_ = NULL;
}
void LoginUtilsImpl::InitProfilePreferences(Profile* user_profile,
const std::string& user_id) {
if (UserManager::Get()->IsCurrentUserNew())
SetFirstLoginPrefs(user_profile->GetPrefs());
if (UserManager::Get()->IsLoggedInAsLocallyManagedUser()) {
User* active_user = UserManager::Get()->GetActiveUser();
std::string managed_user_sync_id =
UserManager::Get()->GetSupervisedUserManager()->
GetUserSyncId(active_user->email());
// TODO(ibraaaa): Remove that when 97% of our users are using M31.
// http://crbug.com/276163
if (managed_user_sync_id.empty())
managed_user_sync_id = "DUMMY_ID";
user_profile->GetPrefs()->SetString(prefs::kManagedUserId,
managed_user_sync_id);
} else {
// Make sure that the google service username is properly set (we do this
// on every sign in, not just the first login, to deal with existing
// profiles that might not have it set yet).
SigninManagerBase* signin_manager =
SigninManagerFactory::GetForProfile(user_profile);
signin_manager->SetAuthenticatedUsername(user_id);
}
}
void LoginUtilsImpl::InitSessionRestoreStrategy() {
CommandLine* command_line = CommandLine::ForCurrentProcess();
bool in_app_mode = chrome::IsRunningInForcedAppMode();
// Are we in kiosk app mode?
if (in_app_mode) {
if (command_line->HasSwitch(::switches::kAppModeOAuth2Token)) {
oauth2_refresh_token_ = command_line->GetSwitchValueASCII(
::switches::kAppModeOAuth2Token);
}
if (command_line->HasSwitch(::switches::kAppModeAuthCode)) {
user_context_.auth_code = command_line->GetSwitchValueASCII(
::switches::kAppModeAuthCode);
}
DCHECK(!has_web_auth_cookies_);
if (!user_context_.auth_code.empty()) {
session_restore_strategy_ = OAuth2LoginManager::RESTORE_FROM_AUTH_CODE;
} else if (!oauth2_refresh_token_.empty()) {
session_restore_strategy_ =
OAuth2LoginManager::RESTORE_FROM_PASSED_OAUTH2_REFRESH_TOKEN;
} else {
session_restore_strategy_ =
OAuth2LoginManager::RESTORE_FROM_SAVED_OAUTH2_REFRESH_TOKEN;
}
return;
}
if (has_web_auth_cookies_) {
session_restore_strategy_ = OAuth2LoginManager::RESTORE_FROM_COOKIE_JAR;
} else if (!user_context_.auth_code.empty()) {
session_restore_strategy_ = OAuth2LoginManager::RESTORE_FROM_AUTH_CODE;
} else {
session_restore_strategy_ =
OAuth2LoginManager::RESTORE_FROM_SAVED_OAUTH2_REFRESH_TOKEN;
}
}
void LoginUtilsImpl::OnProfileCreated(
const std::string& user_id,
Profile* user_profile,
Profile::CreateStatus status) {
CHECK(user_profile);
switch (status) {
case Profile::CREATE_STATUS_CREATED:
InitProfilePreferences(user_profile, user_id);
break;
case Profile::CREATE_STATUS_INITIALIZED:
UserProfileInitialized(user_profile);
break;
case Profile::CREATE_STATUS_LOCAL_FAIL:
case Profile::CREATE_STATUS_REMOTE_FAIL:
case Profile::CREATE_STATUS_CANCELED:
case Profile::MAX_CREATE_STATUS:
NOTREACHED();
break;
}
}
void LoginUtilsImpl::OnOTRProfileCreated(
const std::string& user_id,
Profile* user_profile,
Profile::CreateStatus status) {
CHECK(user_profile);
switch (status) {
case Profile::CREATE_STATUS_CREATED:
InitProfilePreferences(user_profile, user_id);
break;
case Profile::CREATE_STATUS_INITIALIZED:
OTRProfileInitialized(user_profile);
break;
case Profile::CREATE_STATUS_LOCAL_FAIL:
case Profile::CREATE_STATUS_REMOTE_FAIL:
case Profile::CREATE_STATUS_CANCELED:
case Profile::MAX_CREATE_STATUS:
NOTREACHED();
break;
}
}
void LoginUtilsImpl::UserProfileInitialized(Profile* user_profile) {
BootTimesLoader* btl = BootTimesLoader::Get();
btl->AddLoginTimeMarker("UserProfileGotten", false);
if (user_context_.using_oauth) {
// Transfer proxy authentication cache, cookies (optionally) and server
// bound certs from the profile that was used for authentication. This
// profile contains cookies that auth extension should have already put in
// place that will ensure that the newly created session is authenticated
// for the websites that work with the used authentication schema.
ProfileAuthData::Transfer(authenticator_->authentication_profile(),
user_profile,
has_web_auth_cookies_, // transfer_cookies
base::Bind(
&LoginUtilsImpl::CompleteProfileCreate,
AsWeakPtr(),
user_profile));
return;
}
FinalizePrepareProfile(user_profile);
}
void LoginUtilsImpl::OTRProfileInitialized(Profile* user_profile) {
user_profile->OnLogin();
// Send the notification before creating the browser so additional objects
// that need the profile (e.g. the launcher) can be created first.
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED,
content::NotificationService::AllSources(),
content::Details<Profile>(user_profile));
if (delegate_)
delegate_->OnProfilePrepared(user_profile);
}
void LoginUtilsImpl::CompleteProfileCreate(Profile* user_profile) {
RestoreAuthSession(user_profile, has_web_auth_cookies_);
FinalizePrepareProfile(user_profile);
}
void LoginUtilsImpl::RestoreAuthSession(Profile* user_profile,
bool restore_from_auth_cookies) {
CHECK((authenticator_.get() && authenticator_->authentication_profile()) ||
!restore_from_auth_cookies);
if (chrome::IsRunningInForcedAppMode() ||
CommandLine::ForCurrentProcess()->HasSwitch(
chromeos::switches::kOobeSkipPostLogin)) {
return;
}
exit_after_session_restore_ = false;
// Remove legacy OAuth1 token if we have one. If it's valid, we should already
// have OAuth2 refresh token in OAuth2TokenService that could be used to
// retrieve all other tokens and user_context.
OAuth2LoginManager* login_manager =
OAuth2LoginManagerFactory::GetInstance()->GetForProfile(user_profile);
login_manager->AddObserver(this);
login_manager->RestoreSession(
authenticator_.get() && authenticator_->authentication_profile()
? authenticator_->authentication_profile()->GetRequestContext()
: NULL,
session_restore_strategy_,
oauth2_refresh_token_,
user_context_.auth_code);
}
void LoginUtilsImpl::FinalizePrepareProfile(Profile* user_profile) {
BootTimesLoader* btl = BootTimesLoader::Get();
// Own TPM device if, for any reason, it has not been done in EULA
// wizard screen.
CryptohomeClient* client = DBusThreadManager::Get()->GetCryptohomeClient();
btl->AddLoginTimeMarker("TPMOwn-Start", false);
if (cryptohome_util::TpmIsEnabled() && !cryptohome_util::TpmIsBeingOwned()) {
if (cryptohome_util::TpmIsOwned()) {
client->CallTpmClearStoredPasswordAndBlock();
} else {
client->TpmCanAttemptOwnership(EmptyVoidDBusMethodCallback());
}
}
btl->AddLoginTimeMarker("TPMOwn-End", false);
if (UserManager::Get()->IsLoggedInAsRegularUser()) {
SAMLOfflineSigninLimiter* saml_offline_signin_limiter =
SAMLOfflineSigninLimiterFactory::GetForProfile(user_profile);
if (saml_offline_signin_limiter)
saml_offline_signin_limiter->SignedIn(user_context_.auth_flow);
}
user_profile->OnLogin();
// Send the notification before creating the browser so additional objects
// that need the profile (e.g. the launcher) can be created first.
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED,
content::NotificationService::AllSources(),
content::Details<Profile>(user_profile));
// Initialize RLZ only for primary user.
if (UserManager::Get()->GetPrimaryUser() ==
UserManager::Get()->GetUserByProfile(user_profile)) {
InitRlzDelayed(user_profile);
}
// TODO(altimofeev): This pointer should probably never be NULL, but it looks
// like LoginUtilsImpl::OnProfileCreated() may be getting called before
// LoginUtilsImpl::PrepareProfile() has set |delegate_| when Chrome is killed
// during shutdown in tests -- see http://crosbug.com/18269. Replace this
// 'if' statement with a CHECK(delegate_) once the underlying issue is
// resolved.
if (delegate_)
delegate_->OnProfilePrepared(user_profile);
}
void LoginUtilsImpl::InitRlzDelayed(Profile* user_profile) {
#if defined(ENABLE_RLZ)
if (!g_browser_process->local_state()->HasPrefPath(prefs::kRLZBrand)) {
// Read brand code asynchronously from an OEM data and repost ourselves.
google_util::chromeos::InitBrand(
base::Bind(&LoginUtilsImpl::InitRlzDelayed, AsWeakPtr(), user_profile));
return;
}
base::PostTaskAndReplyWithResult(
base::WorkerPool::GetTaskRunner(false),
FROM_HERE,
base::Bind(&base::PathExists, GetRlzDisabledFlagPath()),
base::Bind(&LoginUtilsImpl::InitRlz, AsWeakPtr(), user_profile));
#endif
}
void LoginUtilsImpl::InitRlz(Profile* user_profile, bool disabled) {
#if defined(ENABLE_RLZ)
PrefService* local_state = g_browser_process->local_state();
if (disabled) {
// Empty brand code means an organic install (no RLZ pings are sent).
google_util::chromeos::ClearBrandForCurrentSession();
}
if (disabled != local_state->GetBoolean(prefs::kRLZDisabled)) {
// When switching to RLZ enabled/disabled state, clear all recorded events.
RLZTracker::ClearRlzState();
local_state->SetBoolean(prefs::kRLZDisabled, disabled);
}
// Init the RLZ library.
int ping_delay = user_profile->GetPrefs()->GetInteger(
first_run::GetPingDelayPrefName().c_str());
// Negative ping delay means to send ping immediately after a first search is
// recorded.
RLZTracker::InitRlzFromProfileDelayed(
user_profile, UserManager::Get()->IsCurrentUserNew(),
ping_delay < 0, base::TimeDelta::FromMilliseconds(abs(ping_delay)));
if (delegate_)
delegate_->OnRlzInitialized(user_profile);
#endif
}
void LoginUtilsImpl::CompleteOffTheRecordLogin(const GURL& start_url) {
VLOG(1) << "Completing incognito login";
// For guest session we ask session manager to restart Chrome with --bwsi
// flag. We keep only some of the arguments of this process.
const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
CommandLine command_line(browser_command_line.GetProgram());
std::string cmd_line_str =
GetOffTheRecordCommandLine(start_url,
StartupUtils::IsOobeCompleted(),
browser_command_line,
&command_line);
RestartChrome(cmd_line_str);
}
void LoginUtilsImpl::SetFirstLoginPrefs(PrefService* prefs) {
VLOG(1) << "Setting first login prefs";
BootTimesLoader* btl = BootTimesLoader::Get();
std::string locale = g_browser_process->GetApplicationLocale();
// First, we'll set kLanguagePreloadEngines.
input_method::InputMethodManager* manager =
input_method::InputMethodManager::Get();
std::vector<std::string> input_method_ids;
manager->GetInputMethodUtil()->GetFirstLoginInputMethodIds(
locale, manager->GetCurrentInputMethod(), &input_method_ids);
// Save the input methods in the user's preferences.
StringPrefMember language_preload_engines;
language_preload_engines.Init(prefs::kLanguagePreloadEngines,
prefs);
language_preload_engines.SetValue(JoinString(input_method_ids, ','));
btl->AddLoginTimeMarker("IMEStarted", false);
// Second, we'll set kLanguagePreferredLanguages.
std::vector<std::string> language_codes;
// The current locale should be on the top.
language_codes.push_back(locale);
// Add input method IDs based on the input methods, as there may be
// input methods that are unrelated to the current locale. Example: the
// hardware keyboard layout xkb:us::eng is used for logging in, but the
// UI language is set to French. In this case, we should set "fr,en"
// to the preferred languages preference.
std::vector<std::string> candidates;
manager->GetInputMethodUtil()->GetLanguageCodesFromInputMethodIds(
input_method_ids, &candidates);
for (size_t i = 0; i < candidates.size(); ++i) {
const std::string& candidate = candidates[i];
// Skip if it's already in language_codes.
if (std::count(language_codes.begin(), language_codes.end(),
candidate) == 0) {
language_codes.push_back(candidate);
}
}
// Save the preferred languages in the user's preferences.
StringPrefMember language_preferred_languages;
language_preferred_languages.Init(prefs::kLanguagePreferredLanguages,
prefs);
language_preferred_languages.SetValue(JoinString(language_codes, ','));
}
scoped_refptr<Authenticator> LoginUtilsImpl::CreateAuthenticator(
LoginStatusConsumer* consumer) {
// Screen locker needs new Authenticator instance each time.
if (ScreenLocker::default_screen_locker()) {
if (authenticator_.get())
authenticator_->SetConsumer(NULL);
authenticator_ = NULL;
}
if (authenticator_.get() == NULL) {
authenticator_ = new ParallelAuthenticator(consumer);
} else {
// TODO(nkostylev): Fix this hack by improving Authenticator dependencies.
authenticator_->SetConsumer(consumer);
}
return authenticator_;
}
void LoginUtilsImpl::RestoreAuthenticationSession(Profile* user_profile) {
UserManager* user_manager = UserManager::Get();
// We don't need to restore session for demo/guest/stub/public account users.
if (!user_manager->IsUserLoggedIn() ||
user_manager->IsLoggedInAsGuest() ||
user_manager->IsLoggedInAsPublicAccount() ||
user_manager->IsLoggedInAsDemoUser() ||
user_manager->IsLoggedInAsStub()) {
return;
}
User* user = user_manager->GetUserByProfile(user_profile);
DCHECK(user);
if (!net::NetworkChangeNotifier::IsOffline()) {
pending_restore_sessions_.erase(user->email());
RestoreAuthSession(user_profile, false);
} else {
// Even if we're online we should wait till initial
// OnConnectionTypeChanged() call. Otherwise starting fetchers too early may
// end up canceling all request when initial network connection type is
// processed. See http://crbug.com/121643.
pending_restore_sessions_.insert(user->email());
}
}
void LoginUtilsImpl::OnSessionRestoreStateChanged(
Profile* user_profile,
OAuth2LoginManager::SessionRestoreState state) {
User::OAuthTokenStatus user_status = User::OAUTH_TOKEN_STATUS_UNKNOWN;
OAuth2LoginManager* login_manager =
OAuth2LoginManagerFactory::GetInstance()->GetForProfile(user_profile);
bool connection_error = false;
switch (state) {
case OAuth2LoginManager::SESSION_RESTORE_DONE:
user_status = User::OAUTH2_TOKEN_STATUS_VALID;
break;
case OAuth2LoginManager::SESSION_RESTORE_FAILED:
user_status = User::OAUTH2_TOKEN_STATUS_INVALID;
break;
case OAuth2LoginManager::SESSION_RESTORE_CONNECTION_FAILED:
connection_error = true;
break;
case OAuth2LoginManager::SESSION_RESTORE_NOT_STARTED:
case OAuth2LoginManager::SESSION_RESTORE_PREPARING:
case OAuth2LoginManager::SESSION_RESTORE_IN_PROGRESS:
return;
}
// We should not be clearing existing token state if that was a connection
// error. http://crbug.com/295245
if (!connection_error) {
// We are in one of "done" states here.
UserManager::Get()->SaveUserOAuthStatus(
UserManager::Get()->GetLoggedInUser()->email(),
user_status);
}
login_manager->RemoveObserver(this);
}
void LoginUtilsImpl::OnNewRefreshTokenAvaiable(Profile* user_profile) {
// Check if we were waiting to restart chrome.
if (!exit_after_session_restore_)
return;
OAuth2LoginManager* login_manager =
OAuth2LoginManagerFactory::GetInstance()->GetForProfile(user_profile);
login_manager->RemoveObserver(this);
// Mark user auth token status as valid.
UserManager::Get()->SaveUserOAuthStatus(
UserManager::Get()->GetLoggedInUser()->email(),
User::OAUTH2_TOKEN_STATUS_VALID);
LOG(WARNING) << "Exiting after new refresh token fetched";
// We need to restart cleanly in this case to make sure OAuth2 RT is actually
// saved.
chrome::AttemptRestart();
}
void LoginUtilsImpl::OnConnectionTypeChanged(
net::NetworkChangeNotifier::ConnectionType type) {
UserManager* user_manager = UserManager::Get();
if (type == net::NetworkChangeNotifier::CONNECTION_NONE ||
user_manager->IsLoggedInAsGuest() || !user_manager->IsUserLoggedIn()) {
return;
}
// Need to iterate over all users and their OAuth2 session state.
const UserList& users = user_manager->GetLoggedInUsers();
for (UserList::const_iterator it = users.begin(); it != users.end(); ++it) {
Profile* user_profile = user_manager->GetProfileByUser(*it);
bool should_restore_session =
pending_restore_sessions_.find((*it)->email()) !=
pending_restore_sessions_.end();
OAuth2LoginManager* login_manager =
OAuth2LoginManagerFactory::GetInstance()->GetForProfile(user_profile);
if (login_manager->state() ==
OAuth2LoginManager::SESSION_RESTORE_IN_PROGRESS) {
// If we come online for the first time after successful offline login,
// we need to kick off OAuth token verification process again.
login_manager->ContinueSessionRestore();
} else if (should_restore_session) {
pending_restore_sessions_.erase((*it)->email());
RestoreAuthSession(user_profile, has_web_auth_cookies_);
}
}
}
void LoginUtilsImpl::AttemptRestart(Profile* profile) {
if (session_restore_strategy_ !=
OAuth2LoginManager::RESTORE_FROM_COOKIE_JAR) {
chrome::AttemptRestart();
return;
}
// We can't really quit if the session restore process that mints new
// refresh token is still in progress.
OAuth2LoginManager* login_manager =
OAuth2LoginManagerFactory::GetInstance()->GetForProfile(profile);
if (login_manager->state() !=
OAuth2LoginManager::SESSION_RESTORE_PREPARING &&
login_manager->state() !=
OAuth2LoginManager::SESSION_RESTORE_IN_PROGRESS) {
chrome::AttemptRestart();
return;
}
LOG(WARNING) << "Attempting browser restart during session restore.";
exit_after_session_restore_ = true;
}
// static
void LoginUtils::RegisterPrefs(PrefRegistrySimple* registry) {
registry->RegisterBooleanPref(prefs::kFactoryResetRequested, false);
registry->RegisterBooleanPref(prefs::kRollbackRequested, false);
registry->RegisterStringPref(prefs::kRLZBrand, std::string());
registry->RegisterBooleanPref(prefs::kRLZDisabled, false);
}
// static
LoginUtils* LoginUtils::Get() {
return LoginUtilsWrapper::GetInstance()->get();
}
// static
void LoginUtils::Set(LoginUtils* mock) {
LoginUtilsWrapper::GetInstance()->reset(mock);
}
// static
bool LoginUtils::IsWhitelisted(const std::string& username,
bool* wildcard_match) {
// Skip whitelist check for tests.
if (CommandLine::ForCurrentProcess()->HasSwitch(
chromeos::switches::kOobeSkipPostLogin)) {
return true;
}
CrosSettings* cros_settings = CrosSettings::Get();
bool allow_new_user = false;
cros_settings->GetBoolean(kAccountsPrefAllowNewUser, &allow_new_user);
if (allow_new_user)
return true;
return cros_settings->FindEmailInList(
kAccountsPrefUsers, username, wildcard_match);
}
} // namespace chromeos
| patrickm/chromium.src | chrome/browser/chromeos/login/login_utils.cc | C++ | bsd-3-clause | 36,738 |
package edu.ucdenver.ccp.datasource.fileparsers.snomed;
import edu.ucdenver.ccp.datasource.fileparsers.SingleLineFileRecord;
/*
* #%L
* Colorado Computational Pharmacology's common module
* %%
* Copyright (C) 2012 - 2015 Regents of the University of Colorado
* %%
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the Regents of the University of Colorado nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
import lombok.Getter;
/**
* @author Center for Computational Pharmacology, UC Denver; ccpsupport@ucdenver.edu
*
*/
@Getter
public class SnomedRf2DescriptionFileRecord extends SingleLineFileRecord {
public enum DescriptionType {
FULLY_SPECIFIED_NAME("900000000000003001"),
SYNONYM("900000000000013009");
private final String typeId;
private DescriptionType(String typeId) {
this.typeId = typeId;
}
public String typeId() {
return typeId;
}
public static DescriptionType getType(String typeId) {
for (DescriptionType type : values()) {
if (type.typeId().equals(typeId)) {
return type;
}
}
throw new IllegalArgumentException("Invalid SnoMed description type id: " + typeId);
}
}
/*
* id effectiveTime active moduleId conceptId languageCode typeId term caseSignificanceId
*/
private final String descriptionId;
private final String effectiveTime;
private final boolean active;
private final String moduleId;
private final String conceptId;
private final String languageCode;
private final DescriptionType type;
private final String term;
private final String caseSignificanceId;
/**
* @param byteOffset
* @param lineNumber
* @param definitionId
* @param effectiveTime
* @param active
* @param moduleId
* @param conceptId
* @param languageCode
* @param typeId
* @param term
* @param caseSignificanceId
*/
public SnomedRf2DescriptionFileRecord(String descriptionId, String effectiveTime, boolean active, String moduleId,
String conceptId, String languageCode, DescriptionType type, String term, String caseSignificanceId,
long byteOffset, long lineNumber) {
super(byteOffset, lineNumber);
this.descriptionId = descriptionId;
this.effectiveTime = effectiveTime;
this.active = active;
this.moduleId = moduleId;
this.conceptId = conceptId;
this.languageCode = languageCode;
this.type = type;
this.term = term;
this.caseSignificanceId = caseSignificanceId;
}
}
| UCDenver-ccp/datasource | datasource-fileparsers/src/main/java/edu/ucdenver/ccp/datasource/fileparsers/snomed/SnomedRf2DescriptionFileRecord.java | Java | bsd-3-clause | 3,805 |
<?php
namespace app\controllers;
use app\models\ContactForm;
use app\models\LoginForm;
use Yii;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use yii\web\Controller;
class SiteController extends Controller
{
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout'],
'rules' => [
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['@'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
public function actionIndex()
{
return $this->render('index');
}
public function actionLogin()
{
if (!\Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
}
return $this->render('login', [
'model' => $model,
]);
}
public function actionLogout()
{
Yii::$app->user->logout();
return $this->goHome();
}
public function actionContact()
{
$model = new ContactForm();
if ($model->load(Yii::$app->request->post()) && $model->contact(Yii::$app->params['adminEmail'])) {
Yii::$app->session->setFlash('contactFormSubmitted');
return $this->refresh();
}
return $this->render('contact', [
'model' => $model,
]);
}
public function actionAbout()
{
return $this->render('about');
}
public function actionLayout()
{
$this->layout = 'frontEnd';
return $this->render('index');
// return $this->render('//order/step1');
}
}
| locnes/monstars | controllers/SiteController.php | PHP | bsd-3-clause | 2,402 |
package com.mattunderscore.trees.base;
import static org.junit.Assert.*;
import static org.mockito.Mockito.verify;
import static org.mockito.MockitoAnnotations.initMocks;
import java.util.Iterator;
import java.util.NoSuchElementException;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import com.mattunderscore.iterators.SingletonIterator;
import com.mattunderscore.trees.mutable.MutableNode;
import com.mattunderscore.trees.tree.Node;
/**
* Unit tests for {@link MutableChildIterator}.
*
* @author Matt Champion on 29/08/2015
*/
public final class MutableChildIteratorTest {
@Mock
private MutableNode<String> parent;
@Mock
private MutableNode<String> child;
private Iterator<? extends MutableNode<String>> iterator;
@Before
public void setUp() {
initMocks(this);
iterator = new SingletonIterator<>(child);
}
@Test
public void hasNext() {
final MutableChildIterator<String, MutableNode<String>> mutableIterator = new MutableChildIterator<>(parent, iterator);
assertTrue(mutableIterator.hasNext());
mutableIterator.next();
assertFalse(mutableIterator.hasNext());
}
@Test(expected = NoSuchElementException.class)
public void next() {
final MutableChildIterator<String, MutableNode<String>> mutableIterator = new MutableChildIterator<>(parent, iterator);
final MutableNode<String> node = mutableIterator.next();
assertSame(child, node);
mutableIterator.next();
}
@Test
public void remove() {
final MutableChildIterator<String, MutableNode<String>> mutableIterator = new MutableChildIterator<>(parent, iterator);
mutableIterator.next();
mutableIterator.remove();
verify(parent).removeChild(child);
}
}
| mattunderscorechampion/tree-root | trees-basic-nodes/src/test/java/com/mattunderscore/trees/base/MutableChildIteratorTest.java | Java | bsd-3-clause | 1,823 |
// Copyright 2004-present Facebook. All Rights Reserved.
#include <vector>
#include <string>
#include <osquery/core.h>
#include <osquery/logger.h>
#include <osquery/tables.h>
#include "osquery/events/linux/udev.h"
namespace osquery {
namespace tables {
/**
* @brief Track udev events in Linux
*/
class HardwareEventSubscriber : public EventSubscriber {
DECLARE_EVENTSUBSCRIBER(HardwareEventSubscriber, UdevEventPublisher);
DECLARE_CALLBACK(Callback, UdevEventContext);
public:
void init();
Status Callback(const UdevEventContextRef ec);
};
REGISTER_EVENTSUBSCRIBER(HardwareEventSubscriber);
void HardwareEventSubscriber::init() {
auto subscription = UdevEventPublisher::createSubscriptionContext();
subscription->action = UDEV_EVENT_ACTION_ALL;
BIND_CALLBACK(Callback, subscription);
}
Status HardwareEventSubscriber::Callback(const UdevEventContextRef ec) {
Row r;
if (ec->devtype.empty()) {
// Superfluous hardware event.
return Status(0, "Missing type.");
} else if (ec->devnode.empty() && ec->driver.empty()) {
return Status(0, "Missing node and driver.");
}
struct udev_device *device = ec->device;
r["action"] = ec->action_string;
r["path"] = ec->devnode;
r["type"] = ec->devtype;
r["driver"] = ec->driver;
// UDEV properties.
r["model"] = UdevEventPublisher::getValue(device, "ID_MODEL_FROM_DATABASE");
if (r["path"].empty() && r["model"].empty()) {
// Don't emit mising path/model combos.
return Status(0, "Missing path and model.");
}
r["model_id"] = INTEGER(UdevEventPublisher::getValue(device, "ID_MODEL_ID"));
r["vendor"] = UdevEventPublisher::getValue(device, "ID_VENDOR_FROM_DATABASE");
r["vendor_id"] =
INTEGER(UdevEventPublisher::getValue(device, "ID_VENDOR_ID"));
r["serial"] =
INTEGER(UdevEventPublisher::getValue(device, "ID_SERIAL_SHORT"));
r["revision"] = INTEGER(UdevEventPublisher::getValue(device, "ID_REVISION"));
r["time"] = INTEGER(ec->time);
add(r, ec->time);
return Status(0, "OK");
}
}
}
| Anubisss/osquery | osquery/tables/events/linux/hardware_events.cpp | C++ | bsd-3-clause | 2,025 |
package com.spm.store;
import java.io.Serializable;
import java.util.List;
import android.content.Context;
/**
*
* @author Agustin Sgarlata
* @param <T>
*/
public class DbProvider<T extends Serializable> extends Db4oHelper {
public Class<T> persistentClass;
public DbProvider(Class<T> persistentClass, Context ctx) {
super(ctx);
this.persistentClass = persistentClass;
}
public void store(T obj) {
db().store(obj);
db().commit();
}
public void delete(T obj) {
db().delete(obj);
db().commit();
}
public List<T> findAll() {
return db().query(persistentClass);
}
public List<T> get(T obj) {
return db().queryByExample(obj);
}
} | mural/spm | SPM/src/main/java/com/spm/store/DbProvider.java | Java | bsd-3-clause | 670 |
package main
/*
* CSCI 4229 Assignment 5: Lighting
*
* Author: Zach Anders
*
* Some code derived from CSCI 4229 Examples 9, 10, and 13 (ex9.c, ex10.c, ex13.c)
*
* Code for 2D text display (due to missing windowpos2i) based off some example code
* at http://programmingexamples.net/wiki/OpenGL/Text
*/
import (
"actor"
"entity"
"math/rand"
"os"
"runtime"
"time"
"glutil"
"util"
"world"
"github.com/go-gl/gl"
"github.com/ianremmler/ode"
"github.com/rhencke/glut"
)
var renderQueue util.RenderQueue = util.NewEmptyRenderQueue()
//var currentCamera = CreateDefaultViewport()
var my_world = world.NewWorld()
var player = actor.NewPlayer(&my_world, glutil.Point3D{0, 0, 0}, 5)
var light actor.OrbitActor
var currentMouse = glutil.CreateMouseState()
// Normal order:
//Translate -> Rotate -> Scale
// Creates the display function
func DisplayFunc() {
gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
gl.Enable(gl.DEPTH_TEST)
gl.LoadIdentity()
// currentCamera.PositionSelf()
player.PositionSelf()
my_world.Tick()
renderQueue.RenderAll()
gl.Disable(gl.DEPTH_TEST)
gl.Disable(gl.LIGHTING)
gl.Color3f(.9, .9, .9)
glutil.Print2d(5, 35, "Keys: W,S,A,D : Move Around | Q / E : Move Light left/right | L : Toggle light rotation")
glutil.Print2d(5, 20, "Click and Drag: Rotate | Arrow keys: Rotate")
glutil.Print2d(5, 5, "%s", player.ToString())
gl.Flush()
glut.SwapBuffers()
}
// Creates the key handler function
func KeyDownFunc(ch byte, x int, y int) {
switch ch {
case 27:
os.Exit(0)
break
case 's':
player.Translate(-2.5, 0.0, 0.0)
break
case 'w':
player.Translate(2.5, 0.0, 0.0)
break
case 'd':
player.Translate(0.0, 0.0, -2.5)
break
case 'a':
player.Translate(0.0, 0.0, 2.5)
break
case 'q':
light.AdjustAngle(-5)
break
case 'e':
light.AdjustAngle(5)
break
case 'l':
light.Toggle()
break
}
glut.PostRedisplay()
}
// Creates the special key handler function
func SpecialFunc(key int, x int, y int) {
// Phi: Elevation, Theta: Azimuth
if key == glut.KEY_RIGHT {
player.Rotate(10, 0)
} else if key == glut.KEY_LEFT {
player.Rotate(-10, 0)
} else if key == glut.KEY_UP {
player.Rotate(0, 10)
} else if key == glut.KEY_DOWN {
player.Rotate(0, -10)
}
// Tell GLUT it is necessary to redisplay the scene
glut.PostRedisplay()
}
func MouseMotion(x, y int) {
if currentMouse.LeftDown {
horiz_delta := currentMouse.X - x
vert_delta := currentMouse.Y - y
player.Rotate(int32(horiz_delta)/-5, int32(vert_delta)/5)
player.ImmediateLook()
}
currentMouse.X, currentMouse.Y = x, y
}
func MouseDown(button, state, x, y int) {
currentMouse.X, currentMouse.Y = x, y
switch button {
case glut.LEFT_BUTTON:
currentMouse.LeftDown = (state == glut.DOWN)
break
case glut.MIDDLE_BUTTON:
currentMouse.MiddleDown = (state == glut.DOWN)
break
case glut.RIGHT_BUTTON:
currentMouse.RightDown = (state == glut.DOWN)
break
}
}
/*
* GLUT calls this routine when the window is resized
*/
func Reshape(width int, height int) {
asp := float64(1)
// Ratio of the width to the height of the window
if height > 0 {
asp = float64(width) / float64(height)
}
// Set the viewport to the entire window
gl.Viewport(0, 0, width, height)
player.GetProjection().AspectRatio = asp
player.GetProjection().SetProjectionMatrix()
}
// Idler function. Called whenever GLUT is idle.
func IdleFunc() {
s_time := glut.Get(glut.ELAPSED_TIME)
glut.PostRedisplay()
e_time := glut.Get(glut.ELAPSED_TIME) - s_time
if e_time < 33 {
time.Sleep(time.Duration(33-e_time) * time.Millisecond)
}
}
func setup() {
lightsource := actor.NewBallLight(&my_world, glutil.Point3D{15, 15, 15})
renderQueue.AddNamed(&lightsource, "light")
light = actor.NewOrbitActor(&my_world, &lightsource, glutil.Point3D{0, 15, 0}, 50)
my_world.AddActor(&light)
rand.Seed(0x12345 + 8)
my_world.AddActor(&player)
block := actor.NewBlock(&my_world, glutil.Point3D{22, 0, 0}, glutil.Point3D{10, 20.5, 20}, glutil.Color4D{.5, .3, .1, 1})
my_world.AddActor(&block)
renderQueue.Add(&block)
tmpList := []actor.OrbitActor{}
for i := 0; i < 250; i++ {
speed := rand.Intn(3)
//radius := rand.Intn(50) + 125
radius := 100
x, y, z := float64(rand.Intn(10)-5), float64(rand.Intn(10)-5), float64(rand.Intn(150)-75)
angle := float64(rand.Intn(360))
//cylinder := NewCylinder(&my_world, glutil.Point3D{x, y + 30, z}, 1, 4)
cylinder := actor.NewBlock(&my_world, glutil.Point3D{x, y + 30, z}, glutil.Point3D{.1, .1, .1}, glutil.Color4D{.8, .8, .8, .05})
tmpList = append(tmpList, actor.NewOrbitActor(&my_world, &cylinder, glutil.Point3D{x, y + 0, z}, float64(radius)))
tmpList[i].SetSpeed(int32(speed))
tmpList[i].SetAngle(int32(angle))
tmpList[i].SetAxis(glutil.Point3D{0, 0, 1})
renderQueue.Add(&cylinder)
my_world.AddActor(&tmpList[i])
}
// Create castle
//myCastle := NewCastle()
//renderQueue.AddNamed(&myCastle, "castle")
// Create ground
ground := entity.NewXYPlane(glutil.Point3D{100, 0, 100}, glutil.Point3D{-100, 0, -100}, 0)
ground.SetColor(glutil.Color4D{0.4313725490 * .7, 0.24705882 * .7, 0.098039215 * .7, 1})
ground.SetPolygonOffset(1.0)
renderQueue.Add(&ground)
my_world.AddEntity(&ground.Box)
stairs := actor.NewStairs(&my_world, glutil.Point3D{0, 0, 0})
renderQueue.Add(&stairs)
scale := float64(200)
for i := 0; i < 100; i++ {
x := (rand.Float64() * scale) - (scale / 2)
z := (rand.Float64() * scale) - (scale / 2)
x_scale, z_scale := (rand.Float64()/2)+.75, (rand.Float64()/2)+.75
y_scale := (rand.Float64() * 1) + .75
if (x < -5 || x > 20) && (z < -5 || z > 20) {
tree1 := entity.NewTree(glutil.Point3D{x, 0, z}, x_scale, y_scale, z_scale)
renderQueue.Add(&tree1)
}
}
// Put camera somewhere
//currentCamera.Translate(5, -5, 28)
player.Translate(10, 0, -20)
player.ImmediateJump() // Skip interpolation
player.Rotate(-120, 0)
player.ImmediateLook() // Skip interpolation
}
func main() {
// Let go use 2 threads
runtime.GOMAXPROCS(2)
// Init
glut.InitDisplayMode(glut.RGB | glut.DOUBLE | glut.DEPTH)
glut.InitWindowSize(750, 750)
glut.CreateWindow("Zach Anders - Assignment 5")
setup()
// Display Callbacks
glut.DisplayFunc(DisplayFunc)
glut.IdleFunc(IdleFunc)
glut.ReshapeFunc(Reshape)
// Input Callbacks
glut.SpecialFunc(SpecialFunc)
glut.KeyboardFunc(KeyDownFunc)
glut.MotionFunc(MouseMotion)
glut.MouseFunc(MouseDown)
glut.MainLoop()
}
| ZachAnders/Graphics_HW5_lighting | src/main/scene_main.go | GO | bsd-3-clause | 6,411 |
from django import forms
from ncdjango.interfaces.arcgis.form_fields import SrField
class PointForm(forms.Form):
x = forms.FloatField()
y = forms.FloatField()
projection = SrField() | consbio/ncdjango | ncdjango/interfaces/data/forms.py | Python | bsd-3-clause | 195 |
<?
$this->title = Yii::t("UserModule.user", 'Create profile field');
$this->breadcrumbs=array(
Yii::t("UserModule.user", 'Profile fields')=>array('admin'),
Yii::t("UserModule.user", 'Create'));
?>
<?php echo $this->renderPartial('_form', array('model'=>$model)); ?>
| stsoft/printable | protected/modules/profile/views/fields/create.php | PHP | bsd-3-clause | 270 |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2015, Alcatel-Lucent Inc, 2017 Nokia
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from .fetchers import NUPermissionsFetcher
from .fetchers import NUMetadatasFetcher
from .fetchers import NUGlobalMetadatasFetcher
from bambou import NURESTObject
class NUAvatar(NURESTObject):
""" Represents a Avatar in the VSD
Notes:
Avatar
"""
__rest_name__ = "avatar"
__resource_name__ = "avatars"
## Constants
CONST_ENTITY_SCOPE_GLOBAL = "GLOBAL"
CONST_ENTITY_SCOPE_ENTERPRISE = "ENTERPRISE"
def __init__(self, **kwargs):
""" Initializes a Avatar instance
Notes:
You can specify all parameters while calling this methods.
A special argument named `data` will enable you to load the
object from a Python dictionary
Examples:
>>> avatar = NUAvatar(id=u'xxxx-xxx-xxx-xxx', name=u'Avatar')
>>> avatar = NUAvatar(data=my_dict)
"""
super(NUAvatar, self).__init__()
# Read/Write Attributes
self._last_updated_by = None
self._last_updated_date = None
self._embedded_metadata = None
self._entity_scope = None
self._creation_date = None
self._owner = None
self._external_id = None
self._type = None
self.expose_attribute(local_name="last_updated_by", remote_name="lastUpdatedBy", attribute_type=str, is_required=False, is_unique=False)
self.expose_attribute(local_name="last_updated_date", remote_name="lastUpdatedDate", attribute_type=str, is_required=False, is_unique=False)
self.expose_attribute(local_name="embedded_metadata", remote_name="embeddedMetadata", attribute_type=list, is_required=False, is_unique=False)
self.expose_attribute(local_name="entity_scope", remote_name="entityScope", attribute_type=str, is_required=False, is_unique=False, choices=[u'ENTERPRISE', u'GLOBAL'])
self.expose_attribute(local_name="creation_date", remote_name="creationDate", attribute_type=str, is_required=False, is_unique=False)
self.expose_attribute(local_name="owner", remote_name="owner", attribute_type=str, is_required=False, is_unique=False)
self.expose_attribute(local_name="external_id", remote_name="externalID", attribute_type=str, is_required=False, is_unique=True)
self.expose_attribute(local_name="type", remote_name="type", attribute_type=str, is_required=False, is_unique=False)
# Fetchers
self.permissions = NUPermissionsFetcher.fetcher_with_object(parent_object=self, relationship="child")
self.metadatas = NUMetadatasFetcher.fetcher_with_object(parent_object=self, relationship="child")
self.global_metadatas = NUGlobalMetadatasFetcher.fetcher_with_object(parent_object=self, relationship="child")
self._compute_args(**kwargs)
# Properties
@property
def last_updated_by(self):
""" Get last_updated_by value.
Notes:
ID of the user who last updated the object.
This attribute is named `lastUpdatedBy` in VSD API.
"""
return self._last_updated_by
@last_updated_by.setter
def last_updated_by(self, value):
""" Set last_updated_by value.
Notes:
ID of the user who last updated the object.
This attribute is named `lastUpdatedBy` in VSD API.
"""
self._last_updated_by = value
@property
def last_updated_date(self):
""" Get last_updated_date value.
Notes:
Time stamp when this object was last updated.
This attribute is named `lastUpdatedDate` in VSD API.
"""
return self._last_updated_date
@last_updated_date.setter
def last_updated_date(self, value):
""" Set last_updated_date value.
Notes:
Time stamp when this object was last updated.
This attribute is named `lastUpdatedDate` in VSD API.
"""
self._last_updated_date = value
@property
def embedded_metadata(self):
""" Get embedded_metadata value.
Notes:
Metadata objects associated with this entity. This will contain a list of Metadata objects if the API request is made using the special flag to enable the embedded Metadata feature. Only a maximum of Metadata objects is returned based on the value set in the system configuration.
This attribute is named `embeddedMetadata` in VSD API.
"""
return self._embedded_metadata
@embedded_metadata.setter
def embedded_metadata(self, value):
""" Set embedded_metadata value.
Notes:
Metadata objects associated with this entity. This will contain a list of Metadata objects if the API request is made using the special flag to enable the embedded Metadata feature. Only a maximum of Metadata objects is returned based on the value set in the system configuration.
This attribute is named `embeddedMetadata` in VSD API.
"""
self._embedded_metadata = value
@property
def entity_scope(self):
""" Get entity_scope value.
Notes:
Specify if scope of entity is Data center or Enterprise level
This attribute is named `entityScope` in VSD API.
"""
return self._entity_scope
@entity_scope.setter
def entity_scope(self, value):
""" Set entity_scope value.
Notes:
Specify if scope of entity is Data center or Enterprise level
This attribute is named `entityScope` in VSD API.
"""
self._entity_scope = value
@property
def creation_date(self):
""" Get creation_date value.
Notes:
Time stamp when this object was created.
This attribute is named `creationDate` in VSD API.
"""
return self._creation_date
@creation_date.setter
def creation_date(self, value):
""" Set creation_date value.
Notes:
Time stamp when this object was created.
This attribute is named `creationDate` in VSD API.
"""
self._creation_date = value
@property
def owner(self):
""" Get owner value.
Notes:
Identifies the user that has created this object.
"""
return self._owner
@owner.setter
def owner(self, value):
""" Set owner value.
Notes:
Identifies the user that has created this object.
"""
self._owner = value
@property
def external_id(self):
""" Get external_id value.
Notes:
External object ID. Used for integration with third party systems
This attribute is named `externalID` in VSD API.
"""
return self._external_id
@external_id.setter
def external_id(self, value):
""" Set external_id value.
Notes:
External object ID. Used for integration with third party systems
This attribute is named `externalID` in VSD API.
"""
self._external_id = value
@property
def type(self):
""" Get type value.
Notes:
The image type
"""
return self._type
@type.setter
def type(self, value):
""" Set type value.
Notes:
The image type
"""
self._type = value
| nuagenetworks/vspk-python | vspk/v6/nuavatar.py | Python | bsd-3-clause | 9,831 |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//------------------------------------------------------------------------------
// Description of the life cycle of a instance of MetricsService.
//
// OVERVIEW
//
// A MetricsService instance is typically created at application startup. It is
// the central controller for the acquisition of log data, and the automatic
// transmission of that log data to an external server. Its major job is to
// manage logs, grouping them for transmission, and transmitting them. As part
// of its grouping, MS finalizes logs by including some just-in-time gathered
// memory statistics, snapshotting the current stats of numerous histograms,
// closing the logs, translating to protocol buffer format, and compressing the
// results for transmission. Transmission includes submitting a compressed log
// as data in a URL-post, and retransmitting (or retaining at process
// termination) if the attempted transmission failed. Retention across process
// terminations is done using the the PrefServices facilities. The retained logs
// (the ones that never got transmitted) are compressed and base64-encoded
// before being persisted.
//
// Logs fall into one of two categories: "initial logs," and "ongoing logs."
// There is at most one initial log sent for each complete run of Chrome (from
// startup, to browser shutdown). An initial log is generally transmitted some
// short time (1 minute?) after startup, and includes stats such as recent crash
// info, the number and types of plugins, etc. The external server's response
// to the initial log conceptually tells this MS if it should continue
// transmitting logs (during this session). The server response can actually be
// much more detailed, and always includes (at a minimum) how often additional
// ongoing logs should be sent.
//
// After the above initial log, a series of ongoing logs will be transmitted.
// The first ongoing log actually begins to accumulate information stating when
// the MS was first constructed. Note that even though the initial log is
// commonly sent a full minute after startup, the initial log does not include
// much in the way of user stats. The most common interlog period (delay)
// is 30 minutes. That time period starts when the first user action causes a
// logging event. This means that if there is no user action, there may be long
// periods without any (ongoing) log transmissions. Ongoing logs typically
// contain very detailed records of user activities (ex: opened tab, closed
// tab, fetched URL, maximized window, etc.) In addition, just before an
// ongoing log is closed out, a call is made to gather memory statistics. Those
// memory statistics are deposited into a histogram, and the log finalization
// code is then called. In the finalization, a call to a Histogram server
// acquires a list of all local histograms that have been flagged for upload
// to the UMA server. The finalization also acquires the most recent number
// of page loads, along with any counts of renderer or plugin crashes.
//
// When the browser shuts down, there will typically be a fragment of an ongoing
// log that has not yet been transmitted. At shutdown time, that fragment is
// closed (including snapshotting histograms), and persisted, for potential
// transmission during a future run of the product.
//
// There are two slightly abnormal shutdown conditions. There is a
// "disconnected scenario," and a "really fast startup and shutdown" scenario.
// In the "never connected" situation, the user has (during the running of the
// process) never established an internet connection. As a result, attempts to
// transmit the initial log have failed, and a lot(?) of data has accumulated in
// the ongoing log (which didn't yet get closed, because there was never even a
// contemplation of sending it). There is also a kindred "lost connection"
// situation, where a loss of connection prevented an ongoing log from being
// transmitted, and a (still open) log was stuck accumulating a lot(?) of data,
// while the earlier log retried its transmission. In both of these
// disconnected situations, two logs need to be, and are, persistently stored
// for future transmission.
//
// The other unusual shutdown condition, termed "really fast startup and
// shutdown," involves the deliberate user termination of the process before
// the initial log is even formed or transmitted. In that situation, no logging
// is done, but the historical crash statistics remain (unlogged) for inclusion
// in a future run's initial log. (i.e., we don't lose crash stats).
//
// With the above overview, we can now describe the state machine's various
// states, based on the State enum specified in the state_ member. Those states
// are:
//
// INITIALIZED, // Constructor was called.
// INIT_TASK_SCHEDULED, // Waiting for deferred init tasks to finish.
// INIT_TASK_DONE, // Waiting for timer to send initial log.
// SENDING_LOGS, // Sending logs and creating new ones when we run out.
//
// In more detail, we have:
//
// INITIALIZED, // Constructor was called.
// The MS has been constructed, but has taken no actions to compose the
// initial log.
//
// INIT_TASK_SCHEDULED, // Waiting for deferred init tasks to finish.
// Typically about 30 seconds after startup, a task is sent to a second thread
// (the file thread) to perform deferred (lower priority and slower)
// initialization steps such as getting the list of plugins. That task will
// (when complete) make an async callback (via a Task) to indicate the
// completion.
//
// INIT_TASK_DONE, // Waiting for timer to send initial log.
// The callback has arrived, and it is now possible for an initial log to be
// created. This callback typically arrives back less than one second after
// the deferred init task is dispatched.
//
// SENDING_LOGS, // Sending logs an creating new ones when we run out.
// Logs from previous sessions have been loaded, and initial logs have been
// created (an optional stability log and the first metrics log). We will
// send all of these logs, and when run out, we will start cutting new logs
// to send. We will also cut a new log if we expect a shutdown.
//
// The progression through the above states is simple, and sequential.
// States proceed from INITIAL to SENDING_LOGS, and remain in the latter until
// shutdown.
//
// Also note that whenever we successfully send a log, we mirror the list
// of logs into the PrefService. This ensures that IF we crash, we won't start
// up and retransmit our old logs again.
//
// Due to race conditions, it is always possible that a log file could be sent
// twice. For example, if a log file is sent, but not yet acknowledged by
// the external server, and the user shuts down, then a copy of the log may be
// saved for re-transmission. These duplicates could be filtered out server
// side, but are not expected to be a significant problem.
//
//
//------------------------------------------------------------------------------
#include "components/metrics/metrics_service.h"
#include <algorithm>
#include "base/bind.h"
#include "base/callback.h"
#include "base/metrics/histogram.h"
#include "base/metrics/histogram_base.h"
#include "base/metrics/histogram_samples.h"
#include "base/metrics/sparse_histogram.h"
#include "base/metrics/statistics_recorder.h"
#include "base/prefs/pref_registry_simple.h"
#include "base/prefs/pref_service.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/platform_thread.h"
#include "base/threading/thread.h"
#include "base/threading/thread_restrictions.h"
#include "base/time/time.h"
#include "base/tracked_objects.h"
#include "base/values.h"
#include "components/metrics/metrics_log.h"
#include "components/metrics/metrics_log_manager.h"
#include "components/metrics/metrics_log_uploader.h"
#include "components/metrics/metrics_pref_names.h"
#include "components/metrics/metrics_reporting_scheduler.h"
#include "components/metrics/metrics_service_client.h"
#include "components/metrics/metrics_state_manager.h"
#include "components/variations/entropy_provider.h"
namespace metrics {
namespace {
// Check to see that we're being called on only one thread.
bool IsSingleThreaded() {
static base::PlatformThreadId thread_id = 0;
if (!thread_id)
thread_id = base::PlatformThread::CurrentId();
return base::PlatformThread::CurrentId() == thread_id;
}
// The delay, in seconds, after starting recording before doing expensive
// initialization work.
#if defined(OS_ANDROID) || defined(OS_IOS)
// On mobile devices, a significant portion of sessions last less than a minute.
// Use a shorter timer on these platforms to avoid losing data.
// TODO(dfalcantara): To avoid delaying startup, tighten up initialization so
// that it occurs after the user gets their initial page.
const int kInitializationDelaySeconds = 5;
#else
const int kInitializationDelaySeconds = 30;
#endif
// The maximum number of events in a log uploaded to the UMA server.
const int kEventLimit = 2400;
// If an upload fails, and the transmission was over this byte count, then we
// will discard the log, and not try to retransmit it. We also don't persist
// the log to the prefs for transmission during the next chrome session if this
// limit is exceeded.
const size_t kUploadLogAvoidRetransmitSize = 100 * 1024;
// Interval, in minutes, between state saves.
const int kSaveStateIntervalMinutes = 5;
enum ResponseStatus {
UNKNOWN_FAILURE,
SUCCESS,
BAD_REQUEST, // Invalid syntax or log too large.
NO_RESPONSE,
NUM_RESPONSE_STATUSES
};
ResponseStatus ResponseCodeToStatus(int response_code) {
switch (response_code) {
case -1:
return NO_RESPONSE;
case 200:
return SUCCESS;
case 400:
return BAD_REQUEST;
default:
return UNKNOWN_FAILURE;
}
}
#if defined(OS_ANDROID) || defined(OS_IOS)
void MarkAppCleanShutdownAndCommit(CleanExitBeacon* clean_exit_beacon,
PrefService* local_state) {
clean_exit_beacon->WriteBeaconValue(true);
local_state->SetInteger(prefs::kStabilityExecutionPhase,
MetricsService::SHUTDOWN_COMPLETE);
// Start writing right away (write happens on a different thread).
local_state->CommitPendingWrite();
}
#endif // defined(OS_ANDROID) || defined(OS_IOS)
} // namespace
SyntheticTrialGroup::SyntheticTrialGroup(uint32 trial, uint32 group) {
id.name = trial;
id.group = group;
}
SyntheticTrialGroup::~SyntheticTrialGroup() {
}
// static
MetricsService::ShutdownCleanliness MetricsService::clean_shutdown_status_ =
MetricsService::CLEANLY_SHUTDOWN;
MetricsService::ExecutionPhase MetricsService::execution_phase_ =
MetricsService::UNINITIALIZED_PHASE;
// static
void MetricsService::RegisterPrefs(PrefRegistrySimple* registry) {
DCHECK(IsSingleThreaded());
MetricsStateManager::RegisterPrefs(registry);
MetricsLog::RegisterPrefs(registry);
registry->RegisterInt64Pref(prefs::kInstallDate, 0);
registry->RegisterInt64Pref(prefs::kStabilityLaunchTimeSec, 0);
registry->RegisterInt64Pref(prefs::kStabilityLastTimestampSec, 0);
registry->RegisterStringPref(prefs::kStabilityStatsVersion, std::string());
registry->RegisterInt64Pref(prefs::kStabilityStatsBuildTime, 0);
registry->RegisterBooleanPref(prefs::kStabilityExitedCleanly, true);
registry->RegisterIntegerPref(prefs::kStabilityExecutionPhase,
UNINITIALIZED_PHASE);
registry->RegisterBooleanPref(prefs::kStabilitySessionEndCompleted, true);
registry->RegisterIntegerPref(prefs::kMetricsSessionID, -1);
registry->RegisterListPref(prefs::kMetricsInitialLogs);
registry->RegisterListPref(prefs::kMetricsOngoingLogs);
registry->RegisterInt64Pref(prefs::kUninstallLaunchCount, 0);
registry->RegisterInt64Pref(prefs::kUninstallMetricsUptimeSec, 0);
}
MetricsService::MetricsService(MetricsStateManager* state_manager,
MetricsServiceClient* client,
PrefService* local_state)
: log_manager_(local_state, kUploadLogAvoidRetransmitSize),
histogram_snapshot_manager_(this),
state_manager_(state_manager),
client_(client),
local_state_(local_state),
clean_exit_beacon_(client->GetRegistryBackupKey(), local_state),
recording_active_(false),
reporting_active_(false),
test_mode_active_(false),
state_(INITIALIZED),
log_upload_in_progress_(false),
idle_since_last_transmission_(false),
session_id_(-1),
self_ptr_factory_(this),
state_saver_factory_(this) {
DCHECK(IsSingleThreaded());
DCHECK(state_manager_);
DCHECK(client_);
DCHECK(local_state_);
// Set the install date if this is our first run.
int64 install_date = local_state_->GetInt64(prefs::kInstallDate);
if (install_date == 0)
local_state_->SetInt64(prefs::kInstallDate, base::Time::Now().ToTimeT());
}
MetricsService::~MetricsService() {
DisableRecording();
}
void MetricsService::InitializeMetricsRecordingState() {
InitializeMetricsState();
base::Closure upload_callback =
base::Bind(&MetricsService::StartScheduledUpload,
self_ptr_factory_.GetWeakPtr());
scheduler_.reset(
new MetricsReportingScheduler(
upload_callback,
// MetricsServiceClient outlives MetricsService, and
// MetricsReportingScheduler is tied to the lifetime of |this|.
base::Bind(&MetricsServiceClient::GetStandardUploadInterval,
base::Unretained(client_))));
}
void MetricsService::Start() {
HandleIdleSinceLastTransmission(false);
EnableRecording();
EnableReporting();
}
bool MetricsService::StartIfMetricsReportingEnabled() {
const bool enabled = state_manager_->IsMetricsReportingEnabled();
if (enabled)
Start();
return enabled;
}
void MetricsService::StartRecordingForTests() {
test_mode_active_ = true;
EnableRecording();
DisableReporting();
}
void MetricsService::Stop() {
HandleIdleSinceLastTransmission(false);
DisableReporting();
DisableRecording();
}
void MetricsService::EnableReporting() {
if (reporting_active_)
return;
reporting_active_ = true;
StartSchedulerIfNecessary();
}
void MetricsService::DisableReporting() {
reporting_active_ = false;
}
std::string MetricsService::GetClientId() {
return state_manager_->client_id();
}
int64 MetricsService::GetInstallDate() {
return local_state_->GetInt64(prefs::kInstallDate);
}
int64 MetricsService::GetMetricsReportingEnabledDate() {
return local_state_->GetInt64(prefs::kMetricsReportingEnabledTimestamp);
}
scoped_ptr<const base::FieldTrial::EntropyProvider>
MetricsService::CreateEntropyProvider() {
// TODO(asvitkine): Refactor the code so that MetricsService does not expose
// this method.
return state_manager_->CreateEntropyProvider();
}
void MetricsService::EnableRecording() {
DCHECK(IsSingleThreaded());
if (recording_active_)
return;
recording_active_ = true;
state_manager_->ForceClientIdCreation();
client_->SetMetricsClientId(state_manager_->client_id());
if (!log_manager_.current_log())
OpenNewLog();
for (size_t i = 0; i < metrics_providers_.size(); ++i)
metrics_providers_[i]->OnRecordingEnabled();
base::RemoveActionCallback(action_callback_);
action_callback_ = base::Bind(&MetricsService::OnUserAction,
base::Unretained(this));
base::AddActionCallback(action_callback_);
}
void MetricsService::DisableRecording() {
DCHECK(IsSingleThreaded());
if (!recording_active_)
return;
recording_active_ = false;
client_->OnRecordingDisabled();
base::RemoveActionCallback(action_callback_);
for (size_t i = 0; i < metrics_providers_.size(); ++i)
metrics_providers_[i]->OnRecordingDisabled();
PushPendingLogsToPersistentStorage();
}
bool MetricsService::recording_active() const {
DCHECK(IsSingleThreaded());
return recording_active_;
}
bool MetricsService::reporting_active() const {
DCHECK(IsSingleThreaded());
return reporting_active_;
}
void MetricsService::RecordDelta(const base::HistogramBase& histogram,
const base::HistogramSamples& snapshot) {
log_manager_.current_log()->RecordHistogramDelta(histogram.histogram_name(),
snapshot);
}
void MetricsService::InconsistencyDetected(
base::HistogramBase::Inconsistency problem) {
UMA_HISTOGRAM_ENUMERATION("Histogram.InconsistenciesBrowser",
problem, base::HistogramBase::NEVER_EXCEEDED_VALUE);
}
void MetricsService::UniqueInconsistencyDetected(
base::HistogramBase::Inconsistency problem) {
UMA_HISTOGRAM_ENUMERATION("Histogram.InconsistenciesBrowserUnique",
problem, base::HistogramBase::NEVER_EXCEEDED_VALUE);
}
void MetricsService::InconsistencyDetectedInLoggedCount(int amount) {
UMA_HISTOGRAM_COUNTS("Histogram.InconsistentSnapshotBrowser",
std::abs(amount));
}
void MetricsService::HandleIdleSinceLastTransmission(bool in_idle) {
// If there wasn't a lot of action, maybe the computer was asleep, in which
// case, the log transmissions should have stopped. Here we start them up
// again.
if (!in_idle && idle_since_last_transmission_)
StartSchedulerIfNecessary();
idle_since_last_transmission_ = in_idle;
}
void MetricsService::OnApplicationNotIdle() {
if (recording_active_)
HandleIdleSinceLastTransmission(false);
}
void MetricsService::RecordStartOfSessionEnd() {
LogCleanShutdown();
RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, false);
}
void MetricsService::RecordCompletedSessionEnd() {
LogCleanShutdown();
RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, true);
}
#if defined(OS_ANDROID) || defined(OS_IOS)
void MetricsService::OnAppEnterBackground() {
scheduler_->Stop();
MarkAppCleanShutdownAndCommit(&clean_exit_beacon_, local_state_);
// At this point, there's no way of knowing when the process will be
// killed, so this has to be treated similar to a shutdown, closing and
// persisting all logs. Unlinke a shutdown, the state is primed to be ready
// to continue logging and uploading if the process does return.
if (recording_active() && state_ >= SENDING_LOGS) {
PushPendingLogsToPersistentStorage();
// Persisting logs closes the current log, so start recording a new log
// immediately to capture any background work that might be done before the
// process is killed.
OpenNewLog();
}
}
void MetricsService::OnAppEnterForeground() {
clean_exit_beacon_.WriteBeaconValue(false);
StartSchedulerIfNecessary();
}
#else
void MetricsService::LogNeedForCleanShutdown() {
clean_exit_beacon_.WriteBeaconValue(false);
// Redundant setting to be sure we call for a clean shutdown.
clean_shutdown_status_ = NEED_TO_SHUTDOWN;
}
#endif // defined(OS_ANDROID) || defined(OS_IOS)
// static
void MetricsService::SetExecutionPhase(ExecutionPhase execution_phase,
PrefService* local_state) {
execution_phase_ = execution_phase;
local_state->SetInteger(prefs::kStabilityExecutionPhase, execution_phase_);
}
void MetricsService::RecordBreakpadRegistration(bool success) {
if (!success)
IncrementPrefValue(prefs::kStabilityBreakpadRegistrationFail);
else
IncrementPrefValue(prefs::kStabilityBreakpadRegistrationSuccess);
}
void MetricsService::RecordBreakpadHasDebugger(bool has_debugger) {
if (!has_debugger)
IncrementPrefValue(prefs::kStabilityDebuggerNotPresent);
else
IncrementPrefValue(prefs::kStabilityDebuggerPresent);
}
void MetricsService::ClearSavedStabilityMetrics() {
for (size_t i = 0; i < metrics_providers_.size(); ++i)
metrics_providers_[i]->ClearSavedStabilityMetrics();
// Reset the prefs that are managed by MetricsService/MetricsLog directly.
local_state_->SetInteger(prefs::kStabilityCrashCount, 0);
local_state_->SetInteger(prefs::kStabilityExecutionPhase,
UNINITIALIZED_PHASE);
local_state_->SetInteger(prefs::kStabilityIncompleteSessionEndCount, 0);
local_state_->SetInteger(prefs::kStabilityLaunchCount, 0);
local_state_->SetBoolean(prefs::kStabilitySessionEndCompleted, true);
}
void MetricsService::PushExternalLog(const std::string& log) {
log_manager_.StoreLog(log, MetricsLog::ONGOING_LOG);
}
//------------------------------------------------------------------------------
// private methods
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Initialization methods
void MetricsService::InitializeMetricsState() {
const int64 buildtime = MetricsLog::GetBuildTime();
const std::string version = client_->GetVersionString();
bool version_changed = false;
if (local_state_->GetInt64(prefs::kStabilityStatsBuildTime) != buildtime ||
local_state_->GetString(prefs::kStabilityStatsVersion) != version) {
local_state_->SetString(prefs::kStabilityStatsVersion, version);
local_state_->SetInt64(prefs::kStabilityStatsBuildTime, buildtime);
version_changed = true;
}
log_manager_.LoadPersistedUnsentLogs();
session_id_ = local_state_->GetInteger(prefs::kMetricsSessionID);
if (!clean_exit_beacon_.exited_cleanly()) {
IncrementPrefValue(prefs::kStabilityCrashCount);
// Reset flag, and wait until we call LogNeedForCleanShutdown() before
// monitoring.
clean_exit_beacon_.WriteBeaconValue(true);
}
bool has_initial_stability_log = false;
if (!clean_exit_beacon_.exited_cleanly() || ProvidersHaveStabilityMetrics()) {
// TODO(rtenneti): On windows, consider saving/getting execution_phase from
// the registry.
int execution_phase =
local_state_->GetInteger(prefs::kStabilityExecutionPhase);
UMA_HISTOGRAM_SPARSE_SLOWLY("Chrome.Browser.CrashedExecutionPhase",
execution_phase);
// If the previous session didn't exit cleanly, or if any provider
// explicitly requests it, prepare an initial stability log -
// provided UMA is enabled.
if (state_manager_->IsMetricsReportingEnabled())
has_initial_stability_log = PrepareInitialStabilityLog();
}
// If no initial stability log was generated and there was a version upgrade,
// clear the stability stats from the previous version (so that they don't get
// attributed to the current version). This could otherwise happen due to a
// number of different edge cases, such as if the last version crashed before
// it could save off a system profile or if UMA reporting is disabled (which
// normally results in stats being accumulated).
if (!has_initial_stability_log && version_changed)
ClearSavedStabilityMetrics();
// Update session ID.
++session_id_;
local_state_->SetInteger(prefs::kMetricsSessionID, session_id_);
// Stability bookkeeping
IncrementPrefValue(prefs::kStabilityLaunchCount);
DCHECK_EQ(UNINITIALIZED_PHASE, execution_phase_);
SetExecutionPhase(START_METRICS_RECORDING, local_state_);
if (!local_state_->GetBoolean(prefs::kStabilitySessionEndCompleted)) {
IncrementPrefValue(prefs::kStabilityIncompleteSessionEndCount);
// This is marked false when we get a WM_ENDSESSION.
local_state_->SetBoolean(prefs::kStabilitySessionEndCompleted, true);
}
// Call GetUptimes() for the first time, thus allowing all later calls
// to record incremental uptimes accurately.
base::TimeDelta ignored_uptime_parameter;
base::TimeDelta startup_uptime;
GetUptimes(local_state_, &startup_uptime, &ignored_uptime_parameter);
DCHECK_EQ(0, startup_uptime.InMicroseconds());
// For backwards compatibility, leave this intact in case Omaha is checking
// them. prefs::kStabilityLastTimestampSec may also be useless now.
// TODO(jar): Delete these if they have no uses.
local_state_->SetInt64(prefs::kStabilityLaunchTimeSec,
base::Time::Now().ToTimeT());
// Bookkeeping for the uninstall metrics.
IncrementLongPrefsValue(prefs::kUninstallLaunchCount);
// Kick off the process of saving the state (so the uptime numbers keep
// getting updated) every n minutes.
ScheduleNextStateSave();
}
void MetricsService::OnUserAction(const std::string& action) {
if (!ShouldLogEvents())
return;
log_manager_.current_log()->RecordUserAction(action);
HandleIdleSinceLastTransmission(false);
}
void MetricsService::FinishedGatheringInitialMetrics() {
DCHECK_EQ(INIT_TASK_SCHEDULED, state_);
state_ = INIT_TASK_DONE;
// Create the initial log.
if (!initial_metrics_log_.get()) {
initial_metrics_log_ = CreateLog(MetricsLog::ONGOING_LOG);
NotifyOnDidCreateMetricsLog();
}
scheduler_->InitTaskComplete();
}
void MetricsService::GetUptimes(PrefService* pref,
base::TimeDelta* incremental_uptime,
base::TimeDelta* uptime) {
base::TimeTicks now = base::TimeTicks::Now();
// If this is the first call, init |first_updated_time_| and
// |last_updated_time_|.
if (last_updated_time_.is_null()) {
first_updated_time_ = now;
last_updated_time_ = now;
}
*incremental_uptime = now - last_updated_time_;
*uptime = now - first_updated_time_;
last_updated_time_ = now;
const int64 incremental_time_secs = incremental_uptime->InSeconds();
if (incremental_time_secs > 0) {
int64 metrics_uptime = pref->GetInt64(prefs::kUninstallMetricsUptimeSec);
metrics_uptime += incremental_time_secs;
pref->SetInt64(prefs::kUninstallMetricsUptimeSec, metrics_uptime);
}
}
void MetricsService::NotifyOnDidCreateMetricsLog() {
DCHECK(IsSingleThreaded());
for (size_t i = 0; i < metrics_providers_.size(); ++i)
metrics_providers_[i]->OnDidCreateMetricsLog();
}
//------------------------------------------------------------------------------
// State save methods
void MetricsService::ScheduleNextStateSave() {
state_saver_factory_.InvalidateWeakPtrs();
base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
base::Bind(&MetricsService::SaveLocalState,
state_saver_factory_.GetWeakPtr()),
base::TimeDelta::FromMinutes(kSaveStateIntervalMinutes));
}
void MetricsService::SaveLocalState() {
RecordCurrentState(local_state_);
// TODO(jar):110021 Does this run down the batteries????
ScheduleNextStateSave();
}
//------------------------------------------------------------------------------
// Recording control methods
void MetricsService::OpenNewLog() {
DCHECK(!log_manager_.current_log());
log_manager_.BeginLoggingWithLog(CreateLog(MetricsLog::ONGOING_LOG));
NotifyOnDidCreateMetricsLog();
if (state_ == INITIALIZED) {
// We only need to schedule that run once.
state_ = INIT_TASK_SCHEDULED;
base::MessageLoop::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&MetricsService::StartGatheringMetrics,
self_ptr_factory_.GetWeakPtr()),
base::TimeDelta::FromSeconds(kInitializationDelaySeconds));
}
}
void MetricsService::StartGatheringMetrics() {
client_->StartGatheringMetrics(
base::Bind(&MetricsService::FinishedGatheringInitialMetrics,
self_ptr_factory_.GetWeakPtr()));
}
void MetricsService::CloseCurrentLog() {
if (!log_manager_.current_log())
return;
// TODO(jar): Integrate bounds on log recording more consistently, so that we
// can stop recording logs that are too big much sooner.
if (log_manager_.current_log()->num_events() > kEventLimit) {
UMA_HISTOGRAM_COUNTS("UMA.Discarded Log Events",
log_manager_.current_log()->num_events());
log_manager_.DiscardCurrentLog();
OpenNewLog(); // Start trivial log to hold our histograms.
}
// Put incremental data (histogram deltas, and realtime stats deltas) at the
// end of all log transmissions (initial log handles this separately).
// RecordIncrementalStabilityElements only exists on the derived
// MetricsLog class.
MetricsLog* current_log = log_manager_.current_log();
DCHECK(current_log);
RecordCurrentEnvironment(current_log);
base::TimeDelta incremental_uptime;
base::TimeDelta uptime;
GetUptimes(local_state_, &incremental_uptime, &uptime);
current_log->RecordStabilityMetrics(metrics_providers_.get(),
incremental_uptime, uptime);
current_log->RecordGeneralMetrics(metrics_providers_.get());
RecordCurrentHistograms();
log_manager_.FinishCurrentLog();
}
void MetricsService::PushPendingLogsToPersistentStorage() {
if (state_ < SENDING_LOGS)
return; // We didn't and still don't have time to get plugin list etc.
CloseCurrentLog();
log_manager_.PersistUnsentLogs();
}
//------------------------------------------------------------------------------
// Transmission of logs methods
void MetricsService::StartSchedulerIfNecessary() {
// Never schedule cutting or uploading of logs in test mode.
if (test_mode_active_)
return;
// Even if reporting is disabled, the scheduler is needed to trigger the
// creation of the initial log, which must be done in order for any logs to be
// persisted on shutdown or backgrounding.
if (recording_active() &&
(reporting_active() || state_ < SENDING_LOGS)) {
scheduler_->Start();
}
}
void MetricsService::StartScheduledUpload() {
DCHECK(state_ >= INIT_TASK_DONE);
// If we're getting no notifications, then the log won't have much in it, and
// it's possible the computer is about to go to sleep, so don't upload and
// stop the scheduler.
// If recording has been turned off, the scheduler doesn't need to run.
// If reporting is off, proceed if the initial log hasn't been created, since
// that has to happen in order for logs to be cut and stored when persisting.
// TODO(stuartmorgan): Call Stop() on the scheduler when reporting and/or
// recording are turned off instead of letting it fire and then aborting.
if (idle_since_last_transmission_ ||
!recording_active() ||
(!reporting_active() && state_ >= SENDING_LOGS)) {
scheduler_->Stop();
scheduler_->UploadCancelled();
return;
}
// If there are unsent logs, send the next one. If not, start the asynchronous
// process of finalizing the current log for upload.
if (state_ == SENDING_LOGS && log_manager_.has_unsent_logs()) {
SendNextLog();
} else {
// There are no logs left to send, so start creating a new one.
client_->CollectFinalMetrics(
base::Bind(&MetricsService::OnFinalLogInfoCollectionDone,
self_ptr_factory_.GetWeakPtr()));
}
}
void MetricsService::OnFinalLogInfoCollectionDone() {
// If somehow there is a log upload in progress, we return and hope things
// work out. The scheduler isn't informed since if this happens, the scheduler
// will get a response from the upload.
DCHECK(!log_upload_in_progress_);
if (log_upload_in_progress_)
return;
// Abort if metrics were turned off during the final info gathering.
if (!recording_active()) {
scheduler_->Stop();
scheduler_->UploadCancelled();
return;
}
if (state_ == INIT_TASK_DONE) {
PrepareInitialMetricsLog();
} else {
DCHECK_EQ(SENDING_LOGS, state_);
CloseCurrentLog();
OpenNewLog();
}
SendNextLog();
}
void MetricsService::SendNextLog() {
DCHECK_EQ(SENDING_LOGS, state_);
if (!reporting_active()) {
scheduler_->Stop();
scheduler_->UploadCancelled();
return;
}
if (!log_manager_.has_unsent_logs()) {
// Should only get here if serializing the log failed somehow.
// Just tell the scheduler it was uploaded and wait for the next log
// interval.
scheduler_->UploadFinished(true, log_manager_.has_unsent_logs());
return;
}
if (!log_manager_.has_staged_log())
log_manager_.StageNextLogForUpload();
SendStagedLog();
}
bool MetricsService::ProvidersHaveStabilityMetrics() {
// Check whether any metrics provider has stability metrics.
for (size_t i = 0; i < metrics_providers_.size(); ++i) {
if (metrics_providers_[i]->HasStabilityMetrics())
return true;
}
return false;
}
bool MetricsService::PrepareInitialStabilityLog() {
DCHECK_EQ(INITIALIZED, state_);
scoped_ptr<MetricsLog> initial_stability_log(
CreateLog(MetricsLog::INITIAL_STABILITY_LOG));
// Do not call NotifyOnDidCreateMetricsLog here because the stability
// log describes stats from the _previous_ session.
if (!initial_stability_log->LoadSavedEnvironmentFromPrefs())
return false;
log_manager_.PauseCurrentLog();
log_manager_.BeginLoggingWithLog(initial_stability_log.Pass());
// Note: Some stability providers may record stability stats via histograms,
// so this call has to be after BeginLoggingWithLog().
log_manager_.current_log()->RecordStabilityMetrics(
metrics_providers_.get(), base::TimeDelta(), base::TimeDelta());
RecordCurrentStabilityHistograms();
// Note: RecordGeneralMetrics() intentionally not called since this log is for
// stability stats from a previous session only.
log_manager_.FinishCurrentLog();
log_manager_.ResumePausedLog();
// Store unsent logs, including the stability log that was just saved, so
// that they're not lost in case of a crash before upload time.
log_manager_.PersistUnsentLogs();
return true;
}
void MetricsService::PrepareInitialMetricsLog() {
DCHECK_EQ(INIT_TASK_DONE, state_);
RecordCurrentEnvironment(initial_metrics_log_.get());
base::TimeDelta incremental_uptime;
base::TimeDelta uptime;
GetUptimes(local_state_, &incremental_uptime, &uptime);
// Histograms only get written to the current log, so make the new log current
// before writing them.
log_manager_.PauseCurrentLog();
log_manager_.BeginLoggingWithLog(initial_metrics_log_.Pass());
// Note: Some stability providers may record stability stats via histograms,
// so this call has to be after BeginLoggingWithLog().
MetricsLog* current_log = log_manager_.current_log();
current_log->RecordStabilityMetrics(metrics_providers_.get(),
base::TimeDelta(), base::TimeDelta());
current_log->RecordGeneralMetrics(metrics_providers_.get());
RecordCurrentHistograms();
log_manager_.FinishCurrentLog();
log_manager_.ResumePausedLog();
// Store unsent logs, including the initial log that was just saved, so
// that they're not lost in case of a crash before upload time.
log_manager_.PersistUnsentLogs();
state_ = SENDING_LOGS;
}
void MetricsService::SendStagedLog() {
DCHECK(log_manager_.has_staged_log());
if (!log_manager_.has_staged_log())
return;
DCHECK(!log_upload_in_progress_);
log_upload_in_progress_ = true;
if (!log_uploader_) {
log_uploader_ = client_->CreateUploader(
base::Bind(&MetricsService::OnLogUploadComplete,
self_ptr_factory_.GetWeakPtr()));
}
const std::string hash =
base::HexEncode(log_manager_.staged_log_hash().data(),
log_manager_.staged_log_hash().size());
bool success = log_uploader_->UploadLog(log_manager_.staged_log(), hash);
UMA_HISTOGRAM_BOOLEAN("UMA.UploadCreation", success);
if (!success) {
// Skip this upload and hope things work out next time.
log_manager_.DiscardStagedLog();
scheduler_->UploadCancelled();
log_upload_in_progress_ = false;
return;
}
HandleIdleSinceLastTransmission(true);
}
void MetricsService::OnLogUploadComplete(int response_code) {
DCHECK_EQ(SENDING_LOGS, state_);
DCHECK(log_upload_in_progress_);
log_upload_in_progress_ = false;
// Log a histogram to track response success vs. failure rates.
UMA_HISTOGRAM_ENUMERATION("UMA.UploadResponseStatus.Protobuf",
ResponseCodeToStatus(response_code),
NUM_RESPONSE_STATUSES);
bool upload_succeeded = response_code == 200;
// Provide boolean for error recovery (allow us to ignore response_code).
bool discard_log = false;
const size_t log_size = log_manager_.staged_log().length();
if (upload_succeeded) {
UMA_HISTOGRAM_COUNTS_10000("UMA.LogSize.OnSuccess", log_size / 1024);
} else if (log_size > kUploadLogAvoidRetransmitSize) {
UMA_HISTOGRAM_COUNTS("UMA.Large Rejected Log was Discarded",
static_cast<int>(log_size));
discard_log = true;
} else if (response_code == 400) {
// Bad syntax. Retransmission won't work.
discard_log = true;
}
if (upload_succeeded || discard_log) {
log_manager_.DiscardStagedLog();
// Store the updated list to disk now that the removed log is uploaded.
log_manager_.PersistUnsentLogs();
}
// Error 400 indicates a problem with the log, not with the server, so
// don't consider that a sign that the server is in trouble.
bool server_is_healthy = upload_succeeded || response_code == 400;
scheduler_->UploadFinished(server_is_healthy, log_manager_.has_unsent_logs());
if (server_is_healthy)
client_->OnLogUploadComplete();
}
void MetricsService::IncrementPrefValue(const char* path) {
int value = local_state_->GetInteger(path);
local_state_->SetInteger(path, value + 1);
}
void MetricsService::IncrementLongPrefsValue(const char* path) {
int64 value = local_state_->GetInt64(path);
local_state_->SetInt64(path, value + 1);
}
bool MetricsService::UmaMetricsProperlyShutdown() {
CHECK(clean_shutdown_status_ == CLEANLY_SHUTDOWN ||
clean_shutdown_status_ == NEED_TO_SHUTDOWN);
return clean_shutdown_status_ == CLEANLY_SHUTDOWN;
}
void MetricsService::AddSyntheticTrialObserver(
SyntheticTrialObserver* observer) {
synthetic_trial_observer_list_.AddObserver(observer);
if (!synthetic_trial_groups_.empty())
observer->OnSyntheticTrialsChanged(synthetic_trial_groups_);
}
void MetricsService::RemoveSyntheticTrialObserver(
SyntheticTrialObserver* observer) {
synthetic_trial_observer_list_.RemoveObserver(observer);
}
void MetricsService::RegisterSyntheticFieldTrial(
const SyntheticTrialGroup& trial) {
for (size_t i = 0; i < synthetic_trial_groups_.size(); ++i) {
if (synthetic_trial_groups_[i].id.name == trial.id.name) {
if (synthetic_trial_groups_[i].id.group != trial.id.group) {
synthetic_trial_groups_[i].id.group = trial.id.group;
synthetic_trial_groups_[i].start_time = base::TimeTicks::Now();
NotifySyntheticTrialObservers();
}
return;
}
}
SyntheticTrialGroup trial_group = trial;
trial_group.start_time = base::TimeTicks::Now();
synthetic_trial_groups_.push_back(trial_group);
NotifySyntheticTrialObservers();
}
void MetricsService::RegisterMetricsProvider(
scoped_ptr<MetricsProvider> provider) {
DCHECK_EQ(INITIALIZED, state_);
metrics_providers_.push_back(provider.release());
}
void MetricsService::CheckForClonedInstall(
scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
state_manager_->CheckForClonedInstall(task_runner);
}
void MetricsService::NotifySyntheticTrialObservers() {
FOR_EACH_OBSERVER(SyntheticTrialObserver, synthetic_trial_observer_list_,
OnSyntheticTrialsChanged(synthetic_trial_groups_));
}
void MetricsService::GetCurrentSyntheticFieldTrials(
std::vector<variations::ActiveGroupId>* synthetic_trials) {
DCHECK(synthetic_trials);
synthetic_trials->clear();
const MetricsLog* current_log = log_manager_.current_log();
for (size_t i = 0; i < synthetic_trial_groups_.size(); ++i) {
if (synthetic_trial_groups_[i].start_time <= current_log->creation_time())
synthetic_trials->push_back(synthetic_trial_groups_[i].id);
}
}
scoped_ptr<MetricsLog> MetricsService::CreateLog(MetricsLog::LogType log_type) {
return make_scoped_ptr(new MetricsLog(state_manager_->client_id(),
session_id_,
log_type,
client_,
local_state_));
}
void MetricsService::RecordCurrentEnvironment(MetricsLog* log) {
std::vector<variations::ActiveGroupId> synthetic_trials;
GetCurrentSyntheticFieldTrials(&synthetic_trials);
log->RecordEnvironment(metrics_providers_.get(), synthetic_trials,
GetInstallDate(), GetMetricsReportingEnabledDate());
UMA_HISTOGRAM_COUNTS_100("UMA.SyntheticTrials.Count",
synthetic_trials.size());
}
void MetricsService::RecordCurrentHistograms() {
DCHECK(log_manager_.current_log());
histogram_snapshot_manager_.PrepareDeltas(
base::Histogram::kNoFlags, base::Histogram::kUmaTargetedHistogramFlag);
}
void MetricsService::RecordCurrentStabilityHistograms() {
DCHECK(log_manager_.current_log());
histogram_snapshot_manager_.PrepareDeltas(
base::Histogram::kNoFlags, base::Histogram::kUmaStabilityHistogramFlag);
}
void MetricsService::LogCleanShutdown() {
// Redundant setting to assure that we always reset this value at shutdown
// (and that we don't use some alternate path, and not call LogCleanShutdown).
clean_shutdown_status_ = CLEANLY_SHUTDOWN;
clean_exit_beacon_.WriteBeaconValue(true);
RecordCurrentState(local_state_);
local_state_->SetInteger(prefs::kStabilityExecutionPhase,
MetricsService::SHUTDOWN_COMPLETE);
}
bool MetricsService::ShouldLogEvents() {
// We simply don't log events to UMA if there is a single incognito
// session visible. The problem is that we always notify using the orginal
// profile in order to simplify notification processing.
return !client_->IsOffTheRecordSessionActive();
}
void MetricsService::RecordBooleanPrefValue(const char* path, bool value) {
DCHECK(IsSingleThreaded());
local_state_->SetBoolean(path, value);
RecordCurrentState(local_state_);
}
void MetricsService::RecordCurrentState(PrefService* pref) {
pref->SetInt64(prefs::kStabilityLastTimestampSec,
base::Time::Now().ToTimeT());
}
} // namespace metrics
| ltilve/chromium | components/metrics/metrics_service.cc | C++ | bsd-3-clause | 42,424 |
/*
* PROJECT: Atomix Development
* LICENSE: BSD 3-Clause (LICENSE.md)
* PURPOSE: Cgt MSIL
* PROGRAMMERS: Aman Priyadarshi (aman.eureka@gmail.com)
*/
using System;
using System.Reflection;
using Atomixilc.Machine;
using Atomixilc.Attributes;
using Atomixilc.Machine.x86;
namespace Atomixilc.IL
{
[ILImpl(ILCode.Cgt)]
internal class Cgt_il : MSIL
{
public Cgt_il()
: base(ILCode.Cgt)
{
}
/*
* URL : https://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.Cgt(v=vs.110).aspx
* Description : Compares two values. If the first value is greater than the second, the integer value 1 (int32) is pushed onto the evaluation stack; otherwise 0 (int32) is pushed onto the evaluation stack.
*/
internal override void Execute(Options Config, OpCodeType xOp, MethodBase method, Optimizer Optimizer)
{
if (Optimizer.vStack.Count < 2)
throw new Exception("Internal Compiler Error: vStack.Count < 2");
var itemA = Optimizer.vStack.Pop();
var itemB = Optimizer.vStack.Pop();
var xCurrentLabel = Helper.GetLabel(xOp.Position);
var xNextLabel = Helper.GetLabel(xOp.NextPosition);
var size = Math.Max(Helper.GetTypeSize(itemA.OperandType, Config.TargetPlatform),
Helper.GetTypeSize(itemB.OperandType, Config.TargetPlatform));
/* The stack transitional behavior, in sequential order, is:
* value1 is pushed onto the stack.
* value2 is pushed onto the stack.
* value2 and value1 are popped from the stack; cgt tests if value1 is greater than value2.
* If value1 is greater than value2, 1 is pushed onto the stack; otherwise 0 is pushed onto the stack.
*/
switch (Config.TargetPlatform)
{
case Architecture.x86:
{
if (itemA.IsFloat || itemB.IsFloat || size > 4)
throw new Exception(string.Format("UnImplemented '{0}'", msIL));
if (!itemA.SystemStack || !itemB.SystemStack)
throw new Exception(string.Format("UnImplemented-RegisterType '{0}'", msIL));
new Pop { DestinationReg = Register.EAX };
new Pop { DestinationReg = Register.EDX };
new Cmp { DestinationReg = Register.EDX, SourceReg = Register.EAX };
new Setg { DestinationReg = Register.AL };
new Movzx { DestinationReg = Register.EAX, SourceReg = Register.AL, Size = 8 };
new Push { DestinationReg = Register.EAX };
Optimizer.vStack.Push(new StackItem(typeof(bool)));
Optimizer.SaveStack(xOp.NextPosition);
}
break;
default:
throw new Exception(string.Format("Unsupported target platform '{0}' for MSIL '{1}'", Config.TargetPlatform, msIL));
}
}
}
}
| amaneureka/AtomOS | src/Compiler/Atomixilc/IL/Comparison/Cgt.cs | C# | bsd-3-clause | 3,259 |
package com.atlassian.pageobjects.components.aui;
import com.atlassian.pageobjects.PageBinder;
import com.atlassian.pageobjects.binder.Init;
import com.atlassian.pageobjects.binder.InvalidPageStateException;
import com.atlassian.pageobjects.components.TabbedComponent;
import com.atlassian.pageobjects.elements.PageElement;
import com.atlassian.pageobjects.elements.PageElementFinder;
import com.atlassian.pageobjects.elements.query.Poller;
import org.openqa.selenium.By;
import javax.inject.Inject;
import java.util.List;
/**
* Represents a tabbed content area created via AUI.
*
* This is an example of a reusable components.
*/
public class AuiTabs implements TabbedComponent
{
@Inject
protected PageBinder pageBinder;
@Inject
protected PageElementFinder elementFinder;
private final By rootLocator;
private PageElement rootElement;
public AuiTabs(By locator)
{
this.rootLocator = locator;
}
@Init
public void initialize()
{
this.rootElement = elementFinder.find(rootLocator);
}
public PageElement selectedTab()
{
List<PageElement> items = rootElement.find(By.className("tabs-menu")).findAll(By.tagName("li"));
for(int i = 0; i < items.size(); i++)
{
PageElement tab = items.get(i);
if(tab.hasClass("active-tab"))
{
return tab;
}
}
throw new InvalidPageStateException("A tab must be active.", this);
}
public PageElement selectedView()
{
List<PageElement> panes = rootElement.findAll(By.className("tabs-pane"));
for(int i = 0; i < panes.size(); i++)
{
PageElement pane = panes.get(i);
if(pane.hasClass("active-pane"))
{
return pane;
}
}
throw new InvalidPageStateException("A pane must be active", this);
}
public List<PageElement> tabs()
{
return rootElement.find(By.className("tabs-menu")).findAll(By.tagName("li"));
}
public PageElement openTab(String tabText)
{
List<PageElement> tabs = rootElement.find(By.className("tabs-menu")).findAll(By.tagName("a"));
for(int i = 0; i < tabs.size(); i++)
{
if(tabs.get(i).getText().equals(tabText))
{
PageElement listItem = tabs.get(i);
listItem.click();
// find the pane and wait until it has class "active-pane"
String tabViewHref = listItem.getAttribute("href");
String tabViewClassName = tabViewHref.substring(tabViewHref.indexOf('#') + 1);
PageElement pane = rootElement.find(By.id(tabViewClassName));
Poller.waitUntilTrue(pane.timed().hasClass("active-pane"));
return pane;
}
}
throw new InvalidPageStateException("Tab not found", this);
}
public PageElement openTab(PageElement tab)
{
String tabIdentifier = tab.getText();
return openTab(tabIdentifier);
}
}
| adini121/atlassian | atlassian-pageobjects-elements/src/main/java/com/atlassian/pageobjects/components/aui/AuiTabs.java | Java | bsd-3-clause | 3,108 |
<?php
/**
* iDatabase数据管理控制器
*
* @author young
* @version 2013.11.22
*
*/
namespace Idatabase\Controller;
use My\Common\Controller\Action;
class ImportController extends Action
{
/**
* 读取当前数据集合的mongocollection实例
*
* @var object
*/
private $_data;
/**
* 读取数据属性结构的mongocollection实例
*
* @var object
*/
private $_structure;
/**
* 读取集合列表集合的mongocollection实例
*
* @var object
*/
private $_collection;
/**
* 当前集合所属项目
*
* @var string
*/
private $_project_id = '';
/**
* 当前集合所属集合 集合的alias别名或者_id的__toString()结果
*
* @var string
*/
private $_collection_id = '';
/**
* 存储数据的物理集合名称
*
* @var string
*/
private $_collection_name = '';
/**
* 存储当前集合的结局结构信息
*
* @var array
*/
private $_schema = null;
/**
* 存储查询显示字段列表
*
* @var array
*/
private $_fields = array();
/**
* Gearman客户端
*
* @var object
*/
private $_gmClient;
/**
* 存储文件
*
* @var object
*/
private $_file;
/**
* 初始化函数
*
* @see \My\Common\ActionController::init()
*/
public function init()
{
resetTimeMemLimit();
$this->_project_id = isset($_REQUEST['__PROJECT_ID__']) ? trim($_REQUEST['__PROJECT_ID__']) : '';
if (empty($this->_project_id))
throw new \Exception('$this->_project_id值未设定');
$this->_collection = $this->model('Idatabase\Model\Collection');
$this->_collection_id = isset($_REQUEST['__COLLECTION_ID__']) ? trim($_REQUEST['__COLLECTION_ID__']) : '';
if (empty($this->_collection_id))
throw new \Exception('$this->_collection_id值未设定');
$this->_collection_id = $this->getCollectionIdByName($this->_collection_id);
$this->_collection_name = 'idatabase_collection_' . $this->_collection_id;
$this->_data = $this->collection($this->_collection_name);
$this->_structure = $this->model('Idatabase\Model\Structure');
$this->_file = $this->model('Idatabase\Model\File');
// 建立gearman客户端连接
$this->_gmClient = $this->gearman()->client();
$this->getSchema();
}
/**
* 将导入数据脚本放置到gearman中进行,加快页面的响应速度
*/
public function importCsvJobAction()
{
// 大数据量导采用mongoimport直接导入的方式导入数据
$collection_id = trim($this->params()->fromPost('__COLLECTION_ID__', null));
$physicalDrop = filter_var($this->params()->fromPost('physicalDrop', false), FILTER_VALIDATE_BOOLEAN);
$upload = $this->params()->fromFiles('import');
if (empty($collection_id) || empty($upload)) {
return $this->msg(false, '上传文件或者集合编号不能为空');
}
$uploadFileNameLower = strtolower($upload['name']);
if (strpos($uploadFileNameLower, '.zip') !== false) {
$bytes = file_get_contents($upload['tmp_name']);
$fileInfo = $this->_file->storeBytesToGridFS($bytes, 'import.zip');
$key = $fileInfo['_id']->__toString();
} else {
if (strpos($uploadFileNameLower, '.csv') === false) {
return $this->msg(false, '请上传csv格式的文件');
}
$bytes = file_get_contents($upload['tmp_name']);
if (! detectUTF8($bytes)) {
return $this->msg(false, '请使用文本编辑器将文件转化为UTF-8格式');
}
$fileInfo = $this->_file->storeBytesToGridFS($bytes, 'import.csv');
$key = $fileInfo['_id']->__toString();
}
$workload = array();
$workload['key'] = $key;
$workload['collection_id'] = $collection_id;
$workload['physicalDrop'] = $physicalDrop;
// $jobHandle = $this->_gmClient->doBackground('dataImport', serialize($workload), $key);
$jobHandle = $this->_gmClient->doBackground('bsonImport', serialize($workload), $key);
$stat = $this->_gmClient->jobStatus($jobHandle);
if (isset($stat[0]) && $stat[0]) {
return $this->msg(true, '数据导入任务已经被受理,请稍后片刻若干分钟,导入时间取决于数据量(1w/s)。');
} else {
return $this->msg(false, '任务提交失败');
}
}
/**
* 导入数据到集合内
*/
public function importAction()
{
try {
$importSheetName = trim($this->params()->fromPost('sheetName', null));
$file = $this->params()->fromFiles('import', null);
if ($importSheetName == null) {
return $this->msg(false, '请设定需要导入的sheet');
}
if ($file == null) {
return $this->msg(false, '请上传Excel数据表格文件');
}
if ($file['error'] === UPLOAD_ERR_OK) {
$fileName = $file['name'];
$filePath = $file['tmp_name'];
$ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
switch ($ext) {
case 'xlsx':
$inputFileType = 'Excel2007';
break;
default:
return $this->msg(false, '很抱歉,您上传的文件格式无法识别,格式要求:*.xlsx');
}
$objReader = \PHPExcel_IOFactory::createReader($inputFileType);
$objReader->setReadDataOnly(true);
$objReader->setLoadSheetsOnly($importSheetName);
$objPHPExcel = $objReader->load($filePath);
if (! in_array($importSheetName, array_values($objPHPExcel->getSheetNames()))) {
return $this->msg(false, 'Sheet:"' . $importSheetName . '",不存在,请检查您导入的Excel表格');
}
$objPHPExcel->setActiveSheetIndexByName($importSheetName);
$objActiveSheet = $objPHPExcel->getActiveSheet();
$sheetData = $objActiveSheet->toArray(null, true, true, true);
$objPHPExcel->disconnectWorksheets();
unset($objReader, $objPHPExcel, $objActiveSheet);
if (empty($sheetData)) {
return $this->msg(false, '请确认表格中未包含有效数据,请复核');
}
$firstRow = array_shift($sheetData);
if (count($firstRow) == 0) {
return $this->msg(false, '标题行数据为空');
}
$titles = array();
foreach ($firstRow as $col => $value) {
$value = trim($value);
if (in_array($value, array_keys($this->_schema), true)) {
$titles[$col] = $this->_schema[$value];
} else
if (in_array($value, array_values($this->_schema), true)) {
$titles[$col] = $value;
}
}
if (count($titles) == 0) {
return $this->msg(false, '无匹配的标题或者标题字段,请检查导入数据的格式是否正确');
}
array_walk($sheetData, function ($row, $rowNumber) use($titles)
{
$insertData = array();
foreach ($titles as $col => $colName) {
$insertData[$colName] = formatData($row[$col], $this->_fields[$colName]);
}
$this->_data->insertByFindAndModify($insertData);
unset($insertData);
});
// 用bson文件代替插入数据
// $bson = '';
// foreach ($sheetData as $rowNumber=>$row) {
// $insertData = array();
// foreach ($titles as $col => $colName) {
// $insertData[$colName] = formatData($row[$col], $this->_fields[$colName]);
// }
// $bson .= bson_encode($insertData);
// }
unset($sheetData);
return $this->msg(true, '导入成功');
} else {
return $this->msg(false, '上传文件失败');
}
} catch (\Exception $e) {
fb(exceptionMsg($e), \FirePHP::LOG);
return $this->msg(false, '导入失败,发生异常');
}
}
/**
* 获取集合的数据结构
*
* @return array
*/
private function getSchema()
{
$this->_schema = array();
$this->_fields = array();
$cursor = $this->_structure->find(array(
'collection_id' => $this->_collection_id
));
while ($cursor->hasNext()) {
$row = $cursor->getNext();
$this->_schema[$row['label']] = $row['field'];
$this->_fields[$row['field']] = $row['type'];
}
return true;
}
/**
* 根据集合的名称获取集合的_id
*
* @param string $name
* @throws \Exception or string
*/
private function getCollectionIdByName($name)
{
try {
new \MongoId($name);
return $name;
} catch (\MongoException $ex) {}
$collectionInfo = $this->_collection->findOne(array(
'project_id' => $this->_project_id,
'name' => $name
));
if ($collectionInfo == null) {
throw new \Exception('集合名称不存在于指定项目');
}
return $collectionInfo['_id']->__toString();
}
}
| icatholic/icc | module/Idatabase/src/Idatabase/Controller/ImportController.php | PHP | bsd-3-clause | 10,381 |
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model app\models\IzinmenutupjalanSearch */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="izinmenutupjalan-search">
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<?= $form->field($model, 'id_imj') ?>
<?= $form->field($model, 'id_akun') ?>
<?= $form->field($model, 'nomor_imj') ?>
<?= $form->field($model, 'tglDikeluarkan_imj') ?>
<?= $form->field($model, 'tglPengajuan_imj') ?>
<?php // echo $form->field($model, 'kepada_imj') ?>
<?php // echo $form->field($model, 'alamat_imj') ?>
<?php // echo $form->field($model, 'namaAcara_imj') ?>
<?php // echo $form->field($model, 'jalanDitutup_imj') ?>
<?php // echo $form->field($model, 'penutupanJalanMaksimal_imj') ?>
<?php // echo $form->field($model, 'tglAcara_imj') ?>
<?php // echo $form->field($model, 'JamAcara_imj') ?>
<?php // echo $form->field($model, 'tglAcaraSelesai_imj') ?>
<?php // echo $form->field($model, 'jamAcaraSelesai_imj') ?>
<?php // echo $form->field($model, 'tembusan_imj') ?>
<?php // echo $form->field($model, 'keterangan_imj') ?>
<div class="form-group">
<?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
<?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
| dinarwm/kppt | views/Izinmenutupjalan/_search.php | PHP | bsd-3-clause | 1,483 |
//
// buffered_write_stream.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2013 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef BOOST_ASIO_BUFFERED_WRITE_STREAM_HPP
#define BOOST_ASIO_BUFFERED_WRITE_STREAM_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <boost/asio/detail/config.hpp>
#include <cstddef>
#include <boost/asio/buffered_write_stream_fwd.hpp>
#include <boost/asio/buffer.hpp>
#include <boost/asio/completion_condition.hpp>
#include <boost/asio/detail/bind_handler.hpp>
#include <boost/asio/detail/buffered_stream_storage.hpp>
#include <boost/asio/detail/noncopyable.hpp>
#include <boost/asio/detail/type_traits.hpp>
#include <boost/asio/error.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/asio/write.hpp>
#include <boost/asio/detail/push_options.hpp>
namespace pdalboost {} namespace boost = pdalboost; namespace pdalboost {
namespace asio {
/// Adds buffering to the write-related operations of a stream.
/**
* The buffered_write_stream class template can be used to add buffering to the
* synchronous and asynchronous write operations of a stream.
*
* @par Thread Safety
* @e Distinct @e objects: Safe.@n
* @e Shared @e objects: Unsafe.
*
* @par Concepts:
* AsyncReadStream, AsyncWriteStream, Stream, SyncReadStream, SyncWriteStream.
*/
template <typename Stream>
class buffered_write_stream
: private noncopyable
{
public:
/// The type of the next layer.
typedef typename remove_reference<Stream>::type next_layer_type;
/// The type of the lowest layer.
typedef typename next_layer_type::lowest_layer_type lowest_layer_type;
#if defined(GENERATING_DOCUMENTATION)
/// The default buffer size.
static const std::size_t default_buffer_size = implementation_defined;
#else
BOOST_ASIO_STATIC_CONSTANT(std::size_t, default_buffer_size = 1024);
#endif
/// Construct, passing the specified argument to initialise the next layer.
template <typename Arg>
explicit buffered_write_stream(Arg& a)
: next_layer_(a),
storage_(default_buffer_size)
{
}
/// Construct, passing the specified argument to initialise the next layer.
template <typename Arg>
buffered_write_stream(Arg& a, std::size_t buffer_size)
: next_layer_(a),
storage_(buffer_size)
{
}
/// Get a reference to the next layer.
next_layer_type& next_layer()
{
return next_layer_;
}
/// Get a reference to the lowest layer.
lowest_layer_type& lowest_layer()
{
return next_layer_.lowest_layer();
}
/// Get a const reference to the lowest layer.
const lowest_layer_type& lowest_layer() const
{
return next_layer_.lowest_layer();
}
/// Get the io_service associated with the object.
pdalboost::asio::io_service& get_io_service()
{
return next_layer_.get_io_service();
}
/// Close the stream.
void close()
{
next_layer_.close();
}
/// Close the stream.
pdalboost::system::error_code close(pdalboost::system::error_code& ec)
{
return next_layer_.close(ec);
}
/// Flush all data from the buffer to the next layer. Returns the number of
/// bytes written to the next layer on the last write operation. Throws an
/// exception on failure.
std::size_t flush();
/// Flush all data from the buffer to the next layer. Returns the number of
/// bytes written to the next layer on the last write operation, or 0 if an
/// error occurred.
std::size_t flush(pdalboost::system::error_code& ec);
/// Start an asynchronous flush.
template <typename WriteHandler>
BOOST_ASIO_INITFN_RESULT_TYPE(WriteHandler,
void (pdalboost::system::error_code, std::size_t))
async_flush(BOOST_ASIO_MOVE_ARG(WriteHandler) handler);
/// Write the given data to the stream. Returns the number of bytes written.
/// Throws an exception on failure.
template <typename ConstBufferSequence>
std::size_t write_some(const ConstBufferSequence& buffers);
/// Write the given data to the stream. Returns the number of bytes written,
/// or 0 if an error occurred and the error handler did not throw.
template <typename ConstBufferSequence>
std::size_t write_some(const ConstBufferSequence& buffers,
pdalboost::system::error_code& ec);
/// Start an asynchronous write. The data being written must be valid for the
/// lifetime of the asynchronous operation.
template <typename ConstBufferSequence, typename WriteHandler>
BOOST_ASIO_INITFN_RESULT_TYPE(WriteHandler,
void (pdalboost::system::error_code, std::size_t))
async_write_some(const ConstBufferSequence& buffers,
BOOST_ASIO_MOVE_ARG(WriteHandler) handler);
/// Read some data from the stream. Returns the number of bytes read. Throws
/// an exception on failure.
template <typename MutableBufferSequence>
std::size_t read_some(const MutableBufferSequence& buffers)
{
return next_layer_.read_some(buffers);
}
/// Read some data from the stream. Returns the number of bytes read or 0 if
/// an error occurred.
template <typename MutableBufferSequence>
std::size_t read_some(const MutableBufferSequence& buffers,
pdalboost::system::error_code& ec)
{
return next_layer_.read_some(buffers, ec);
}
/// Start an asynchronous read. The buffer into which the data will be read
/// must be valid for the lifetime of the asynchronous operation.
template <typename MutableBufferSequence, typename ReadHandler>
BOOST_ASIO_INITFN_RESULT_TYPE(ReadHandler,
void (pdalboost::system::error_code, std::size_t))
async_read_some(const MutableBufferSequence& buffers,
BOOST_ASIO_MOVE_ARG(ReadHandler) handler)
{
detail::async_result_init<
ReadHandler, void (pdalboost::system::error_code, std::size_t)> init(
BOOST_ASIO_MOVE_CAST(ReadHandler)(handler));
next_layer_.async_read_some(buffers,
BOOST_ASIO_MOVE_CAST(BOOST_ASIO_HANDLER_TYPE(ReadHandler,
void (pdalboost::system::error_code, std::size_t)))(init.handler));
return init.result.get();
}
/// Peek at the incoming data on the stream. Returns the number of bytes read.
/// Throws an exception on failure.
template <typename MutableBufferSequence>
std::size_t peek(const MutableBufferSequence& buffers)
{
return next_layer_.peek(buffers);
}
/// Peek at the incoming data on the stream. Returns the number of bytes read,
/// or 0 if an error occurred.
template <typename MutableBufferSequence>
std::size_t peek(const MutableBufferSequence& buffers,
pdalboost::system::error_code& ec)
{
return next_layer_.peek(buffers, ec);
}
/// Determine the amount of data that may be read without blocking.
std::size_t in_avail()
{
return next_layer_.in_avail();
}
/// Determine the amount of data that may be read without blocking.
std::size_t in_avail(pdalboost::system::error_code& ec)
{
return next_layer_.in_avail(ec);
}
private:
/// Copy data into the internal buffer from the specified source buffer.
/// Returns the number of bytes copied.
template <typename ConstBufferSequence>
std::size_t copy(const ConstBufferSequence& buffers);
/// The next layer.
Stream next_layer_;
// The data in the buffer.
detail::buffered_stream_storage storage_;
};
} // namespace asio
} // namespace pdalboost
#include <boost/asio/detail/pop_options.hpp>
#include <boost/asio/impl/buffered_write_stream.hpp>
#endif // BOOST_ASIO_BUFFERED_WRITE_STREAM_HPP
| verma/PDAL | boost/boost/asio/buffered_write_stream.hpp | C++ | bsd-3-clause | 7,635 |
////////////////////////////////////////////////////////////////////////////////////
///
/// \file reporttimeout.cpp
/// \brief This file contains the implementation of a JAUS message.
///
/// <br>Author(s): Bo Sun
/// <br>Created: 17 November 2009
/// <br>Copyright (c) 2009
/// <br>Applied Cognition and Training in Immersive Virtual Environments
/// <br>(ACTIVE) Laboratory
/// <br>Institute for Simulation and Training (IST)
/// <br>University of Central Florida (UCF)
/// <br>All rights reserved.
/// <br>Email: bsun@ist.ucf.edu
/// <br>Web: http://active.ist.ucf.edu
///
/// Redistribution and use in source and binary forms, with or without
/// modification, are permitted provided that the following conditions are met:
/// * Redistributions of source code must retain the above copyright
/// notice, this list of conditions and the following disclaimer.
/// * Redistributions in binary form must reproduce the above copyright
/// notice, this list of conditions and the following disclaimer in the
/// documentation and/or other materials provided with the distribution.
/// * Neither the name of the ACTIVE LAB, IST, UCF, 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 ACTIVE LAB''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 UCF 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 "jaus/core/control/reporttimeout.h"
using namespace JAUS;
////////////////////////////////////////////////////////////////////////////////////
///
/// \brief Constructor, initializes default values.
///
/// \param[in] src Source ID of message sender.
/// \param[in] dest Destination ID of message.
///
////////////////////////////////////////////////////////////////////////////////////
ReportTimeout::ReportTimeout(const Address& dest, const Address& src) : Message(REPORT_TIMEOUT, dest, src)
{
mTimeoutSeconds = 0;
}
////////////////////////////////////////////////////////////////////////////////////
///
/// \brief Copy constructor.
///
////////////////////////////////////////////////////////////////////////////////////
ReportTimeout::ReportTimeout(const ReportTimeout& message) : Message(REPORT_TIMEOUT)
{
*this = message;
}
////////////////////////////////////////////////////////////////////////////////////
///
/// \brief Destructor.
///
////////////////////////////////////////////////////////////////////////////////////
ReportTimeout::~ReportTimeout()
{
}
////////////////////////////////////////////////////////////////////////////////////
///
/// \brief Writes message payload to the packet.
///
/// Message contents are written to the packet following the JAUS standard.
///
/// \param[out] packet Packet to write payload to.
///
/// \return -1 on error, otherwise number of bytes written.
///
////////////////////////////////////////////////////////////////////////////////////
int ReportTimeout::WriteMessageBody(Packet& packet) const
{
int expected = BYTE_SIZE;
int written = 0;
written += packet.Write(mTimeoutSeconds);
return expected == written ? written : -1;
}
////////////////////////////////////////////////////////////////////////////////////
///
/// \brief Reads message payload from the packet.
///
/// Message contents are read from the packet following the JAUS standard.
///
/// \param[in] packet Packet containing message payload data to read.
///
/// \return -1 on error, otherwise number of bytes written.
///
////////////////////////////////////////////////////////////////////////////////////
int ReportTimeout::ReadMessageBody(const Packet& packet)
{
int expected = BYTE_SIZE;
int read = 0;
read += packet.Read(mTimeoutSeconds);
return expected == read ? read : -1;
}
////////////////////////////////////////////////////////////////////////////////////
///
/// \brief Clears message payload data.
///
////////////////////////////////////////////////////////////////////////////////////
void ReportTimeout::ClearMessageBody()
{
mTimeoutSeconds = 0;
}
////////////////////////////////////////////////////////////////////////////////////
///
/// \brief Runs a test case to validate the message class.
///
/// \return 1 on success, otherwise 0.
///
////////////////////////////////////////////////////////////////////////////////////
int ReportTimeout::RunTestCase() const
{
int result = 0;
Packet packet;
ReportTimeout msg1, msg2;
msg1.SetTimeoutSeconds(100);
if( msg1.WriteMessageBody(packet) != -1 &&
msg2.ReadMessageBody(packet) != -1 &&
msg1.GetTimeoutSeconds() == msg2.GetTimeoutSeconds())
{
result = 1;
}
return result;
}
////////////////////////////////////////////////////////////////////////////////////
///
/// \brief Sets equal to.
///
////////////////////////////////////////////////////////////////////////////////////
ReportTimeout& ReportTimeout::operator=(const ReportTimeout& message)
{
if(this != &message)
{
CopyHeaderData(&message);
mTimeoutSeconds = message.mTimeoutSeconds;
}
return *this;
}
/* End of File */
| jmesmon/jaus-- | src/jaus/core/control/reporttimeout.cpp | C++ | bsd-3-clause | 6,127 |
////functionen hämtar alla artiklar med hjälp av getJSON
//och får tillbaka en array med alla artiklar
//efter den är klar kallar den på functionen ShoArtTab.
//som skriver ut alla artiklar i en tabell.
function getAllAdminProducts()
{
$.getJSON("index2.php/getAllProducts").done(showArtTab);
}
//functionen showArtTab får en array av getAllArticle funktionen
//som den loopar igenom och anväder för att skapa upp en tabell med alla de olika
//artiklarna
function showArtTab(cart){
var mainTabell = document.createElement('div');
mainTabell.setAttribute('id', 'mainTabell');
var tbl = document.createElement('table');
tbl.setAttribute('border', '1');
var tr = document.createElement('tr');
var th2 = document.createElement('th');
var txt2 = document.createTextNode('Produktid');
var th3 = document.createElement('th');
var txt3 = document.createTextNode('Produktnamn');
var th4 = document.createElement('th');
var txt4 = document.createTextNode('Kategori');
var th5 = document.createElement('th');
var txt5 = document.createTextNode('Pris');
var th6 = document.createElement('th');
var txt6 = document.createTextNode('Bild');
var th7 = document.createElement('th');
var txt7 = document.createTextNode('Delete');
var th8 = document.createElement('th');
var txt8 = document.createTextNode('Update');
th2.appendChild(txt2);
tr.appendChild(th2);
th3.appendChild(txt3);
tr.appendChild(th3);
th4.appendChild(txt4);
tr.appendChild(th4);
th5.appendChild(txt5);
tr.appendChild(th5);
th6.appendChild(txt6);
tr.appendChild(th6);
th7.appendChild(txt7);
tr.appendChild(th7);
th8.appendChild(txt8);
tr.appendChild(th8);
tbl.appendChild(tr);
var i = 0;
do{
var row = tbl.insertRow(-1);
row.insertCell(-1).innerHTML = cart[i].produktid;
var cell2 = row.insertCell(-1);
cell2.innerHTML = cart[i].namn;
var cell3 = row.insertCell(-1);
cell3.innerHTML = cart[i].kategori;
var cell4 = row.insertCell(-1);
cell4.innerHTML = cart[i].pris;
var cell6 = row.insertCell(-1);
cell6.innerHTML = '<img src="' + cart[i].img + '" height="70" width="70"/>';
var cell7 = row.insertCell(-1);
cell7.innerHTML = "<a href='#' onclick='removeArt(\"" +cart[i].produktid+ "\",\""+ "\");'>Remove</a>";
var cell8 = row.insertCell(-1);
cell8.innerHTML = "<a href='#' onclick='getUpdate(\"" +cart[i].produktid+ "\",\""+ "\");'>Update</a>";
tbl.appendChild(row);
i++;
}while(i< cart.length);
$('#main').html(tbl);
}
//öppnar en dialogruta när man trycker på "Add Article" knappen
//med det som finns i diven med id:addArt
function showAddArt(){
$('#addArt').dialog({
show:'fade', position:'center'
});
}
//när man trycker på "Add Article" knappen i dialogrutan så ska den lägga till datan
//från formuläret som görs med .serialize som hämtar datan från textfälten.
function addArticle(){
$.post('index2.php/AdminController/addProduct',$('#addArtForm').serialize()).done(getAllAdminProducts);
$("#addArt").dialog('close');
}
//tar bort en artikel med att hämta in dess namn och skicka förfrågningen till modellen
function deleteArt(prodid)
{
$.getJSON("index2.php/AdminController/deleteProduct/"+prodid);
}
function removeArt(prodid){
var r=confirm("Vill du ta bort den här produkten?");
if (r==true)
{
x="JA";
} else {
x="NEJ";
}
if(x === "JA"){
deleteArt(prodid);
getAllAdminProducts();
}
}
//en function som tar in namnet
//och använder det när man kallar på getArt
function getUpdate(prodid){
getArt(prodid);
}
//får in artikelid och använder det för att hämta alla artiklar som har samma
//id med hjälp av modellen.
function getArt(prodid){
$.getJSON("index2.php/Controller/getProdById/"+prodid).done(showArt);
}
//en function som visar en dialog ruta med färdig i fylld data i textfällten
//från den uppgift man vill uppdatera.
function showArt(data){
$('#updateId').attr('value',data[0].produktid);
$('#updateNamn').attr('value',data[0].namn);
$('#updateKategori').attr('value',data[0].kategori);
$('#updatePris').attr('value',data[0].pris);
$('#updateImg').attr('value',data[0].img);
$('#update').dialog({
show:'fade', position:'center',
});
}
//när man trycker på uppdatera så hämtar den datan från forumlätert med hjälp av
// .serialize och skickar datan till modellen.
//stänger sen dialogrutan.
function updateArt(){
$.post("index2.php/AdminController/updateProduct/", $('#updateForm').serialize()).done(getAllAdminProducts);
$("#update").dialog('close');
} | cider94/JsKlar | start/admin.js | JavaScript | bsd-3-clause | 4,847 |
<?php
namespace common\models;
use Yii;
use yii\db\ActiveRecord;
/**
* This is the model class for table "template_js".
*
* @property integer $id
* @property integer $template_id
* @property integer $js_id
*
* @property Js $js
* @property Template $template
*/
class TemplateJs extends ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'template_js';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['template_id', 'js_id'], 'required'],
[['template_id', 'js_id'], 'integer']
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'template_id' => Yii::t('app', 'Template ID'),
'js_id' => Yii::t('app', 'Js ID'),
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getJs()
{
return $this->hasOne(Js::className(), ['id' => 'js_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getTemplate()
{
return $this->hasOne(Template::className(), ['id' => 'template_id']);
}
}
| dmitry-grasevich/tg | common/models/TemplateJs.php | PHP | bsd-3-clause | 1,232 |
/**
* Copyright (c) 2015, Legendum Ltd. 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 ntil nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* ntil - create a handler to call a function until the result is good.
*
* This package provides a single method "ntil()" which is called thus:
*
* ntil(performer, success, failure, opts)
*
* checker - a function to check a result and return true or false
* performer - a function to call to perform a task which may succeed or fail
* success - an optional function to process the result of a successful call
* failure - an optional function to process the result of a failed call
* opts - an optional hash of options (see below)
*
* ntil() will return a handler that may be called with any number of arguments.
* The performer function will receive these arguments, with a final "next" arg
* appended to the argument list, such that it should be called on completion,
* passing the result (as a single argument *or* multiple arguments) thus:
*
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*
* var ntil = require('ntil');
* var handler = ntil(
* function(result) { return result === 3 }, // the checker
* function myFunc(a, b, next) { next(a + b) }, // the performer
* function(result) { console.log('success! ' + result) }, // on success
* function(result) { console.log('failure! ' + result) }, // on failure
* {logger: console} // options
* );
*
* handler(1, 1); // this will fail after 7 attempts (taking about a minute)
* handler(1, 2); // this will succeed immediately
*
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*
* ...and here's the equivalent code in a syntax more similar to promises:
*
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*
* var ntil = require('./ntil');
* var handler = ntil(
* function(result) { return result === 3 }
* ).exec(
* function myFunc(a, b, next) { next(a + b) }
* ).done(
* function(result) { console.log('success! ' + result) }
* ).fail(
* function(result) { console.log('failure! ' + result) }
* }.opts(
* {logger: console}
* ).func();
*
* handler(1, 1); // this will fail after 7 attempts (taking about a minute)
* handler(1, 2); // this will succeed immediately
*
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*
* Note that the logger includes "myFunc" in log messages, because the function
* is named. An alternative is to use the "name" option (see below).
*
* The "checker" function checks that the result is 3, causing the first handler
* to fail (it has a result of 2, not 3) and the second handler to succeed.
*
* The output from both these examples is:
*
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*
* perform: 1 failure - trying again in 1 seconds
* perform: success
* success! 3
* perform: 2 failures - trying again in 2 seconds
* perform: 3 failures - trying again in 4 seconds
* perform: 4 failures - trying again in 8 seconds
* perform: 5 failures - trying again in 16 seconds
* perform: 6 failures - trying again in 32 seconds
* perform: too many failures (7)
* failure! 2
*
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*
*
* The options may optionally include:
* name: The name of the "performer" function we're calling, e.g. "getData"
* logger: A logger object that responds to "info" and "warn" method calls
* waitSecs: The initial duration in seconds to wait before retrying
* waitMult: The factor by which to multiply the wait duration upon each retry
* maxCalls: The maximum number of calls to make before failing
*
* Note that "waitSecs" defaults to 1, "waitMult" defaults to 2, and "maxCalls" * defaults to 7.
*
* Ideas for improvement? Email kevin.hutchinson@legendum.com
*/
(function() {
"use strict";
var sig = "Check params: function ntil(checker, performer, success, failure, opts)";
function chain(checker, opts) {
this.opts = function(options) { opts = options; return this }
this.exec = function(perform) { this.perform = perform; return this };
this.done = function(success) { this.success = success; return this };
this.fail = function(failure) { this.failure = failure; return this };
this.func = function() {
return ntil(checker, this.perform, this.success, this.failure, opts);
};
}
function ntil(checker, performer, success, failure, opts) {
opts = opts || {};
if (typeof checker !== 'function') throw sig;
if (typeof performer !== 'function') return new chain(checker, performer);
var name = opts.name || performer.name || 'anonymous function',
logger = opts.logger,
waitSecs = opts.waitSecs || 1,
waitMult = opts.waitMult || 2,
maxCalls = opts.maxCalls || 7; // it takes about a minute for 7 attempts
return function() {
var args = Array.prototype.slice.call(arguments, 0),
wait = waitSecs,
calls = 0;
function next() {
var result = Array.prototype.slice.call(arguments, 0);
if (checker.apply(checker, result) === true) {
if (logger) logger.info(name + ': success');
if (typeof success === 'function') success.apply(success, result);
} else {
calls++;
if (calls < maxCalls) {
if (logger) logger.warn(name + ': ' + calls + ' failure' + (calls === 1 ? '' : 's') + ' - trying again in ' + wait + ' seconds');
setTimeout(function() {
invoke();
}, wait * 1000);
wait *= waitMult;
} else {
if (logger) logger.warn(name + ': too many failures (' + calls + ')');
if (typeof failure === 'function') failure.apply(failure, result);
}
}
}
function invoke() {
try {
performer.apply(performer, args);
} catch (e) {
if (logger) logger.warn(name + ': exception "' + e + '"');
next();
}
}
args.push(next);
invoke();
}
}
if (typeof module !== 'undefined' && module.exports) {
module.exports = ntil;
} else { // browser?
this.ntil = ntil;
}
}).call(this);
| legendum/ntil | ntil.js | JavaScript | bsd-3-clause | 7,810 |
<?php
use yii\bootstrap\ActiveForm;
use yii\helpers\Html;
use yii\grid\GridView;
use yii\helpers\Url;
use app\models\Ticket;
$this->params['breadcrumbs'][] = ['label' => Yii::t('app','ticket list'), 'url' => ['#']];
$this->params['addUrl'] = 'ticket/new';
?>
<div class="row">
<div class="col-lg-12">
<!-- START YOUR CONTENT HERE -->
<div class="portlet"><!-- /Portlet -->
<div class="portlet-heading dark">
<div class="portlet-title">
<h4><i class="fa fa-newspaper-o"></i> <?=Yii::t("app","my ticket") ?></h4>
</div>
<div class="portlet-widgets">
<a data-toggle="collapse" data-parent="#accordion" href="#basic"><i class="fa fa-chevron-down"></i></a>
<span class="divider"></span>
<a href="#" class="box-close"><i class="fa fa-times"></i></a>
</div>
<div class="clearfix"></div>
</div>
<div id="basic" class="panel-collapse collapse in">
<div class="portlet-body">
<div class="row">
<div class="log-lg-12">
<?=Yii::$app->session->getFlash("message")?>
</div>
<div class="col-lg-12">
<?=GridView::widget( [
'dataProvider' => $dataProvider,
//'filterModel' => $model,
'tableOptions' => ['class'=>'table table-bordered table-hover tc-table table-responsive'],
'layout' => '<div class="hidden-sm hidden-xs hidden-md">{summary}</div>{errors}{items}<div class="pagination pull-right">{pager}</div> <div class="clearfix"></div>',
'columns'=>[
['class' => 'yii\grid\SerialColumn'],
'ticket_id' => [
'attribute' => 'ticket_id',
'footer' => Yii::t('app','id'),
'headerOptions' => ['class'=>'hidden-xs hidden-sm'],
'contentOptions'=> ['class'=>'hidden-xs hidden-sm'],
'footerOptions' => ['class'=>'hidden-xs hidden-sm'],
],
'ticket_date' => [
'attribute' => 'ticket_date',
'footer' => Yii::t('app','date'),
],
'ticket_subject' => [
'attribute' => 'ticket_subject',
'footer' => Yii::t('app','subject'),
],
'ticket_status_string' => [
'attribute' => 'ticket_status_string',
'footer' => Yii::t('app','status'),
'headerOptions' => ['class'=>'hidden-xs hidden-sm'],
'contentOptions'=> ['class'=>'hidden-xs hidden-sm'],
'footerOptions' => ['class'=>'hidden-xs hidden-sm'],
],
'helpdesk_name' => [
'attribute' => 'helpdesk_name',
'footer' => Yii::t('app','support'),
],
],
'showFooter' => true ,
] );?>
</div>
</div>
</div>
</div>
</div><!--/Portlet -->
</div> <!-- Enf of col lg-->
</div> <!-- ENd of row -->
<script>
//for tables checkbox dem
jQuery(function($) {
$('.input-group.date').datepicker({
autoclose : true,
format: "dd/mm/yyyy"
});
$('table th input:checkbox').on('click' , function(){
var that = this;
$(this).closest('table').find('tr > td:first-child input:checkbox')
.each(function(){
this.checked = that.checked;
$(this).closest('tr').toggleClass('selected');
});
});
$('.btn-pwd').click(function (e) {
if (!confirm('<?=Yii::t('app/message','msg btn password')?>')) return false;
return true;
});
$('.btn-delete').click(function (e) {
if (!confirm('<?=Yii::t('app/message','msg btn delete')?>')) return false;
return true;
});
});
</script> | suhe/bdoticket | views/ticket/ticket_all_request.php | PHP | bsd-3-clause | 3,532 |
<?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model app\models\Category */
$this->title = 'Update Consultant Category: ' . ' ' . $model->category;
$this->params['breadcrumbs'][] = ['label' => 'Categories', 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => $model->category, 'url' => ['view', 'id' => $model->categoryid]];
$this->params['breadcrumbs'][] = 'Update';
?>
<div class="category-update">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
]) ?>
</div>
| prayogo/pms.yii2 | views/category/update.php | PHP | bsd-3-clause | 565 |
<?php
namespace app\controllers\user;
use Yii;
use dektrium\user\controllers\ProfileController as PController;
use app\models\ProfileSearch;
/**
* UserInfoController implements the CRUD actions for UserInfo model.
*/
class ProfileController extends PController
{
/*public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
];
}*/
/**
* Lists all UserInfo models.
* @return mixed
*/
public function actionIndex()
{
$searchModel = new ProfileSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single UserInfo model.
* @param integer $id
* @return mixed
*/
/*public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}*/
/**
* Creates a new UserInfo model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/
/*public function actionCreate()
{
$model = new UserInfo();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}*/
/**
* Updates an existing UserInfo model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id
* @return mixed
*/
/*public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}*/
/**
* Deletes an existing UserInfo model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* @param integer $id
* @return mixed
*/
/*public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}*/
/**
* Finds the UserInfo model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return UserInfo the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
/*protected function findModel($id)
{
if (($model = UserInfo::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}*/
}
| ASLANTORRET/rgktask | controllers/user/ProfileController.php | PHP | bsd-3-clause | 3,088 |
/*
* [The BSD 3-Clause License]
* Copyright (c) 2015, Samuel Suffos
* 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. Neither the name of the copyright holder nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Matlab.Nodes
{
[Serializable]
public abstract class InnerNode : InternalNode
{
#region CONSTRUCTORS:
protected InnerNode()
: base()
{
return;
}
#endregion
}
}
| samuel-suffos/matlab-parser | Matlab.Nodes/02 Node/02 Internal/02 Inner/00 Base/InnerNode.cs | C# | bsd-3-clause | 2,008 |
#!/usr/bin/python
import os
# With the addition of Keystone, to use an openstack cloud you should
# authenticate against keystone, which returns a **Token** and **Service
# Catalog**. The catalog contains the endpoint for all services the
# user/tenant has access to - including nova, glance, keystone, swift.
#
# *NOTE*: Using the 2.0 *auth api* does not mean that compute api is 2.0. We
# will use the 1.1 *compute api*
os.environ['OS_AUTH_URL'] = "https://keystone.rc.nectar.org.au:5000/v2.0/"
# With the addition of Keystone we have standardized on the term **tenant**
# as the entity that owns the resources.
os.environ['OS_TENANT_ID'] = "123456789012345678901234567890"
os.environ['OS_TENANT_NAME'] = "tenant_name"
# In addition to the owning entity (tenant), openstack stores the entity
# performing the action as the **user**.
os.environ['OS_USERNAME'] = "joe.bloggs@uni.edu.au"
# With Keystone you pass the keystone password.
os.environ['OS_PASSWORD'] = "????????????????????"
| wettenhj/mytardis-swift-uploader | openrc.py | Python | bsd-3-clause | 994 |
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/**
* @var yii\web\View $this
* @var app\models\Image $model
* @var yii\widgets\ActiveForm $form
*/
?>
<div class="image-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => 50]) ?>
<?= $form->field($model, 'location_shooting')->textInput(['maxlength' => 200]) ?>
<?= $form->field($model, 'file')->textarea(['rows' => 6]) ?>
<?= $form->field($model, 'upload_date')->textInput() ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
| novomirskoy/yii2gallery | views/image/_form.php | PHP | bsd-3-clause | 754 |
<?php
/*
Copyright (c) 2012, Silvercore Dev. (www.silvercoredev.com)
Todos os direitos reservados.
Ver o arquivo licenca.txt na raiz do BlackbirdIS para mais detalhes.
*/
session_start();
if (!isset($_SESSION["bis"]) || $_SESSION["bis"] != 1) {
header("Location: index.php");
die();
}
?> | silvercoredev/BlackbirdIS | 1.0/src/BlackbirdIS/admin/vsession.php | PHP | bsd-3-clause | 319 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from .local import Local # noqa
from .production import Production # noqa
# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app
| HEG-Arc/Appagoo | appagoo/config/__init__.py | Python | bsd-3-clause | 288 |
/**
* History.js Core
* @author Benjamin Arthur Lupton <contact@balupton.com>
* @copyright 2010-2011 Benjamin Arthur Lupton <contact@balupton.com>
* @license New BSD License <http://creativecommons.org/licenses/BSD/>
*/
(function(window,undefined){
"use strict";
// ========================================================================
// Initialise
// Localise Globals
var
console = window.console||undefined, // Prevent a JSLint complain
document = window.document, // Make sure we are using the correct document
navigator = window.navigator, // Make sure we are using the correct navigator
sessionStorage = false, // sessionStorage
setTimeout = window.setTimeout,
clearTimeout = window.clearTimeout,
setInterval = window.setInterval,
clearInterval = window.clearInterval,
JSON = window.JSON,
alert = window.alert,
History = window.History = window.History||{}, // Public History Object
history = window.history; // Old History Object
// MooTools Compatibility
JSON.stringify = JSON.stringify||JSON.encode;
JSON.parse = JSON.parse||JSON.decode;
try {
sessionStorage = window.sessionStorage; // This will throw an exception in some browsers when cookies/localStorage are explicitly disabled (i.e. Chrome)
sessionStorage.setItem('TEST', '1');
sessionStorage.removeItem('TEST');
} catch(e) {
sessionStorage = false;
}
// Check Existence
if ( typeof History.init !== 'undefined' ) {
throw new Error('History.js Core has already been loaded...');
}
// Initialise History
History.init = function(){
// Check Load Status of Adapter
if ( typeof History.Adapter === 'undefined' ) {
return false;
}
// Check Load Status of Core
if ( typeof History.initCore !== 'undefined' ) {
History.initCore();
}
// Check Load Status of HTML4 Support
if ( typeof History.initHtml4 !== 'undefined' ) {
History.initHtml4();
}
// Return true
return true;
};
// ========================================================================
// Initialise Core
// Initialise Core
History.initCore = function(){
// Initialise
if ( typeof History.initCore.initialized !== 'undefined' ) {
// Already Loaded
return false;
}
else {
History.initCore.initialized = true;
}
// ====================================================================
// Options
/**
* History.options
* Configurable options
*/
History.options = History.options||{};
/**
* History.options.hashChangeInterval
* How long should the interval be before hashchange checks
*/
History.options.hashChangeInterval = History.options.hashChangeInterval || 100;
/**
* History.options.safariPollInterval
* How long should the interval be before safari poll checks
*/
History.options.safariPollInterval = History.options.safariPollInterval || 500;
/**
* History.options.doubleCheckInterval
* How long should the interval be before we perform a double check
*/
History.options.doubleCheckInterval = History.options.doubleCheckInterval || 500;
/**
* History.options.storeInterval
* How long should we wait between store calls
*/
History.options.storeInterval = History.options.storeInterval || 5000;
/**
* History.options.busyDelay
* How long should we wait between busy events
*/
History.options.busyDelay = History.options.busyDelay || 250;
/**
* History.options.debug
* If true will enable debug messages to be logged
*/
History.options.debug = History.options.debug || false;
/**
* History.options.initialTitle
* What is the title of the initial state
*/
History.options.initialTitle = History.options.initialTitle || document.title;
// ====================================================================
// Interval record
/**
* History.intervalList
* List of intervals set, to be cleared when document is unloaded.
*/
History.intervalList = [];
/**
* History.clearAllIntervals
* Clears all setInterval instances.
*/
History.clearAllIntervals = function(){
var i, il = History.intervalList;
if (typeof il !== "undefined" && il !== null) {
for (i = 0; i < il.length; i++) {
clearInterval(il[i]);
}
History.intervalList = null;
}
};
// ====================================================================
// Debug
/**
* History.debug(message,...)
* Logs the passed arguments if debug enabled
*/
History.debug = function(){
if ( (History.options.debug||false) ) {
History.log.apply(History,arguments);
}
};
/**
* History.log(message,...)
* Logs the passed arguments
*/
History.log = function(){
// Prepare
var
consoleExists = !(typeof console === 'undefined' || typeof console.log === 'undefined' || typeof console.log.apply === 'undefined'),
textarea = document.getElementById('log'),
message,
i,n,
args,arg
;
// Write to Console
if ( consoleExists ) {
args = Array.prototype.slice.call(arguments);
message = args.shift();
if ( typeof console.debug !== 'undefined' ) {
console.debug.apply(console,[message,args]);
}
else {
console.log.apply(console,[message,args]);
}
}
else {
message = ("\n"+arguments[0]+"\n");
}
// Write to log
for ( i=1,n=arguments.length; i<n; ++i ) {
arg = arguments[i];
if ( typeof arg === 'object' && typeof JSON !== 'undefined' ) {
try {
arg = JSON.stringify(arg);
}
catch ( Exception ) {
// Recursive Object
}
}
message += "\n"+arg+"\n";
}
// Textarea
if ( textarea ) {
textarea.value += message+"\n-----\n";
textarea.scrollTop = textarea.scrollHeight - textarea.clientHeight;
}
// No Textarea, No Console
else if ( !consoleExists ) {
alert(message);
}
// Return true
return true;
};
// ====================================================================
// Emulated Status
/**
* History.getInternetExplorerMajorVersion()
* Get's the major version of Internet Explorer
* @return {integer}
* @license Public Domain
* @author Benjamin Arthur Lupton <contact@balupton.com>
* @author James Padolsey <https://gist.github.com/527683>
*/
History.getInternetExplorerMajorVersion = function(){
var result = History.getInternetExplorerMajorVersion.cached =
(typeof History.getInternetExplorerMajorVersion.cached !== 'undefined')
? History.getInternetExplorerMajorVersion.cached
: (function(){
var v = 3,
div = document.createElement('div'),
all = div.getElementsByTagName('i');
while ( (div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->') && all[0] ) {}
return (v > 4) ? v : false;
})()
;
return result;
};
/**
* History.isInternetExplorer()
* Are we using Internet Explorer?
* @return {boolean}
* @license Public Domain
* @author Benjamin Arthur Lupton <contact@balupton.com>
*/
History.isInternetExplorer = function(){
var result =
History.isInternetExplorer.cached =
(typeof History.isInternetExplorer.cached !== 'undefined')
? History.isInternetExplorer.cached
: Boolean(History.getInternetExplorerMajorVersion())
;
return result;
};
/**
* History.emulated
* Which features require emulating?
*/
History.emulated = {
pushState: !Boolean(
window.history && window.history.pushState && window.history.replaceState
&& !(
(/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i).test(navigator.userAgent) /* disable for versions of iOS before version 4.3 (8F190) */
|| (/AppleWebKit\/5([0-2]|3[0-2])/i).test(navigator.userAgent) /* disable for the mercury iOS browser, or at least older versions of the webkit engine */
)
),
hashChange: Boolean(
!(('onhashchange' in window) || ('onhashchange' in document))
||
(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8)
)
};
/**
* History.enabled
* Is History enabled?
*/
History.enabled = !History.emulated.pushState;
/**
* History.bugs
* Which bugs are present
*/
History.bugs = {
/**
* Safari 5 and Safari iOS 4 fail to return to the correct state once a hash is replaced by a `replaceState` call
* https://bugs.webkit.org/show_bug.cgi?id=56249
*/
setHash: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),
/**
* Safari 5 and Safari iOS 4 sometimes fail to apply the state change under busy conditions
* https://bugs.webkit.org/show_bug.cgi?id=42940
*/
safariPoll: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),
/**
* MSIE 6 and 7 sometimes do not apply a hash even it was told to (requiring a second call to the apply function)
*/
ieDoubleCheck: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8),
/**
* MSIE 6 requires the entire hash to be encoded for the hashes to trigger the onHashChange event
*/
hashEscape: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 7)
};
/**
* History.isEmptyObject(obj)
* Checks to see if the Object is Empty
* @param {Object} obj
* @return {boolean}
*/
History.isEmptyObject = function(obj) {
for ( var name in obj ) {
return false;
}
return true;
};
/**
* History.cloneObject(obj)
* Clones a object and eliminate all references to the original contexts
* @param {Object} obj
* @return {Object}
*/
History.cloneObject = function(obj) {
var hash,newObj;
if ( obj ) {
hash = JSON.stringify(obj);
newObj = JSON.parse(hash);
}
else {
newObj = {};
}
return newObj;
};
History.extendObject = function(obj, extension) {
for (var key in extension)
{
if (extension.hasOwnProperty(key))
{
obj[key] = extension[key];
}
}
};
History.setSessionStorageItem = function(key, value)
{
try
{
sessionStorage.setItem(key, value);
}
catch(e)
{
try
{
// hack: Workaround for a bug seen on iPads. Sometimes the quota exceeded error comes up and simply
// removing/resetting the storage can work.
sessionStorage.removeItem(key);
sessionStorage.setItem(key, value);
}
catch(e)
{
try
{
// no permissions or quota exceed
if (e.name === 'QuotaExceededError' ||
e.name === 'NS_ERROR_DOM_QUOTA_REACHED')
{
History.Adapter.trigger(window, 'storageQuotaExceed');
sessionStorage.setItem(key, value);
}
}
catch(e)
{
}
}
}
}
// ====================================================================
// URL Helpers
/**
* History.getRootUrl()
* Turns "http://mysite.com/dir/page.html?asd" into "http://mysite.com"
* @return {String} rootUrl
*/
History.getRootUrl = function(){
// Create
var rootUrl = document.location.protocol+'//'+(document.location.hostname||document.location.host);
if ( document.location.port||false ) {
rootUrl += ':'+document.location.port;
}
rootUrl += '/';
// Return
return rootUrl;
};
/**
* History.getBaseHref()
* Fetches the `href` attribute of the `<base href="...">` element if it exists
* @return {String} baseHref
*/
History.getBaseHref = function(){
// Create
var
baseElements = document.getElementsByTagName('base'),
baseElement = null,
baseHref = '';
// Test for Base Element
if ( baseElements.length === 1 ) {
// Prepare for Base Element
baseElement = baseElements[0];
baseHref = baseElement.href.replace(/[^\/]+$/,'');
}
// Adjust trailing slash
baseHref = baseHref.replace(/\/+$/,'');
if ( baseHref ) baseHref += '/';
// Return
return baseHref;
};
/**
* History.getBaseUrl()
* Fetches the baseHref or basePageUrl or rootUrl (whichever one exists first)
* @return {String} baseUrl
*/
History.getBaseUrl = function(){
// Create
var baseUrl = History.getBaseHref()||History.getBasePageUrl()||History.getRootUrl();
// Return
return baseUrl;
};
/**
* History.getPageUrl()
* Fetches the URL of the current page
* @return {String} pageUrl
*/
History.getPageUrl = function(){
// Fetch
var
State = History.getState(false,false),
stateUrl = (State||{}).url||document.location.href,
pageUrl;
// Create
pageUrl = stateUrl.replace(/\/+$/,'').replace(/[^\/]+$/,function(part,index,string){
return (/\./).test(part) ? part : part+'/';
});
// Return
return pageUrl;
};
/**
* History.getBasePageUrl()
* Fetches the Url of the directory of the current page
* @return {String} basePageUrl
*/
History.getBasePageUrl = function(){
// Create
var basePageUrl = document.location.href.replace(/[#\?].*/,'').replace(/[^\/]+$/,function(part,index,string){
return (/[^\/]$/).test(part) ? '' : part;
}).replace(/\/+$/,'')+'/';
// Return
return basePageUrl;
};
/**
* History.getFullUrl(url)
* Ensures that we have an absolute URL and not a relative URL
* @param {string} url
* @param {Boolean} allowBaseHref
* @return {string} fullUrl
*/
History.getFullUrl = function(url,allowBaseHref){
// Prepare
var fullUrl = url, firstChar = url.substring(0,1);
allowBaseHref = (typeof allowBaseHref === 'undefined') ? true : allowBaseHref;
// Check
if ( /[a-z]+\:\/\//.test(url) ) {
// Full URL
}
else if ( firstChar === '/' ) {
// Root URL
fullUrl = History.getRootUrl()+url.replace(/^\/+/,'');
}
else if ( firstChar === '#' ) {
// Anchor URL
fullUrl = History.getPageUrl().replace(/#.*/,'')+url;
}
else if ( firstChar === '?' ) {
// Query URL
fullUrl = History.getPageUrl().replace(/[\?#].*/,'')+url;
}
else {
// Relative URL
if ( allowBaseHref ) {
fullUrl = History.getBaseUrl()+url.replace(/^(\.\/)+/,'');
} else {
fullUrl = History.getBasePageUrl()+url.replace(/^(\.\/)+/,'');
}
// We have an if condition above as we do not want hashes
// which are relative to the baseHref in our URLs
// as if the baseHref changes, then all our bookmarks
// would now point to different locations
// whereas the basePageUrl will always stay the same
}
// Return
return fullUrl.replace(/\#$/,'');
};
/**
* History.getShortUrl(url)
* Ensures that we have a relative URL and not a absolute URL
* @param {string} url
* @return {string} url
*/
History.getShortUrl = function(url){
// Prepare
var shortUrl = url, baseUrl = History.getBaseUrl(), rootUrl = History.getRootUrl();
// Trim baseUrl
if ( History.emulated.pushState ) {
// We are in a if statement as when pushState is not emulated
// The actual url these short urls are relative to can change
// So within the same session, we the url may end up somewhere different
shortUrl = shortUrl.replace(baseUrl,'');
}
// Trim rootUrl
shortUrl = shortUrl.replace(rootUrl,'/');
// Ensure we can still detect it as a state
if ( History.isTraditionalAnchor(shortUrl) ) {
shortUrl = './'+shortUrl;
}
// Clean It
shortUrl = shortUrl.replace(/^(\.\/)+/g,'./').replace(/\#$/,'');
// Return
return shortUrl;
};
// ====================================================================
// State Storage
/**
* History.store
* The store for all session specific data
*/
History.store = {};
/**
* History.idToState
* 1-1: State ID to State Object
*/
History.idToState = History.idToState||{};
/**
* History.stateToId
* 1-1: State String to State ID
*/
History.stateToId = History.stateToId||{};
/**
* History.urlToId
* 1-1: State URL to State ID
*/
History.urlToId = History.urlToId||{};
/**
* History.storedStates
* Store the states in an array
*/
History.storedStates = History.storedStates||[];
/**
* History.savedStates
* Saved the states in an array
*/
History.savedStates = History.savedStates||[];
/**
* History.noramlizeStore()
* Noramlize the store by adding necessary values
*/
History.normalizeStore = function(){
History.store.idToState = History.store.idToState||{};
History.store.urlToId = History.store.urlToId||{};
History.store.stateToId = History.store.stateToId||{};
};
/**
* History.getState()
* Get an object containing the data, title and url of the current state
* @param {Boolean} friendly
* @param {Boolean} create
* @return {Object} State
*/
History.getState = function(friendly,create){
// Prepare
if ( typeof friendly === 'undefined' ) { friendly = true; }
if ( typeof create === 'undefined' ) { create = true; }
// Fetch
var State = History.getLastSavedState();
// Create
if ( !State && create ) {
State = History.createStateObject();
}
// Adjust
if ( friendly ) {
State = History.cloneObject(State);
State.url = State.cleanUrl||State.url;
}
// Return
return State;
};
/**
* History.getIdByState(State)
* Gets a ID for a State
* @param {State} newState
* @return {String} id
*/
History.getIdByState = function(newState){
// Fetch ID
var id = History.extractId(newState.url),
lastSavedState,
str;
if ( !id ) {
// Find ID via State String
str = History.getStateString(newState);
if ( typeof History.stateToId[str] !== 'undefined' ) {
id = History.stateToId[str];
}
else if ( typeof History.store.stateToId[str] !== 'undefined' ) {
id = History.store.stateToId[str];
}
else {
id = sessionStorage ? sessionStorage.getItem('uniqId') : new Date().getTime();
if (id == undefined){
id = 0;
}
lastSavedState = History.getLastSavedState();
if (lastSavedState)
{
id = lastSavedState.id + 1;
if (sessionStorage)
{
History.setSessionStorageItem('uniqId', id);
}
}
else
{
// Generate a new ID
while (true)
{
++id;
if (typeof History.idToState[id] === 'undefined' && typeof History.store.idToState[id] === 'undefined')
{
if (sessionStorage)
{
History.setSessionStorageItem('uniqId', id);
}
break;
}
}
}
// Apply the new State to the ID
History.stateToId[str] = id;
History.idToState[id] = newState;
}
}
// Return ID
return id;
};
/**
* History.normalizeState(State)
* Expands a State Object
* @param {object} State
* @return {object}
*/
History.normalizeState = function(oldState){
// Variables
var newState, dataNotEmpty;
// Prepare
if ( !oldState || (typeof oldState !== 'object') ) {
oldState = {};
}
// Check
if ( typeof oldState.normalized !== 'undefined' ) {
return oldState;
}
// Adjust
if ( !oldState.data || (typeof oldState.data !== 'object') ) {
oldState.data = {};
}
// ----------------------------------------------------------------
// Create
newState = {};
newState.normalized = true;
newState.title = oldState.title||'';
newState.url = History.getFullUrl(History.unescapeString(oldState.url||document.location.href));
newState.hash = History.getShortUrl(newState.url);
newState.data = History.cloneObject(oldState.data);
// Fetch ID
newState.id = History.getIdByState(newState);
// ----------------------------------------------------------------
// Clean the URL
newState.cleanUrl = newState.url.replace(/\??\&_suid.*/,'');
newState.url = newState.cleanUrl;
// Check to see if we have more than just a url
dataNotEmpty = !History.isEmptyObject(newState.data);
// Apply
if ( newState.title || dataNotEmpty ) {
// Add ID to Hash
newState.hash = History.getShortUrl(newState.url).replace(/\??\&_suid.*/,'');
if ( !/\?/.test(newState.hash) ) {
newState.hash += '?';
}
newState.hash += '&_suid='+newState.id;
}
// Create the Hashed URL
newState.hashedUrl = History.getFullUrl(newState.hash);
// ----------------------------------------------------------------
// Update the URL if we have a duplicate
if ( (History.emulated.pushState || History.bugs.safariPoll) && History.hasUrlDuplicate(newState) ) {
newState.url = newState.hashedUrl;
}
// ----------------------------------------------------------------
// Return
return newState;
};
/**
* History.createStateObject(data,title,url)
* Creates a object based on the data, title and url state params
* @param {object} data
* @param {string} title
* @param {string} url
* @return {object}
*/
History.createStateObject = function(data,title,url){
// Hashify
var State = {
'data': data,
'title': title,
'url': url
};
// Expand the State
State = History.normalizeState(State);
// Return object
return State;
};
/**
* History.getStateById(id)
* Get a state by it's UID
* @param {String} id
*/
History.getStateById = function(id){
// Prepare
id = String(id);
// Retrieve
var State = History.idToState[id] || History.store.idToState[id] || undefined;
// Return State
return State;
};
/**
* Get a State's String
* @param {State} passedState
*/
History.getStateString = function(passedState){
// Prepare
var State, cleanedState, str;
// Fetch
State = History.normalizeState(passedState);
// Clean
cleanedState = {
data: State.data,
title: passedState.title,
url: passedState.url
};
// Fetch
str = JSON.stringify(cleanedState);
// Return
return str;
};
/**
* Get a State's ID
* @param {State} passedState
* @return {String} id
*/
History.getStateId = function(passedState){
// Prepare
var State, id;
// Fetch
State = History.normalizeState(passedState);
// Fetch
id = State.id;
// Return
return id;
};
/**
* History.getHashByState(State)
* Creates a Hash for the State Object
* @param {State} passedState
* @return {String} hash
*/
History.getHashByState = function(passedState){
// Prepare
var State, hash;
// Fetch
State = History.normalizeState(passedState);
// Hash
hash = State.hash;
// Return
return hash;
};
/**
* History.extractId(url_or_hash)
* Get a State ID by it's URL or Hash
* @param {string} url_or_hash
* @return {string} id
*/
History.extractId = function ( url_or_hash ) {
// Prepare
var id,parts,url;
// Extract
parts = /(.*)\&_suid=([0-9]+)$/.exec(url_or_hash);
url = parts ? (parts[1]||url_or_hash) : url_or_hash;
id = parts ? String(parts[2]||'') : '';
// Return
return id||false;
};
/**
* History.isTraditionalAnchor
* Checks to see if the url is a traditional anchor or not
* @param {String} url_or_hash
* @return {Boolean}
*/
History.isTraditionalAnchor = function(url_or_hash){
// Check
var isTraditional = !(/[\/\?\.]/.test(url_or_hash));
// Return
return isTraditional;
};
/**
* History.extractState
* Get a State by it's URL or Hash
* @param {String} url_or_hash
* @return {State|null}
*/
History.extractState = function(url_or_hash,create){
// Prepare
var State = null, id, url;
create = create||false;
// Fetch SUID
id = History.extractId(url_or_hash);
if ( id ) {
State = History.getStateById(id);
}
// Fetch SUID returned no State
if ( !State ) {
// Fetch URL
url = History.getFullUrl(url_or_hash);
// Check URL
id = History.getIdByUrl(url)||false;
if ( id ) {
State = History.getStateById(id);
}
// Create State
if ( !State && create && !History.isTraditionalAnchor(url_or_hash) ) {
State = History.createStateObject(null,null,url);
}
}
// Return
return State;
};
/**
* History.getIdByUrl()
* Get a State ID by a State URL
*/
History.getIdByUrl = function(url){
// Fetch
var id = History.urlToId[url] || History.store.urlToId[url] || undefined;
// Return
return id;
};
/**
* History.getLastSavedState()
* Get an object containing the data, title and url of the current state
* @return {Object} State
*/
History.getLastSavedState = function(){
return History.savedStates[History.savedStates.length-1]||undefined;
};
/**
* History.getLastStoredState()
* Get an object containing the data, title and url of the current state
* @return {Object} State
*/
History.getLastStoredState = function(){
return History.storedStates[History.storedStates.length-1]||undefined;
};
/**
* History.hasUrlDuplicate
* Checks if a Url will have a url conflict
* @param {Object} newState
* @return {Boolean} hasDuplicate
*/
History.hasUrlDuplicate = function(newState) {
// Prepare
var hasDuplicate = false,
oldState;
// Fetch
oldState = History.extractState(newState.url);
// Check
hasDuplicate = oldState && oldState.id !== newState.id;
// Return
return hasDuplicate;
};
/**
* History.storeState
* Store a State
* @param {Object} newState
* @return {Object} newState
*/
History.storeState = function(newState){
// Store the State
History.urlToId[newState.url] = newState.id;
// Push the State
History.storedStates.push(History.cloneObject(newState));
// Return newState
return newState;
};
/**
* History.isLastSavedState(newState)
* Tests to see if the state is the last state
* @param {Object} newState
* @return {boolean} isLast
*/
History.isLastSavedState = function(newState){
// Prepare
var isLast = false,
newId, oldState, oldId;
// Check
if ( History.savedStates.length ) {
newId = newState.id;
oldState = History.getLastSavedState();
oldId = oldState.id;
// Check
isLast = (newId === oldId);
}
// Return
return isLast;
};
/**
* History.saveState
* Push a State
* @param {Object} newState
* @return {boolean} changed
*/
History.saveState = function(newState){
// Check Hash
if ( History.isLastSavedState(newState) ) {
return false;
}
// Push the State
History.savedStates.push(History.cloneObject(newState));
// Return true
return true;
};
/**
* History.getStateByIndex()
* Gets a state by the index
* @param {integer} index
* @return {Object}
*/
History.getStateByIndex = function(index){
// Prepare
var State = null;
// Handle
if ( typeof index === 'undefined' ) {
// Get the last inserted
State = History.savedStates[History.savedStates.length-1];
}
else if ( index < 0 ) {
// Get from the end
State = History.savedStates[History.savedStates.length+index];
}
else {
// Get from the beginning
State = History.savedStates[index];
}
// Return State
return State;
};
// ====================================================================
// Hash Helpers
/**
* History.getHash()
* Gets the current document hash
* @return {string}
*/
History.getHash = function(){
var hash = History.unescapeHash(document.location.hash);
return hash;
};
/**
* History.unescapeString()
* Unescape a string
* @param {String} str
* @return {string}
*/
History.unescapeString = function(str){
// Prepare
var result = str,
tmp;
// Unescape hash
while ( true ) {
tmp = window.unescape(result);
if ( tmp === result ) {
break;
}
result = tmp;
}
// Return result
return result;
};
/**
* History.unescapeHash()
* normalize and Unescape a Hash
* @param {String} hash
* @return {string}
*/
History.unescapeHash = function(hash){
// Prepare
var result = History.normalizeHash(hash);
// Unescape hash
result = History.unescapeString(result);
// Return result
return result;
};
/**
* History.normalizeHash()
* normalize a hash across browsers
* @return {string}
*/
History.normalizeHash = function(hash){
// Prepare
var result = hash.replace(/[^#]*#/,'').replace(/#.*/, '');
// Return result
return result;
};
/**
* History.setHash(hash)
* Sets the document hash
* @param {string} hash
* @return {History}
*/
History.setHash = function(hash,queue){
// Prepare
var adjustedHash, State, pageUrl;
// Handle Queueing
if ( queue !== false && History.busy() ) {
// Wait + Push to Queue
//History.debug('History.setHash: we must wait', arguments);
History.pushQueue({
scope: History,
callback: History.setHash,
args: arguments,
queue: queue
});
return false;
}
// Log
//History.debug('History.setHash: called',hash);
// Prepare
adjustedHash = History.escapeHash(hash);
// Make Busy + Continue
History.busy(true);
// Check if hash is a state
State = History.extractState(hash,true);
if ( State && !History.emulated.pushState ) {
// Hash is a state so skip the setHash
//History.debug('History.setHash: Hash is a state so skipping the hash set with a direct pushState call',arguments);
// PushState
History.pushState(State.data,State.title,State.url,false);
}
else if ( document.location.hash !== adjustedHash ) {
// Hash is a proper hash, so apply it
// Handle browser bugs
if ( History.bugs.setHash ) {
// Fix Safari Bug https://bugs.webkit.org/show_bug.cgi?id=56249
// Fetch the base page
pageUrl = History.getPageUrl();
// Safari hash apply
History.pushState(null,null,pageUrl+'#'+adjustedHash,false);
}
else {
// Normal hash apply
document.location.hash = adjustedHash;
}
}
// Chain
return History;
};
/**
* History.escape()
* normalize and Escape a Hash
* @return {string}
*/
History.escapeHash = function(hash){
// Prepare
var result = History.normalizeHash(hash);
// Escape hash
result = window.escape(result);
// IE6 Escape Bug
if ( !History.bugs.hashEscape ) {
// Restore common parts
result = result
.replace(/\%21/g,'!')
.replace(/\%26/g,'&')
.replace(/\%3D/g,'=')
.replace(/\%3F/g,'?');
}
// Return result
return result;
};
/**
* History.getHashByUrl(url)
* Extracts the Hash from a URL
* @param {string} url
* @return {string} url
*/
History.getHashByUrl = function(url){
// Extract the hash
var hash = String(url)
.replace(/([^#]*)#?([^#]*)#?(.*)/, '$2')
;
// Unescape hash
hash = History.unescapeHash(hash);
// Return hash
return hash;
};
/**
* History.setTitle(title)
* Applies the title to the document
* @param {State} newState
* @return {Boolean}
*/
History.setTitle = function(newState){
// Prepare
var title = newState.title,
firstState;
// Initial
if ( !title ) {
firstState = History.getStateByIndex(0);
if ( firstState && firstState.url === newState.url ) {
title = firstState.title||History.options.initialTitle;
}
}
// Apply
try {
document.getElementsByTagName('title')[0].innerHTML = title.replace('<','<').replace('>','>').replace(' & ',' & ');
}
catch ( Exception ) { }
document.title = title;
// Chain
return History;
};
// ====================================================================
// Queueing
/**
* History.queues
* The list of queues to use
* First In, First Out
*/
History.queues = [];
/**
* History.busy(value)
* @param {boolean} value [optional]
* @return {boolean} busy
*/
History.busy = function(value){
// Apply
if ( typeof value !== 'undefined' ) {
//History.debug('History.busy: changing ['+(History.busy.flag||false)+'] to ['+(value||false)+']', History.queues.length);
History.busy.flag = value;
}
// Default
else if ( typeof History.busy.flag === 'undefined' ) {
History.busy.flag = false;
}
// Queue
if ( !History.busy.flag ) {
// Execute the next item in the queue
clearTimeout(History.busy.timeout);
var fireNext = function(){
var i, queue, item;
if ( History.busy.flag ) return;
for ( i=History.queues.length-1; i >= 0; --i ) {
queue = History.queues[i];
if ( queue.length === 0 ) continue;
item = queue.shift();
History.fireQueueItem(item);
History.busy.timeout = setTimeout(fireNext,History.options.busyDelay);
}
};
History.busy.timeout = setTimeout(fireNext,History.options.busyDelay);
}
// Return
return History.busy.flag;
};
/**
* History.busy.flag
*/
History.busy.flag = false;
/**
* History.fireQueueItem(item)
* Fire a Queue Item
* @param {Object} item
* @return {Mixed} result
*/
History.fireQueueItem = function(item){
return item.callback.apply(item.scope||History,item.args||[]);
};
/**
* History.pushQueue(callback,args)
* Add an item to the queue
* @param {Object} item [scope,callback,args,queue]
*/
History.pushQueue = function(item){
// Prepare the queue
History.queues[item.queue||0] = History.queues[item.queue||0]||[];
// Add to the queue
History.queues[item.queue||0].push(item);
// Chain
return History;
};
/**
* History.queue (item,queue), (func,queue), (func), (item)
* Either firs the item now if not busy, or adds it to the queue
*/
History.queue = function(item,queue){
// Prepare
if ( typeof item === 'function' ) {
item = {
callback: item
};
}
if ( typeof queue !== 'undefined' ) {
item.queue = queue;
}
// Handle
if ( History.busy() ) {
History.pushQueue(item);
} else {
History.fireQueueItem(item);
}
// Chain
return History;
};
/**
* History.clearQueue()
* Clears the Queue
*/
History.clearQueue = function(){
History.busy.flag = false;
History.queues = [];
return History;
};
// ====================================================================
// IE Bug Fix
/**
* History.stateChanged
* States whether or not the state has changed since the last double check was initialised
*/
History.stateChanged = false;
/**
* History.doubleChecker
* Contains the timeout used for the double checks
*/
History.doubleChecker = false;
/**
* History.doubleCheckComplete()
* Complete a double check
* @return {History}
*/
History.doubleCheckComplete = function(){
// Update
History.stateChanged = true;
// Clear
History.doubleCheckClear();
// Chain
return History;
};
/**
* History.doubleCheckClear()
* Clear a double check
* @return {History}
*/
History.doubleCheckClear = function(){
// Clear
if ( History.doubleChecker ) {
clearTimeout(History.doubleChecker);
History.doubleChecker = false;
}
// Chain
return History;
};
/**
* History.doubleCheck()
* Create a double check
* @return {History}
*/
History.doubleCheck = function(tryAgain){
// Reset
History.stateChanged = false;
History.doubleCheckClear();
// Fix IE6,IE7 bug where calling history.back or history.forward does not actually change the hash (whereas doing it manually does)
// Fix Safari 5 bug where sometimes the state does not change: https://bugs.webkit.org/show_bug.cgi?id=42940
if ( History.bugs.ieDoubleCheck ) {
// Apply Check
History.doubleChecker = setTimeout(
function(){
History.doubleCheckClear();
if ( !History.stateChanged ) {
//History.debug('History.doubleCheck: State has not yet changed, trying again', arguments);
// Re-Attempt
tryAgain();
}
return true;
},
History.options.doubleCheckInterval
);
}
// Chain
return History;
};
// ====================================================================
// Safari Bug Fix
/**
* History.safariStatePoll()
* Poll the current state
* @return {History}
*/
History.safariStatePoll = function(){
// Poll the URL
// Get the Last State which has the new URL
var
urlState = History.extractState(document.location.href),
newState;
// Check for a difference
if ( !History.isLastSavedState(urlState) ) {
newState = urlState;
}
else {
return;
}
// Check if we have a state with that url
// If not create it
if ( !newState ) {
//History.debug('History.safariStatePoll: new');
newState = History.createStateObject();
}
// Apply the New State
//History.debug('History.safariStatePoll: trigger');
History.Adapter.trigger(window,'popstate');
// Chain
return History;
};
// ====================================================================
// State Aliases
/**
* History.back(queue)
* Send the browser history back one item
* @param {Integer} queue [optional]
*/
History.back = function(queue){
//History.debug('History.back: called', arguments);
// Handle Queueing
if ( queue !== false && History.busy() ) {
// Wait + Push to Queue
//History.debug('History.back: we must wait', arguments);
History.pushQueue({
scope: History,
callback: History.back,
args: arguments,
queue: queue
});
return false;
}
// Make Busy + Continue
History.busy(true);
// Fix certain browser bugs that prevent the state from changing
History.doubleCheck(function(){
History.back(false);
});
// Go back
history.go(-1);
// End back closure
return true;
};
/**
* History.forward(queue)
* Send the browser history forward one item
* @param {Integer} queue [optional]
*/
History.forward = function(queue){
//History.debug('History.forward: called', arguments);
// Handle Queueing
if ( queue !== false && History.busy() ) {
// Wait + Push to Queue
//History.debug('History.forward: we must wait', arguments);
History.pushQueue({
scope: History,
callback: History.forward,
args: arguments,
queue: queue
});
return false;
}
// Make Busy + Continue
History.busy(true);
// Fix certain browser bugs that prevent the state from changing
History.doubleCheck(function(){
History.forward(false);
});
// Go forward
history.go(1);
// End forward closure
return true;
};
/**
* History.go(index,queue)
* Send the browser history back or forward index times
* @param {Integer} queue [optional]
*/
History.go = function(index,queue){
//History.debug('History.go: called', arguments);
// Prepare
var i;
// Handle
if ( index > 0 ) {
// Forward
for ( i=1; i<=index; ++i ) {
History.forward(queue);
}
}
else if ( index < 0 ) {
// Backward
for ( i=-1; i>=index; --i ) {
History.back(queue);
}
}
else {
throw new Error('History.go: History.go requires a positive or negative integer passed.');
}
// Chain
return History;
};
// ====================================================================
// HTML5 State Support
// Non-Native pushState Implementation
if ( History.emulated.pushState ) {
/*
* Provide Skeleton for HTML4 Browsers
*/
// Prepare
var emptyFunction = function(){};
History.pushState = History.pushState||emptyFunction;
History.replaceState = History.replaceState||emptyFunction;
} // History.emulated.pushState
// Native pushState Implementation
else {
/*
* Use native HTML5 History API Implementation
*/
/**
* History.onPopState(event,extra)
* Refresh the Current State
*/
History.onPopState = function(event,extra){
// Prepare
var stateId = false, newState = false, currentHash, currentState;
// Reset the double check
History.doubleCheckComplete();
// Check for a Hash, and handle apporiatly
currentHash = History.getHash();
if ( currentHash ) {
// Expand Hash
currentState = History.extractState(currentHash||document.location.href,true);
if ( currentState ) {
// We were able to parse it, it must be a State!
// Let's forward to replaceState
//History.debug('History.onPopState: state anchor', currentHash, currentState);
History.replaceState(currentState.data, currentState.title, currentState.url, false);
}
else {
// Traditional Anchor
//History.debug('History.onPopState: traditional anchor', currentHash);
History.Adapter.trigger(window,'anchorchange');
History.busy(false);
}
// We don't care for hashes
History.expectedStateId = false;
return false;
}
// Ensure
stateId = History.Adapter.extractEventData('state',event,extra) || false;
// Fetch State
if ( stateId ) {
// Vanilla: Back/forward button was used
newState = History.getStateById(stateId);
}
else if ( History.expectedStateId ) {
// Vanilla: A new state was pushed, and popstate was called manually
newState = History.getStateById(History.expectedStateId);
}
else {
// Initial State
newState = History.extractState(document.location.href);
}
// The State did not exist in our store
if ( !newState ) {
// Regenerate the State
newState = History.createStateObject(null,null,document.location.href);
}
// Clean
History.expectedStateId = false;
// Check if we are the same state
if ( History.isLastSavedState(newState) ) {
// There has been no change (just the page's hash has finally propagated)
//History.debug('History.onPopState: no change', newState, History.savedStates);
History.busy(false);
return false;
}
// Store the State
History.storeState(newState);
History.saveState(newState);
// Force update of the title
History.setTitle(newState);
// Fire Our Event
History.Adapter.trigger(window,'statechange');
History.busy(false);
// Return true
return true;
};
History.Adapter.bind(window,'popstate',History.onPopState);
/**
* History.pushState(data,title,url)
* Add a new State to the history object, become it, and trigger onpopstate
* We have to trigger for HTML4 compatibility
* @param {object} data
* @param {string} title
* @param {string} url
* @return {true}
*/
History.pushState = function(data,title,url,queue){
//History.debug('History.pushState: called', arguments);
// Check the State
if ( History.getHashByUrl(url) && History.emulated.pushState ) {
throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
}
// Handle Queueing
if ( queue !== false && History.busy() ) {
// Wait + Push to Queue
//History.debug('History.pushState: we must wait', arguments);
History.pushQueue({
scope: History,
callback: History.pushState,
args: arguments,
queue: queue
});
return false;
}
// Make Busy + Continue
History.busy(true);
// Create the newState
var newState = History.createStateObject(data,title,url);
// Check it
if ( History.isLastSavedState(newState) ) {
// Won't be a change
History.busy(false);
}
else {
//remove previously stored state, because it can be and can be non empty
History.Adapter.trigger(window, 'stateremove', { stateId: newState.id });
// Store the newState
History.storeState(newState);
History.expectedStateId = newState.id;
// Push the newState
history.pushState(newState.id,newState.title,newState.url);
// Fire HTML5 Event
History.Adapter.trigger(window,'popstate');
}
// End pushState closure
return true;
};
/**
* History.replaceState(data,title,url)
* Replace the State and trigger onpopstate
* We have to trigger for HTML4 compatibility
* @param {object} data
* @param {string} title
* @param {string} url
* @param {object} queue
* @param {boolean} createNewState
* @return {true}
*/
History.replaceState = function(data,title,url,queue,createNewState){
//History.debug('History.replaceState: called', arguments);
// Check the State
if ( History.getHashByUrl(url) && History.emulated.pushState ) {
throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
}
// Handle Queueing
if ( queue !== false && History.busy() ) {
// Wait + Push to Queue
//History.debug('History.replaceState: we must wait', arguments);
History.pushQueue({
scope: History,
callback: History.replaceState,
args: arguments,
queue: queue
});
return false;
}
// Make Busy + Continue
History.busy(true);
// Create the newState
var newState;
if (createNewState)
{
data.rnd = new Date().getTime();
newState = History.createStateObject(data, title, url);
}
else
{
newState = History.getState();
newState.data = data;
History.idToState[newState.id] = newState;
History.extendObject(History.getLastSavedState(), newState);
}
// Check it
if ( History.isLastSavedState(newState) ) {
// Won't be a change
History.busy(false);
}
else {
// Store the newState
History.storeState(newState);
History.expectedStateId = newState.id;
// Push the newState
history.replaceState(newState.id,newState.title,newState.url);
// Fire HTML5 Event
History.Adapter.trigger(window,'popstate');
}
// End replaceState closure
return true;
};
} // !History.emulated.pushState
// ====================================================================
// Initialise
/**
* Load the Store
*/
if ( sessionStorage ) {
// Fetch
try {
History.store = JSON.parse(/*LZString.decompress*/(sessionStorage.getItem('History.store')))||{};
}
catch ( err ) {
History.store = {};
}
// Normalize
History.normalizeStore();
}
else {
// Default Load
History.store = {};
History.normalizeStore();
}
/**
* Clear Intervals on exit to prevent memory leaks
*/
History.Adapter.bind(window,"beforeunload",History.clearAllIntervals);
History.Adapter.bind(window,"unload",History.clearAllIntervals);
/**
* Create the initial State
*/
History.saveState(History.storeState(History.extractState(document.location.href,true)));
/**
* Bind for Saving Store
*/
if ( sessionStorage ) {
// When the page is closed
History.onUnload = function(){
// Prepare
var currentStore, item;
// Fetch
try {
currentStore = JSON.parse(/*LZString.decompress*/(sessionStorage.getItem('History.store')))||{};
}
catch ( err ) {
currentStore = {};
}
// Ensure
currentStore.idToState = currentStore.idToState || {};
currentStore.urlToId = currentStore.urlToId || {};
currentStore.stateToId = currentStore.stateToId || {};
// Sync
for ( item in History.idToState ) {
if ( !History.idToState.hasOwnProperty(item) ) {
continue;
}
currentStore.idToState[item] = History.idToState[item];
}
for ( item in History.urlToId ) {
if ( !History.urlToId.hasOwnProperty(item) ) {
continue;
}
currentStore.urlToId[item] = History.urlToId[item];
}
for ( item in History.stateToId ) {
if ( !History.stateToId.hasOwnProperty(item) ) {
continue;
}
currentStore.stateToId[item] = History.stateToId[item];
}
var historyEntries = [];
var maxHistoryEntriesCount = 10;
//slice overweight entries
for ( item in currentStore.idToState ) {
if ( !currentStore.idToState.hasOwnProperty(item) ) {
continue;
}
currentStore.idToState[item].entryId = item;
historyEntries.push(currentStore.idToState[item]);
}
if (historyEntries.length > maxHistoryEntriesCount)
{
historyEntries.sort(function(e1, e2)
{
return e1.entryId - e2.entryId;
});
var excludedEntries = historyEntries.slice(0, historyEntries.length - maxHistoryEntriesCount);
for (var entryIndex = 0; entryIndex < excludedEntries.length; entryIndex++)
{
var entry = excludedEntries[entryIndex];
delete currentStore.idToState[entry.entryId];
for (var url in currentStore.urlToId )
{
if (currentStore.urlToId.hasOwnProperty(url) &&
currentStore.urlToId[url] == entry.entryId)
{
delete currentStore.urlToId[url];
}
}
for (var state in currentStore.stateToId )
{
if (currentStore.stateToId.hasOwnProperty(state) &&
currentStore.stateToId[state] == entry.entryId)
{
delete currentStore.stateToId[state];
}
}
History.Adapter.trigger(window, 'stateremove', { stateId: entry.entryId });
}
}
// Update
History.store = currentStore;
History.normalizeStore();
// Store
History.setSessionStorageItem('History.store', /*LZString.compress*/(JSON.stringify(currentStore)));
};
// For Internet Explorer
History.intervalList.push(setInterval(History.onUnload,History.options.storeInterval));
// For Other Browsers
History.Adapter.bind(window,'beforeunload',History.onUnload);
History.Adapter.bind(window,'unload',History.onUnload);
// Both are enabled for consistency
}
// Non-Native pushState Implementation
if ( !History.emulated.pushState ) {
// Be aware, the following is only for native pushState implementations
// If you are wanting to include something for all browsers
// Then include it above this if block
/**
* Setup Safari Fix
*/
if ( History.bugs.safariPoll ) {
History.intervalList.push(setInterval(History.safariStatePoll, History.options.safariPollInterval));
}
/**
* Ensure Cross Browser Compatibility
*/
if ( navigator.vendor === 'Apple Computer, Inc.' || (navigator.appCodeName||'') === 'Mozilla' ) {
/**
* Fix Safari HashChange Issue
*/
// Setup Alias
History.Adapter.bind(window,'hashchange',function(){
History.Adapter.trigger(window,'popstate');
});
// Initialise Alias
if ( History.getHash() ) {
History.Adapter.onDomLoad(function(){
History.Adapter.trigger(window,'hashchange');
});
}
}
} // !History.emulated.pushState
}; // History.initCore
// Try and Initialise History
History.init();
})(window);
| SkReD/history.js | scripts/uncompressed/history.js | JavaScript | bsd-3-clause | 50,992 |
require 'spree_auto_invoice'
require 'rails'
module SpreeAutoInvoice
class Railtie < Rails::Railtie
rake_tasks do
require '../tasks/spree_auto_invoice.rake'
end
end
end
| geekcups-team/spree_auto_invoice | lib/spree_auto_invoice/railtie.rb | Ruby | bsd-3-clause | 188 |
<?php
use librarys\helpers\utils\String;
?>
<!-- 文章正文 下面部分 -->
<div class="a_info neinf">
<div>
<div class="a_rea a_hop">
<h2>
<span><a href="http://jb.9939.com/article_list.shtml">更多文章>></a></span>
与“<font style="color:#F00"><?php echo String::cutString($title, 8, 1)?></font>”相似的文章
</h2>
<ul class="a_prev">
<?php
if (isset($relArticles['list']) && !empty($relArticles['list'])) {
$leftRelArticles = array_splice($relArticles['list'], 0, 12);
foreach ($leftRelArticles as $relArticle){
?>
<li>
<a href="<?php echo '/article/'.date("Y/md", $relArticle["inputtime"]).'/'.$relArticle['id'].'.shtml' ; ?>" title="<?php echo $relArticle['title']; ?>"><?php echo $relArticle['title']; ?></a>
</li>
<?php
}
}
?>
</ul>
</div>
</div>
<div>
<div class="a_rea a_hop inpc">
<h2>
<span>
<a href="http://ask.9939.com/asking/" class="inqu">我要提问</a>
<a href="http://ask.9939.com/">更多问答>></a>
</span>
<img src="/images/pi_02.png">
</h2>
<ul class="a_mon">
<?php
if (isset($asks['list']) && !empty($asks['list'])) {
foreach ($asks['list'] as $outerKey => $outerAsk){
?>
<li>
<h3>
<a href="<?php echo \yii\helpers\Url::to('@ask/id/' . $outerAsk['ask']['id']); ?>" title="<?php echo $outerAsk['ask']['title']; ?>">
<?php echo $outerAsk['ask']['title']; ?>
</a>
</h3>
<p>
<?php
if (isset($outerAsk['answer']) && !empty($outerAsk['answer'])) {
?>
<?php echo \librarys\helpers\utils\String::cutString($outerAsk['answer']['content'], 54); ?>
<?php
}
?>
<a href="<?php echo \yii\helpers\Url::to('@ask/id/' . $outerAsk['ask']['id']); ?>">详细</a>
</p>
</li>
<?php
}
}
?>
</ul>
</div>
</div>
<?php
if (isset($disease) && !empty($disease)) {
?>
<!--热门疾病-->
<div class="a_rea a_hop inpc" style="background: none;">
<h2>
<span>
<?php
if (isset($isSymptom) && $isSymptom == 1) {
?>
<a href="/zhengzhuang/<?php echo $disease['pinyin_initial']; ?>/jiancha/">更多>></a>
<?php
}else {
?>
<a href="/<?php echo $disease['pinyin_initial']; ?>/lcjc/">更多>></a>
<?php } ?>
</span>
<img src="/images/reche.gif">
</h2>
<div class="nipat">
<?php
if (isset($isSymptom) && $isSymptom == 1){
?>
<h3><?php echo $disease['name']; ?><span>症状</span></h3>
<p><?php echo String::cutString($disease['examine'], 100); ?>
<a href="/zhengzhuang/<?php echo $disease['pinyin_initial']; ?>/jiancha/">详细</a>
</p>
<?php
}else {
?>
<h3><?php echo $disease['name']; ?><span>疾病</span></h3>
<p><?php echo String::cutString($disease['inspect'], 100); ?>
<a href="/<?php echo $disease['pinyin_initial']; ?>/lcjc/">详细</a>
</p>
<?php
}
?>
</div>
</div>
<?php } ?>
<div class="a_rea a_hop inpc" style="background: none;">
<h2>
<img src="/images/everb.gif">
</h2>
<?php
if (isset($disease) && !empty($disease)) {
?>
<ul class="finin clearfix">
<?php
if (isset($stillFind) && !empty($stillFind)) {
foreach ($stillFind as $find){
?>
<li>
<a href="http://jb.9939.com/so/<?php echo $find['pinyin']; ?>/" title="<?php echo $find['keywords']; ?>">
<?php echo $find['keywords']; ?>
</a>
</li>
<?php
}
}
?>
</ul>
<?php
}
?>
</div>
<!-- 图谱部分 Start -->
<?php echo $this->render('detail_below_pic'); ?>
<!-- 图谱部分 End -->
</div> | VampireMe/admin-9939-com | frontend/views/article/detail_below.php | PHP | bsd-3-clause | 5,416 |
// Copyright (c) 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/extensions/settings_api_bubble_helpers.h"
#include <utility>
#include "build/build_config.h"
#include "chrome/browser/extensions/ntp_overridden_bubble_delegate.h"
#include "chrome/browser/extensions/settings_api_bubble_delegate.h"
#include "chrome/browser/extensions/settings_api_helpers.h"
#include "chrome/browser/ui/browser_dialogs.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/extensions/extension_message_bubble_bridge.h"
#include "chrome/browser/ui/extensions/extension_settings_overridden_dialog.h"
#include "chrome/browser/ui/extensions/settings_overridden_params_providers.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/ui/toolbar/toolbar_actions_bar.h"
#include "chrome/browser/ui/ui_features.h"
#include "chrome/common/extensions/manifest_handlers/settings_overrides_handler.h"
#include "chrome/common/url_constants.h"
#include "content/public/browser/browser_url_handler.h"
#include "content/public/browser/navigation_entry.h"
#include "extensions/common/constants.h"
namespace extensions {
namespace {
// Whether the NTP post-install UI is enabled. By default, this is limited to
// Windows, Mac, and ChromeOS, but can be overridden for testing.
#if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_CHROMEOS)
bool g_ntp_post_install_ui_enabled = true;
#else
bool g_ntp_post_install_ui_enabled = false;
#endif
#if defined(OS_WIN) || defined(OS_MACOSX)
void ShowSettingsApiBubble(SettingsApiOverrideType type,
Browser* browser) {
ToolbarActionsModel* model = ToolbarActionsModel::Get(browser->profile());
if (model->has_active_bubble())
return;
std::unique_ptr<ExtensionMessageBubbleController> settings_api_bubble(
new ExtensionMessageBubbleController(
new SettingsApiBubbleDelegate(browser->profile(), type), browser));
if (!settings_api_bubble->ShouldShow())
return;
settings_api_bubble->SetIsActiveBubble();
std::unique_ptr<ToolbarActionsBarBubbleDelegate> bridge(
new ExtensionMessageBubbleBridge(std::move(settings_api_bubble)));
browser->window()->GetExtensionsContainer()->ShowToolbarActionBubbleAsync(
std::move(bridge));
}
#endif
} // namespace
void SetNtpPostInstallUiEnabledForTesting(bool enabled) {
g_ntp_post_install_ui_enabled = enabled;
}
void MaybeShowExtensionControlledHomeNotification(Browser* browser) {
#if defined(OS_WIN) || defined(OS_MACOSX)
ShowSettingsApiBubble(BUBBLE_TYPE_HOME_PAGE, browser);
#endif
}
void MaybeShowExtensionControlledSearchNotification(
content::WebContents* web_contents,
AutocompleteMatch::Type match_type) {
#if defined(OS_WIN) || defined(OS_MACOSX)
if (!AutocompleteMatch::IsSearchType(match_type) ||
match_type == AutocompleteMatchType::SEARCH_OTHER_ENGINE) {
return;
}
Browser* browser = chrome::FindBrowserWithWebContents(web_contents);
if (!browser)
return;
if (base::FeatureList::IsEnabled(
features::kExtensionSettingsOverriddenDialogs)) {
base::Optional<ExtensionSettingsOverriddenDialog::Params> params =
settings_overridden_params::GetSearchOverriddenParams(
browser->profile());
if (!params)
return;
auto dialog = std::make_unique<ExtensionSettingsOverriddenDialog>(
std::move(*params), browser->profile());
if (!dialog->ShouldShow())
return;
chrome::ShowExtensionSettingsOverriddenDialog(std::move(dialog), browser);
} else {
ShowSettingsApiBubble(BUBBLE_TYPE_SEARCH_ENGINE, browser);
}
#endif
}
void MaybeShowExtensionControlledNewTabPage(
Browser* browser, content::WebContents* web_contents) {
if (!g_ntp_post_install_ui_enabled)
return;
// Acknowledge existing extensions if necessary.
NtpOverriddenBubbleDelegate::MaybeAcknowledgeExistingNtpExtensions(
browser->profile());
// Jump through a series of hoops to see if the web contents is pointing to
// an extension-controlled NTP.
// TODO(devlin): Some of this is redundant with the checks in the bubble/
// dialog. We should consolidate, but that'll be simpler once we only have
// one UI option. In the meantime, extra checks don't hurt.
content::NavigationEntry* entry =
web_contents->GetController().GetVisibleEntry();
if (!entry)
return;
GURL active_url = entry->GetURL();
if (!active_url.SchemeIs(extensions::kExtensionScheme))
return; // Not a URL that we care about.
// See if the current active URL matches a transformed NewTab URL.
GURL ntp_url(chrome::kChromeUINewTabURL);
content::BrowserURLHandler::GetInstance()->RewriteURLIfNecessary(
&ntp_url, web_contents->GetBrowserContext());
if (ntp_url != active_url)
return; // Not being overridden by an extension.
Profile* const profile = browser->profile();
ToolbarActionsModel* model = ToolbarActionsModel::Get(profile);
if (model->has_active_bubble())
return;
if (base::FeatureList::IsEnabled(
features::kExtensionSettingsOverriddenDialogs)) {
base::Optional<ExtensionSettingsOverriddenDialog::Params> params =
settings_overridden_params::GetNtpOverriddenParams(profile);
if (!params)
return;
auto dialog = std::make_unique<ExtensionSettingsOverriddenDialog>(
std::move(*params), profile);
if (!dialog->ShouldShow())
return;
chrome::ShowExtensionSettingsOverriddenDialog(std::move(dialog), browser);
return;
}
std::unique_ptr<ExtensionMessageBubbleController> ntp_overridden_bubble(
new ExtensionMessageBubbleController(
new NtpOverriddenBubbleDelegate(profile), browser));
if (!ntp_overridden_bubble->ShouldShow())
return;
ntp_overridden_bubble->SetIsActiveBubble();
std::unique_ptr<ToolbarActionsBarBubbleDelegate> bridge(
new ExtensionMessageBubbleBridge(std::move(ntp_overridden_bubble)));
browser->window()->GetExtensionsContainer()->ShowToolbarActionBubbleAsync(
std::move(bridge));
}
} // namespace extensions
| endlessm/chromium-browser | chrome/browser/ui/extensions/settings_api_bubble_helpers.cc | C++ | bsd-3-clause | 6,229 |
package org.broadinstitute.hellbender.engine;
import org.broadinstitute.barclay.argparser.CommandLineProgramProperties;
import org.broadinstitute.hellbender.cmdline.TestProgramGroup;
/**
* A Dummy / Placeholder class that can be used where a {@link GATKTool} is required.
* DO NOT USE THIS FOR ANYTHING OTHER THAN TESTING.
* THIS MUST BE IN THE ENGINE PACKAGE DUE TO SCOPE ON `features`!
* Created by jonn on 9/19/18.
*/
@CommandLineProgramProperties(
summary = "A dummy GATKTool to help test Funcotator.",
oneLineSummary = "Dummy dumb dumb tool for testing.",
programGroup = TestProgramGroup.class
)
public final class DummyPlaceholderGatkTool extends GATKTool {
public DummyPlaceholderGatkTool() {
parseArgs(new String[]{});
onStartup();
}
@Override
public void traverse() {
}
@Override
void initializeFeatures(){
features = new FeatureManager(this, FeatureDataSource.DEFAULT_QUERY_LOOKAHEAD_BASES, cloudPrefetchBuffer, cloudIndexPrefetchBuffer,
referenceArguments.getReferencePath());
}
}
| magicDGS/gatk | src/test/java/org/broadinstitute/hellbender/engine/DummyPlaceholderGatkTool.java | Java | bsd-3-clause | 1,099 |
// Standard system includes
#include <assert.h>
#include <errno.h> // -EINVAL, -ENODEV
#include <netdb.h> // gethostbyname
#include <sys/poll.h>
#include <sys/types.h> // connect
#include <sys/socket.h> // connect
#include <trace.h>
#define MY_TRACE_PREFIX "EthernetServer"
extern "C" {
#include "string.h"
}
#include "Ethernet.h"
#include "EthernetClient.h"
#include "EthernetServer.h"
EthernetServer::EthernetServer(uint16_t port)
{
_port = port;
_sock = -1;
_init_ok = false;
pclients = new EthernetClient[MAX_SOCK_NUM];
_pcli_inactivity_counter = new int[MAX_SOCK_NUM];
_scansock = 0;
if (pclients == NULL){
trace_error("%s OOM condition", __func__);
return;
}
for(int sock = 0; sock < MAX_SOCK_NUM; sock++){
_pcli_inactivity_counter[sock] = 0;
pclients[sock].id = sock;
}
}
EthernetServer::~EthernetServer()
{
if (pclients != NULL){
delete [] pclients;
pclients = NULL;
}
if(_pcli_inactivity_counter != NULL){
delete [] _pcli_inactivity_counter;
_pcli_inactivity_counter = NULL;
}
}
void EthernetServer::begin()
{
int ret;
extern int errno;
_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (_sock < 0){
trace_error("unable to open a TCP socket!");
return;
}
_sin.sin_addr.s_addr = INADDR_ANY;
_sin.sin_family = AF_INET;
_sin.sin_port = htons(_port);
ret = bind(_sock, (struct sockaddr*)&_sin, sizeof(_sin));
if ( ret < 0){
trace_error("%s unable to bind port %d", __func__, _port);
return;
}
//socket(sock, SnMR::TCP, _port, 0);
ret = listen(_sock, MAX_SOCK_NUM);
if ( ret < 0){
trace_error("%s unable to listen on port %d", __func__, _port);
return;
}
for(int sock = 0; sock < MAX_SOCK_NUM; sock++)
EthernetClass::_server_port[sock] = _port;
// mark as available
_init_ok = true;
}
static int _accept(int sock, struct sockaddr * psin, socklen_t * psize)
{
return accept(sock, psin, psize);
}
void EthernetServer::accept()
{
struct pollfd ufds;
int ret = 0, size_val, success = 0;
extern int errno;
if (_sock == -1)
return;
ufds.fd = _sock;
ufds.events = POLLIN;
ufds.revents = 0;
ret = poll(&ufds, 1, 0);
if ( ret < 0 ){
trace_error("%s error on poll errno %d", __func__, errno);
_sock = -1;
close(_sock);
return;
}
if(ufds.revents&POLLIN){
//trace_debug("%s in activity on socket %d - calling accept()", __func__, _sock);
size_val = sizeof(_cli_sin);
ret = _accept(_sock, (struct sockaddr*)&_cli_sin, (socklen_t*)&size_val);
if ( ret < 0){
close(_sock);
_sock = -1;
trace_error("%s Fail to accept() sock %d port %d", __func__, _sock, _port);
return;
}
for(int sock = 0; sock < MAX_SOCK_NUM && success == 0; sock++){
if (pclients[sock]._sock == -1){
pclients[sock]._sock = ret;
pclients[sock]._pCloseServer = this;
pclients[sock].connect_true = true;
pclients[sock]._inactive_counter = &_pcli_inactivity_counter[sock];
success = 1;
}
}
if ( success == 0 ){
trace_error("%s detect connect event - unable to allocate socket slot !", __func__);
}
}
}
EthernetClient EthernetServer::available()
{
accept();
// Scan for next connection - meaning don't return the same one each time
for(int sock = 0; sock < MAX_SOCK_NUM; sock++){
if (pclients[sock]._sock != -1 && sock != _scansock){
//trace_debug("Returning socket entity %d socket %d", sock, pclients[sock]._sock);
_scansock = sock;
return pclients[sock];
}
}
// scan for any connection
for(int sock = 0; sock < MAX_SOCK_NUM; sock++){
if (pclients[sock]._sock != -1){
//trace_debug("Returning socket entity %d socket %d", sock, pclients[sock]._sock);
_scansock = sock;
return pclients[sock];
}
}
//trace_debug("%s no client to return", __func__);
_scansock = 0;
return pclients[0];
}
size_t EthernetServer::write(uint8_t b)
{
return write(&b, 1);
}
size_t EthernetServer::write(const uint8_t *buffer, size_t size)
{
size_t n = 0;
//accept();
// This routine writes the given data to all current clients
for(int sock = 0; sock < MAX_SOCK_NUM; sock++){
if (pclients[sock]._sock != -1){
n += pclients[sock].write(buffer, size);
}
}
return n;
}
void EthernetServer::closeNotify(int idx)
{
if (idx < MAX_SOCK_NUM)
pclients[idx]._sock = -1;
} | ilc-opensource/io-js | target/device/libio/arduino/x86/libraries/Ethernet/EthernetServer.cpp | C++ | bsd-3-clause | 4,266 |
'use strict';
module.exports = function (Logger, $rootScope) {
return {
restrict: 'A',
scope: {
hasRank: '='
},
link: function ($scope, elem, attrs) {
$rootScope.$watch('currentUser', function () {
Logger.info('Checking for rank: ' + $scope.hasRank);
if ($rootScope.currentUser && $rootScope.currentUser.rank >= $scope.hasRank) {
elem.show();
} else {
elem.hide();
}
});
}
};
};
| e1528532/libelektra | src/tools/rest-frontend/resources/assets/js/directives/permission/HasRankDirective.js | JavaScript | bsd-3-clause | 571 |
/*
* Created on 02/04/2005
*
* JRandTest package
*
* Copyright (c) 2005, Zur Aougav, aougav@hotmail.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* Neither the name of the JRandTest 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.
*/
package com.fasteasytrade.jrandtest.algo;
import java.math.BigInteger;
import java.util.Random;
/**
* QuadraidResidue1 Prng algorithm from NIST test package
* <p>
* Fix random p, prime, length 512 bits.
* <p>
* Fix random g, prime, length 512 bits. g < p.
* <p>
* Each prng iteration calculate g = g**2 mod p.<br>
* The lowest 64 bits of g are the prng result.
*
* @author Zur Aougav
*/
public class QuadraticResidue1Prng extends Cipher {
/**
* n's length/num of bits
*/
public final int bit_length = 512;
/**
* prime (with probability < 2 ** -100).
* <p>
* Length of p is bit_length = 512 bits = 64 bytes.
*/
BigInteger p;
/**
* Initial g is a random prime (with probability < 2 ** -100)
* <p>
* Length of g is bit_length = 512 bits = 64 bytes.
* <p>
* g is the "state" of the prng.
* <p>
* g = take 64 lowr bits of ( g**2 mod n ).
*/
BigInteger g;
/**
* g0 is the "initial state" of the prng.
* <p>
* reset method set g to g0.
*/
BigInteger g0;
QuadraticResidue1Prng() {
setup(bit_length);
}
QuadraticResidue1Prng(int x) {
if (x < bit_length) {
setup(bit_length);
} else {
setup(x);
}
}
QuadraticResidue1Prng(BigInteger p, BigInteger g) {
this.p = p;
this.g = g;
g0 = g;
}
QuadraticResidue1Prng(BigInteger p, BigInteger g, BigInteger g0) {
this.p = p;
this.g = g;
this.g0 = g0;
}
/**
* Generate the key and seed for Quadratic Residue Prng.
* <p>
* Select random primes - p, g. g < p.
*
* @param len
* length of p and g, num of bits.
*/
void setup(int len) {
Random rand = new Random();
p = BigInteger.probablePrime(len, rand);
g = BigInteger.probablePrime(len, rand);
/**
* if g >= p swap(g, p).
*/
if (g.compareTo(p) > -1) {
BigInteger temp = g;
g = p;
p = temp;
}
/**
* here for sure g < p
*/
g0 = g;
}
/**
* calculate g**2 mod p and returns lowest 64 bits, long.
*
*/
public long nextLong() {
g = g.multiply(g).mod(p);
/**
* set g to 2 if g <= 1.
*/
if (g.compareTo(BigInteger.ONE) < 1) {
g = BigInteger.valueOf(2);
}
return g.longValue();
}
/**
* Public key.
*
* @return p prime (with probability < 2 ** -100)
*/
public BigInteger getP() {
return p;
}
/**
* Secret key
*
* @return g prime (with probability < 2 ** -100)
*/
public BigInteger getG() {
return g;
}
/**
* Reset "state" of prng by setting g to g0 (initial g).
*
*/
public void reset() {
g = g0;
}
} | cryptopony/jrandtest | src/com/fasteasytrade/jrandtest/algo/QuadraticResidue1Prng.java | Java | bsd-3-clause | 4,818 |
/*
* Copyright (c) 2011 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 "core/inspector/MainThreadDebugger.h"
#include "bindings/core/v8/BindingSecurity.h"
#include "bindings/core/v8/DOMWrapperWorld.h"
#include "bindings/core/v8/ScriptController.h"
#include "bindings/core/v8/SourceLocation.h"
#include "bindings/core/v8/V8ErrorHandler.h"
#include "bindings/core/v8/V8Node.h"
#include "bindings/core/v8/V8Window.h"
#include "bindings/core/v8/WorkerOrWorkletScriptController.h"
#include "core/dom/ContainerNode.h"
#include "core/dom/Document.h"
#include "core/dom/Element.h"
#include "core/dom/ExecutionContext.h"
#include "core/dom/StaticNodeList.h"
#include "core/events/ErrorEvent.h"
#include "core/frame/Deprecation.h"
#include "core/frame/FrameConsole.h"
#include "core/frame/FrameHost.h"
#include "core/frame/LocalDOMWindow.h"
#include "core/frame/LocalFrame.h"
#include "core/frame/Settings.h"
#include "core/frame/UseCounter.h"
#include "core/inspector/ConsoleMessage.h"
#include "core/inspector/ConsoleMessageStorage.h"
#include "core/inspector/IdentifiersFactory.h"
#include "core/inspector/InspectedFrames.h"
#include "core/inspector/InspectorTaskRunner.h"
#include "core/timing/MemoryInfo.h"
#include "core/workers/MainThreadWorkletGlobalScope.h"
#include "core/xml/XPathEvaluator.h"
#include "core/xml/XPathResult.h"
#include "platform/UserGestureIndicator.h"
#include "platform/inspector_protocol/Values.h"
#include "platform/v8_inspector/public/V8Inspector.h"
#include "wtf/PtrUtil.h"
#include "wtf/ThreadingPrimitives.h"
#include <memory>
namespace blink {
namespace {
int frameId(LocalFrame* frame)
{
ASSERT(frame);
return WeakIdentifierMap<LocalFrame>::identifier(frame);
}
Mutex& creationMutex()
{
DEFINE_THREAD_SAFE_STATIC_LOCAL(Mutex, mutex, (new Mutex));
return mutex;
}
LocalFrame* toFrame(ExecutionContext* context)
{
if (!context)
return nullptr;
if (context->isDocument())
return toDocument(context)->frame();
if (context->isMainThreadWorkletGlobalScope())
return toMainThreadWorkletGlobalScope(context)->frame();
return nullptr;
}
}
MainThreadDebugger* MainThreadDebugger::s_instance = nullptr;
MainThreadDebugger::MainThreadDebugger(v8::Isolate* isolate)
: ThreadDebugger(isolate)
, m_taskRunner(wrapUnique(new InspectorTaskRunner()))
, m_paused(false)
{
MutexLocker locker(creationMutex());
ASSERT(!s_instance);
s_instance = this;
}
MainThreadDebugger::~MainThreadDebugger()
{
MutexLocker locker(creationMutex());
ASSERT(s_instance == this);
s_instance = nullptr;
}
void MainThreadDebugger::reportConsoleMessage(ExecutionContext* context, MessageSource source, MessageLevel level, const String& message, SourceLocation* location)
{
if (LocalFrame* frame = toFrame(context))
frame->console().reportMessageToClient(source, level, message, location);
}
int MainThreadDebugger::contextGroupId(ExecutionContext* context)
{
LocalFrame* frame = toFrame(context);
return frame ? contextGroupId(frame) : 0;
}
void MainThreadDebugger::setClientMessageLoop(std::unique_ptr<ClientMessageLoop> clientMessageLoop)
{
ASSERT(!m_clientMessageLoop);
ASSERT(clientMessageLoop);
m_clientMessageLoop = std::move(clientMessageLoop);
}
void MainThreadDebugger::didClearContextsForFrame(LocalFrame* frame)
{
DCHECK(isMainThread());
if (frame->localFrameRoot() == frame)
v8Inspector()->resetContextGroup(contextGroupId(frame));
}
void MainThreadDebugger::contextCreated(ScriptState* scriptState, LocalFrame* frame, SecurityOrigin* origin)
{
ASSERT(isMainThread());
v8::HandleScope handles(scriptState->isolate());
DOMWrapperWorld& world = scriptState->world();
std::unique_ptr<protocol::DictionaryValue> auxData = protocol::DictionaryValue::create();
auxData->setBoolean("isDefault", world.isMainWorld());
auxData->setString("frameId", IdentifiersFactory::frameId(frame));
V8ContextInfo contextInfo(scriptState->context(), contextGroupId(frame), world.isIsolatedWorld() ? world.isolatedWorldHumanReadableName() : "");
if (origin)
contextInfo.origin = origin->toRawString();
contextInfo.auxData = auxData->toJSONString();
contextInfo.hasMemoryOnConsole = scriptState->getExecutionContext()->isDocument();
v8Inspector()->contextCreated(contextInfo);
}
void MainThreadDebugger::contextWillBeDestroyed(ScriptState* scriptState)
{
v8::HandleScope handles(scriptState->isolate());
v8Inspector()->contextDestroyed(scriptState->context());
}
void MainThreadDebugger::exceptionThrown(ExecutionContext* context, ErrorEvent* event)
{
LocalFrame* frame = nullptr;
ScriptState* scriptState = nullptr;
if (context->isDocument()) {
frame = toDocument(context)->frame();
if (!frame)
return;
scriptState = event->world() ? ScriptState::forWorld(frame, *event->world()) : nullptr;
} else if (context->isMainThreadWorkletGlobalScope()) {
frame = toMainThreadWorkletGlobalScope(context)->frame();
if (!frame)
return;
scriptState = toMainThreadWorkletGlobalScope(context)->scriptController()->getScriptState();
} else {
NOTREACHED();
}
frame->console().reportMessageToClient(JSMessageSource, ErrorMessageLevel, event->messageForConsole(), event->location());
const String16 defaultMessage = "Uncaught";
if (scriptState && scriptState->contextIsValid()) {
ScriptState::Scope scope(scriptState);
v8::Local<v8::Value> exception = V8ErrorHandler::loadExceptionFromErrorEventWrapper(scriptState, event, scriptState->context()->Global());
SourceLocation* location = event->location();
v8Inspector()->exceptionThrown(scriptState->context(), defaultMessage, exception, event->messageForConsole(), location->url(), location->lineNumber(), location->columnNumber(), location->takeStackTrace(), location->scriptId());
}
}
int MainThreadDebugger::contextGroupId(LocalFrame* frame)
{
LocalFrame* localFrameRoot = frame->localFrameRoot();
return frameId(localFrameRoot);
}
MainThreadDebugger* MainThreadDebugger::instance()
{
ASSERT(isMainThread());
V8PerIsolateData* data = V8PerIsolateData::from(V8PerIsolateData::mainThreadIsolate());
ASSERT(data->threadDebugger() && !data->threadDebugger()->isWorker());
return static_cast<MainThreadDebugger*>(data->threadDebugger());
}
void MainThreadDebugger::interruptMainThreadAndRun(std::unique_ptr<InspectorTaskRunner::Task> task)
{
MutexLocker locker(creationMutex());
if (s_instance) {
s_instance->m_taskRunner->appendTask(std::move(task));
s_instance->m_taskRunner->interruptAndRunAllTasksDontWait(s_instance->m_isolate);
}
}
void MainThreadDebugger::runMessageLoopOnPause(int contextGroupId)
{
LocalFrame* pausedFrame = WeakIdentifierMap<LocalFrame>::lookup(contextGroupId);
// Do not pause in Context of detached frame.
if (!pausedFrame)
return;
ASSERT(pausedFrame == pausedFrame->localFrameRoot());
m_paused = true;
if (UserGestureToken* token = UserGestureIndicator::currentToken())
token->setPauseInDebugger();
// Wait for continue or step command.
if (m_clientMessageLoop)
m_clientMessageLoop->run(pausedFrame);
}
void MainThreadDebugger::quitMessageLoopOnPause()
{
m_paused = false;
if (m_clientMessageLoop)
m_clientMessageLoop->quitNow();
}
void MainThreadDebugger::muteMetrics(int contextGroupId)
{
LocalFrame* frame = WeakIdentifierMap<LocalFrame>::lookup(contextGroupId);
if (frame && frame->host()) {
frame->host()->useCounter().muteForInspector();
frame->host()->deprecation().muteForInspector();
}
}
void MainThreadDebugger::unmuteMetrics(int contextGroupId)
{
LocalFrame* frame = WeakIdentifierMap<LocalFrame>::lookup(contextGroupId);
if (frame && frame->host()) {
frame->host()->useCounter().unmuteForInspector();
frame->host()->deprecation().unmuteForInspector();
}
}
v8::Local<v8::Context> MainThreadDebugger::ensureDefaultContextInGroup(int contextGroupId)
{
LocalFrame* frame = WeakIdentifierMap<LocalFrame>::lookup(contextGroupId);
ScriptState* scriptState = frame ? ScriptState::forMainWorld(frame) : nullptr;
return scriptState ? scriptState->context() : v8::Local<v8::Context>();
}
void MainThreadDebugger::beginEnsureAllContextsInGroup(int contextGroupId)
{
LocalFrame* frame = WeakIdentifierMap<LocalFrame>::lookup(contextGroupId);
frame->settings()->setForceMainWorldInitialization(true);
}
void MainThreadDebugger::endEnsureAllContextsInGroup(int contextGroupId)
{
LocalFrame* frame = WeakIdentifierMap<LocalFrame>::lookup(contextGroupId);
frame->settings()->setForceMainWorldInitialization(false);
}
bool MainThreadDebugger::canExecuteScripts(int contextGroupId)
{
LocalFrame* frame = WeakIdentifierMap<LocalFrame>::lookup(contextGroupId);
return frame->script().canExecuteScripts(NotAboutToExecuteScript);
}
void MainThreadDebugger::resumeStartup(int contextGroupId)
{
LocalFrame* frame = WeakIdentifierMap<LocalFrame>::lookup(contextGroupId);
if (m_clientMessageLoop)
m_clientMessageLoop->resumeStartup(frame);
}
void MainThreadDebugger::consoleAPIMessage(int contextGroupId, V8ConsoleAPIType type, const String16& message, const String16& url, unsigned lineNumber, unsigned columnNumber, V8StackTrace* stackTrace)
{
LocalFrame* frame = WeakIdentifierMap<LocalFrame>::lookup(contextGroupId);
if (!frame)
return;
if (type == V8ConsoleAPIType::kClear && frame->host())
frame->host()->consoleMessageStorage().clear();
std::unique_ptr<SourceLocation> location = SourceLocation::create(url, lineNumber, columnNumber, stackTrace ? stackTrace->clone() : nullptr, 0);
frame->console().reportMessageToClient(ConsoleAPIMessageSource, consoleAPITypeToMessageLevel(type), message, location.get());
}
v8::MaybeLocal<v8::Value> MainThreadDebugger::memoryInfo(v8::Isolate* isolate, v8::Local<v8::Context> context)
{
ExecutionContext* executionContext = toExecutionContext(context);
ASSERT_UNUSED(executionContext, executionContext);
ASSERT(executionContext->isDocument());
return toV8(MemoryInfo::create(), context->Global(), isolate);
}
void MainThreadDebugger::installAdditionalCommandLineAPI(v8::Local<v8::Context> context, v8::Local<v8::Object> object)
{
ThreadDebugger::installAdditionalCommandLineAPI(context, object);
createFunctionProperty(context, object, "$", MainThreadDebugger::querySelectorCallback, "function $(selector, [startNode]) { [Command Line API] }");
createFunctionProperty(context, object, "$$", MainThreadDebugger::querySelectorAllCallback, "function $$(selector, [startNode]) { [Command Line API] }");
createFunctionProperty(context, object, "$x", MainThreadDebugger::xpathSelectorCallback, "function $x(xpath, [startNode]) { [Command Line API] }");
}
static Node* secondArgumentAsNode(const v8::FunctionCallbackInfo<v8::Value>& info)
{
if (info.Length() > 1) {
if (Node* node = V8Node::toImplWithTypeCheck(info.GetIsolate(), info[1]))
return node;
}
ExecutionContext* executionContext = toExecutionContext(info.GetIsolate()->GetCurrentContext());
if (executionContext->isDocument())
return toDocument(executionContext);
return nullptr;
}
void MainThreadDebugger::querySelectorCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
if (info.Length() < 1)
return;
String selector = toCoreStringWithUndefinedOrNullCheck(info[0]);
if (selector.isEmpty())
return;
Node* node = secondArgumentAsNode(info);
if (!node || !node->isContainerNode())
return;
ExceptionState exceptionState(ExceptionState::ExecutionContext, "$", "CommandLineAPI", info.Holder(), info.GetIsolate());
Element* element = toContainerNode(node)->querySelector(AtomicString(selector), exceptionState);
if (exceptionState.throwIfNeeded())
return;
if (element)
info.GetReturnValue().Set(toV8(element, info.Holder(), info.GetIsolate()));
else
info.GetReturnValue().Set(v8::Null(info.GetIsolate()));
}
void MainThreadDebugger::querySelectorAllCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
if (info.Length() < 1)
return;
String selector = toCoreStringWithUndefinedOrNullCheck(info[0]);
if (selector.isEmpty())
return;
Node* node = secondArgumentAsNode(info);
if (!node || !node->isContainerNode())
return;
ExceptionState exceptionState(ExceptionState::ExecutionContext, "$$", "CommandLineAPI", info.Holder(), info.GetIsolate());
// toV8(elementList) doesn't work here, since we need a proper Array instance, not NodeList.
StaticElementList* elementList = toContainerNode(node)->querySelectorAll(AtomicString(selector), exceptionState);
if (exceptionState.throwIfNeeded() || !elementList)
return;
v8::Isolate* isolate = info.GetIsolate();
v8::Local<v8::Context> context = isolate->GetCurrentContext();
v8::Local<v8::Array> nodes = v8::Array::New(isolate, elementList->length());
for (size_t i = 0; i < elementList->length(); ++i) {
Element* element = elementList->item(i);
if (!nodes->Set(context, i, toV8(element, info.Holder(), info.GetIsolate())).FromMaybe(false))
return;
}
info.GetReturnValue().Set(nodes);
}
void MainThreadDebugger::xpathSelectorCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
if (info.Length() < 1)
return;
String selector = toCoreStringWithUndefinedOrNullCheck(info[0]);
if (selector.isEmpty())
return;
Node* node = secondArgumentAsNode(info);
if (!node || !node->isContainerNode())
return;
ExceptionState exceptionState(ExceptionState::ExecutionContext, "$x", "CommandLineAPI", info.Holder(), info.GetIsolate());
XPathResult* result = XPathEvaluator::create()->evaluate(selector, node, nullptr, XPathResult::kAnyType, ScriptValue(), exceptionState);
if (exceptionState.throwIfNeeded() || !result)
return;
if (result->resultType() == XPathResult::kNumberType) {
info.GetReturnValue().Set(toV8(result->numberValue(exceptionState), info.Holder(), info.GetIsolate()));
} else if (result->resultType() == XPathResult::kStringType) {
info.GetReturnValue().Set(toV8(result->stringValue(exceptionState), info.Holder(), info.GetIsolate()));
} else if (result->resultType() == XPathResult::kBooleanType) {
info.GetReturnValue().Set(toV8(result->booleanValue(exceptionState), info.Holder(), info.GetIsolate()));
} else {
v8::Isolate* isolate = info.GetIsolate();
v8::Local<v8::Context> context = isolate->GetCurrentContext();
v8::Local<v8::Array> nodes = v8::Array::New(isolate);
size_t index = 0;
while (Node* node = result->iterateNext(exceptionState)) {
if (exceptionState.throwIfNeeded())
return;
if (!nodes->Set(context, index++, toV8(node, info.Holder(), info.GetIsolate())).FromMaybe(false))
return;
}
info.GetReturnValue().Set(nodes);
}
exceptionState.throwIfNeeded();
}
} // namespace blink
| danakj/chromium | third_party/WebKit/Source/core/inspector/MainThreadDebugger.cpp | C++ | bsd-3-clause | 16,837 |
Spree.user_class.class_eval do
belongs_to :supplier, class_name: 'Spree::Supplier', optional: true
has_many :variants, through: :supplier
def supplier?
supplier.present?
end
def supplier_admin?
spree_roles.map(&:name).include?("supplier_admin")
end
def market_maker?
has_admin_role?
end
def has_admin_role?
spree_roles.map(&:name).include?("admin")
end
end
| boomerdigital/solidus_marketplace | app/models/spree/user_decorator.rb | Ruby | bsd-3-clause | 400 |
# Possible discounts:
# - Node (administer inline with nodes)
# - Bulk amounts on nodes
# - User
# - Group of users
# - Order (this is more-or-less a voucher)
# - Shipping costs
# Possible amounts:
# - Percentage
# - Fixed amount
# Flag indicating if a discount can be combined with other discounts.
# Boolean "offer" to include in list of offers. Default to true if discount is at node level.
# Save all applied discounts when ordering in a ManyToMany relationship with Order.
| bhell/jimi | jimi/jimi/price/models/discount.py | Python | bsd-3-clause | 478 |
// Copyright © 2017 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System;
using System.Threading.Tasks;
namespace CefSharp.Test
{
public static class WebBrowserTestExtensions
{
public static Task<LoadUrlAsyncResponse> LoadRequestAsync(this IWebBrowser browser, IRequest request)
{
if(request == null)
{
throw new ArgumentNullException("request");
}
//If using .Net 4.6 then use TaskCreationOptions.RunContinuationsAsynchronously
//and switch to tcs.TrySetResult below - no need for the custom extension method
var tcs = new TaskCompletionSource<LoadUrlAsyncResponse>(TaskCreationOptions.RunContinuationsAsynchronously);
EventHandler<LoadErrorEventArgs> loadErrorHandler = null;
EventHandler<LoadingStateChangedEventArgs> loadingStateChangeHandler = null;
loadErrorHandler = (sender, args) =>
{
//Ignore Aborted
//Currently invalid SSL certificates which aren't explicitly allowed
//end up with CefErrorCode.Aborted, I've created the following PR
//in the hopes of getting this fixed.
//https://bitbucket.org/chromiumembedded/cef/pull-requests/373
if (args.ErrorCode == CefErrorCode.Aborted)
{
return;
}
//If LoadError was called then we'll remove both our handlers
//as we won't need to capture LoadingStateChanged, we know there
//was an error
browser.LoadError -= loadErrorHandler;
browser.LoadingStateChanged -= loadingStateChangeHandler;
tcs.TrySetResult(new LoadUrlAsyncResponse(args.ErrorCode, -1));
};
loadingStateChangeHandler = (sender, args) =>
{
//Wait for while page to finish loading not just the first frame
if (!args.IsLoading)
{
var host = args.Browser.GetHost();
var navEntry = host?.GetVisibleNavigationEntry();
int statusCode = navEntry?.HttpStatusCode ?? -1;
//By default 0 is some sort of error, we map that to -1
//so that it's clearer that something failed.
if (statusCode == 0)
{
statusCode = -1;
}
browser.LoadingStateChanged -= loadingStateChangeHandler;
//This is required when using a standard TaskCompletionSource
//Extension method found in the CefSharp.Internals namespace
tcs.TrySetResult(new LoadUrlAsyncResponse(CefErrorCode.None, statusCode));
}
};
browser.LoadingStateChanged += loadingStateChangeHandler;
browser.GetMainFrame().LoadRequest(request);
return tcs.Task;
}
public static Task<bool> WaitForQUnitTestExeuctionToComplete(this IWebBrowser browser)
{
//If using .Net 4.6 then use TaskCreationOptions.RunContinuationsAsynchronously
//and switch to tcs.TrySetResult below - no need for the custom extension method
var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
EventHandler<JavascriptMessageReceivedEventArgs> handler = null;
handler = (sender, args) =>
{
browser.JavascriptMessageReceived -= handler;
dynamic msg = args.Message;
//Wait for while page to finish loading not just the first frame
if (msg.Type == "QUnitExecutionComplete")
{
var details = msg.Details;
var total = (int)details.total;
var passed = (int)details.passed;
tcs.TrySetResult(total == passed);
}
else
{
tcs.TrySetException(new Exception("WaitForQUnitTestExeuctionToComplete - Incorrect Message Type"));
}
};
browser.JavascriptMessageReceived += handler;
return tcs.Task;
}
}
}
| Livit/CefSharp | CefSharp.Test/WebBrowserTestExtensions.cs | C# | bsd-3-clause | 4,472 |
<?php
use yii\db\Migration;
class m160407_113339_vraagenAndAwnserFixjes extends Migration
{
public function safeUp()
{
$this->alterColumn('vraag', 'text', 'blob');
$this->alterColumn('antwoord', 'text', 'blob');
}
public function safeDown()
{
$this->alterColumn('vraag', 'text', 'string(128)');
$this->alterColumn('antwoord', 'text', 'string(128)');
}
}
| foxoffire33/testList | console/migrations/m160407_113339_vraagenAndAwnserFixjes.php | PHP | bsd-3-clause | 414 |
<?php
use SerializerKit\XmlSerializer;
class XmlSerializerTest extends PHPUnit_Framework_TestCase
{
function test()
{
$xmls = new XmlSerializer;
$string = $xmls->encode(array(
'title' => 'War and Peace',
'isbn' => 123123123,
'authors' => array(
array( 'name' => 'First', 'email' => 'Email-1' ),
array( 'name' => 'Second', 'email' => 'Email-2' ),
),
));
ok( $string );
$data = $xmls->decode( $string );
ok( $data['title'] );
ok( $data['isbn'] );
ok( is_array($data['authors']) );
ok( $data['authors'][0] );
ok( $data['authors'][1] );
}
}
| c9s/php-SerializerKit | tests/XmlSerializerTest.php | PHP | bsd-3-clause | 715 |
/**
* @file
* Money is a value object representing a monetary value. It does not use
* floating point numbers, so it avoids rounding errors.
* The only operation that may cause stray cents is split, it assures that no
* cents vanish by distributing as evenly as possible among the parts it splits into.
*
* Money has no notion of currency, so working in a single currency -- no matter
* which one -- is appropriate usage.
*
* In lack of better terminology, Money uses "dollars" and "cents".
*
* One dollar is assumed to be 100 cents.
*
* The cent number is guaranteed to be below 100.
*/
Module("Cactus.Data", function (m) {
/**
* @param natural dollars
* @param natural cents
* if > 100 then dollars are added until cents < 100.
*/
var Money = Class("Money", {
has : {
/**
* @type int
*/
amount : null
},
methods : {
BUILD : function (dollars, cents) {
var dollars = parseInt(dollars, 10);
var cents = parseInt(cents, 10);
if (dollars !== 0 && cents < 0) {
throw new Error("Money: cents < 0");
}
if (isNaN(dollars)) {
throw new Error("Money: dollars is NaN");
}
if (isNaN(cents)) {
throw new Error("Money: cents is NaN");
}
return {
amount : dollars * 100 + (dollars < 0 ? -1 * cents : cents)
};
},
/**
* @return int
*/
_getAmount : function () {
return this.amount;
},
/**
* @return natural
*/
getDollars : function () {
if (this.amount < 0) {
return Math.ceil(this.amount / 100);
} else {
return Math.floor(this.amount / 100);
}
},
/**
* @return natural
*/
getCents : function () {
if (this.amount < 0 && this.getDollars() === 0) {
return this.amount % 100;
} else {
return Math.abs(this.amount % 100);
}
},
/**
* The value with zero padded cents if < 100, and . used as the decimal
* separator.
*
* @return string
*/
toString : function () {
if (this.isNegative()) {
if (this.gt(new Money(-1, 0))) {
var cents = (-this.getCents()) < 10
? "0" + (-this.getCents()) : (-this.getCents());
return "-0." + cents;
}
}
var cents = this.getCents() < 10
? "0" + this.getCents() : this.getCents();
return this.getDollars() + "." + cents;
},
/**
* @param Money money
* @return Money
*/
add : function (money) {
return Money._fromAmount(this._getAmount() + money._getAmount());
},
/**
* @param Money money
* @return Money
*/
sub : function (money) {
return Money._fromAmount(this._getAmount() - money._getAmount());
},
/**
* @param number multiplier
* @return Money
*/
mult : function (multiplier) {
return Money._fromAmount(this._getAmount() * multiplier);
},
/**
* @return Boolean
*/
isPositive : function () {
return this._getAmount() > 0;
},
/**
* @return Boolean
*/
isNegative : function () {
return this._getAmount() < 0;
},
/**
* @return Boolean
*/
isZero : function () {
return this._getAmount() === 0;
},
/**
* @param Money money
* @return Boolean
*/
equals : function (money) {
return this._getAmount() === money._getAmount();
},
/**
* @param Money money
* @return Boolean
*/
gt : function (money) {
return this._getAmount() > money._getAmount();
},
/**
* @param Money money
* @return Boolean
*/
lt : function (money) {
return money.gt(this);
},
/**
* @param Money money
* @return Money
*/
negate : function () {
return Money._fromAmount(-this._getAmount());
},
/**
* Splits the object into parts, the remaining cents are distributed from
* the first element of the result and onward.
*
* @param int divisor
* @return Array<Money>
*/
split : function (divisor) {
var dividend = this._getAmount();
var quotient = Math.floor(dividend / divisor);
var remainder = dividend - quotient * divisor;
var res = [];
var moneyA = Money._fromAmount(quotient + 1);
var moneyB = Money._fromAmount(quotient);
for (var i = 0; i < remainder; i++) {
res.push(moneyA);
}
for (i = 0; i < divisor - remainder; i++) {
res.push(moneyB);
}
return res;
},
/**
* @return Hash{
* dollars : int,
* cents : int
* }
*/
serialize : function () {
return {
dollars : this.getDollars(),
cents : this.getCents()
};
}
}
});
/**
* @param String s
* @return Money
*/
Money.fromString = function (s) {
if (s === null) {
throw new Error("Money.fromString: String was null.");
}
if (s === "") {
throw new Error("Money.fromString: String was empty.");
}
if (!/^-?\d+(?:\.\d{2})?$/.test(s)) {
throw new Error("Money.fromString: Invalid format, got: " + s);
}
var a = s.split(".");
if (a.length === 1) {
return new Money(parseInt(a[0], 10), 0);
} else if (a.length === 2) {
return new Money(parseInt(a[0], 10), parseInt(a[1], 10));
} else {
throw new Error("Money:fromString: BUG: RegExp should have prevent this from happening.");
}
};
/**
* @param int amount
* @return Money
*/
Money._fromAmount = function (amount) {
if (amount > 0) {
return new Money(Math.floor(amount / 100), amount % 100);
} else {
return new Money(Math.ceil(amount / 100), Math.abs(amount) < 100 ? (amount % 100) : -(amount % 100));
}
};
/**
* @param Array<Money> ms
* @return Money
*/
Money.sum = function (ms) {
var sum = new Money(0, 0);
for (var i = 0; i < ms.length; i++) {
sum = sum.add(ms[i]);
}
return sum;
};
m.Money = Money;
});
| bergmark/Cactus | module/Core/lib/Data/Money.js | JavaScript | bsd-3-clause | 6,415 |
#include "Shape.h"
#include "DynBase.h"
//#include <iostream>
using std::cout;
using std::endl;
Shape::~Shape()
{
cout << "~Shape ..." << endl;
}
void Circle::Draw()
{
cout << "Circle::Draw() ..." << endl;
}
Circle::~Circle()
{
cout << "~Circle ..." << endl;
}
void Square::Draw()
{
cout << "Square::Draw() ..." << endl;
}
Square::~Square()
{
cout << "~Square ..." << endl;
}
void Rectangle::Draw()
{
cout << "Rectangle::Draw() ..." << endl;
}
Rectangle::~Rectangle()
{
cout << "~Rectangle ..." << endl;
}
REGISTER_CLASS(Circle);
REGISTER_CLASS(Square);
REGISTER_CLASS(Rectangle);
/*class CircleRegister
{
public:
static void* NewInstance()
{
return new Rectangle;
}
private:
static Register reg_;
};
Register CircleRegister::reg_("Circle", CircleRegister::NewInstance);*/ | lixinyancici/code-for-learning-cpp | cppbasic/Shape.cpp | C++ | bsd-3-clause | 796 |
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
'use strict';
import {
IContentsModel
} from 'jupyter-js-services';
import {
Message
} from 'phosphor-messaging';
import {
PanelLayout
} from 'phosphor-panel';
import {
Widget
} from 'phosphor-widget';
import {
FileButtons
} from './buttons';
import {
BreadCrumbs
} from './crumbs';
import {
DirListing
} from './listing';
import {
FileBrowserModel
} from './model';
import {
FILE_BROWSER_CLASS, showErrorMessage
} from './utils';
/**
* The class name added to the filebrowser crumbs node.
*/
const CRUMBS_CLASS = 'jp-FileBrowser-crumbs';
/**
* The class name added to the filebrowser buttons node.
*/
const BUTTON_CLASS = 'jp-FileBrowser-buttons';
/**
* The class name added to the filebrowser listing node.
*/
const LISTING_CLASS = 'jp-FileBrowser-listing';
/**
* The duration of auto-refresh in ms.
*/
const REFRESH_DURATION = 30000;
/**
* A widget which hosts a file browser.
*
* The widget uses the Jupyter Contents API to retreive contents,
* and presents itself as a flat list of files and directories with
* breadcrumbs.
*/
export
class FileBrowserWidget extends Widget {
/**
* Construct a new file browser.
*
* @param model - The file browser view model.
*/
constructor(model: FileBrowserModel) {
super();
this.addClass(FILE_BROWSER_CLASS);
this._model = model;
this._model.refreshed.connect(this._handleRefresh, this)
this._crumbs = new BreadCrumbs(model);
this._buttons = new FileButtons(model);
this._listing = new DirListing(model);
this._crumbs.addClass(CRUMBS_CLASS);
this._buttons.addClass(BUTTON_CLASS);
this._listing.addClass(LISTING_CLASS);
let layout = new PanelLayout();
layout.addChild(this._crumbs);
layout.addChild(this._buttons);
layout.addChild(this._listing);
this.layout = layout;
}
/**
* Dispose of the resources held by the file browser.
*/
dispose() {
this._model = null;
this._crumbs = null;
this._buttons = null;
this._listing = null;
super.dispose();
}
/**
* Get the model used by the file browser.
*
* #### Notes
* This is a read-only property.
*/
get model(): FileBrowserModel {
return this._model;
}
/**
* Get the widget factory for the widget.
*/
get widgetFactory(): (model: IContentsModel) => Widget {
return this._listing.widgetFactory;
}
/**
* Set the widget factory for the widget.
*/
set widgetFactory(factory: (model: IContentsModel) => Widget) {
this._listing.widgetFactory = factory;
}
/**
* Change directory.
*/
cd(path: string): Promise<void> {
return this._model.cd(path);
}
/**
* Open the currently selected item(s).
*
* Changes to the first directory encountered.
* Emits [[openRequested]] signals for files.
*/
open(): void {
let foundDir = false;
let items = this._model.sortedItems;
for (let item of items) {
if (!this._model.isSelected(item.name)) {
continue;
}
if (item.type === 'directory' && !foundDir) {
foundDir = true;
this._model.open(item.name).catch(error =>
showErrorMessage(this, 'Open directory', error)
);
} else {
this.model.open(item.name);
}
}
}
/**
* Create a new untitled file or directory in the current directory.
*/
newUntitled(type: string, ext?: string): Promise<IContentsModel> {
return this.model.newUntitled(type, ext);
}
/**
* Rename the first currently selected item.
*/
rename(): Promise<string> {
return this._listing.rename();
}
/**
* Cut the selected items.
*/
cut(): void {
this._listing.cut();
}
/**
* Copy the selected items.
*/
copy(): void {
this._listing.copy();
}
/**
* Paste the items from the clipboard.
*/
paste(): Promise<void> {
return this._listing.paste();
}
/**
* Delete the currently selected item(s).
*/
delete(): Promise<void> {
return this._listing.delete();
}
/**
* Duplicate the currently selected item(s).
*/
duplicate(): Promise<void> {
return this._listing.duplicate();
}
/**
* Download the currently selected item(s).
*/
download(): Promise<void> {
return this._listing.download();
}
/**
* Shut down kernels on the applicable currently selected items.
*/
shutdownKernels(): Promise<void> {
return this._listing.shutdownKernels();
}
/**
* Refresh the current directory.
*/
refresh(): Promise<void> {
return this._model.refresh().catch(
error => showErrorMessage(this, 'Refresh Error', error)
);
}
/**
* Select next item.
*/
selectNext(): void {
this._listing.selectNext();
}
/**
* Select previous item.
*/
selectPrevious(): void {
this._listing.selectPrevious();
}
/**
* A message handler invoked on an `'after-attach'` message.
*/
protected onAfterAttach(msg: Message): void {
super.onAfterAttach(msg);
this.refresh();
}
/**
* A message handler invoked on an `'after-show'` message.
*/
protected onAfterShow(msg: Message): void {
super.onAfterShow(msg);
this.refresh();
}
/**
* Handle a model refresh.
*/
private _handleRefresh(): void {
clearTimeout(this._timeoutId);
this._timeoutId = setTimeout(() => this.refresh(), REFRESH_DURATION);
}
private _model: FileBrowserModel = null;
private _crumbs: BreadCrumbs = null;
private _buttons: FileButtons = null;
private _listing: DirListing = null;
private _timeoutId = -1;
}
| jupyter/jupyter-js-filebrowser | src/browser.ts | TypeScript | bsd-3-clause | 5,682 |
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "solicitud_prestamo".
*
* @property integer $SPRE_ID
* @property string $PE_RUT
* @property string $SPRE_DESCRIPCION
* @property string $SPRE_FECHA
* @property string $SPRE_ESTADO
* @property string $SPRE_TEXTO
*
* @property Persona $pERUT
* @property SpreHeSolicita[] $spreHeSolicitas
*/
class SolicitudPrestamo extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'solicitud_prestamo';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['PE_RUT'], 'required'],
[['SPRE_FECHA'], 'safe'],
[['SPRE_DESCRIPCION'], 'string'],
[['PE_RUT'], 'string', 'max' => 12],
[['SPRE_TITULO'], 'string', 'max' => 50],
[['SPRE_ESTADO'], 'string', 'max' => 20]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'SPRE_ID' => 'ID',
'PE_RUT' => 'Persona',
'SPRE_TITULO' => 'Título',
'SPRE_FECHA' => 'Fecha',
'SPRE_ESTADO' => 'Estado',
'SPRE_DESCRIPCION' => 'Descripción',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getPERUT()
{
return $this->hasOne(Persona::className(), ['PE_RUT' => 'PE_RUT']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getSpreHeSolicitas()
{
return $this->hasMany(SpreHeSolicita::className(), ['SPRE_ID' => 'SPRE_ID']);
}
}
| malikeox/mymltda2 | models/SolicitudPrestamo.php | PHP | bsd-3-clause | 1,651 |
<?php
namespace app\models;
use app\models\query\ActionQuery;
use app\models\query\CommentQuery;
use Yii;
use yii\db\ActiveRecord;
/**
* This is the model class for table "comment".
*
* @property integer $id
* @property integer $action_id
* @property string $content
*
* @property Action $action
*/
class Comment extends ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'comment';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['action_id', 'content'], 'required'],
[['action_id'], 'integer'],
[['content'], 'string', 'max' => 255],
[['action_id'], 'exist', 'skipOnError' => true, 'targetClass' => Action::className(), 'targetAttribute' => ['action_id' => 'id']],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'action_id' => Yii::t('app', 'Action ID'),
'content' => Yii::t('app', 'Content'),
];
}
/**
* @return ActionQuery
*/
public function getAction()
{
return $this->hasOne(Action::className(), ['id' => 'action_id'])->inverseOf('comments');
}
/**
* @inheritdoc
* @return CommentQuery the active query used by this AR class.
*/
public static function find()
{
return new CommentQuery(get_called_class());
}
}
| mixartemev/hd | models/Comment.php | PHP | bsd-3-clause | 1,500 |
// 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/net/sdch_dictionary_fetcher.h"
#include "base/bind.h"
#include "base/compiler_specific.h"
#include "base/message_loop.h"
#include "chrome/browser/profiles/profile.h"
#include "content/public/common/url_fetcher.h"
#include "net/base/load_flags.h"
#include "net/url_request/url_request_context_getter.h"
#include "net/url_request/url_request_status.h"
SdchDictionaryFetcher::SdchDictionaryFetcher(
net::URLRequestContextGetter* context)
: ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)),
task_is_pending_(false),
context_(context) {
DCHECK(CalledOnValidThread());
}
SdchDictionaryFetcher::~SdchDictionaryFetcher() {
DCHECK(CalledOnValidThread());
}
// static
void SdchDictionaryFetcher::Shutdown() {
net::SdchManager::Shutdown();
}
void SdchDictionaryFetcher::Schedule(const GURL& dictionary_url) {
DCHECK(CalledOnValidThread());
// Avoid pushing duplicate copy onto queue. We may fetch this url again later
// and get a different dictionary, but there is no reason to have it in the
// queue twice at one time.
if (!fetch_queue_.empty() && fetch_queue_.back() == dictionary_url) {
net::SdchManager::SdchErrorRecovery(
net::SdchManager::DICTIONARY_ALREADY_SCHEDULED_TO_DOWNLOAD);
return;
}
if (attempted_load_.find(dictionary_url) != attempted_load_.end()) {
net::SdchManager::SdchErrorRecovery(
net::SdchManager::DICTIONARY_ALREADY_TRIED_TO_DOWNLOAD);
return;
}
attempted_load_.insert(dictionary_url);
fetch_queue_.push(dictionary_url);
ScheduleDelayedRun();
}
void SdchDictionaryFetcher::ScheduleDelayedRun() {
if (fetch_queue_.empty() || current_fetch_.get() || task_is_pending_)
return;
MessageLoop::current()->PostDelayedTask(FROM_HERE,
base::Bind(&SdchDictionaryFetcher::StartFetching,
weak_factory_.GetWeakPtr()),
base::TimeDelta::FromMilliseconds(kMsDelayFromRequestTillDownload));
task_is_pending_ = true;
}
void SdchDictionaryFetcher::StartFetching() {
DCHECK(task_is_pending_);
task_is_pending_ = false;
DCHECK(context_.get());
current_fetch_.reset(content::URLFetcher::Create(
fetch_queue_.front(), content::URLFetcher::GET, this));
fetch_queue_.pop();
current_fetch_->SetRequestContext(context_.get());
current_fetch_->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
net::LOAD_DO_NOT_SAVE_COOKIES);
current_fetch_->Start();
}
void SdchDictionaryFetcher::OnURLFetchComplete(
const net::URLFetcher* source) {
if ((200 == source->GetResponseCode()) &&
(source->GetStatus().status() == net::URLRequestStatus::SUCCESS)) {
std::string data;
source->GetResponseAsString(&data);
net::SdchManager::Global()->AddSdchDictionary(data, source->GetURL());
}
current_fetch_.reset(NULL);
ScheduleDelayedRun();
}
| robclark/chromium | chrome/browser/net/sdch_dictionary_fetcher.cc | C++ | bsd-3-clause | 3,016 |
<?php
use yii\helpers\Html;
use mdm\admin\models\Assignment;
use backend\models\UserBackend;
use yii\base\Object;
$user = new UserBackend();
$list = UserBackend::find()->where([])->asArray()->all();
//print_r($list);
//echo "<br>";
$euserId = "";
for($i=0;$i<count($list);$i++){
$tmpId = $list[$i]["id"];
$assign = new Assignment($tmpId);
$test = $assign->getItems();
//print_r($test);
//echo "<br>";
if(array_key_exists("企业管理员",$test["assigned"])){
$euserId = $tmpId;
break;
}
}
//echo "userId=".$euserId;
/* @var $this \yii\web\View */
/* @var $content string */
if (Yii::$app->controller->action->id === 'login') {
/**
* Do not use this code in your template. Remove it.
* Instead, use the code $this->layout = '//main-login'; in your controller.
*/
echo $this->render(
'main-login',
['content' => $content]
);
} else {
if (class_exists('backend\assets\AppAsset')) {
backend\assets\AppAsset::register($this);
} else {
app\assets\AppAsset::register($this);
}
dmstr\web\AdminLteAsset::register($this);
$directoryAsset = Yii::$app->assetManager->getPublishedUrl('@vendor/almasaeed2010/adminlte/dist');
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">
<head>
<meta charset="<?= Yii::$app->charset ?>"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<?= Html::csrfMetaTags() ?>
<title><?= Html::encode($this->title) ?></title>
<?php $this->head() ?>
</head>
<body class="hold-transition <?= \dmstr\helpers\AdminLteHelper::skinClass() ?> sidebar-mini">
<?php $this->beginBody() ?>
<div class="wrapper">
<?= $this->render(
'header.php',
['directoryAsset' => $directoryAsset,'euserId'=>$euserId]
) ?>
<?= $this->render(
'left.php',
['directoryAsset' => $directoryAsset,'euserId'=>$euserId]
)
?>
<?= $this->render(
'content.php',
['content' => $content, 'directoryAsset' => $directoryAsset]
) ?>
</div>
<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>
<?php } ?>
| 201528013359030/partyqing2 | backend/views/layouts/main.php | PHP | bsd-3-clause | 2,292 |
package de.uni.freiburg.iig.telematik.wolfgang.properties.check;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import de.invation.code.toval.graphic.component.DisplayFrame;
import de.invation.code.toval.graphic.util.SpringUtilities;
import de.uni.freiburg.iig.telematik.sepia.petrinet.cpn.properties.cwn.CWNProperties;
import de.uni.freiburg.iig.telematik.sepia.petrinet.properties.PropertyCheckingResult;
import javax.swing.SpringLayout;
public class CWNPropertyCheckView extends AbstractPropertyCheckView<CWNProperties> {
private static final long serialVersionUID = -950169446391727139L;
private PropertyCheckResultLabel lblStructure;
private PropertyCheckResultLabel lblInOutPlaces;
private PropertyCheckResultLabel lblConnectedness;
private PropertyCheckResultLabel lblValidMarking;
private PropertyCheckResultLabel lblCFDependency;
private PropertyCheckResultLabel lblNoDeadTransitions;
private PropertyCheckResultLabel lblCompletion;
private PropertyCheckResultLabel lblOptionComplete;
private PropertyCheckResultLabel lblBounded;
@Override
protected String getHeadline() {
return "Colored WF Net Check";
}
@Override
protected void addSpecificFields(JPanel pnl) {
lblStructure = new PropertyCheckResultLabel("\u2022 CWN Structure", PropertyCheckingResult.UNKNOWN);
pnl.add(lblStructure);
JPanel pnlStructureSub = new JPanel(new SpringLayout());
pnl.add(pnlStructureSub);
lblInOutPlaces = new PropertyCheckResultLabel("\u2022 Valid InOut Places", PropertyCheckingResult.UNKNOWN);
pnlStructureSub.add(lblInOutPlaces);
lblConnectedness = new PropertyCheckResultLabel("\u2022 Strong Connectedness", PropertyCheckingResult.UNKNOWN);
pnlStructureSub.add(lblConnectedness);
lblValidMarking = new PropertyCheckResultLabel("\u2022 Valid Initial Marking", PropertyCheckingResult.UNKNOWN);
pnlStructureSub.add(lblValidMarking);
lblCFDependency = new PropertyCheckResultLabel("\u2022 Control Flow Dependency", PropertyCheckingResult.UNKNOWN);
pnlStructureSub.add(lblCFDependency);
SpringUtilities.makeCompactGrid(pnlStructureSub, pnlStructureSub.getComponentCount(), 1, 15, 0, 0, 0);
pnl.add(new JPopupMenu.Separator());
lblBounded = new PropertyCheckResultLabel("\u2022 Is Bounded", PropertyCheckingResult.UNKNOWN);
pnl.add(lblBounded);
pnl.add(new JPopupMenu.Separator());
lblOptionComplete = new PropertyCheckResultLabel("\u2022 Option To Complete", PropertyCheckingResult.UNKNOWN);
pnl.add(lblOptionComplete);
pnl.add(new JPopupMenu.Separator());
lblCompletion = new PropertyCheckResultLabel("\u2022 Proper Completion", PropertyCheckingResult.UNKNOWN);
pnl.add(lblCompletion);
pnl.add(new JPopupMenu.Separator());
lblNoDeadTransitions = new PropertyCheckResultLabel("\u2022 No Dead Transitions", PropertyCheckingResult.UNKNOWN);
pnl.add(lblNoDeadTransitions);
}
@Override
public void resetFieldContent() {
super.updateFieldContent(null, null);
lblStructure.updatePropertyCheckingResult(PropertyCheckingResult.UNKNOWN);
lblInOutPlaces.updatePropertyCheckingResult(PropertyCheckingResult.UNKNOWN);
lblConnectedness.updatePropertyCheckingResult(PropertyCheckingResult.UNKNOWN);
lblValidMarking.updatePropertyCheckingResult(PropertyCheckingResult.UNKNOWN);
lblCFDependency.updatePropertyCheckingResult(PropertyCheckingResult.UNKNOWN);
lblBounded.updatePropertyCheckingResult(PropertyCheckingResult.UNKNOWN);
lblOptionComplete.updatePropertyCheckingResult(PropertyCheckingResult.UNKNOWN);
lblCompletion.updatePropertyCheckingResult(PropertyCheckingResult.UNKNOWN);
lblNoDeadTransitions.updatePropertyCheckingResult(PropertyCheckingResult.UNKNOWN);
}
@Override
public void updateFieldContent(CWNProperties checkResult, Exception exception) {
super.updateFieldContent(checkResult, exception);
lblStructure.updatePropertyCheckingResult(checkResult.hasCWNStructure);
lblInOutPlaces.updatePropertyCheckingResult(checkResult.validInOutPlaces);
lblConnectedness.updatePropertyCheckingResult(checkResult.strongConnectedness);
lblValidMarking.updatePropertyCheckingResult(checkResult.validInitialMarking);
lblCFDependency.updatePropertyCheckingResult(checkResult.controlFlowDependency);
lblBounded.updatePropertyCheckingResult(checkResult.isBounded);
lblOptionComplete.updatePropertyCheckingResult(checkResult.optionToCompleteAndProperCompletion);
lblCompletion.updatePropertyCheckingResult(checkResult.optionToCompleteAndProperCompletion);
lblNoDeadTransitions.updatePropertyCheckingResult(checkResult.noDeadTransitions);
}
public static void main(String[] args) {
CWNPropertyCheckView view = new CWNPropertyCheckView();
view.setUpGui();
view.updateFieldContent(new CWNProperties(), null);
new DisplayFrame(view, true);
}
}
| iig-uni-freiburg/WOLFGANG | src/de/uni/freiburg/iig/telematik/wolfgang/properties/check/CWNPropertyCheckView.java | Java | bsd-3-clause | 5,138 |
/*
* Zorbage: an algebraic data hierarchy for use in numeric processing.
*
* Copyright (c) 2016-2021 Barry DeZonia All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* Neither the name of the <copyright holder> nor the names of its contributors may
* be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package nom.bdezonia.zorbage.algorithm;
import java.math.BigDecimal;
import java.math.MathContext;
import nom.bdezonia.zorbage.algebra.Addition;
import nom.bdezonia.zorbage.algebra.Algebra;
import nom.bdezonia.zorbage.algebra.Conjugate;
import nom.bdezonia.zorbage.algebra.Invertible;
import nom.bdezonia.zorbage.algebra.Multiplication;
import nom.bdezonia.zorbage.algebra.RealConstants;
import nom.bdezonia.zorbage.algebra.SetComplex;
import nom.bdezonia.zorbage.algebra.Trigonometric;
import nom.bdezonia.zorbage.algebra.Unity;
import nom.bdezonia.zorbage.datasource.IndexedDataSource;
/**
*
* @author Barry DeZonia
*
*/
public class InvFFT {
// do not instantiate
private InvFFT() {}
/**
*
* @param <T>
* @param <U>
* @param <V>
* @param <W>
* @param cmplxAlg
* @param realAlg
* @param a
* @param b
*/
public static
<T extends Algebra<T,U> & Addition<U> & Multiplication<U> & Conjugate<U>,
U extends SetComplex<W>,
V extends Algebra<V,W> & Trigonometric<W> & RealConstants<W> & Unity<W> &
Multiplication<W> & Addition<W> & Invertible<W>,
W>
void compute(T cmplxAlg, V realAlg, IndexedDataSource<U> a,IndexedDataSource<U> b)
{
long aSize = a.size();
long bSize = b.size();
if (aSize != FFT.enclosingPowerOf2(aSize))
throw new IllegalArgumentException("input size is not a power of 2");
if (aSize != bSize)
throw new IllegalArgumentException("output size does not match input size");
U one_over_n = cmplxAlg.construct((BigDecimal.ONE.divide(BigDecimal.valueOf(aSize), new MathContext(100))).toString());
nom.bdezonia.zorbage.algorithm.Conjugate.compute(cmplxAlg, a, b);
FFT.compute(cmplxAlg, realAlg, b, b);
nom.bdezonia.zorbage.algorithm.Conjugate.compute(cmplxAlg, b, b);
Scale.compute(cmplxAlg, one_over_n, b, b);
}
}
| bdezonia/zorbage | src/main/java/nom/bdezonia/zorbage/algorithm/InvFFT.java | Java | bsd-3-clause | 3,423 |
import matplotlib.pyplot as plt
import numpy as np
import scalpplot
from scalpplot import plot_scalp
from positions import POS_10_5
from scipy import signal
def plot_timeseries(frames, time=None, offset=None, color='k', linestyle='-'):
frames = np.asarray(frames)
if offset == None:
offset = np.max(np.std(frames, axis=0)) * 3
if time == None:
time = np.arange(frames.shape[0])
plt.plot(time, frames - np.mean(frames, axis=0) +
np.arange(frames.shape[1]) * offset, color=color, ls=linestyle)
def plot_scalpgrid(scalps, sensors, locs=POS_10_5, width=None,
clim=None, cmap=None, titles=None):
'''
Plots a grid with scalpplots. Scalps contains the different scalps in the
rows, sensors contains the names for the columns of scalps, locs is a dict
that maps the sensor-names to locations.
Width determines the width of the grid that contains the plots. Cmap selects
a colormap, for example plt.cm.RdBu_r is very useful for AUC-ROC plots.
Clim is a list containing the minimim and maximum value mapped to a color.
Titles is an optional list with titles for each subplot.
Returns a list with subplots for further manipulation.
'''
scalps = np.asarray(scalps)
assert scalps.ndim == 2
nscalps = scalps.shape[0]
subplots = []
if not width:
width = int(min(8, np.ceil(np.sqrt(nscalps))))
height = int(np.ceil(nscalps/float(width)))
if not clim:
clim = [np.min(scalps), np.max(scalps)]
plt.clf()
for i in range(nscalps):
subplots.append(plt.subplot(height, width, i + 1))
plot_scalp(scalps[i], sensors, locs, clim=clim, cmap=cmap)
if titles:
plt.title(titles[i])
# plot colorbar next to last scalp
bb = plt.gca().get_position()
plt.colorbar(cax=plt.axes([bb.xmax + bb.width/10, bb.ymin, bb.width/10,
bb.height]), ticks=np.linspace(clim[0], clim[1], 5).round(2))
return subplots
| breuderink/psychic | psychic/plots.py | Python | bsd-3-clause | 1,878 |
package main
import (
"encoding/json"
"fmt"
"log"
"time"
"github.com/boltdb/bolt"
)
type Entry struct {
Id string `json:"id"`
Url string `json:"url"`
Subreddit string `json:"subreddit"`
}
//InitDB initializes the BoltDB instance and loads in the database file.
func InitDB() {
var err error
db, err = bolt.Open("data.db", 0600, &bolt.Options{Timeout: 1 * time.Second})
CheckErr(err, "InitDB() - Open Database", true)
err = db.Update(func(tx *bolt.Tx) error {
var err error
_, err = tx.CreateBucketIfNotExists([]byte("to_handle"))
if err != nil {
return fmt.Errorf("create bucket: %s", err)
}
_, err = tx.CreateBucketIfNotExists([]byte("handled"))
if err != nil {
return fmt.Errorf("create bucket: %s", err)
}
_, err = tx.CreateBucketIfNotExists([]byte("credentials"))
if err != nil {
return fmt.Errorf("create bucket: %s", err)
}
return nil
})
CheckErr(err, "InitDB() - Create Buckets", true)
}
//CloseDB closes the BoltDB database safely during the shutdown cleanup.
func CloseDB() {
fmt.Print("Closing database...")
db.Close()
fmt.Println("Done!")
fmt.Println("Goodbye! <3")
}
//ReadCreds reads the credential bucket from BotlDB.
func ReadCreds() {
var user, pass []byte
err := db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("credentials"))
u := b.Get([]byte("user"))
p := b.Get([]byte("pass"))
if u != nil && p != nil {
user = make([]byte, len(u))
pass = make([]byte, len(p))
copy(user, u)
copy(pass, p)
}
return nil
})
CheckErr(err, "ReadCreds() - Read Database", true)
username = string(user)
password = string(pass)
if username == "" || password == "" {
log.Fatalln("Fatal Error: One or more stored credentials are missing, cannot continue without credentials!")
}
}
//UpdateCreds takes the current credentials and inserts them into
//the BoltDB database.
func UpdateCreds(user, pass string) {
err := db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("credentials"))
err := b.Put([]byte("user"), []byte(user))
if err != nil {
return err
}
err = b.Put([]byte("pass"), []byte(pass))
return err
})
CheckErr(err, "UpdateCreds() - Write Database", true)
}
//ClearCreds removes the stores credentials from the database.
func ClearCreds() {
err := db.Update(func(tx *bolt.Tx) error {
err := tx.DeleteBucket([]byte("credentials"))
if err != nil {
return err
}
_, err = tx.CreateBucketIfNotExists([]byte("credentials"))
return err
})
CheckErr(err, "ClearCreds() - Delete Bucket", true)
}
//ClearDB removes all entires from the BotlDB database.
func ClearDB() {
ClearCreds()
err := db.Update(func(tx *bolt.Tx) error {
err := tx.DeleteBucket([]byte("to_handle"))
if err != nil {
return err
}
err = tx.DeleteBucket([]byte("handled"))
if err != nil {
return err
}
_, err = tx.CreateBucketIfNotExists([]byte("to_handle"))
if err != nil {
return err
}
_, err = tx.CreateBucketIfNotExists([]byte("handled"))
return err
})
CheckErr(err, "ClearDB() - Delete Bucket", true)
}
//KeyExists checks if a given key exists within the given BoltDB bucket.
func KeyExists(id, bucket string) bool {
exists := false
err := db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(bucket))
v := b.Get([]byte(id))
exists = v != nil
return nil
})
CheckErr(err, "KeyExists() - Read Database", true)
return exists
}
//HandleLater takes the id (reddit thing_id) of a submission that the
//bot has determined to be offending, and adds it to the bucket of
//posts to be handled in the future.
func HandleLater(entry Entry) {
bytes, err := json.Marshal(entry)
if !CheckErr(err, "HandleLater() - Marshal JSON", false) {
err := db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("to_handle"))
err := b.Put([]byte(entry.Id), bytes)
return err
})
CheckErr(err, "HandleLater() - Add ID", true)
}
}
//AddToHandled adds the id (reddit thing_id) to the BoltDB handled bucket.
func AddToHandled(id string) {
err := db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("handled"))
err := b.Put([]byte(id), []byte(""))
return err
})
CheckErr(err, "AddToHandled() - Add 'handled' ID", true)
err = db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("to_handle"))
err := b.Delete([]byte(id))
return err
})
CheckErr(err, "AddToHandled() - Delete 'to_handle' ID", true)
}
func FetchFromQueue() *Entry {
var val []byte
needhandle := false
err := db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("to_handle"))
c := b.Cursor()
k, v := c.First()
if k != nil {
needhandle = true
val = make([]byte, len(v))
copy(val, v)
}
return nil
})
CheckErr(err, "FetchFromQueue() - Read Database", true)
if needhandle {
log.Printf("Handling one post: %s\n", val)
entry := &Entry{}
json.Unmarshal(val, entry)
return entry
}
return nil
}
//PrintList reads all of the data from the specified BoltDB bucket
//and lists it out to the console.
func PrintList(bucket string) {
db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(bucket))
c := b.Cursor()
for k, v := c.First(); k != nil; k, v = c.Next() {
fmt.Printf("key=%s, value=%s\n", k, v)
}
return nil
})
}
| Term1nal/gifvbot | db.go | GO | bsd-3-clause | 5,499 |
package eu.monnetproject.sim.entity;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import eu.monnetproject.util.Logger;
import eu.monnetproject.label.LabelExtractor;
import eu.monnetproject.label.LabelExtractorFactory;
import eu.monnetproject.lang.Language;
import eu.monnetproject.ontology.Entity;
import eu.monnetproject.sim.EntitySimilarityMeasure;
import eu.monnetproject.sim.StringSimilarityMeasure;
import eu.monnetproject.sim.string.Levenshtein;
import eu.monnetproject.sim.token.TokenBagOfWordsCosine;
import eu.monnetproject.sim.util.Functions;
import eu.monnetproject.sim.util.SimilarityUtils;
import eu.monnetproject.tokenizer.FairlyGoodTokenizer;
import eu.monnetproject.translatorimpl.Translator;
import eu.monnetproject.util.Logging;
/**
* Levenshtein similarity.
* Intralingual aggregation: average
* Interlingual aggregation: maximum
*
* @author Dennis Spohr
*
*/
public class MaximumAverageLevenshtein implements EntitySimilarityMeasure {
private Logger log = Logging.getLogger(this);
private final String name = this.getClass().getName();
private LabelExtractorFactory lef;
private LabelExtractor lex = null;
private Collection<Language> languages = Collections.emptySet();
private StringSimilarityMeasure measure;
private boolean includePuns = false;
private Translator translator;
public MaximumAverageLevenshtein(LabelExtractorFactory lef) {
this.lef = lef;
this.measure = new Levenshtein();
this.translator = new Translator();
}
public void configure(Properties properties) {
this.languages = SimilarityUtils.getLanguages(properties.getProperty("languages", ""));
for (Language lang : this.languages) {
log.info("Requested language: "+lang);
}
this.includePuns = SimilarityUtils.getIncludePuns(properties.getProperty("include_puns", "false"));
}
@Override
public double getScore(Entity srcEntity, Entity tgtEntity) {
if (this.lex == null) {
this.lex = this.lef.getExtractor(SimilarityUtils.determineLabelProperties(srcEntity, tgtEntity), true, false);
}
if (this.languages.size() < 1) {
log.warning("No languages specified in config file.");
this.languages = SimilarityUtils.determineLanguages(srcEntity, tgtEntity);
String langs = "";
for (Language lang : languages) {
langs += lang.getName()+", ";
}
try {
log.warning("Using "+langs.substring(0, langs.lastIndexOf(","))+".");
} catch (Exception e) {
log.severe("No languages in source and target ontology.");
}
}
Map<Language, Collection<String>> srcMap = null;
Map<Language, Collection<String>> tgtMap = null;
if (includePuns) {
srcMap = SimilarityUtils.getLabelsIncludingPuns(srcEntity,lex);
tgtMap = SimilarityUtils.getLabelsIncludingPuns(tgtEntity,lex);
} else {
srcMap = SimilarityUtils.getLabelsExcludingPuns(srcEntity,lex);
tgtMap = SimilarityUtils.getLabelsExcludingPuns(tgtEntity,lex);
}
List<Double> intralingualScores = new ArrayList<Double>();
for (Language language : this.languages) {
Collection<String> srcLabels = srcMap.get(language);
Collection<String> tgtLabels = tgtMap.get(language);
if (srcLabels == null) {
if (translator == null) {
log.warning("Can't match in "+language+" because "+srcEntity.getURI()+" has no labels in "+language+" and no translator is available.");
continue;
}
srcLabels = SimilarityUtils.getTranslatedLabels(srcEntity,language,translator,lex);
}
if (tgtLabels == null) {
if (translator == null) {
log.warning("Can't match in "+language+" because "+tgtEntity.getURI()+" has no labels in "+language+" and no translator is available.");
continue;
}
tgtLabels = SimilarityUtils.getTranslatedLabels(tgtEntity,language,translator,lex);
}
double[] scores = new double[srcLabels.size()*tgtLabels.size()];
int index = 0;
for (String srcLabel : srcLabels) {
for (String tgtLabel : tgtLabels) {
scores[index++] = measure.getScore(srcLabel, tgtLabel);
}
}
intralingualScores.add(Functions.mean(scores));
}
if (intralingualScores.size() < 1)
return 0.;
double[] intralingualScoresArray = new double[intralingualScores.size()];
for (int i = 0; i < intralingualScores.size(); i++) {
intralingualScoresArray[i] = intralingualScores.get(i);
}
return Functions.max(intralingualScoresArray);
}
@Override
public String getName() {
return this.name;
}
}
| monnetproject/coal | nlp.sim/src/main/java/eu/monnetproject/sim/entity/MaximumAverageLevenshtein.java | Java | bsd-3-clause | 4,639 |
/*
-- MAGMA (version 1.5.0-beta3) --
Univ. of Tennessee, Knoxville
Univ. of California, Berkeley
Univ. of Colorado, Denver
@date July 2014
@generated from zgels_gpu.cpp normal z -> d, Fri Jul 18 17:34:16 2014
*/
#include "common_magma.h"
/**
Purpose
-------
Solves the overdetermined, least squares problem
min || A*X - C ||
using the QR factorization A.
The underdetermined problem (m < n) is not currently handled.
Arguments
---------
@param[in]
trans magma_trans_t
- = MagmaNoTrans: the linear system involves A.
Only TRANS=MagmaNoTrans is currently handled.
@param[in]
m INTEGER
The number of rows of the matrix A. M >= 0.
@param[in]
n INTEGER
The number of columns of the matrix A. M >= N >= 0.
@param[in]
nrhs INTEGER
The number of columns of the matrix C. NRHS >= 0.
@param[in,out]
dA DOUBLE_PRECISION array on the GPU, dimension (LDA,N)
On entry, the M-by-N matrix A.
On exit, A is overwritten by details of its QR
factorization as returned by DGEQRF.
@param[in]
ldda INTEGER
The leading dimension of the array A, LDDA >= M.
@param[in,out]
dB DOUBLE_PRECISION array on the GPU, dimension (LDDB,NRHS)
On entry, the M-by-NRHS matrix C.
On exit, the N-by-NRHS solution matrix X.
@param[in]
lddb INTEGER
The leading dimension of the array dB. LDDB >= M.
@param[out]
hwork (workspace) DOUBLE_PRECISION array, dimension MAX(1,LWORK).
On exit, if INFO = 0, HWORK(1) returns the optimal LWORK.
@param[in]
lwork INTEGER
The dimension of the array HWORK,
LWORK >= (M - N + NB)*(NRHS + NB) + NRHS*NB,
where NB is the blocksize given by magma_get_dgeqrf_nb( M ).
\n
If LWORK = -1, then a workspace query is assumed; the routine
only calculates the optimal size of the HWORK array, returns
this value as the first entry of the HWORK array.
@param[out]
info INTEGER
- = 0: successful exit
- < 0: if INFO = -i, the i-th argument had an illegal value
@ingroup magma_dgels_driver
********************************************************************/
extern "C" magma_int_t
magma_dgels_gpu( magma_trans_t trans, magma_int_t m, magma_int_t n, magma_int_t nrhs,
double *dA, magma_int_t ldda,
double *dB, magma_int_t lddb,
double *hwork, magma_int_t lwork,
magma_int_t *info)
{
double *dT;
double *tau;
magma_int_t k;
magma_int_t nb = magma_get_dgeqrf_nb(m);
magma_int_t lwkopt = (m - n + nb)*(nrhs + nb) + nrhs*nb;
int lquery = (lwork == -1);
hwork[0] = MAGMA_D_MAKE( (double)lwkopt, 0. );
*info = 0;
/* For now, N is the only case working */
if ( trans != MagmaNoTrans )
*info = -1;
else if (m < 0)
*info = -2;
else if (n < 0 || m < n) /* LQ is not handle for now*/
*info = -3;
else if (nrhs < 0)
*info = -4;
else if (ldda < max(1,m))
*info = -6;
else if (lddb < max(1,m))
*info = -8;
else if (lwork < lwkopt && ! lquery)
*info = -10;
if (*info != 0) {
magma_xerbla( __func__, -(*info) );
return *info;
}
else if (lquery)
return *info;
k = min(m,n);
if (k == 0) {
hwork[0] = MAGMA_D_ONE;
return *info;
}
/*
* Allocate temporary buffers
*/
int ldtwork = ( 2*k + ((n+31)/32)*32 )*nb;
if (nb < nrhs)
ldtwork = ( 2*k + ((n+31)/32)*32 )*nrhs;
if (MAGMA_SUCCESS != magma_dmalloc( &dT, ldtwork )) {
*info = MAGMA_ERR_DEVICE_ALLOC;
return *info;
}
magma_dmalloc_cpu( &tau, k );
if ( tau == NULL ) {
magma_free( dT );
*info = MAGMA_ERR_HOST_ALLOC;
return *info;
}
magma_dgeqrf_gpu( m, n, dA, ldda, tau, dT, info );
if ( *info == 0 ) {
magma_dgeqrs_gpu( m, n, nrhs,
dA, ldda, tau, dT,
dB, lddb, hwork, lwork, info );
}
magma_free( dT );
magma_free_cpu(tau);
return *info;
}
| EmergentOrder/magma | src/dgels_gpu.cpp | C++ | bsd-3-clause | 4,392 |
<?php
use AudioDidact\GlobalFunctions;
/**
* Returns Pug rendered HTML for the User page, either view or edit
*
* @param $webID string webID of the user's page to be rendered
* @param $edit boolean true if the user is logged in and viewing their own page
* @param null|string $verifyEmail null or string if the user is trying to verify their email address
* @return string HTML of User's page from Pug
*/
function makeUserPage($webID, $edit, $verifyEmail = null){
$dal = GlobalFunctions::getDAL();
$user = $dal->getUserByWebID($webID);
if($user == null){
echo "<script type=\"text/javascript\">alert(\"Invalid User!\");window.location = \"/" . SUBDIR . "\";</script>";
exit();
}
if($edit){
$title = "User Page | $webID | Edit";
}
else{
$title = "User Page | $webID";
}
$emailVerify = 0;
if($verifyEmail != null && !$user->isEmailVerified()){
$result = $user->verifyEmailVerificationCode($verifyEmail);
// If the email verification code is correct, update the user information
if($result){
$user->setEmailVerified(1);
$user->setEmailVerificationCodes([]);
$dal->updateUser($user);
$emailVerify = 1;
}
else{
$emailVerify = 2;
}
}
$userData = ["privateFeed" => $user->isPrivateFeed(), "fName" => $user->getFname(), "lName" => $user->getLname(),
"gender" => $user->getGender(), "webID" => $user->getWebID(), "username" => $user->getUsername(),
"email" => $user->getEmail(), "feedLength" => $user->getFeedLength(), "feedDetails" => $user->getFeedDetails()
];
$episodeData = [];
if($edit || $userData["privateFeed"] == 0){
$items = $dal->getFeed($user);
for($x = 0; $x < $user->getFeedLength() && isset($items[$x]); $x++){
/** @var \AudioDidact\Video $i */
$i = $items[$x];
$descr = $i->getDesc();
// Limit description to 3 lines initially
$words = explode("\n", $descr, 4);
if(count($words) > 3){
$words[3] = "<p id='" . $i->getId() . "' style='display:none;'>" . trim($words[3]) . " </p></p>";
$words[4] = "<a onclick='$(\"#" . $i->getId() . "\").show();'>Continue Reading...</a>";
}
$descr = implode("\n", $words);
$descr = mb_ereg_replace('(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.%-=#~\@!]*(\?\S+)?)?)?)', '<a href="\\1" target="_blank">\\1</a>', $descr);
$descr = nl2br($descr);
$thumb = LOCAL_URL . DOWNLOAD_PATH . '/' . $i->getThumbnailFilename();
$episodeFile = LOCAL_URL . DOWNLOAD_PATH . '/' . $i->getFilename() . $i->getFileExtension();
$episodeData[] = ["title" => $i->getTitle(), "author" => $i->getAuthor(), "id" => $i->getId(),
"description" => $descr, "thumbnail" => $thumb, "episodeFile" => $episodeFile, "isVideo" => $i->isIsVideo()];
}
}
$options = ["edit" => $edit, "episodes" => $episodeData, "emailverify" => $emailVerify, "pageUser" => $userData,
"stats" => generateStatistics($user)];
return GlobalFunctions::generatePug("views/userPage.pug", $title, $options);
}
/**
* Returns Array with informative statistics about all videos in the feed
*
* @param \AudioDidact\User $user
* @return array
*/
function generateStatistics(\AudioDidact\User $user){
$dal = GlobalFunctions::getDAL();
$stats = [];
$feed = $dal->getFullFeedHistory($user);
$stats["numVids"] = count($feed);
$time = 0;
foreach($feed as $v){
/** @var \AudioDidact\Video $v */
$time += $v->getDuration();
}
$timeConversion = GlobalFunctions::secondsToTime($time);
$timeList = [];
foreach($timeConversion as $unit => $value){
if($value > 0){
$timeList[] = $value . " " . GlobalFunctions::pluralize($unit, $value);
}
}
$stats["totalTime"] = GlobalFunctions::arrayToCommaSeparatedString($timeList);
return $stats;
}
| md100play/AudioDidact | src/userPageGenerator.php | PHP | bsd-3-clause | 3,652 |
/*!
* \file dcxtab.cpp
* \brief blah
*
* blah
*
* \author David Legault ( clickhere at scriptsdb dot org )
* \version 1.0
*
* \b Revisions
*
* © ScriptsDB.org - 2006
*/
#include "defines.h"
#include "Classes/dcxtab.h"
#include "Classes/dcxdialog.h"
/*!
* \brief Constructor
*
* \param ID Control ID
* \param p_Dialog Parent DcxDialog Object
* \param mParentHwnd Parent Window Handle
* \param rc Window Rectangle
* \param styles Window Style Tokenized List
*/
DcxTab::DcxTab( UINT ID, DcxDialog * p_Dialog, HWND mParentHwnd, RECT * rc, TString & styles )
: DcxControl(ID, p_Dialog)
, m_bClosable(false)
, m_bGradient(false)
{
LONG Styles = 0, ExStyles = 0;
BOOL bNoTheme = FALSE;
this->parseControlStyles( styles, &Styles, &ExStyles, &bNoTheme );
this->m_Hwnd = CreateWindowEx(
ExStyles | WS_EX_CONTROLPARENT,
DCX_TABCTRLCLASS,
NULL,
WS_CHILD | Styles,
rc->left, rc->top, rc->right - rc->left, rc->bottom - rc->top,
mParentHwnd,
(HMENU) ID,
GetModuleHandle(NULL),
NULL);
if (!IsWindow(this->m_Hwnd))
throw "Unable To Create Window";
if ( bNoTheme )
Dcx::UXModule.dcxSetWindowTheme( this->m_Hwnd , L" ", L" " );
/*
HWND hHwndTip = TabCtrl_GetToolTips( this->m_Hwnd );
if ( IsWindow( hHwndTip ) ) {
TOOLINFO ti;
ZeroMemory( &ti, sizeof( TOOLINFO ) );
ti.cbSize = sizeof( TOOLINFO );
ti.uFlags = TTF_SUBCLASS | TTF_IDISHWND;
ti.hwnd = mParentHwnd;
ti.uId = (UINT) this->m_Hwnd;
ti.lpszText = LPSTR_TEXTCALLBACK;
SendMessage( hHwndTip, TTM_ADDTOOL, (WPARAM) 0, (LPARAM) &ti );
}
*/
//if (p_Dialog->getToolTip() != NULL) {
// if (styles.istok("tooltips")) {
// this->m_ToolTipHWND = p_Dialog->getToolTip();
// TabCtrl_SetToolTips(this->m_Hwnd,this->m_ToolTipHWND);
// //AddToolTipToolInfo(this->m_ToolTipHWND, this->m_Hwnd);
// }
//}
this->setControlFont( GetStockFont( DEFAULT_GUI_FONT ), FALSE );
this->registreDefaultWindowProc( );
SetProp( this->m_Hwnd, "dcx_cthis", (HANDLE) this );
}
/*!
* \brief blah
*
* blah
*/
DcxTab::~DcxTab( ) {
ImageList_Destroy( this->getImageList( ) );
int n = 0, nItems = TabCtrl_GetItemCount( this->m_Hwnd );
while ( n < nItems ) {
this->deleteLParamInfo( n );
++n;
}
this->unregistreDefaultWindowProc( );
}
/*!
* \brief blah
*
* blah
*/
void DcxTab::parseControlStyles( TString & styles, LONG * Styles, LONG * ExStyles, BOOL * bNoTheme ) {
unsigned int i = 1, numtok = styles.numtok( );
//*ExStyles = WS_EX_CONTROLPARENT;
while ( i <= numtok ) {
if ( styles.gettok( i ) == "vertical" )
*Styles |= TCS_VERTICAL;
else if ( styles.gettok( i ) == "bottom" )
*Styles |= TCS_BOTTOM;
else if ( styles.gettok( i ) == "right" )
*Styles |= TCS_RIGHT;
else if ( styles.gettok( i ) == "fixedwidth" )
*Styles |= TCS_FIXEDWIDTH;
else if ( styles.gettok( i ) == "buttons" )
*Styles |= TCS_BUTTONS;
else if ( styles.gettok( i ) == "flat" )
*Styles |= TCS_FLATBUTTONS;
else if ( styles.gettok( i ) == "hot" )
*Styles |= TCS_HOTTRACK;
else if ( styles.gettok( i ) == "multiline" )
*Styles |= TCS_MULTILINE;
else if ( styles.gettok( i ) == "rightjustify" )
*Styles |= TCS_RIGHTJUSTIFY;
else if ( styles.gettok( i ) == "scrollopposite" )
*Styles |= TCS_SCROLLOPPOSITE;
//else if ( styles.gettok( i ) == "tooltips" )
// *Styles |= TCS_TOOLTIPS;
else if ( styles.gettok( i ) == "flatseps" )
*ExStyles |= TCS_EX_FLATSEPARATORS;
else if (styles.gettok(i) == "closable") {
this->m_bClosable = true;
*Styles |= TCS_OWNERDRAWFIXED;
}
else if ( styles.gettok( i ) == "gradient" )
this->m_bGradient = true;
i++;
}
this->parseGeneralControlStyles( styles, Styles, ExStyles, bNoTheme );
}
/*!
* \brief $xdid Parsing Function
*
* \param input [NAME] [ID] [PROP] (OPTIONS)
* \param szReturnValue mIRC Data Container
*
* \return > void
*/
void DcxTab::parseInfoRequest( TString & input, char * szReturnValue ) {
int numtok = input.numtok( );
TString prop(input.gettok( 3 ));
if ( prop == "text" && numtok > 3 ) {
int nItem = input.gettok( 4 ).to_int( ) - 1;
if ( nItem > -1 && nItem < TabCtrl_GetItemCount( this->m_Hwnd ) ) {
TCITEM tci;
ZeroMemory( &tci, sizeof( TCITEM ) );
tci.mask = TCIF_TEXT;
tci.pszText = szReturnValue;
tci.cchTextMax = MIRC_BUFFER_SIZE_CCH;
TabCtrl_GetItem( this->m_Hwnd, nItem, &tci );
return;
}
}
else if ( prop == "num" ) {
wnsprintf( szReturnValue, MIRC_BUFFER_SIZE_CCH, "%d", TabCtrl_GetItemCount( this->m_Hwnd ) );
return;
}
// [NAME] [ID] [PROP] [N]
else if ( prop == "icon" && numtok > 3 ) {
int iTab = input.gettok( 4 ).to_int( ) - 1;
if ( iTab > -1 && iTab < TabCtrl_GetItemCount( this->m_Hwnd ) ) {
TCITEM tci;
ZeroMemory( &tci, sizeof( TCITEM ) );
tci.mask = TCIF_IMAGE;
TabCtrl_GetItem( this->m_Hwnd, iTab, &tci );
wnsprintf( szReturnValue, MIRC_BUFFER_SIZE_CCH, "%d", tci.iImage + 1 );
return;
}
}
else if ( prop == "sel" ) {
int nItem = TabCtrl_GetCurSel( this->m_Hwnd );
if ( nItem > -1 && nItem < TabCtrl_GetItemCount( this->m_Hwnd ) ) {
wnsprintf( szReturnValue, MIRC_BUFFER_SIZE_CCH, "%d", nItem + 1 );
return;
}
}
else if ( prop == "seltext" ) {
int nItem = TabCtrl_GetCurSel( this->m_Hwnd );
if ( nItem > -1 && nItem < TabCtrl_GetItemCount( this->m_Hwnd ) ) {
TCITEM tci;
ZeroMemory( &tci, sizeof( TCITEM ) );
tci.mask = TCIF_TEXT;
tci.pszText = szReturnValue;
tci.cchTextMax = MIRC_BUFFER_SIZE_CCH;
TabCtrl_GetItem( this->m_Hwnd, nItem, &tci );
return;
}
}
else if ( prop == "childid" && numtok > 3 ) {
int nItem = input.gettok( 4 ).to_int( ) - 1;
if ( nItem > -1 && nItem < TabCtrl_GetItemCount( this->m_Hwnd ) ) {
TCITEM tci;
ZeroMemory( &tci, sizeof( TCITEM ) );
tci.mask = TCIF_PARAM;
TabCtrl_GetItem( this->m_Hwnd, nItem, &tci );
LPDCXTCITEM lpdtci = (LPDCXTCITEM) tci.lParam;
DcxControl * c = this->m_pParentDialog->getControlByHWND( lpdtci->mChildHwnd );
if ( c != NULL )
wnsprintf( szReturnValue, MIRC_BUFFER_SIZE_CCH, "%d", c->getUserID( ) );
return;
}
}
// [NAME] [ID] [PROP]
else if (prop == "mouseitem") {
TCHITTESTINFO tchi;
tchi.flags = TCHT_ONITEM;
GetCursorPos(&tchi.pt);
MapWindowPoints(NULL, this->m_Hwnd, &tchi.pt, 1);
int tab = TabCtrl_HitTest(this->m_Hwnd, &tchi);
wnsprintf(szReturnValue, MIRC_BUFFER_SIZE_CCH, "%d", tab +1);
return;
}
else if ( this->parseGlobalInfoRequest( input, szReturnValue ) )
return;
szReturnValue[0] = 0;
}
/*!
* \brief blah
*
* blah
*/
void DcxTab::parseCommandRequest( TString & input ) {
XSwitchFlags flags(input.gettok(3));
int numtok = input.numtok( );
// xdid -r [NAME] [ID] [SWITCH]
if (flags['r']) {
int n = 0;
TCITEM tci;
int nItems = TabCtrl_GetItemCount(this->m_Hwnd);
while (n < nItems) {
ZeroMemory(&tci, sizeof(TCITEM));
tci.mask = TCIF_PARAM;
if (TabCtrl_GetItem(this->m_Hwnd, n, &tci)) {
LPDCXTCITEM lpdtci = (LPDCXTCITEM) tci.lParam;
if (lpdtci != NULL && lpdtci->mChildHwnd != NULL && IsWindow(lpdtci->mChildHwnd)) {
DestroyWindow(lpdtci->mChildHwnd);
delete lpdtci;
}
}
++n;
}
TabCtrl_DeleteAllItems(this->m_Hwnd);
}
// xdid -a [NAME] [ID] [SWITCH] [N] [ICON] [TEXT][TAB][ID] [CONTROL] [X] [Y] [W] [H] (OPTIONS)[TAB](TOOLTIP)
if ( flags['a'] && numtok > 4 ) {
TCITEM tci;
ZeroMemory( &tci, sizeof( TCITEM ) );
tci.mask = TCIF_IMAGE | TCIF_PARAM;
TString data(input.gettok( 1, TSTAB ).trim());
TString control_data;
if ( input.numtok( TSTAB ) > 1 )
control_data = input.gettok( 2, TSTAB ).trim();
TString tooltip;
if ( input.numtok( TSTAB ) > 2 )
tooltip = input.gettok( 3, -1, TSTAB ).trim();
int nIndex = data.gettok( 4 ).to_int( ) - 1;
if ( nIndex == -1 )
nIndex += TabCtrl_GetItemCount( this->m_Hwnd ) + 1;
tci.iImage = data.gettok( 5 ).to_int( ) - 1;
// Extra params
LPDCXTCITEM lpdtci = new DCXTCITEM;
if (lpdtci == NULL) {
this->showError(NULL, "-a", "Unable To Create Control, Unable to Allocate Memory");
return;
}
lpdtci->tsTipText = tooltip;
tci.lParam = (LPARAM) lpdtci;
// Itemtext
TString itemtext;
if ( data.numtok( ) > 5 ) {
itemtext = data.gettok( 6, -1 );
tci.mask |= TCIF_TEXT;
if (this->m_bClosable)
itemtext += " ";
tci.pszText = itemtext.to_chr( );
}
if ( control_data.numtok( ) > 5 ) {
UINT ID = mIRC_ID_OFFSET + (UINT)control_data.gettok( 1 ).to_int( );
if ( ID > mIRC_ID_OFFSET - 1 &&
!IsWindow( GetDlgItem( this->m_pParentDialog->getHwnd( ), ID ) ) &&
this->m_pParentDialog->getControlByID( ID ) == NULL )
{
try {
DcxControl * p_Control = DcxControl::controlFactory(this->m_pParentDialog,ID,control_data,2,
CTLF_ALLOW_TREEVIEW |
CTLF_ALLOW_LISTVIEW |
CTLF_ALLOW_RICHEDIT |
CTLF_ALLOW_DIVIDER |
CTLF_ALLOW_PANEL |
CTLF_ALLOW_TAB |
CTLF_ALLOW_REBAR |
CTLF_ALLOW_WEBCTRL |
CTLF_ALLOW_EDIT |
CTLF_ALLOW_IMAGE |
CTLF_ALLOW_LIST
,this->m_Hwnd);
if ( p_Control != NULL ) {
lpdtci->mChildHwnd = p_Control->getHwnd( );
this->m_pParentDialog->addControl( p_Control );
}
}
catch ( char *err ) {
this->showErrorEx(NULL, "-a", "Unable To Create Control %d (%s)", ID - mIRC_ID_OFFSET, err);
}
}
else
this->showErrorEx(NULL, "-a", "Control with ID \"%d\" already exists", ID - mIRC_ID_OFFSET );
}
TabCtrl_InsertItem( this->m_Hwnd, nIndex, &tci );
this->activateSelectedTab( );
}
// xdid -c [NAME] [ID] [SWITCH] [N]
else if ( flags['c'] && numtok > 3 ) {
int nItem = input.gettok( 4 ).to_int( ) - 1;
if ( nItem > -1 && nItem < TabCtrl_GetItemCount( this->m_Hwnd ) ) {
TabCtrl_SetCurSel( this->m_Hwnd, nItem );
this->activateSelectedTab( );
}
}
// xdid -d [NAME] [ID] [SWITCH] [N]
else if ( flags['d'] && numtok > 3 ) {
int nItem = input.gettok( 4 ).to_int( ) - 1;
// if a valid item to delete
if ( nItem > -1 && nItem < TabCtrl_GetItemCount( this->m_Hwnd ) ) {
int curSel = TabCtrl_GetCurSel(this->m_Hwnd);
TCITEM tci;
ZeroMemory( &tci, sizeof( TCITEM ) );
tci.mask = TCIF_PARAM;
if (TabCtrl_GetItem(this->m_Hwnd, nItem, &tci)) {
LPDCXTCITEM lpdtci = (LPDCXTCITEM) tci.lParam;
if ( lpdtci != NULL && lpdtci->mChildHwnd != NULL && IsWindow( lpdtci->mChildHwnd ) ) {
DestroyWindow( lpdtci->mChildHwnd );
delete lpdtci;
}
}
TabCtrl_DeleteItem( this->m_Hwnd, nItem );
// select the next tab item if its the current one
if (curSel == nItem) {
if (nItem < TabCtrl_GetItemCount(this->m_Hwnd))
TabCtrl_SetCurSel(this->m_Hwnd, nItem);
else
TabCtrl_SetCurSel(this->m_Hwnd, nItem -1);
this->activateSelectedTab( );
}
}
}
// xdid -l [NAME] [ID] [SWITCH] [N] [ICON]
else if ( flags['l'] && numtok > 4 ) {
int nItem = input.gettok( 4 ).to_int( ) - 1;
int nIcon = input.gettok( 5 ).to_int( ) - 1;
if ( nItem > -1 && nItem < TabCtrl_GetItemCount( this->m_Hwnd ) ) {
TCITEM tci;
ZeroMemory( &tci, sizeof( TCITEM ) );
tci.mask = TCIF_IMAGE;
tci.iImage = nIcon;
TabCtrl_SetItem( this->m_Hwnd, nItem, &tci );
}
}
// xdid -m [NAME] [ID] [SWITCH] [X] [Y]
else if ( flags['m'] && numtok > 4 ) {
int X = input.gettok( 4 ).to_int( );
int Y = input.gettok( 5 ).to_int( );
TabCtrl_SetItemSize( this->m_Hwnd, X, Y );
}
// This it to avoid an invalid flag message.
// xdid -r [NAME] [ID] [SWITCH]
else if ( flags['r'] ) {
}
// xdid -t [NAME] [ID] [SWITCH] [N] (text)
else if ( flags['t'] && numtok > 3 ) {
int nItem = input.gettok( 4 ).to_int( ) - 1;
if ( nItem > -1 && nItem < TabCtrl_GetItemCount( this->m_Hwnd ) ) {
TString itemtext;
TCITEM tci;
ZeroMemory( &tci, sizeof( TCITEM ) );
tci.mask = TCIF_TEXT;
if ( numtok > 4 )
itemtext = input.gettok( 5, -1 ).trim();
tci.pszText = itemtext.to_chr( );
TabCtrl_SetItem( this->m_Hwnd, nItem, &tci );
}
}
// xdid -v [DNAME] [ID] [SWITCH] [N] [POS]
else if (flags['v'] && numtok > 4) {
int nItem = input.gettok(4).to_int();
int pos = input.gettok(5).to_int();
BOOL adjustDelete = FALSE;
if (nItem == pos)
return;
else if ((nItem < 1) || (nItem > TabCtrl_GetItemCount(this->m_Hwnd)))
return;
else if ((pos < 1) || (pos > TabCtrl_GetItemCount(this->m_Hwnd)))
return;
// does the nItem index get shifted after we insert
if (nItem > pos)
adjustDelete = TRUE;
// decrement coz of 0-index
nItem--;
// get the item we're moving
char* text = new char[MIRC_BUFFER_SIZE_CCH];
TCITEM tci;
ZeroMemory(&tci, sizeof(TCITEM));
tci.pszText = text;
tci.cchTextMax = MIRC_BUFFER_SIZE_CCH;
tci.mask = TCIF_IMAGE | TCIF_PARAM | TCIF_TEXT | TCIF_STATE;
TabCtrl_GetItem(this->m_Hwnd, nItem, &tci);
// insert it into the new position
TabCtrl_InsertItem(this->m_Hwnd, pos, &tci);
// remove the old tab item
TabCtrl_DeleteItem(this->m_Hwnd, (adjustDelete ? nItem +1 : nItem));
delete [] text;
}
// xdid -w [NAME] [ID] [SWITCH] [FLAGS] [INDEX] [FILENAME]
else if (flags['w'] && numtok > 5) {
HIMAGELIST himl;
HICON icon;
TString flag(input.gettok( 4 ));
int index = input.gettok( 5 ).to_int();
TString filename(input.gettok(6, -1));
if ((himl = this->getImageList()) == NULL) {
himl = this->createImageList();
if (himl)
this->setImageList(himl);
}
icon = dcxLoadIcon(index, filename, false, flag);
ImageList_AddIcon(himl, icon);
DestroyIcon(icon);
}
// xdid -y [NAME] [ID] [SWITCH] [+FLAGS]
else if ( flags['y'] ) {
ImageList_Destroy( this->getImageList( ) );
}
else
this->parseGlobalCommandRequest( input, flags );
}
/*!
* \brief blah
*
* blah
*/
HIMAGELIST DcxTab::getImageList( ) {
return TabCtrl_GetImageList( this->m_Hwnd );
}
/*!
* \brief blah
*
* blah
*/
void DcxTab::setImageList( HIMAGELIST himl ) {
TabCtrl_SetImageList( this->m_Hwnd, himl );
}
/*!
* \brief blah
*
* blah
*/
HIMAGELIST DcxTab::createImageList( ) {
return ImageList_Create( 16, 16, ILC_COLOR32|ILC_MASK, 1, 0 );
}
/*!
* \brief blah
*
* blah
*/
void DcxTab::deleteLParamInfo( const int nItem ) {
TCITEM tci;
ZeroMemory( &tci, sizeof( TCITEM ) );
tci.mask = TCIF_PARAM;
if ( TabCtrl_GetItem( this->m_Hwnd, nItem, &tci ) ) {
LPDCXTCITEM lpdtci = (LPDCXTCITEM) tci.lParam;
if ( lpdtci != NULL )
delete lpdtci;
}
}
/*!
* \brief blah
*
* blah
*/
void DcxTab::activateSelectedTab( ) {
int nTab = TabCtrl_GetItemCount( this->m_Hwnd );
int nSel = TabCtrl_GetCurSel( this->m_Hwnd );
if ( nTab > 0 ) {
RECT tabrect, rc;
GetWindowRect( this->m_Hwnd, &tabrect );
TabCtrl_AdjustRect( this->m_Hwnd, FALSE, &tabrect );
GetWindowRect( this->m_Hwnd, &rc );
OffsetRect( &tabrect, -rc.left, -rc.top );
/*
char data[500];
wnsprintf( data, 500, "WRECT %d %d %d %d - ARECT %d %d %d %d",
rc.left, rc.top, rc.right-rc.left, rc.bottom-rc.top,
tabrect.left, tabrect.top, tabrect.right-tabrect.left, tabrect.bottom-tabrect.top );
mIRCError( data );
*/
TCITEM tci;
ZeroMemory( &tci, sizeof( TCITEM ) );
tci.mask = TCIF_PARAM;
HDWP hdwp = BeginDeferWindowPos( 0 );
while ( nTab-- ) {
TabCtrl_GetItem( this->m_Hwnd, nTab, &tci );
LPDCXTCITEM lpdtci = (LPDCXTCITEM) tci.lParam;
if ( lpdtci->mChildHwnd != NULL && IsWindow( lpdtci->mChildHwnd ) ) {
if ( nTab == nSel ) {
hdwp = DeferWindowPos( hdwp, lpdtci->mChildHwnd, NULL,
tabrect.left, tabrect.top, tabrect.right-tabrect.left, tabrect.bottom-tabrect.top,
SWP_SHOWWINDOW | SWP_NOZORDER | SWP_NOOWNERZORDER );
}
else {
hdwp = DeferWindowPos( hdwp, lpdtci->mChildHwnd, NULL, 0, 0, 0, 0,
SWP_HIDEWINDOW | SWP_NOSIZE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOREDRAW | SWP_NOACTIVATE | SWP_NOOWNERZORDER );
}
}
}
EndDeferWindowPos( hdwp );
}
}
void DcxTab::getTab(int index, LPTCITEM tcItem) {
TabCtrl_GetItem(this->m_Hwnd, index, tcItem);
}
int DcxTab::getTabCount() {
return TabCtrl_GetItemCount(this->m_Hwnd);
}
void DcxTab::GetCloseButtonRect(const RECT& rcItem, RECT& rcCloseButton)
{
// ----------
//rcCloseButton.top = rcItem.top + 2;
//rcCloseButton.bottom = rcCloseButton.top + (m_iiCloseButton.rcImage.bottom - m_iiCloseButton.rcImage.top);
//rcCloseButton.right = rcItem.right - 2;
//rcCloseButton.left = rcCloseButton.right - (m_iiCloseButton.rcImage.right - m_iiCloseButton.rcImage.left);
// ----------
rcCloseButton.top = rcItem.top + 2;
rcCloseButton.bottom = rcCloseButton.top + (16);
rcCloseButton.right = rcItem.right - 2;
rcCloseButton.left = rcCloseButton.right - (16);
// ----------
}
TString DcxTab::getStyles(void) {
TString styles(__super::getStyles());
DWORD ExStyles, Styles;
Styles = GetWindowStyle(this->m_Hwnd);
ExStyles = GetWindowExStyle(this->m_Hwnd);
if (Styles & TCS_VERTICAL)
styles.addtok("vertical", " ");
if (Styles & TCS_BOTTOM)
styles.addtok("bottom", " ");
if (Styles & TCS_RIGHT)
styles.addtok("right", " ");
if (Styles & TCS_FIXEDWIDTH)
styles.addtok("fixedwidth", " ");
if (Styles & TCS_RIGHT)
styles.addtok("buttons", " ");
if (Styles & TCS_BUTTONS)
styles.addtok("flat", " ");
if (Styles & TCS_FLATBUTTONS)
styles.addtok("flat", " ");
if (Styles & TCS_HOTTRACK)
styles.addtok("hot", " ");
if (Styles & TCS_MULTILINE)
styles.addtok("multiline", " ");
if (Styles & TCS_RIGHTJUSTIFY)
styles.addtok("rightjustify", " ");
if (Styles & TCS_SCROLLOPPOSITE)
styles.addtok("scrollopposite", " ");
if (ExStyles & TCS_EX_FLATSEPARATORS)
styles.addtok("flatseps", " ");
if (this->m_bClosable)
styles.addtok("closable", " ");
if (this->m_bGradient)
styles.addtok("gradient", " ");
return styles;
}
void DcxTab::toXml(TiXmlElement * xml) {
if (xml == NULL)
return;
__super::toXml(xml);
int count = this->getTabCount();
char buf[MIRC_BUFFER_SIZE_CCH];
TCITEM tci;
for (int i = 0; i < count; i++) {
tci.cchTextMax = MIRC_BUFFER_SIZE_CCH -1;
tci.pszText = buf;
tci.mask |= TCIF_TEXT;
if(TabCtrl_GetItem(this->m_Hwnd, i, &tci)) {
LPDCXTCITEM lpdtci = (LPDCXTCITEM) tci.lParam;
if (lpdtci != NULL) {
DcxControl * ctrl = this->m_pParentDialog->getControlByHWND(lpdtci->mChildHwnd);
if (ctrl != NULL) {
TiXmlElement * ctrlxml = ctrl->toXml();
// we need to remove hidden style here
TString styles(ctrlxml->Attribute("styles"));
if (styles.len() > 0) {
styles.remtok("hidden", 1);
if (styles.len() > 0)
ctrlxml->SetAttribute("styles", styles.to_chr());
else
ctrlxml->RemoveAttribute("styles");
}
if (tci.mask & TCIF_TEXT)
ctrlxml->SetAttribute("caption", tci.pszText);
xml->LinkEndChild(ctrlxml);
}
}
}
}
}
/*!
* \brief blah
*
* blah
*/
LRESULT DcxTab::ParentMessage(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL &bParsed)
{
switch (uMsg) {
case WM_NOTIFY :
{
LPNMHDR hdr = (LPNMHDR) lParam;
if (!hdr)
break;
switch (hdr->code) {
case NM_RCLICK:
{
if (this->m_pParentDialog->getEventMask() & DCX_EVENT_CLICK) {
TCHITTESTINFO tchi;
tchi.flags = TCHT_ONITEM;
GetCursorPos(&tchi.pt);
MapWindowPoints(NULL, this->m_Hwnd, &tchi.pt, 1);
int tab = TabCtrl_HitTest(this->m_Hwnd, &tchi);
TabCtrl_GetCurSel(this->m_Hwnd);
if (tab != -1)
this->execAliasEx("%s,%d,%d", "rclick", this->getUserID(), tab +1);
}
bParsed = TRUE;
break;
}
case NM_CLICK:
{
if (this->m_pParentDialog->getEventMask() & DCX_EVENT_CLICK) {
int tab = TabCtrl_GetCurFocus(this->m_Hwnd);
//int tab = TabCtrl_GetCurSel(this->m_Hwnd);
if (tab != -1) {
if (this->m_bClosable) {
RECT rcCloseButton, rc;
POINT pt;
GetCursorPos(&pt);
MapWindowPoints(NULL,this->m_Hwnd, &pt, 1);
TabCtrl_GetItemRect(this->m_Hwnd, tab, &rc);
GetCloseButtonRect(rc, rcCloseButton);
if (PtInRect(&rcCloseButton, pt)) {
this->execAliasEx("%s,%d,%d", "closetab", this->getUserID(), tab +1);
break;
}
}
this->execAliasEx("%s,%d,%d", "sclick", this->getUserID(), tab +1);
}
}
}
// fall through.
case TCN_SELCHANGE:
{
this->activateSelectedTab();
bParsed = TRUE;
}
break;
}
break;
}
// Original source based on code from eMule 0.47 source code available at http://www.emule-project.net
case WM_DRAWITEM:
{
if (!m_bClosable)
break;
DRAWITEMSTRUCT *idata = (DRAWITEMSTRUCT *)lParam;
if ((idata == NULL) || (!IsWindow(idata->hwndItem)))
break;
//DcxControl *c_this = (DcxControl *) GetProp(idata->hwndItem, "dcx_cthis");
//if (c_this == NULL)
// break;
RECT rect;
int nTabIndex = idata->itemID;
if (nTabIndex < 0)
break;
CopyRect(&rect, &idata->rcItem);
// if themes are active use them.
// call default WndProc(), DrawThemeParentBackgroundUx() is only temporary
DcxControl::DrawCtrlBackground(idata->hDC, this, &rect);
//DrawThemeParentBackgroundUx(this->m_Hwnd, idata->hDC, &rect);
//CopyRect(&rect, &idata->rcItem);
if (this->m_bGradient) {
if (this->m_clrBackText == -1)
// Gives a nice silver/gray gradient
XPopupMenuItem::DrawGradient(idata->hDC, &rect, GetSysColor(COLOR_BTNHIGHLIGHT), GetSysColor(COLOR_BTNFACE), TRUE);
else
XPopupMenuItem::DrawGradient(idata->hDC, &rect, GetSysColor(COLOR_BTNHIGHLIGHT), this->m_clrBackText, TRUE);
}
rect.left += 1+ GetSystemMetrics(SM_CXEDGE); // move in past border.
// TODO: (twig) Ook can u take a look at this plz? string stuff isnt my forte
TString label((UINT)MIRC_BUFFER_SIZE_CCH);
TC_ITEM tci;
tci.mask = TCIF_TEXT | TCIF_IMAGE | TCIF_STATE;
tci.pszText = label.to_chr();
tci.cchTextMax = MIRC_BUFFER_SIZE_CCH;
tci.dwStateMask = TCIS_HIGHLIGHTED;
if (!TabCtrl_GetItem(this->getHwnd(), nTabIndex, &tci)) {
this->showError(NULL, "DcxTab Fatal Error", "Invalid item");
break;
}
// fill the rect so it appears to "merge" with the tab page content
//if (!dcxIsThemeActive())
//FillRect(idata->hDC, &rect, GetSysColorBrush(COLOR_BTNFACE));
// set transparent so text background isnt annoying
int iOldBkMode = SetBkMode(idata->hDC, TRANSPARENT);
// Draw icon on left side if the item has an icon
if (tci.iImage != -1) {
ImageList_DrawEx( this->getImageList(), tci.iImage, idata->hDC, rect.left, rect.top, 0, 0, CLR_NONE, CLR_NONE, ILD_TRANSPARENT );
IMAGEINFO ii;
ImageList_GetImageInfo( this->getImageList(), tci.iImage, &ii);
rect.left += (ii.rcImage.right - ii.rcImage.left);
}
// Draw 'Close button' at right side
if (m_bClosable) {
RECT rcCloseButton;
GetCloseButtonRect(rect, rcCloseButton);
// Draw systems close button ? or do you want a custom close button?
DrawFrameControl(idata->hDC, &rcCloseButton, DFC_CAPTION, DFCS_CAPTIONCLOSE | DFCS_FLAT | DFCS_TRANSPARENT);
//MoveToEx( idata->hDC, rcCloseButton.left, rcCloseButton.top, NULL );
//LineTo( idata->hDC, rcCloseButton.right, rcCloseButton.bottom );
//MoveToEx( idata->hDC, rcCloseButton.right, rcCloseButton.top, NULL );
//LineTo( idata->hDC, rcCloseButton.left, rcCloseButton.bottom );
rect.right = rcCloseButton.left - 2;
}
COLORREF crOldColor = 0;
if (tci.dwState & TCIS_HIGHLIGHTED)
crOldColor = SetTextColor(idata->hDC, GetSysColor(COLOR_HIGHLIGHTTEXT));
rect.top += 1+ GetSystemMetrics(SM_CYEDGE); //4;
//DrawText(idata->hDC, label.to_chr(), label.len(), &rect, DT_SINGLELINE | DT_TOP | DT_NOPREFIX);
// allow mirc formatted text.
//mIRC_DrawText(idata->hDC, label, &rect, DT_SINGLELINE | DT_TOP | DT_NOPREFIX, false, this->m_bUseUTF8);
//if (!this->m_bCtrlCodeText) {
// if (this->m_bShadowText)
// dcxDrawShadowText(idata->hDC, label.to_wchr(this->m_bUseUTF8), label.wlen(),&rect, DT_WORD_ELLIPSIS | DT_LEFT | DT_TOP | DT_SINGLELINE, GetTextColor(idata->hDC), 0, 5, 5);
// else
// DrawTextW( idata->hDC, label.to_wchr(this->m_bUseUTF8), label.wlen( ), &rect, DT_WORD_ELLIPSIS | DT_LEFT | DT_TOP | DT_SINGLELINE );
//}
//else
// mIRC_DrawText( idata->hDC, label, &rect, DT_WORD_ELLIPSIS | DT_LEFT | DT_TOP | DT_SINGLELINE, this->m_bShadowText, this->m_bUseUTF8);
this->ctrlDrawText(idata->hDC, label, &rect, DT_WORD_ELLIPSIS | DT_LEFT | DT_TOP | DT_SINGLELINE);
if (tci.dwState & TCIS_HIGHLIGHTED)
SetTextColor(idata->hDC, crOldColor);
SetBkMode(idata->hDC, iOldBkMode);
break;
}
}
return 0L;
}
LRESULT DcxTab::PostMessage( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL & bParsed )
{
LRESULT lRes = 0L;
switch( uMsg ) {
case WM_CONTEXTMENU:
case WM_LBUTTONUP:
break;
case WM_NOTIFY :
{
LPNMHDR hdr = (LPNMHDR) lParam;
if (!hdr)
break;
//if (hdr->hwndFrom == this->m_ToolTipHWND) {
// switch(hdr->code) {
// case TTN_GETDISPINFO:
// {
// LPNMTTDISPINFO di = (LPNMTTDISPINFO)lParam;
// di->lpszText = this->m_tsToolTip.to_chr();
// di->hinst = NULL;
// bParsed = TRUE;
// }
// break;
// case TTN_LINKCLICK:
// {
// bParsed = TRUE;
// this->execAliasEx("%s,%d", "tooltiplink", this->getUserID());
// }
// break;
// default:
// break;
// }
//}
if (IsWindow(hdr->hwndFrom)) {
DcxControl *c_this = (DcxControl *) GetProp(hdr->hwndFrom,"dcx_cthis");
if (c_this != NULL)
lRes = c_this->ParentMessage(uMsg, wParam, lParam, bParsed);
}
}
break;
case WM_HSCROLL:
case WM_VSCROLL:
case WM_COMMAND:
{
if (IsWindow((HWND) lParam)) {
DcxControl *c_this = (DcxControl *) GetProp((HWND) lParam,"dcx_cthis");
if (c_this != NULL)
lRes = c_this->ParentMessage(uMsg, wParam, lParam, bParsed);
}
}
break;
case WM_DELETEITEM:
{
DELETEITEMSTRUCT *idata = (DELETEITEMSTRUCT *)lParam;
if ((idata != NULL) && (IsWindow(idata->hwndItem))) {
DcxControl *c_this = (DcxControl *) GetProp(idata->hwndItem,"dcx_cthis");
if (c_this != NULL)
lRes = c_this->ParentMessage(uMsg, wParam, lParam, bParsed);
}
}
break;
case WM_MEASUREITEM:
{
HWND cHwnd = GetDlgItem(this->m_Hwnd, wParam);
if (IsWindow(cHwnd)) {
DcxControl *c_this = (DcxControl *) GetProp(cHwnd,"dcx_cthis");
if (c_this != NULL)
lRes = c_this->ParentMessage(uMsg, wParam, lParam, bParsed);
}
}
break;
case WM_SIZE:
{
this->activateSelectedTab( );
if (this->m_pParentDialog->getEventMask() & DCX_EVENT_SIZE)
this->execAliasEx("%s,%d", "sizing", this->getUserID( ) );
}
break;
case WM_ERASEBKGND:
{
if (this->isExStyle(WS_EX_TRANSPARENT))
this->DrawParentsBackground((HDC)wParam);
else
DcxControl::DrawCtrlBackground((HDC) wParam,this);
bParsed = TRUE;
return TRUE;
}
break;
case WM_PAINT:
{
if (!this->m_bAlphaBlend)
break;
PAINTSTRUCT ps;
HDC hdc;
hdc = BeginPaint( this->m_Hwnd, &ps );
bParsed = TRUE;
// Setup alpha blend if any.
LPALPHAINFO ai = this->SetupAlphaBlend(&hdc);
lRes = CallWindowProc( this->m_DefaultWindowProc, this->m_Hwnd, uMsg, (WPARAM) hdc, lParam );
this->FinishAlphaBlend(ai);
EndPaint( this->m_Hwnd, &ps );
}
break;
//case WM_CLOSE:
// {
// if (GetKeyState(VK_ESCAPE) != 0) // don't allow the window to close if escape is pressed. Needs looking into for a better method.
// bParsed = TRUE;
// }
// break;
case WM_DESTROY:
{
delete this;
bParsed = TRUE;
}
break;
default:
lRes = this->CommonMessage( uMsg, wParam, lParam, bParsed);
break;
}
return lRes;
}
| dlsocool/dcx | Classes/dcxtab.cpp | C++ | bsd-3-clause | 29,210 |
package uk.ac.soton.ecs.comp3204.l3;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagLayout;
import java.io.IOException;
import javax.swing.JPanel;
import org.openimaj.content.slideshow.Slide;
import org.openimaj.content.slideshow.SlideshowApplication;
import org.openimaj.data.dataset.VFSGroupDataset;
import org.openimaj.image.DisplayUtilities.ImageComponent;
import org.openimaj.image.FImage;
import org.openimaj.image.ImageUtilities;
import uk.ac.soton.ecs.comp3204.l3.FaceDatasetDemo.FaceDatasetProvider;
import uk.ac.soton.ecs.comp3204.utils.Utils;
import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration;
/**
* Visualise mean-centered face images
*
* @author Jonathon Hare (jsh2@ecs.soton.ac.uk)
*
*/
@Demonstration(title = "Mean-centred faces demo")
public class MeanCenteredFacesDemo implements Slide {
@Override
public Component getComponent(int width, int height) throws IOException {
final VFSGroupDataset<FImage> dataset = FaceDatasetProvider.getDataset();
final FImage mean = dataset.getRandomInstance().fill(0f);
for (final FImage i : dataset) {
mean.addInplace(i);
}
mean.divideInplace(dataset.numInstances());
final JPanel outer = new JPanel();
outer.setOpaque(false);
outer.setPreferredSize(new Dimension(width, height));
outer.setLayout(new GridBagLayout());
final JPanel base = new JPanel();
base.setOpaque(false);
base.setPreferredSize(new Dimension(width, height - 50));
base.setLayout(new FlowLayout());
for (int i = 0; i < 60; i++) {
final FImage img = dataset.getRandomInstance().subtract(mean).normalise();
final ImageComponent ic = new ImageComponent(true, false);
ic.setAllowPanning(false);
ic.setAllowZoom(false);
ic.setShowPixelColours(false);
ic.setShowXYPosition(false);
ic.setImage(ImageUtilities.createBufferedImageForDisplay(img));
base.add(ic);
}
outer.add(base);
return outer;
}
@Override
public void close() {
// do nothing
}
public static void main(String[] args) throws IOException {
new SlideshowApplication(new MeanCenteredFacesDemo(), 1024, 768, Utils.BACKGROUND_IMAGE);
}
}
| jonhare/COMP3204 | app/src/main/java/uk/ac/soton/ecs/comp3204/l3/MeanCenteredFacesDemo.java | Java | bsd-3-clause | 2,176 |
package com.salesforce.dva.argus.service.mq.kafka;
import com.fasterxml.jackson.databind.JavaType;
import java.io.Serializable;
import java.util.List;
public interface Consumer {
<T extends Serializable> List<T> dequeueFromBuffer(String topic, Class<T> type, int timeout, int limit);
<T extends Serializable> List<T> dequeueFromBuffer(String topic, JavaType type, int timeout, int limit);
void shutdown();
} | salesforce/Argus | ArgusCore/src/main/java/com/salesforce/dva/argus/service/mq/kafka/Consumer.java | Java | bsd-3-clause | 424 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('setlist', '0012_remove_show_leg'),
]
operations = [
migrations.CreateModel(
name='Show2',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('venue', models.ForeignKey(to='setlist.Venue', to_field='id')),
('tour', models.ForeignKey(to='setlist.Tour', to_field='id')),
('date', models.DateField(db_index=True)),
('setlist', models.TextField(default=b'', blank=True)),
('notes', models.TextField(default=b'', blank=True)),
('source', models.TextField(default=b'', blank=True)),
],
options={
},
bases=(models.Model,),
),
]
| tylereaves/26md | setlist/migrations/0013_show2.py | Python | bsd-3-clause | 970 |
// An object that encapsulates everything we need to run a 'find'
// operation, encoded in the REST API format.
var Parse = require('parse/node').Parse;
import { default as FilesController } from './Controllers/FilesController';
// restOptions can include:
// skip
// limit
// order
// count
// include
// keys
// redirectClassNameForKey
function RestQuery(config, auth, className, restWhere = {}, restOptions = {}) {
this.config = config;
this.auth = auth;
this.className = className;
this.restWhere = restWhere;
this.response = null;
this.findOptions = {};
if (!this.auth.isMaster) {
this.findOptions.acl = this.auth.user ? [this.auth.user.id] : null;
if (this.className == '_Session') {
if (!this.findOptions.acl) {
throw new Parse.Error(Parse.Error.INVALID_SESSION_TOKEN,
'This session token is invalid.');
}
this.restWhere = {
'$and': [this.restWhere, {
'user': {
__type: 'Pointer',
className: '_User',
objectId: this.auth.user.id
}
}]
};
}
}
this.doCount = false;
// The format for this.include is not the same as the format for the
// include option - it's the paths we should include, in order,
// stored as arrays, taking into account that we need to include foo
// before including foo.bar. Also it should dedupe.
// For example, passing an arg of include=foo.bar,foo.baz could lead to
// this.include = [['foo'], ['foo', 'baz'], ['foo', 'bar']]
this.include = [];
for (var option in restOptions) {
switch(option) {
case 'keys':
this.keys = new Set(restOptions.keys.split(','));
this.keys.add('objectId');
this.keys.add('createdAt');
this.keys.add('updatedAt');
break;
case 'count':
this.doCount = true;
break;
case 'skip':
case 'limit':
this.findOptions[option] = restOptions[option];
break;
case 'order':
var fields = restOptions.order.split(',');
var sortMap = {};
for (var field of fields) {
if (field[0] == '-') {
sortMap[field.slice(1)] = -1;
} else {
sortMap[field] = 1;
}
}
this.findOptions.sort = sortMap;
break;
case 'include':
var paths = restOptions.include.split(',');
var pathSet = {};
for (var path of paths) {
// Add all prefixes with a .-split to pathSet
var parts = path.split('.');
for (var len = 1; len <= parts.length; len++) {
pathSet[parts.slice(0, len).join('.')] = true;
}
}
this.include = Object.keys(pathSet).sort((a, b) => {
return a.length - b.length;
}).map((s) => {
return s.split('.');
});
break;
case 'redirectClassNameForKey':
this.redirectKey = restOptions.redirectClassNameForKey;
this.redirectClassName = null;
break;
default:
throw new Parse.Error(Parse.Error.INVALID_JSON,
'bad option: ' + option);
}
}
}
// A convenient method to perform all the steps of processing a query
// in order.
// Returns a promise for the response - an object with optional keys
// 'results' and 'count'.
// TODO: consolidate the replaceX functions
RestQuery.prototype.execute = function() {
return Promise.resolve().then(() => {
return this.buildRestWhere();
}).then(() => {
return this.runFind();
}).then(() => {
return this.runCount();
}).then(() => {
return this.handleInclude();
}).then(() => {
return this.response;
});
};
RestQuery.prototype.buildRestWhere = function() {
return Promise.resolve().then(() => {
return this.getUserAndRoleACL();
}).then(() => {
return this.redirectClassNameForKey();
}).then(() => {
return this.validateClientClassCreation();
}).then(() => {
return this.replaceSelect();
}).then(() => {
return this.replaceDontSelect();
}).then(() => {
return this.replaceInQuery();
}).then(() => {
return this.replaceNotInQuery();
});
}
// Uses the Auth object to get the list of roles, adds the user id
RestQuery.prototype.getUserAndRoleACL = function() {
if (this.auth.isMaster || !this.auth.user) {
return Promise.resolve();
}
return this.auth.getUserRoles().then((roles) => {
roles.push(this.auth.user.id);
this.findOptions.acl = roles;
return Promise.resolve();
});
};
// Changes the className if redirectClassNameForKey is set.
// Returns a promise.
RestQuery.prototype.redirectClassNameForKey = function() {
if (!this.redirectKey) {
return Promise.resolve();
}
// We need to change the class name based on the schema
return this.config.database.redirectClassNameForKey(
this.className, this.redirectKey).then((newClassName) => {
this.className = newClassName;
this.redirectClassName = newClassName;
});
};
// Validates this operation against the allowClientClassCreation config.
RestQuery.prototype.validateClientClassCreation = function() {
let sysClass = ['_User', '_Installation', '_Role', '_Session', '_Product'];
if (this.config.allowClientClassCreation === false && !this.auth.isMaster
&& sysClass.indexOf(this.className) === -1) {
return this.config.database.collectionExists(this.className).then((hasClass) => {
if (hasClass === true) {
return Promise.resolve();
}
throw new Parse.Error(Parse.Error.OPERATION_FORBIDDEN,
'This user is not allowed to access ' +
'non-existent class: ' + this.className);
});
} else {
return Promise.resolve();
}
};
// Replaces a $inQuery clause by running the subquery, if there is an
// $inQuery clause.
// The $inQuery clause turns into an $in with values that are just
// pointers to the objects returned in the subquery.
RestQuery.prototype.replaceInQuery = function() {
var inQueryObject = findObjectWithKey(this.restWhere, '$inQuery');
if (!inQueryObject) {
return;
}
// The inQuery value must have precisely two keys - where and className
var inQueryValue = inQueryObject['$inQuery'];
if (!inQueryValue.where || !inQueryValue.className) {
throw new Parse.Error(Parse.Error.INVALID_QUERY,
'improper usage of $inQuery');
}
var subquery = new RestQuery(
this.config, this.auth, inQueryValue.className,
inQueryValue.where);
return subquery.execute().then((response) => {
var values = [];
for (var result of response.results) {
values.push({
__type: 'Pointer',
className: inQueryValue.className,
objectId: result.objectId
});
}
delete inQueryObject['$inQuery'];
if (Array.isArray(inQueryObject['$in'])) {
inQueryObject['$in'] = inQueryObject['$in'].concat(values);
} else {
inQueryObject['$in'] = values;
}
// Recurse to repeat
return this.replaceInQuery();
});
};
// Replaces a $notInQuery clause by running the subquery, if there is an
// $notInQuery clause.
// The $notInQuery clause turns into a $nin with values that are just
// pointers to the objects returned in the subquery.
RestQuery.prototype.replaceNotInQuery = function() {
var notInQueryObject = findObjectWithKey(this.restWhere, '$notInQuery');
if (!notInQueryObject) {
return;
}
// The notInQuery value must have precisely two keys - where and className
var notInQueryValue = notInQueryObject['$notInQuery'];
if (!notInQueryValue.where || !notInQueryValue.className) {
throw new Parse.Error(Parse.Error.INVALID_QUERY,
'improper usage of $notInQuery');
}
var subquery = new RestQuery(
this.config, this.auth, notInQueryValue.className,
notInQueryValue.where);
return subquery.execute().then((response) => {
var values = [];
for (var result of response.results) {
values.push({
__type: 'Pointer',
className: notInQueryValue.className,
objectId: result.objectId
});
}
delete notInQueryObject['$notInQuery'];
if (Array.isArray(notInQueryObject['$nin'])) {
notInQueryObject['$nin'] = notInQueryObject['$nin'].concat(values);
} else {
notInQueryObject['$nin'] = values;
}
// Recurse to repeat
return this.replaceNotInQuery();
});
};
// Replaces a $select clause by running the subquery, if there is a
// $select clause.
// The $select clause turns into an $in with values selected out of
// the subquery.
// Returns a possible-promise.
RestQuery.prototype.replaceSelect = function() {
var selectObject = findObjectWithKey(this.restWhere, '$select');
if (!selectObject) {
return;
}
// The select value must have precisely two keys - query and key
var selectValue = selectObject['$select'];
// iOS SDK don't send where if not set, let it pass
if (!selectValue.query ||
!selectValue.key ||
typeof selectValue.query !== 'object' ||
!selectValue.query.className ||
Object.keys(selectValue).length !== 2) {
throw new Parse.Error(Parse.Error.INVALID_QUERY,
'improper usage of $select');
}
var subquery = new RestQuery(
this.config, this.auth, selectValue.query.className,
selectValue.query.where);
return subquery.execute().then((response) => {
var values = [];
for (var result of response.results) {
values.push(result[selectValue.key]);
}
delete selectObject['$select'];
if (Array.isArray(selectObject['$in'])) {
selectObject['$in'] = selectObject['$in'].concat(values);
} else {
selectObject['$in'] = values;
}
// Keep replacing $select clauses
return this.replaceSelect();
})
};
// Replaces a $dontSelect clause by running the subquery, if there is a
// $dontSelect clause.
// The $dontSelect clause turns into an $nin with values selected out of
// the subquery.
// Returns a possible-promise.
RestQuery.prototype.replaceDontSelect = function() {
var dontSelectObject = findObjectWithKey(this.restWhere, '$dontSelect');
if (!dontSelectObject) {
return;
}
// The dontSelect value must have precisely two keys - query and key
var dontSelectValue = dontSelectObject['$dontSelect'];
if (!dontSelectValue.query ||
!dontSelectValue.key ||
typeof dontSelectValue.query !== 'object' ||
!dontSelectValue.query.className ||
Object.keys(dontSelectValue).length !== 2) {
throw new Parse.Error(Parse.Error.INVALID_QUERY,
'improper usage of $dontSelect');
}
var subquery = new RestQuery(
this.config, this.auth, dontSelectValue.query.className,
dontSelectValue.query.where);
return subquery.execute().then((response) => {
var values = [];
for (var result of response.results) {
values.push(result[dontSelectValue.key]);
}
delete dontSelectObject['$dontSelect'];
if (Array.isArray(dontSelectObject['$nin'])) {
dontSelectObject['$nin'] = dontSelectObject['$nin'].concat(values);
} else {
dontSelectObject['$nin'] = values;
}
// Keep replacing $dontSelect clauses
return this.replaceDontSelect();
})
};
// Returns a promise for whether it was successful.
// Populates this.response with an object that only has 'results'.
RestQuery.prototype.runFind = function() {
return this.config.database.find(
this.className, this.restWhere, this.findOptions).then((results) => {
if (this.className == '_User') {
for (var result of results) {
delete result.password;
}
}
this.config.filesController.expandFilesInObject(this.config, results);
if (this.keys) {
var keySet = this.keys;
results = results.map((object) => {
var newObject = {};
for (var key in object) {
if (keySet.has(key)) {
newObject[key] = object[key];
}
}
return newObject;
});
}
if (this.redirectClassName) {
for (var r of results) {
r.className = this.redirectClassName;
}
}
this.response = {results: results};
});
};
// Returns a promise for whether it was successful.
// Populates this.response.count with the count
RestQuery.prototype.runCount = function() {
if (!this.doCount) {
return;
}
this.findOptions.count = true;
delete this.findOptions.skip;
delete this.findOptions.limit;
return this.config.database.find(
this.className, this.restWhere, this.findOptions).then((c) => {
this.response.count = c;
});
};
// Augments this.response with data at the paths provided in this.include.
RestQuery.prototype.handleInclude = function() {
if (this.include.length == 0) {
return;
}
var pathResponse = includePath(this.config, this.auth,
this.response, this.include[0]);
if (pathResponse.then) {
return pathResponse.then((newResponse) => {
this.response = newResponse;
this.include = this.include.slice(1);
return this.handleInclude();
});
} else if (this.include.length > 0) {
this.include = this.include.slice(1);
return this.handleInclude();
}
return pathResponse;
};
// Adds included values to the response.
// Path is a list of field names.
// Returns a promise for an augmented response.
function includePath(config, auth, response, path) {
var pointers = findPointers(response.results, path);
if (pointers.length == 0) {
return response;
}
var className = null;
var objectIds = {};
for (var pointer of pointers) {
if (className === null) {
className = pointer.className;
} else {
if (className != pointer.className) {
throw new Parse.Error(Parse.Error.INVALID_JSON,
'inconsistent type data for include');
}
}
objectIds[pointer.objectId] = true;
}
if (!className) {
throw new Parse.Error(Parse.Error.INVALID_JSON,
'bad pointers');
}
// Get the objects for all these object ids
var where = {'objectId': {'$in': Object.keys(objectIds)}};
var query = new RestQuery(config, auth, className, where);
return query.execute().then((includeResponse) => {
var replace = {};
for (var obj of includeResponse.results) {
obj.__type = 'Object';
obj.className = className;
if(className == "_User"){
delete obj.sessionToken;
}
replace[obj.objectId] = obj;
}
var resp = {
results: replacePointers(response.results, path, replace)
};
if (response.count) {
resp.count = response.count;
}
return resp;
});
}
// Object may be a list of REST-format object to find pointers in, or
// it may be a single object.
// If the path yields things that aren't pointers, this throws an error.
// Path is a list of fields to search into.
// Returns a list of pointers in REST format.
function findPointers(object, path) {
if (object instanceof Array) {
var answer = [];
for (var x of object) {
answer = answer.concat(findPointers(x, path));
}
return answer;
}
if (typeof object !== 'object') {
throw new Parse.Error(Parse.Error.INVALID_QUERY,
'can only include pointer fields');
}
if (path.length == 0) {
if (object.__type == 'Pointer') {
return [object];
}
throw new Parse.Error(Parse.Error.INVALID_QUERY,
'can only include pointer fields');
}
var subobject = object[path[0]];
if (!subobject) {
return [];
}
return findPointers(subobject, path.slice(1));
}
// Object may be a list of REST-format objects to replace pointers
// in, or it may be a single object.
// Path is a list of fields to search into.
// replace is a map from object id -> object.
// Returns something analogous to object, but with the appropriate
// pointers inflated.
function replacePointers(object, path, replace) {
if (object instanceof Array) {
return object.map((obj) => replacePointers(obj, path, replace));
}
if (typeof object !== 'object') {
return object;
}
if (path.length == 0) {
if (object.__type == 'Pointer') {
return replace[object.objectId];
}
return object;
}
var subobject = object[path[0]];
if (!subobject) {
return object;
}
var newsub = replacePointers(subobject, path.slice(1), replace);
var answer = {};
for (var key in object) {
if (key == path[0]) {
answer[key] = newsub;
} else {
answer[key] = object[key];
}
}
return answer;
}
// Finds a subobject that has the given key, if there is one.
// Returns undefined otherwise.
function findObjectWithKey(root, key) {
if (typeof root !== 'object') {
return;
}
if (root instanceof Array) {
for (var item of root) {
var answer = findObjectWithKey(item, key);
if (answer) {
return answer;
}
}
}
if (root && root[key]) {
return root;
}
for (var subkey in root) {
var answer = findObjectWithKey(root[subkey], key);
if (answer) {
return answer;
}
}
}
module.exports = RestQuery;
| aneeshd16/parse-server | src/RestQuery.js | JavaScript | bsd-3-clause | 17,157 |
<?php
use yii\bootstrap\Html;
/**
* @var $this \yii\web\View
* @var $content string
*/
?>
<?php $this->beginContent('@app/views/layouts/base.php') ?>
<div class="wrap">
<?= $this->render('//shared/admin_panel') ?>
<?= $this->render('//shared/header') ?>
<a class="logo" href="/">
<?php echo Html::img("@web/files/img/logo.png") ?>
</a>
<?= $this->render('//shared/menu') ?>
<?php
if (isset($this->blocks['topBanner'])) {
echo $this->blocks['topBanner'];
}
?>
<div class="container"><?= $content ?></div>
</div>
<footer class="footer">
<div class="container">
<p class="pull-left">© Vetoni <?= date('Y') ?></p>
<p class="pull-right"><?= Yii::powered() ?></p>
</div>
</footer>
<?php $this->endContent() ?> | vetoni/toko | views/layouts/main.php | PHP | bsd-3-clause | 874 |
<?php
/*=========================================================================
MIDAS Server
Copyright (c) Kitware SAS. 20 rue de la Villette. All rights reserved.
69328 Lyon, FRANCE.
See Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
/** Assetstore Model Base*/
abstract class AssetstoreModelBase extends AppModel
{
/** Constructor*/
public function __construct()
{
parent::__construct();
$this->_name = 'assetstore';
$this->_key = 'assetstore_id';
$this->_mainData = array(
'assetstore_id' => array('type' => MIDAS_DATA),
'name' => array('type' => MIDAS_DATA),
'itemrevision_id' => array('type' => MIDAS_DATA),
'path' => array('type' => MIDAS_DATA),
'type' => array('type' => MIDAS_DATA),
'bitstreams' => array('type' => MIDAS_ONE_TO_MANY, 'model' => 'Bitstream', 'parent_column' => 'assetstore_id', 'child_column' => 'assetstore_id'),
);
$this->initialize(); // required
} // end __construct()
/** Abstract functions */
abstract function getAll();
/** save an assetsore*/
public function save($dao)
{
parent::save($dao);
}
/** delete an assetstore (and all the items in it)*/
public function delete($dao)
{
if(!$dao instanceof AssetstoreDao)
{
throw new Zend_Exception("Error param.");
}
$bitreams = $dao->getBitstreams();
$items = array();
foreach($bitreams as $key => $bitstream)
{
$revision = $bitstream->getItemrevision();
if(empty($revision))
{
continue;
}
$item = $revision->getItem();
if(empty($item))
{
continue;
}
$items[$item->getKey()] = $item;
}
$modelLoader = new MIDAS_ModelLoader();
$item_model = $modelLoader->loadModel('Item');
foreach($items as $item)
{
$item_model->delete($item);
}
parent::delete($dao);
}// delete
} // end class AssetstoreModelBase | mgrauer/midas3score | core/models/base/AssetstoreModelBase.php | PHP | bsd-3-clause | 2,220 |
package eu.monnetproject.util;
import java.util.*;
/**
* Utility function to syntactically sugar properties for OSGi.
* This allows you to create a property map as follows
* <code>Props.prop("key1","value1")</code><br/>
* <code> .prop("key2","value2")</code>
*/
public final class Props {
public static PropsMap prop(String key, Object value) {
PropsMap pm = new PropsMap();
pm.put(key,value);
return pm;
}
public static class PropsMap extends Hashtable<String,Object> {
public PropsMap prop(String key, Object value) {
put(key,value);
return this;
}
}
} | monnetproject/coal | nlp.sim/src/main/java/eu/monnetproject/util/Props.java | Java | bsd-3-clause | 590 |
# -*- coding: utf-8 -*-
from collections import OrderedDict
import locale
from optparse import make_option
from verify.management.commands import VerifyBaseCommand
from verify.models import *
from verify.politici_models import *
from django.db.models import Q, Count
__author__ = 'guglielmo'
class Command(VerifyBaseCommand):
"""
Report delle statistiche di genere complessive, a livello nazionale,
per tutti gli organi di tutte le istituzioni.
Può limitarsi a una o più istituzioni, se si passa un elenco di institution_id
"""
args = '<institution_id institution_id ...>'
help = "Check that all locations have only male components (list locations with female components)."
option_list = VerifyBaseCommand.option_list
def execute_verification(self, *args, **options):
self.csv_headers = ["ISTITUZIONE", "INCARICO", "N_DONNE", "N_UOMINI", "N_TOTALI", "PERC_DONNE", "PERC_UOMINI"]
institutions = OpInstitution.objects.using('politici').all()
if args:
institutions = institutions.filter(id__in=args)
self.logger.info(
"Verification {0} launched with institutions limited to {1}".format(
self.__class__.__module__, ",".join(institutions.values_list('id', flat=True))
)
)
else:
self.logger.info(
"Verification {0} launched for all institutions".format(
self.__class__.__module__
)
)
self.ok_locs = []
self.ko_locs = []
for institution in institutions:
charge_types_ids = OpInstitutionCharge.objects.using('politici').\
filter(date_end__isnull=True,
content__deleted_at__isnull=True).\
filter(institution=institution).\
values_list('charge_type', flat=True).\
distinct()
charge_types = OpChargeType.objects.using('politici').\
filter(id__in=charge_types_ids)
for charge_type in charge_types:
self.logger.info(
"Counting {0} in {1}".format(
charge_type.name, institution.name
)
)
qs = OpInstitutionCharge.objects.using('politici').\
filter(date_end__isnull=True,
content__deleted_at__isnull=True).\
filter(institution=institution,
charge_type=charge_type)
n_tot = qs.count()
n_fem = qs.filter(politician__sex__iexact='f').count()
n_mal = n_tot - n_fem
merged = [institution.name, charge_type.name, n_fem, n_mal, n_tot,]
merged.append(locale.format("%.2f",100. * n_fem / float(n_tot) ))
merged.append(locale.format("%.2f",100. * n_mal / float(n_tot) ))
self.ko_locs.append(merged)
outcome = Verification.OUTCOME.failed
self.logger.info(
"Report for {0} institutions generated.".format(
len(self.ko_locs)
)
)
return outcome
| openpolis/op-verify | project/verify/management/commands/generi_in_istituzioni.py | Python | bsd-3-clause | 3,219 |
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2016. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import edu.wpi.first.wpilibj.hal.FRCNetComm.tResourceType;
import edu.wpi.first.wpilibj.hal.HAL;
import edu.wpi.first.wpilibj.hal.HAL;
/**
* Handle input from standard Joysticks connected to the Driver Station. This class handles standard
* input that comes from the Driver Station. Each time a value is requested the most recent value is
* returned. There is a single class instance for each joystick and the mapping of ports to hardware
* buttons depends on the code in the driver station.
*/
public class Joystick extends GenericHID {
static final byte kDefaultXAxis = 0;
static final byte kDefaultYAxis = 1;
static final byte kDefaultZAxis = 2;
static final byte kDefaultTwistAxis = 2;
static final byte kDefaultThrottleAxis = 3;
static final int kDefaultTriggerButton = 1;
static final int kDefaultTopButton = 2;
/**
* Represents an analog axis on a joystick.
*/
public enum AxisType {
kX(0), kY(1), kZ(2), kTwist(3), kThrottle(4), kNumAxis(5);
@SuppressWarnings("MemberName")
public final int value;
private AxisType(int value) {
this.value = value;
}
}
/**
* Represents a digital button on the JoyStick.
*/
public enum ButtonType {
kTrigger(0), kTop(1), kNumButton(2);
@SuppressWarnings("MemberName")
public final int value;
private ButtonType(int value) {
this.value = value;
}
}
/**
* Represents a rumble output on the JoyStick.
*/
public enum RumbleType {
kLeftRumble, kRightRumble
}
private final DriverStation m_ds;
private final int m_port;
private final byte[] m_axes;
private final byte[] m_buttons;
private int m_outputs;
private short m_leftRumble;
private short m_rightRumble;
/**
* Construct an instance of a joystick. The joystick index is the usb port on the drivers
* station.
*
* @param port The port on the driver station that the joystick is plugged into.
*/
public Joystick(final int port) {
this(port, AxisType.kNumAxis.value, ButtonType.kNumButton.value);
m_axes[AxisType.kX.value] = kDefaultXAxis;
m_axes[AxisType.kY.value] = kDefaultYAxis;
m_axes[AxisType.kZ.value] = kDefaultZAxis;
m_axes[AxisType.kTwist.value] = kDefaultTwistAxis;
m_axes[AxisType.kThrottle.value] = kDefaultThrottleAxis;
m_buttons[ButtonType.kTrigger.value] = kDefaultTriggerButton;
m_buttons[ButtonType.kTop.value] = kDefaultTopButton;
HAL.report(tResourceType.kResourceType_Joystick, port);
}
/**
* Protected version of the constructor to be called by sub-classes.
*
* <p>This constructor allows the subclass to configure the number of constants for axes and
* buttons.
*
* @param port The port on the driver station that the joystick is plugged into.
* @param numAxisTypes The number of axis types in the enum.
* @param numButtonTypes The number of button types in the enum.
*/
protected Joystick(int port, int numAxisTypes, int numButtonTypes) {
m_ds = DriverStation.getInstance();
m_axes = new byte[numAxisTypes];
m_buttons = new byte[numButtonTypes];
m_port = port;
}
/**
* Get the X value of the joystick. This depends on the mapping of the joystick connected to the
* current port.
*
* @param hand Unused
* @return The X value of the joystick.
*/
public double getX(Hand hand) {
return getRawAxis(m_axes[AxisType.kX.value]);
}
/**
* Get the Y value of the joystick. This depends on the mapping of the joystick connected to the
* current port.
*
* @param hand Unused
* @return The Y value of the joystick.
*/
public double getY(Hand hand) {
return getRawAxis(m_axes[AxisType.kY.value]);
}
/**
* Get the Z value of the joystick. This depends on the mapping of the joystick connected to the
* current port.
*
* @param hand Unused
* @return The Z value of the joystick.
*/
public double getZ(Hand hand) {
return getRawAxis(m_axes[AxisType.kZ.value]);
}
/**
* Get the twist value of the current joystick. This depends on the mapping of the joystick
* connected to the current port.
*
* @return The Twist value of the joystick.
*/
public double getTwist() {
return getRawAxis(m_axes[AxisType.kTwist.value]);
}
/**
* Get the throttle value of the current joystick. This depends on the mapping of the joystick
* connected to the current port.
*
* @return The Throttle value of the joystick.
*/
public double getThrottle() {
return getRawAxis(m_axes[AxisType.kThrottle.value]);
}
/**
* Get the value of the axis.
*
* @param axis The axis to read, starting at 0.
* @return The value of the axis.
*/
public double getRawAxis(final int axis) {
return m_ds.getStickAxis(m_port, axis);
}
/**
* For the current joystick, return the axis determined by the argument.
*
* <p>This is for cases where the joystick axis is returned programatically, otherwise one of the
* previous functions would be preferable (for example getX()).
*
* @param axis The axis to read.
* @return The value of the axis.
*/
public double getAxis(final AxisType axis) {
switch (axis) {
case kX:
return getX();
case kY:
return getY();
case kZ:
return getZ();
case kTwist:
return getTwist();
case kThrottle:
return getThrottle();
default:
return 0.0;
}
}
/**
* For the current joystick, return the number of axis.
*/
public int getAxisCount() {
return m_ds.getStickAxisCount(m_port);
}
/**
* Read the state of the trigger on the joystick.
*
* <p>Look up which button has been assigned to the trigger and read its state.
*
* @param hand This parameter is ignored for the Joystick class and is only here to complete the
* GenericHID interface.
* @return The state of the trigger.
*/
public boolean getTrigger(Hand hand) {
return getRawButton(m_buttons[ButtonType.kTrigger.value]);
}
/**
* Read the state of the top button on the joystick.
*
* <p>Look up which button has been assigned to the top and read its state.
*
* @param hand This parameter is ignored for the Joystick class and is only here to complete the
* GenericHID interface.
* @return The state of the top button.
*/
public boolean getTop(Hand hand) {
return getRawButton(m_buttons[ButtonType.kTop.value]);
}
/**
* This is not supported for the Joystick. This method is only here to complete the GenericHID
* interface.
*
* @param hand This parameter is ignored for the Joystick class and is only here to complete the
* GenericHID interface.
* @return The state of the bumper (always false)
*/
public boolean getBumper(Hand hand) {
return false;
}
/**
* Get the button value (starting at button 1).
*
* <p>The appropriate button is returned as a boolean value.
*
* @param button The button number to be read (starting at 1).
* @return The state of the button.
*/
public boolean getRawButton(final int button) {
return m_ds.getStickButton(m_port, (byte) button);
}
/**
* For the current joystick, return the number of buttons.
*/
public int getButtonCount() {
return m_ds.getStickButtonCount(m_port);
}
/**
* Get the angle in degrees of a POV on the joystick.
*
* <p>The POV angles start at 0 in the up direction, and increase clockwise (eg right is 90,
* upper-left is 315).
*
* @param pov The index of the POV to read (starting at 0)
* @return the angle of the POV in degrees, or -1 if the POV is not pressed.
*/
public int getPOV(int pov) {
return m_ds.getStickPOV(m_port, pov);
}
/**
* For the current joystick, return the number of POVs.
*/
public int getPOVCount() {
return m_ds.getStickPOVCount(m_port);
}
/**
* Get buttons based on an enumerated type.
*
* <p>The button type will be looked up in the list of buttons and then read.
*
* @param button The type of button to read.
* @return The state of the button.
*/
public boolean getButton(ButtonType button) {
switch (button) {
case kTrigger:
return getTrigger();
case kTop:
return getTop();
default:
return false;
}
}
/**
* Get the magnitude of the direction vector formed by the joystick's current position relative to
* its origin.
*
* @return The magnitude of the direction vector
*/
public double getMagnitude() {
return Math.sqrt(Math.pow(getX(), 2) + Math.pow(getY(), 2));
}
/**
* Get the direction of the vector formed by the joystick and its origin in radians.
*
* @return The direction of the vector in radians
*/
public double getDirectionRadians() {
return Math.atan2(getX(), -getY());
}
/**
* Get the direction of the vector formed by the joystick and its origin in degrees.
*
* <p>Uses acos(-1) to represent Pi due to absence of readily accessable Pi constant in C++
*
* @return The direction of the vector in degrees
*/
public double getDirectionDegrees() {
return Math.toDegrees(getDirectionRadians());
}
/**
* Get the channel currently associated with the specified axis.
*
* @param axis The axis to look up the channel for.
* @return The channel fr the axis.
*/
public int getAxisChannel(AxisType axis) {
return m_axes[axis.value];
}
/**
* Set the channel associated with a specified axis.
*
* @param axis The axis to set the channel for.
* @param channel The channel to set the axis to.
*/
public void setAxisChannel(AxisType axis, int channel) {
m_axes[axis.value] = (byte) channel;
}
/**
* Get the value of isXbox for the current joystick.
*
* @return A boolean that is true if the controller is an xbox controller.
*/
public boolean getIsXbox() {
return m_ds.getJoystickIsXbox(m_port);
}
/**
* Get the HID type of the current joystick.
*
* @return The HID type value of the current joystick.
*/
public int getType() {
return m_ds.getJoystickType(m_port);
}
/**
* Get the name of the current joystick.
*
* @return The name of the current joystick.
*/
public String getName() {
return m_ds.getJoystickName(m_port);
}
/**
* Get the port number of the joystick.
*
* @return The port number of the joystick.
*/
public int getPort() {
return m_port;
}
/**
* Get the axis type of a joystick axis.
*
* @return the axis type of a joystick axis.
*/
public int getAxisType(int axis) {
return m_ds.getJoystickAxisType(m_port, axis);
}
/**
* Set the rumble output for the joystick. The DS currently supports 2 rumble values, left rumble
* and right rumble.
*
* @param type Which rumble value to set
* @param value The normalized value (0 to 1) to set the rumble to
*/
public void setRumble(RumbleType type, float value) {
if (value < 0) {
value = 0;
} else if (value > 1) {
value = 1;
}
if (type == RumbleType.kLeftRumble) {
m_leftRumble = (short) (value * 65535);
} else {
m_rightRumble = (short) (value * 65535);
}
HAL.setJoystickOutputs((byte) m_port, m_outputs, m_leftRumble, m_rightRumble);
}
/**
* Set a single HID output value for the joystick.
*
* @param outputNumber The index of the output to set (1-32)
* @param value The value to set the output to
*/
public void setOutput(int outputNumber, boolean value) {
m_outputs = (m_outputs & ~(1 << (outputNumber - 1))) | ((value ? 1 : 0) << (outputNumber - 1));
HAL.setJoystickOutputs((byte) m_port, m_outputs, m_leftRumble, m_rightRumble);
}
/**
* Set all HID output values for the joystick.
*
* @param value The 32 bit output value (1 bit for each output)
*/
public void setOutputs(int value) {
m_outputs = value;
HAL.setJoystickOutputs((byte) m_port, m_outputs, m_leftRumble, m_rightRumble);
}
}
| PeterMitrano/allwpilib | wpilibj/src/athena/java/edu/wpi/first/wpilibj/Joystick.java | Java | bsd-3-clause | 12,635 |
package sdp
func (s Session) appendAttributes(attrs Attributes) Session {
for _, v := range attrs {
if v.Value == blank {
s = s.AddFlag(v.Key)
} else {
s = s.AddAttribute(v.Key, v.Value)
}
}
return s
}
// Append encodes message to Session and returns result.
//
// See RFC 4566 Section 5.
func (m *Message) Append(s Session) Session {
s = s.AddVersion(m.Version)
s = s.AddOrigin(m.Origin)
s = s.AddSessionName(m.Name)
if len(m.Info) > 0 {
s = s.AddSessionInfo(m.Info)
}
if len(m.URI) > 0 {
s = s.AddURI(m.URI)
}
if len(m.Email) > 0 {
s = s.AddEmail(m.Email)
}
if len(m.Phone) > 0 {
s = s.AddPhone(m.Phone)
}
if !m.Connection.Blank() {
s = s.AddConnectionData(m.Connection)
}
for t, v := range m.Bandwidths {
s = s.AddBandwidth(t, v)
}
// One or more time descriptions ("t=" and "r=" lines)
for _, t := range m.Timing {
s = s.AddTiming(t.Start, t.End)
if len(t.Offsets) > 0 {
s = s.AddRepeatTimesCompact(t.Repeat, t.Active, t.Offsets...)
}
}
if len(m.TZAdjustments) > 0 {
s = s.AddTimeZones(m.TZAdjustments...)
}
if !m.Encryption.Blank() {
s = s.AddEncryption(m.Encryption)
}
s = s.appendAttributes(m.Attributes)
for i := range m.Medias {
s = s.AddMediaDescription(m.Medias[i].Description)
if len(m.Medias[i].Title) > 0 {
s = s.AddSessionInfo(m.Medias[i].Title)
}
if !m.Medias[i].Connection.Blank() {
s = s.AddConnectionData(m.Medias[i].Connection)
}
for t, v := range m.Medias[i].Bandwidths {
s = s.AddBandwidth(t, v)
}
if !m.Medias[i].Encryption.Blank() {
s = s.AddEncryption(m.Medias[i].Encryption)
}
s = s.appendAttributes(m.Medias[i].Attributes)
}
return s
}
| ernado/sdp | encoder.go | GO | bsd-3-clause | 1,664 |
<?php
if(!class_exists('AbstractQueuedJob')) return;
/**
* A Job for running a external link check for published pages
*
*/
class CheckLinksJob extends AbstractQueuedJob implements QueuedJob {
public function getTitle() {
return _t('CheckLinksJob.TITLE', 'Checking for broken links');
}
public function getJobType() {
return QueuedJob::QUEUED;
}
public function getSignature() {
return md5(get_class($this));
}
/**
* Check an individual page
*/
public function process() {
$task = CheckLinksTask::create();
$track = $task->runLinksCheck(1);
$this->currentStep = $track->CompletedPages;
$this->totalSteps = $track->TotalPages;
$this->isComplete = $track->Status === 'Completed';
}
}
| blpraveen/silverstripe-brokenlinks | code/jobs/CheckLinksJob.php | PHP | bsd-3-clause | 722 |
#!/usr/bin/env python
from distutils.core import setup
setup(name='django-modeltranslation',
version='0.4.0-alpha1',
description='Translates Django models using a registration approach.',
long_description='The modeltranslation application can be used to '
'translate dynamic content of existing models to an '
'arbitrary number of languages without having to '
'change the original model classes. It uses a '
'registration approach (comparable to Django\'s admin '
'app) to be able to add translations to existing or '
'new projects and is fully integrated into the Django '
'admin backend.',
author='Peter Eschler',
author_email='p.eschler@nmy.de',
maintainer='Dirk Eschler',
maintainer_email='d.eschler@nmy.de',
url='http://code.google.com/p/django-modeltranslation/',
packages=['modeltranslation', 'modeltranslation.management',
'modeltranslation.management.commands'],
package_data={'modeltranslation': ['static/modeltranslation/css/*.css',
'static/modeltranslation/js/*.js']},
include_package_data = True,
requires=['django(>=1.0)'],
download_url='http://django-modeltranslation.googlecode.com/files/django-modeltranslation-0.4.0-alpha1.tar.gz',
classifiers=['Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License'],
license='New BSD')
| google-code-export/django-modeltranslation | setup.py | Python | bsd-3-clause | 1,631 |
<div class="row">
<div class="col-xs-12">
<div class="box">
<?= \yii\grid\GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
'idadvert',
[
'label' => 'title',
'value' => 'title',
],
'user.email',
'price',
'created_at:datetime',
[
'class' => 'yii\grid\ActionColumn',
'template' => '{view} {delete}',
'buttons' => [
'view' => function ($url, $model, $key) {
return \yii\helpers\Html::a("<span class=\"glyphicon glyphicon-eye-open\"></span>", Yii::$app->params['baseUrl']. "/view-advert/".$key, ['target' => '_blank']);
}
],
]
],
]) ?>
</div>
</div>
</div> | lastfocus/lol-project | backend/views/advert/index.php | PHP | bsd-3-clause | 1,090 |
#include "stdfx.h"
//#include "tfxparam.h"
#include "trop.h"
//===================================================================
class PremultiplyFx : public TStandardRasterFx {
FX_PLUGIN_DECLARATION(PremultiplyFx)
TRasterFxPort m_input;
public:
PremultiplyFx() { addInputPort("Source", m_input); }
~PremultiplyFx(){};
bool doGetBBox(double frame, TRectD &bBox, const TRenderSettings &info) {
if (m_input.isConnected())
return m_input->doGetBBox(frame, bBox, info);
else {
bBox = TRectD();
return false;
}
}
void doCompute(TTile &tile, double frame, const TRenderSettings &ri);
bool canHandle(const TRenderSettings &info, double frame) { return true; }
};
//------------------------------------------------------------------------------
void PremultiplyFx::doCompute(TTile &tile, double frame,
const TRenderSettings &ri) {
if (!m_input.isConnected()) return;
m_input->compute(tile, frame, ri);
TRop::premultiply(tile.getRaster());
}
FX_PLUGIN_IDENTIFIER(PremultiplyFx, "premultiplyFx");
| walkerka/opentoonz | toonz/sources/stdfx/premultiplyfx.cpp | C++ | bsd-3-clause | 1,082 |
// Copyright 2020 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 "ash/components/phonehub/multidevice_setup_state_updater.h"
#include "ash/components/phonehub/pref_names.h"
#include "ash/components/phonehub/util/histogram_util.h"
#include "base/callback_helpers.h"
#include "chromeos/components/multidevice/logging/logging.h"
#include "chromeos/services/multidevice_setup/public/cpp/prefs.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/pref_service.h"
namespace chromeos {
namespace phonehub {
namespace {
using multidevice_setup::mojom::Feature;
using multidevice_setup::mojom::FeatureState;
using multidevice_setup::mojom::HostStatus;
} // namespace
// static
void MultideviceSetupStateUpdater::RegisterPrefs(PrefRegistrySimple* registry) {
registry->RegisterBooleanPref(prefs::kIsAwaitingVerifiedHost, false);
}
MultideviceSetupStateUpdater::MultideviceSetupStateUpdater(
PrefService* pref_service,
multidevice_setup::MultiDeviceSetupClient* multidevice_setup_client,
NotificationAccessManager* notification_access_manager)
: pref_service_(pref_service),
multidevice_setup_client_(multidevice_setup_client),
notification_access_manager_(notification_access_manager) {
multidevice_setup_client_->AddObserver(this);
notification_access_manager_->AddObserver(this);
}
MultideviceSetupStateUpdater::~MultideviceSetupStateUpdater() {
multidevice_setup_client_->RemoveObserver(this);
notification_access_manager_->RemoveObserver(this);
}
void MultideviceSetupStateUpdater::OnNotificationAccessChanged() {
switch (notification_access_manager_->GetAccessStatus()) {
case NotificationAccessManager::AccessStatus::kAccessGranted:
if (IsWaitingForAccessToInitiallyEnableNotifications()) {
PA_LOG(INFO) << "Enabling PhoneHubNotifications for the first time now "
<< "that access has been granted by the phone.";
multidevice_setup_client_->SetFeatureEnabledState(
Feature::kPhoneHubNotifications, /*enabled=*/true,
/*auth_token=*/absl::nullopt, base::DoNothing());
}
break;
case NotificationAccessManager::AccessStatus::kAvailableButNotGranted:
FALLTHROUGH;
case NotificationAccessManager::AccessStatus::kProhibited:
// Disable kPhoneHubNotifications if notification access has been revoked
// by the phone.
PA_LOG(INFO) << "Disabling PhoneHubNotifications feature.";
multidevice_setup_client_->SetFeatureEnabledState(
Feature::kPhoneHubNotifications, /*enabled=*/false,
/*auth_token=*/absl::nullopt, base::DoNothing());
break;
}
}
void MultideviceSetupStateUpdater::OnHostStatusChanged(
const multidevice_setup::MultiDeviceSetupClient::HostStatusWithDevice&
host_device_with_status) {
EnablePhoneHubIfAwaitingVerifiedHost();
}
void MultideviceSetupStateUpdater::OnFeatureStatesChanged(
const multidevice_setup::MultiDeviceSetupClient::FeatureStatesMap&
feature_state_map) {
EnablePhoneHubIfAwaitingVerifiedHost();
}
bool MultideviceSetupStateUpdater::
IsWaitingForAccessToInitiallyEnableNotifications() const {
// If the Phone Hub notifications feature has never been explicitly set, we
// should enable it after
// 1. the top-level Phone Hub feature is enabled, and
// 2. the phone has granted access.
// We do *not* want disrupt the feature state if it was already explicitly set
// by the user.
return multidevice_setup::IsDefaultFeatureEnabledValue(
Feature::kPhoneHubNotifications, pref_service_) &&
multidevice_setup_client_->GetFeatureState(Feature::kPhoneHub) ==
FeatureState::kEnabledByUser;
}
void MultideviceSetupStateUpdater::EnablePhoneHubIfAwaitingVerifiedHost() {
bool is_awaiting_verified_host =
pref_service_->GetBoolean(prefs::kIsAwaitingVerifiedHost);
const HostStatus host_status =
multidevice_setup_client_->GetHostStatus().first;
const FeatureState feature_state =
multidevice_setup_client_->GetFeatureState(Feature::kPhoneHub);
// Enable the PhoneHub feature if the phone is verified and there was an
// intent to enable the feature. We also ensure that the feature is currently
// disabled and not in state like kNotSupportedByPhone or kProhibitedByPolicy.
if (is_awaiting_verified_host && host_status == HostStatus::kHostVerified &&
feature_state == FeatureState::kDisabledByUser) {
multidevice_setup_client_->SetFeatureEnabledState(
Feature::kPhoneHub, /*enabled=*/true, /*auth_token=*/absl::nullopt,
base::DoNothing());
util::LogFeatureOptInEntryPoint(util::OptInEntryPoint::kSetupFlow);
}
UpdateIsAwaitingVerifiedHost();
}
void MultideviceSetupStateUpdater::UpdateIsAwaitingVerifiedHost() {
// Wait to enable Phone Hub until after host phone is verified. The intent to
// enable Phone Hub must be persisted in the event that this class is
// destroyed before the phone is verified.
const HostStatus host_status =
multidevice_setup_client_->GetHostStatus().first;
if (host_status ==
HostStatus::kHostSetLocallyButWaitingForBackendConfirmation) {
pref_service_->SetBoolean(prefs::kIsAwaitingVerifiedHost, true);
return;
}
// The intent to enable Phone Hub after host verification was fulfilled.
// Note: We don't want to reset the pref if, say, the host status is
// kNoEligibleHosts; that might just be a transient state seen during
// start-up, for instance. It is true that we don't want to enable Phone Hub
// if the user explicitly disabled it in settings, however, that can only
// occur after the host becomes verified and we first enable Phone Hub.
const bool is_awaiting_verified_host =
pref_service_->GetBoolean(prefs::kIsAwaitingVerifiedHost);
const FeatureState feature_state =
multidevice_setup_client_->GetFeatureState(Feature::kPhoneHub);
if (is_awaiting_verified_host && host_status == HostStatus::kHostVerified &&
feature_state == FeatureState::kEnabledByUser) {
pref_service_->SetBoolean(prefs::kIsAwaitingVerifiedHost, false);
return;
}
}
} // namespace phonehub
} // namespace chromeos
| scheib/chromium | ash/components/phonehub/multidevice_setup_state_updater.cc | C++ | bsd-3-clause | 6,304 |
/*
* jQuery File Upload Plugin JS Example 8.9.1
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2010, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*/
/* global $, window */
$(function () {
'use strict';
// Initialize the jQuery File Upload widget:
$('#fileupload').fileupload({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: root_url + '/media/upload'
});
// Enable iframe cross-domain access via redirect option:
$('#fileupload').fileupload(
'option',
'redirect',
window.location.href.replace(
/\/[^\/]*$/,
'/cors/result.html?%s'
)
);
if (window.location.hostname === 'blueimp.github.io') {
// Demo settings:
$('#fileupload').fileupload('option', {
url: '//jquery-file-upload.appspot.com/',
// Enable image resizing, except for Android and Opera,
// which actually support image resizing, but fail to
// send Blob objects via XHR requests:
disableImageResize: /Android(?!.*Chrome)|Opera/
.test(window.navigator.userAgent),
maxFileSize: 5000000,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i
});
// Upload server status check for browsers with CORS support:
if ($.support.cors) {
$.ajax({
url: '//jquery-file-upload.appspot.com/',
type: 'HEAD'
}).fail(function () {
$('<div class="alert alert-danger"/>')
.text('Upload server currently unavailable - ' +
new Date())
.appendTo('#fileupload');
});
}
} else {
// Load existing files:
$('#fileupload').addClass('fileupload-processing');
$.ajax({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: $('#fileupload').fileupload('option', 'url'),
dataType: 'json',
context: $('#fileupload')[0]
}).always(function () {
$(this).removeClass('fileupload-processing');
}).done(function (result) {
$(this).fileupload('option', 'done')
.call(this, $.Event('done'), {result: result});
});
}
///////////////////////////////////////////////
});
| vohoanglong07/yii_basic | web/js/fileupload/main.js | JavaScript | bsd-3-clause | 2,550 |
module Spree
module Admin
class AuthorsController < ResourceController
def index
params[:q] ||= {}
params[:q][:deleted_at_null] ||= "1"
@search = @authors.ransack(params[:q])
@authors = @search.result.page(params[:page]).per(Spree::Config[:admin_products_per_page])
@authors = @authors.includes(:user_detail)
end
def update
author_info = Spree::UserDetail.find_or_create_by(user_id: params[:id])
result = author_info.update_attributes(author_params[:user_detail])
if result
flash[:success] = flash_message_for(@author, :successfully_updated)
respond_with(@author) do |format|
format.html { redirect_to admin_authors_path }
format.json { render layout: false, status: :updated }
end
else
invoke_callbacks(:update, :fails)
respond_with(@author)
end
end
protected
def collection
page = params[:page].to_i > 0 ? params[:page].to_i : 1
per_page = params[:per_page].to_i > 0 ? params[:per_page].to_i : 20
Spree::User.authors.page(page).per(per_page)
end
private
def author_params
params.require(:author).permit(:id, { user_detail: [:nickname, :website_url, :bio_info] })
end
end
end
end
| mehadesai/spree-multi-blogs | app/controllers/spree/admin/authors_controller.rb | Ruby | bsd-3-clause | 1,361 |
<?php namespace xp\runtime;
/**
* Wrap code passed in from the command line.
*
* @see https://wiki.php.net/rfc/group_use_declarations
* @test xp://net.xp_framework.unittest.runtime.CodeTest
*/
class Code {
private $fragment, $imports;
/**
* Creates a new code instance
*
* @param string $input
*/
public function __construct($input) {
// Shebang
if (0 === strncmp($input, '#!', 2)) {
$input= substr($input, strcspn($input, "\n") + 1);
}
// PHP open tags
if (0 === strncmp($input, '<?', 2)) {
$input= substr($input, strcspn($input, "\r\n\t =") + 1);
}
$this->fragment= trim($input, "\r\n\t ;").';';
$this->imports= [];
while (0 === strncmp($this->fragment, 'use ', 4)) {
$delim= strpos($this->fragment, ';');
foreach ($this->importsIn(substr($this->fragment, 4, $delim - 4)) as $import) {
$this->imports[]= $import;
}
$this->fragment= ltrim(substr($this->fragment, $delim + 1), ' ');
}
}
/** @return string */
public function fragment() { return $this->fragment; }
/** @return string */
public function expression() {
return strstr($this->fragment, 'return ') || strstr($this->fragment, 'return;')
? $this->fragment
: 'return '.$this->fragment
;
}
/** @return string[] */
public function imports() { return $this->imports; }
/** @return string */
public function head() {
return empty($this->imports) ? '' : 'use '.implode(', ', $this->imports).';';
}
/**
* Returns types used inside a `use ...` directive.
*
* @param string $use
* @return string[]
*/
private function importsIn($use) {
$name= strrpos($use, '\\') + 1;
$used= [];
if ('{' === $use{$name}) {
$namespace= substr($use, 0, $name);
foreach (explode(',', substr($use, $name + 1, -1)) as $type) {
$used[]= $namespace.trim($type);
}
} else {
foreach (explode(',', $use) as $type) {
$used[]= trim($type);
}
}
return $used;
}
} | johannes85/core | src/main/php/xp/runtime/Code.class.php | PHP | bsd-3-clause | 2,041 |
#!/usr/bin/python
# Copyright (c) 2009, Purdue University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright notice, this
# list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
#
# Neither the name of the Purdue University nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Test for Credential cache library."""
__copyright__ = 'Copyright (C) 2009, Purdue University'
__license__ = 'BSD'
__version__ = '#TRUNK#'
import unittest
import os
import roster_core
from roster_server import credentials
CONFIG_FILE = 'test_data/roster.conf' # Example in test_data
SCHEMA_FILE = '../roster-core/data/database_schema.sql'
DATA_FILE = 'test_data/test_data.sql'
class TestCredentialsLibrary(unittest.TestCase):
def setUp(self):
self.config_instance = roster_core.Config(file_name=CONFIG_FILE)
self.cred_instance = credentials.CredCache(self.config_instance,
u'sharrell')
db_instance = self.config_instance.GetDb()
db_instance.CreateRosterDatabase()
data = open(DATA_FILE, 'r').read()
db_instance.StartTransaction()
db_instance.cursor.execute(data)
db_instance.EndTransaction()
db_instance.close()
self.core_instance = roster_core.Core(u'sharrell', self.config_instance)
def is_valid_uuid (self, uuid):
"""
TAKEN FROM THE BLUEZ MODULE
is_valid_uuid (uuid) -> bool
returns True if uuid is a valid 128-bit UUID.
valid UUIDs are always strings taking one of the following forms:
XXXX
XXXXXXXX
XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
where each X is a hexadecimal digit (case insensitive)
"""
try:
if len (uuid) == 4:
if int (uuid, 16) < 0: return False
elif len (uuid) == 8:
if int (uuid, 16) < 0: return False
elif len (uuid) == 36:
pieces = uuid.split ("-")
if len (pieces) != 5 or \
len (pieces[0]) != 8 or \
len (pieces[1]) != 4 or \
len (pieces[2]) != 4 or \
len (pieces[3]) != 4 or \
len (pieces[4]) != 12:
return False
[ int (p, 16) for p in pieces ]
else:
return False
except ValueError:
return False
except TypeError:
return False
return True
def testCredentials(self):
self.assertTrue(self.cred_instance.Authenticate(u'sharrell', 'test'))
cred_string = self.cred_instance.GetCredentials(u'sharrell', 'test',
self.core_instance)
self.assertEqual(self.cred_instance.CheckCredential(cred_string,
u'sharrell',
self.core_instance),
u'')
self.assertEqual(self.cred_instance.CheckCredential(u'test', u'sharrell',
self.core_instance),
None)
if( __name__ == '__main__' ):
unittest.main()
| stephenlienharrell/roster-dns-management | test/credentials_test.py | Python | bsd-3-clause | 4,275 |
#!/usr/bin/env python
import sys
import hyperdex.client
from hyperdex.client import LessEqual, GreaterEqual, Range, Regex, LengthEquals, LengthLessEqual, LengthGreaterEqual
c = hyperdex.client.Client(sys.argv[1], int(sys.argv[2]))
def to_objectset(xs):
return set([frozenset(x.items()) for x in xs])
assert c.put('kv', 'k', {}) == True
assert c.get('kv', 'k') == {'v': {}}
assert c.put('kv', 'k', {'v': {1: 3.14, 2: 0.25, 3: 1.0}}) == True
assert c.get('kv', 'k') == {'v': {1: 3.14, 2: 0.25, 3: 1.0}}
assert c.put('kv', 'k', {'v': {}}) == True
assert c.get('kv', 'k') == {'v': {}}
| hyc/HyperDex | test/python/DataTypeMapIntFloat.py | Python | bsd-3-clause | 585 |
<?php
namespace yiicms\components\core;
# Websun template parser, version 0.1.80
# http://webew.ru/articles/3609.webew
/*
0.1.80 - allowed_extensions option implemented
0.1.71 - replaced too new array declaration [] with array() - keeping PHP 5.3 compatibility
0.1.70 - added :^N and :^i
0.1.60 - __construct() accepts an array as of now
(wrapping function accepts distinct variables still)
- "no_global_variables" setting implemented
0.1.55 - fixed misbehavior of functions' args parsing
when dealing with comma inside of double quotes
like @function(*var*, "string,string")
По поводу массивов в JSON-нотации в качестве скалярных величин:
// 1. Как *var* вытащить из json_decode?
// Сначала *var* => json_encode(*var*, 1)
// (это будет голый массив данных; не-data-свойства потеряются)
// 2. Как указывать кодировку (json_decode только в UTF-8),
// $WEBSUN_CHARSET?
// 2а) Как вообще избавиться от %u0441 вместо кириллицы?
// возможно только для UTF-8 или избирательно 1251,
// т.к. нужно ловить буквы и делать им кодирование в %uXXXX
// Всё это будет очень долго, особенно если это проводить
// для каждой переменной
// (хотя там можно поставить костыль на [ и { -
// если не встретили в начале, то обрабатываем как обычно)
0.1.54 - $WEBSUN_ALLOWED_CALLBACKS instead of $WEBSUN_VISIBLES
0.1.53 - list of visible functions as a global variable for all versions
(for a while - see v. 0.1.51)
0.1.53(beta) - added trim() at the beginning get_var_or_string()
0.1.52(beta) - using is_numeric() when parsing ifs (opposite to v.0.1.17)
0.1.51(beta) - list of visible functions added (draft)
prior to PHP 5.6 - as a global array variable
PHP 5.6 and higher - as a namespace
0.1.50 - fixed default paths handling (see __construct() )
0.1.49 - added preg_quote() in parse_cycle() for searching array's name
0.1.48 - $ can be used in templates_root direcory path
(^ makes no sense, because it means templates_root path itself)
0.1.47 - called back the possibility of spaces before variables,
because it makes parsing of cycles harder:
instead of [*|&..]array: we must catch [*|&..]\s*array,
which (according to one of the tests) works ~10% slower;
simple (non-cycle) variables and constants
(literally how it is described in comment to previous version)
can still work - this unofficial possibility will be left
0.1.46 - spaces can be like {?* a = b *}, {?* a > b *}
(especially convenient when using constants: {?*a = =CONST*})
0.1.45 - now spaces can be around &, | and variable names in ifs
0.1.44 - loosen parse_cycle() regexp
to accept arrays with non-alphanumeric keys
(for example, it may occur handy to use
some non-latin string as a key),
now {%* anything here *} is accepted.
Note: except of dots in "anything", which are
still interpreted as key separators.
0.1.43 - some fixes in profiling:
parse_template's time is not added to total
instead of this, total time is calculated
as a time of highest level parse_template run
Note: profiling by itself may increase
total run time up to 60%
0.1.42 - loosen regexp at check_if_condition_part()
from [$=]?[\w.\^]*+ to [^*=<>]*+
now any variable name can be used in ifs,
not just alphanumeric;
such loose behaviour looks more flexible
and parallels var_value() algorithm
(which can interpret any variable name
except of with dots)
0.1.41 - fixed find_and_parse_cycle():
"array_name:" prefixed with & is also catched
(required for ifs like {?*array:key1&array:key2*})
0.1.40 - fixed error in check_if_condition_part()
(pattern)
0.1.39 - fixed error in check_if_condition_part()
(forgotten vars like array^COUNT>1 etc.)
0.1.38 - fixed error in if alternatives (see 0.1.37)
introduced check_if_condition_part() method
added possibility of "AND", not just "OR" in if alternatives:
{?*var_1="one"|var_2="two"*} it is OR {*var_1="one"|var_2="two"*?}
{?*var_1="one"&var_2="two"*} it is AND {*var_1="one"&var_2="two"*?}
Fixed profiling!
Now any profiling information is passed to the higher level -
otherwise (as it previously was) each object instance (i.e. each
call of nested template or module) produced it's own and private
timesheet.
0.1.37 - fixes in var_value():
parsing of | (if alternatives) now goes before
parsing of strings ("..")
so things like {?*var_1="one"|var_2="two"*} ... {*var_1="one"|var_2="two"*?}
are possible
(but things like {?*var="one|two"*} are not)
0.1.36 - correct string literals parsing - var_value() fix
(important when passed to module)
0.1.35 - two literals comparison is accepted in if's now
(previously only variable was allowed at the left)
Needed to do so because of :^KEY parsing - those
are converted to literals BEFORE ifs are processed
Substituted ("[^"*][\w.:$|\^]*+) subpattern
with the ("[^"*]+"|[\w.:$|\^]*+) one
0.1.34 - fixed surpassing variables to child templates
(now {* + *var1|var2* | *tpl1|tpl2* *} works)
0.1.33 - fixed parse_if (now {?*var1|var2*}..{*var1|var2*?} works)
0.1.32 - fixed getting template name from variable
(now variable can be like {*var1|var2|"string"*}
as everywhere else)
0.1.31 - fixed /r/n deletion from the end of the pattern
0.1.30 - fixed parse_cycle() function:
regexp now catches {* *%array:subarray* | ... *}
(previously missed it)
0.1.29 - fixed a misprint
0.1.28 - A bunch of little fixes.
Added profiling mode (experimental
for a while so not recommended to use
hardly).
Regexp for ifs speeded up by substituting
loose [^<>=]* with strict [\w.:$\^]*+
(boosted the usecase about 100 times)
In parse_cycle - also
([\w$.]*) instead of ([-\w$.]*)
(don't remember, what "-" was for).
Constants are now handled in var_value
(with all other stuff like ^COUNT etc.)
instead of in get_var_or_string().
0.1.27 - "alt" version is main now
added {* + *some* | >{*var*} *} -
templates right inside of the var
0.1.26 - fixed some things with $matches dealing in parsee_if
0.1.25 - version suffix changed "beta" (b) to "alternative" (alt)
0.1.25 - fixed replacement of array:foo -
Now it is more strict and occurs if only
symbols *=<>| precede array:foo
( =<> - for {*array:foo_1>array:foo_2*}, |
- for {*array:foo_1|array:foo_2*},
* - for just {*array:foo*} )
0.1.24 - (beta) rewriting regexps with no named subpatterns
for compatibility with old PHP versions
(PCRE documentation is unclear and issues like
new PHP and no support of named subpatterns occur)
EXCEPT pattern for addvars method
0.1.23 - fixed ^KEY parsing a little (removed preg_quote and fixed regexp)
0.1.22 - now not only *array:foo* (and *array:^KEY*) is caught,
but array:foo and array:^KEY as well
Needed it because otherwise if clauses like {*array:a|array:b*}
are not parsed. This required substitution of str_replace with
with preg_replace which had no visible affect on perfomance.
0.1.21 - fixed some in var_value() (substr sometimes returns FALSE not empty string)
everything is mb* now
0.1.20 - fixed trimming \r\n at the end
of the template
0.1.19 - websun_parse_template_path() fixed
to set current templates directory
to the one of template specified
0.1.18 - KEY added
0.1.17 - fixed some in var_value()
теперь по умолчанию корневой каталог шаблона -
тот, в котором выполняется вызвавший функцию скрипт
добавлены ^COUNT (0.1.13)
добавлены if'ы: {*var_1|var_2|"строка"|1234(число)*}
в if'ах добавлено сравнение с переменными:
{?*a>b*}..{*a>b?*}
{?*a>"строка"*}..{*a>"строка"*?}
{?*a>3*}..{*a>3*?}
*/
class websun
{
public $vars;
public $templates_root_dir; // templates_root_dir указывать без закрывающего слэша!
public $templates_current_dir;
public $TIMES;
public $no_global_vars;
private $profiling;
private $predecessor; // объект шаблонизатора верхнего уровня, из которого делался вызов текущего
function __construct($options)
{
// $options - ассоциативный массив с ключами:
// - data - данные
// - templates_root - корневой каталог шаблонизатора
// - predecessor - объект-родитель (из которого вызывается дочерний)
// - allowed_extensions - список разрешенных расширений шаблонов (по умолчанию: *.tpl, *.html, *.css, *.js)
// - no_global_vars - разрешать ли использовать в шаблонах переменные глобальной области видимости
// - profiling - включать ли измерения скорости (пока не до конца отлажено)
$this->vars = $options['data'];
if (isset($options['templates_root']) AND $options['templates_root']) // корневой каталог шаблонов
{
$this->templates_root_dir = $this->template_real_path($options['templates_root']);
} else { // если не указан, то принимается каталог файла, в котором вызван websun
// С 0.50 - НЕ getcwd()! Т.к. текущий каталог - тот, откуда он запускается,
// $this->templates_root_dir = getcwd();
foreach (debug_backtrace() as $trace) {
if (preg_match('/^websun_parse_template/', $trace['function'])) {
$this->templates_root_dir = dirname($trace['file']);
break;
}
}
if (!$this->templates_root_dir) {
foreach (debug_backtrace() as $trace) {
if ($trace['class'] == 'websun') {
$this->templates_root_dir = dirname($trace['file']);
break;
}
}
}
}
$this->templates_current_dir = $this->templates_root_dir . '/';
$this->predecessor = (isset($options['predecessor']) ? $options['predecessor'] : false);
$this->allowed_extensions = (isset($options['allowed_extensions']))
? $options['allowed_extensions']
: ['tpl', 'html', 'css', 'js'];
$this->no_global_vars = (isset($options['no_global_vars']) ? $options['no_global_vars'] : false);
$this->profiling = (isset($options['profiling']) ? $options['profiling'] : false);
}
function parse_template($template)
{
if ($this->profiling) {
$start = microtime(1);
}
$template = preg_replace('/ \\/\* (.*?) \*\\/ /sx', '', $template);
/**ПЕРЕПИСАТЬ ПО JEFFREY FRIEDL'У !!!**/
$template = str_replace('\\\\', "\x01", $template); // убираем двойные слэши
$template = str_replace('\*', "\x02", $template); // и экранированные звездочки
// С 0.1.51 отключили
// $template = preg_replace_callback( // дописывающие модули
// '/
// {\*
// &(\w+)
// (?P<args>\([^*]*\))?
// \*}
// /x',
// array($this, 'addvars'),
// $template
// );
$template = $this->find_and_parse_cycle($template);
$template = $this->find_and_parse_if($template);
$template = preg_replace_callback( // переменные, шаблоны и модули
'/
{\*
(.*?)
\*}
/x',
/* подумать о том, чтобы вместо (.*?)
использовать жадное, но более строгое
(
(?:
[^*]*+
|
\*(?!})
)+
)
*/
[$this, 'parse_vars_templates_functions'],
$template
);
$template = str_replace("\x01", '\\\\', $template); // возвращаем двойные слэши обратно
$template = str_replace("\x02", '*', $template); // а звездочки - уже без экранирования
if ($this->profiling AND !$this->predecessor) {
$this->TIMES['_TOTAL'] = round(microtime(1) - $start, 4) . " s";
// ksort($this->TIMES);
echo '<pre>' . print_r($this->TIMES, 1) . '</pre>';
}
return $template;
}
// // дописывание массива переменных из шаблона
// // (хак для Бурцева)
// 0.1.51 - убрали; все равно Бурцев не пользуется
// function addvars($matches) {
// // if ($this->profiling)
// // // $start = microtime(1);
// //
// // $module_name = 'module_'.$matches[1];
// // # ДОБАВИТЬ КЛАССЫ ПОТОМ
// // $args = (isset($matches['args']))
// // // ? explode(',', mb_substr($matches['args'], 1, -1) ) // убираем скобки
// // // : array();
// // $this->vars = array_merge(
// // // $this->vars,
// // // call_user_func_array($module_name, $args)
// // // ); // call_user_func_array быстрее, чем call_user_func
// //
// // if ($this->profiling)
// // // $this->write_time(__FUNCTION__, $start, microtime(1));
// //
// // return TRUE;
// }
function var_value($string)
{
if ($this->profiling) {
$start = microtime(1);
}
if (mb_substr($string, 0, 1) == '=') { # константа
$C = mb_substr($string, 1);
$out = (defined($C)) ? constant($C) : '';
}
// можно делать if'ы:
// {*var_1|var_2|"строка"|134*}
// сработает первая часть, которая TRUE
elseif (mb_strpos($string, '|') !== false) {
$f = __FUNCTION__;
foreach (explode('|', $string) as $str) {
// останавливаемся при первом же TRUE
if ($val = $this->$f($str)) {
break;
}
}
$out = $val;
} elseif ( # скалярная величина
mb_substr($string, 0, 1) == '"'
AND
mb_substr($string, -1) == '"'
) {
$out = mb_substr($string, 1, -1);
} elseif (is_numeric($string)) {
$out = $string;
} else {
if (mb_substr($string, 0, 1) == '$') {
// глобальная переменная
if (!$this->no_global_vars) {
$string = mb_substr($string, 1);
$value = $GLOBALS;
} else {
$value = '';
}
} else {
$value = $this->vars;
}
// допустимы выражения типа {*var^COUNT*}
// (вернет count($var)) )
if (mb_substr($string, -6) == '^COUNT') {
$string = mb_substr($string, 0, -6);
$return_mode = 'count';
} else {
$return_mode = false;
} // default
$rawkeys = explode('.', $string);
$keys = [];
foreach ($rawkeys as $v) {
if ($v !== '') {
$keys[] = $v;
}
}
// array_filter() использовать не получается,
// т.к. числовой индекс 0 она тоже считает за FALSE и убирает
// поэтому нужно сравнение с учетом типа
// пустая строка указывает на корневой массив
foreach ($keys as $k) {
if (is_array($value) AND isset($value[$k])) {
$value = $value[$k];
} elseif (is_object($value)) {
try {
$value = $value->$k;
} catch (\Exception $e) {
$value = null;
break;
}
} else {
$value = null;
break;
}
}
// в зависимости от $return_mode действуем по-разному:
$out = (!$return_mode)
// возвращаем значение переменной (обычный случай)
? $value
// возвращаем число элементов в массиве
: (is_array($value) ? count($value) : false);
}
if ($this->profiling) {
$this->write_time(__FUNCTION__, $start, microtime(1));
}
return $out;
}
function find_and_parse_cycle($template)
{
if ($this->profiling) {
$start = microtime(1);
}
// пришлось делать специальную функцию, чтобы реализовать рекурсию
$out = preg_replace_callback(
'/
{%\* ([^*]*) \*}
(.*?)
{\* \1 \*%}
/sx',
[$this, 'parse_cycle'],
$template
);
if ($this->profiling) {
$this->write_time(__FUNCTION__, $start, microtime(1));
}
return $out;
}
function parse_cycle($matches)
{
if ($this->profiling) {
$start = microtime(1);
}
$array_name = $matches[1];
$array = $this->var_value($array_name);
$array_name_quoted = preg_quote($array_name);
if (!is_array($array)) {
return false;
}
$parsed = '';
$dot = ($array_name != '' AND $array_name != '$')
? '.'
: '';
$i = 0;
$n = 1;
foreach ($array as $key => $value) {
$parsed .= preg_replace(
[// массив поиска
"/(?<=[*=<>|&%])\s*$array_name_quoted\:\^KEY\b/",
"/(?<=[*=<>|&%])\s*$array_name_quoted\:\^i\b/",
"/(?<=[*=<>|&%])\s*$array_name_quoted\:\^N\b/",
"/(?<=[*=<>|&%])\s*$array_name_quoted\:/"
],
[// массив замены
'"' . $key . '"', // preg_quote для ключей нельзя,
'"' . $i . '"',
'"' . $n . '"',
$array_name . $dot . $key . '.' // т.к. в них бывает удобно
], // хранить некоторые данные,
$matches[2] // а preg_quote слишком многое экранирует
);
$i++;
$n++;
}
$parsed = $this->find_and_parse_cycle($parsed);
if ($this->profiling) {
$this->write_time(__FUNCTION__, $start, microtime(1));
}
return $parsed;
}
function find_and_parse_if($template)
{
if ($this->profiling) {
$start = microtime(1);
}
$out = preg_replace_callback(
'/
{ (\?\!?) \*([^*]*)\* } # открывающее условие
(.*?) # тело if
{\*\2\* \1} # закрывающее условие
/sx',
[$this, 'parse_if'],
$template
);
if ($this->profiling) {
$this->write_time(__FUNCTION__, $start, microtime(1));
}
return $out;
}
function parse_if($matches)
{
// 1 - ? или ?!
// 2 - тело условия
// 3 - тело if
if ($this->profiling) {
$start = microtime(1);
}
$final_check = false;
$separator = (strpos($matches[2], '&'))
? '&' // "AND"
: '|'; // "OR"
$parts = explode($separator, $matches[2]);
$parts = array_map('trim', $parts); // убираем пробелы по краям
$checks = [];
foreach ($parts as $p) {
$checks[] = $this->check_if_condition_part($p);
}
if ($separator == '|') // режим "OR"
{
$final_check = in_array(true, $checks);
} else // режим "AND"
{
$final_check = !in_array(false, $checks);
}
$result = ($matches[1] == '?')
? $final_check
: !$final_check;
$parsed_if = ($result)
? $this->find_and_parse_if($matches[3])
: '';
if ($this->profiling) {
$this->write_time(__FUNCTION__, $start, microtime(1));
}
return $parsed_if;
}
function check_if_condition_part($str)
{
if ($this->profiling) {
$start = microtime(1);
}
preg_match(
'/^
(
"[^"*]+" # строковый литерал
| # или
[^*<>=]*+ # имя переменной
)
(?: # если есть сравнение с чем-то:
([=<>]) # знак сравнения
\s*
(.*) # то, с чем сравнивают
)?
$
/x',
$str,
$matches
);
$left = $this->var_value(trim($matches[1]));
if (!isset($matches[2])) {
$check = ($left == true);
} else {
$right = (isset($matches[3]))
? $this->var_value($matches[3])
: false;
switch ($matches[2]) {
case '=':
$check = ($left == $right);
break;
case '>':
$check = ($left > $right);
break;
case '<':
$check = ($left < $right);
break;
default:
$check = ($left == true);
}
}
if ($this->profiling) {
$this->write_time(__FUNCTION__, $start, microtime(1));
}
return $check;
}
function parse_vars_templates_functions($matches)
{
if ($this->profiling) {
$start = microtime(1);
}
// тут обрабатываем сразу всё - и переменные, и шаблоны, и модули
$work = $matches[1];
$work = trim($work); // убираем пробелы по краям
if (mb_substr($work, 0, 1) == '@') { // модуль {* @name(arg1,arg2) | template *}
$p = '/
^
([^(|]++) # 1 - имя модуля
(?: \( ([^)]*+) \) \s* )? # 2 - аргументы
(?: \| \s* (.*+) )? # 3 - это уже до конца
$ # (именно .*+, а не .++)
/x';
if (preg_match($p, mb_substr($work, 1), $m)) {
$function_name = $this->get_var_or_string($m[1]);
// С версии 0.1.51 - проверяем по специальному списку
// if (PHP_VERSION_ID / 100 > 506) { // это включим позже, получим PHP 5.6
// $list = - тут ссылка на константу из namespace
// else
global $WEBSUN_ALLOWED_CALLBACKS;
$list = $WEBSUN_ALLOWED_CALLBACKS;
// }
if ($list and in_array($function_name, $list)) {
$allowed = true;
} else {
$allowed = false;
trigger_error("<b>$function_name()</b> is not in the list of allowed callbacks.", E_USER_WARNING);
}
if ($allowed) {
$args = [];
if (isset($m[2])) {
preg_match_all('/[^",]+|"[^"]*"/', $m[2], $tmp);
if ($tmp) {
// от промежутков между аргументами и запятыми останутся пробелы; их надо убрать
$tmp = array_filter(array_map('trim', $tmp[0]));
$args = array_map([$this, 'get_var_or_string'], $tmp);
}
unset($tmp);
}
$subvars = call_user_func_array($function_name, $args);
// print_r(array_map( array($this, 'get_var_or_string'), explode(',', $m[2]) )); exit;
if (isset($m[3])) // передали указание на шаблон
{
$html = $this->call_template($m[3], $subvars);
} else {
$html = $subvars;
} // шаблон не указан => модуль возвращает строку
} else {
$html = '';
}
} else {
$html = '';
} // вызов модуля сделан некорректно
} elseif (mb_substr($work, 0, 1) == '+') {
// шаблон - {* +*vars_var*|*tpl_var* *}
// переменная как шаблон - {* +*var* | >*template_inside* *}
$html = '';
$parts = preg_split(
'/(?<=[\*\s])\|(?=[\*\s])/', // вертикальная черта
mb_substr($work, 1) // должна ловиться только как разделитель
// между переменной и шаблоном, но не должна ловиться
// как разделитель внутри нотации переменой или шаблона
// (например, {* + *var1|$GLOBAL* | *tpl1|tpl2* *}
);
$parts = array_map('trim', $parts); // убираем пробелы по краям
if (!isset($parts[1])) { // если нет разделителя (|) - значит,
// передали только имя шаблона +template
$html = $this->call_template($parts[0], $this->vars);
} else {
$varname_string = mb_substr($parts[0], 1, -1); // убираем звездочки
// {* +*vars* | шаблон *} - простая передача переменной шаблону
// {* +*?vars* | шаблон *} - подключение шаблона только в случае, если vars == TRUE
// {* +*%vars* | шаблон *} - подключение шаблона не для самого vars, а для каждого его дочернего элемента
$indicator = mb_substr($varname_string, 0, 1);
if ($indicator == '?') {
if ($subvars = $this->var_value(mb_substr($varname_string, 1))) // 0.1.27 $html = $this->parse_child_template($tplname, $subvars);
{
$html = $this->call_template($parts[1], $subvars);
}
} elseif ($indicator == '%') {
if ($subvars = $this->var_value(mb_substr($varname_string, 1))) {
foreach ($subvars as $row) {
// 0.1.27 $html .= $this->parse_child_template($tplname, $row);
$html .= $this->call_template($parts[1], $row);
}
}
} else {
$subvars = $this->var_value($varname_string);
// 0.1.27 $html = $this->parse_child_template($tplname, $subvars);
$html = $this->call_template($parts[1], $subvars);
}
}
} else {
$html = $this->var_value($work);
} // переменная (+ константы - тут же)
if ($this->profiling) {
$this->write_time(__FUNCTION__, $start, microtime(1));
}
return $html;
}
function call_template($template_notation, $vars)
{
if ($this->profiling) {
$start = microtime(1);
}
// $template_notation - либо путь к шаблону,
// либо переменная, содержащая путь к шаблону,
// либо шаблон прямо в переменной - если >*var*
$c = __CLASS__; // нужен объект этого же класса - делаем
$subobject = new $c([
'data' => $vars,
'templates_root' => $this->templates_root_dir,
'predecessor' => $this,
'no_global_vars' => $this->no_global_vars,
'profiling' => $this->profiling,
]);
$template_notation = trim($template_notation);
if (mb_substr($template_notation, 0, 1) == '>') {
// шаблон прямо в переменной
$v = mb_substr($template_notation, 1);
$subtemplate = $this->get_var_or_string($v);
$subobject->templates_current_dir = $this->templates_current_dir;
} else {
$path = $this->get_var_or_string($template_notation);
$subobject->templates_current_dir = pathinfo($this->template_real_path($path), PATHINFO_DIRNAME) . '/';
$subtemplate = $this->get_template($path);
}
$result = $subobject->parse_template($subtemplate);
if ($this->profiling) {
$this->write_time(__FUNCTION__, $start, microtime(1));
}
return $result;
}
function get_var_or_string($str)
{
// используется, в основном,
// для получения имён шаблонов и модулей
$str = trim($str);
if ($this->profiling) {
$start = microtime(1);
}
if (mb_substr($str, 0, 1) == '*' AND mb_substr($str, -1) == '*') {
$out = $this->var_value(mb_substr($str, 1, -1));
} // если вокруг есть звездочки - значит, перменная
else // нет звездочек - значит, обычная строка-литерал
{
$out = (mb_substr($str, 0, 1) == '"' AND mb_substr($str, -1) == '"') // строка
? mb_substr($str, 1, -1)
: $str;
}
if ($this->profiling) {
$this->write_time(__FUNCTION__, $start, microtime(1));
}
return $out;
}
function get_template($tpl)
{
if ($this->profiling) {
$start = microtime(1);
}
if (!$tpl) {
return false;
}
$tpl_real_path = $this->template_real_path($tpl);
$ext = pathinfo($tpl_real_path, PATHINFO_EXTENSION);
if (!in_array($ext, $this->allowed_extensions)) {
trigger_error(
"Template's <b>$tpl_real_path</b> extension is not in the allowed list ("
. implode(", ", $this->allowed_extensions) . ").
Check <b>allowed_extensions</b> option.",
E_USER_WARNING
);
return '';
}
// return rtrim(file_get_contents($tpl_real_path), "\r\n");
// (убираем перенос строки, присутствующий в конце любого файла)
$out = preg_replace(
'/\r?\n$/',
'',
file_get_contents($tpl_real_path)
);
if ($this->profiling) {
$this->write_time(__FUNCTION__, $start, microtime(1));
}
return $out;
}
function template_real_path($tpl)
{
// функция определяет реальный путь к шаблону в файловой системе
// первый символ пути к шаблону определяет тип пути
// если в начале адреса есть / - интерпретируем как абсолютный путь ФС
// если второй символ пути - двоеточие (путь вида C:/ - Windows) -
// также интепретируем как абсолютный путь ФС
// если есть ^ - отталкиваемся от $templates_root_dir
// если $ - от $_SERVER[DOCUMENT_ROOT]
// во всех остальных случаях отталкиваемся от каталога текущего шаблона - templates_current_dir
if ($this->profiling) {
$start = microtime(1);
}
$dir_indicator = mb_substr($tpl, 0, 1);
$adjust_tpl_path = true;
if ($dir_indicator == '^') {
$dir = $this->templates_root_dir;
} elseif ($dir_indicator == '$') {
$dir = $_SERVER['DOCUMENT_ROOT'];
} elseif ($dir_indicator == '/') {
$dir = '';
$adjust_tpl_path = false;
} // абсолютный путь для ФС
else {
if (mb_substr($tpl, 1, 1) == ':') // Windows - указан абсолютный путь - вида С:/...
{
$dir = '';
} else {
$dir = $this->templates_current_dir;
}
$adjust_tpl_path = false; // в обоих случаях строку к пути менять не надо
}
if ($adjust_tpl_path) {
$tpl = mb_substr($tpl, 1);
}
$tpl_real_path = $dir . $tpl;
if ($this->profiling) {
$this->write_time(__FUNCTION__, $start, microtime(1));
}
return $tpl_real_path;
}
function write_time($method, $start, $end)
{
//echo ($this->predecessor) . '<br>';
if (!$this->predecessor) {
$time = &$this->TIMES;
} else {
$time = &$this->predecessor->TIMES;
}
if (!isset($time[$method])) {
$time[$method] = [
'n' => 0,
'last' => 0,
'total' => 0,
'avg' => 0
];
}
$time[$method]['n'] += 1;
$time[$method]['last'] = round($end - $start, 4);
$time[$method]['total'] += $time[$method]['last'];
$time[$method]['avg'] = round($time[$method]['total'] / $time[$method]['n'], 4);
}
}
function websun_parse_template_path(
$data,
$template_path,
$templates_root_dir = false,
$no_global_vars = false
// $profiling = FALSE - пока убрали
)
{
// функция-обёртка для быстрого вызова класса
// принимает шаблон в виде пути к нему
$W = new websun([
'data' => $data,
'templates_root' => $templates_root_dir,
'no_global_vars' => $no_global_vars
]);
$tpl = $W->get_template($template_path);
$W->templates_current_dir = pathinfo($W->template_real_path($template_path), PATHINFO_DIRNAME) . '/';
$string = $W->parse_template($tpl);
return $string;
}
function websun_parse_template(
$data,
$template_code,
$templates_root_dir = false,
$no_global_vars = false
// profiling пока убрали
)
{
// функция-обёртка для быстрого вызова класса
// принимает шаблон непосредственно в виде кода
$W = new websun([
'data' => $data,
'templates_root' => $templates_root_dir,
'no_global_vars' => $no_global_vars
]);
$string = $W->parse_template($template_code);
return $string;
}
?>
| muratymt/yiicms | components/core/websun.php | PHP | bsd-3-clause | 37,601 |
/*!
* speedt
* Copyright(c) 2015 speedt <13837186852@qq.com>
* BSD 3 Licensed
*/
'use strict';
var utils = require('speedt-utils');
var Service = function(app){
var self = this;
// TODO
self.serverId = app.getServerId();
self.connCount = 0;
self.loginedCount = 0;
self.logined = {};
};
module.exports = Service;
var proto = Service.prototype;
proto.increaseConnectionCount = function(){
return ++this.connCount;
};
proto.decreaseConnectionCount = function(uid){
var self = this;
// TODO
var result = [--self.connCount];
// TODO
if(uid) result.push(removeLoginedUser.call(self, uid));
return result;
};
proto.replaceLoginedUser = function(uid, info){
var self = this;
// TODO
var user = self.logined[uid];
if(user) return updateUserInfo.call(self, user, info);
// TODO
self.loginedCount++;
// TODO
info.uid = uid;
self.logined[uid] = info;
};
var updateUserInfo = function(user, info){
var self = this;
// TODO
for(var p in info){
if(info.hasOwnProperty(p) && typeof 'function' !== info[p]){
self.logined[user.uid][p] = info[p];
} // END
} // END
};
var removeLoginedUser = function(uid){
var self = this;
// TODO
if(!self.logined[uid]) return;
// TODO
delete self.logined[uid];
// TODO
return --self.loginedCount;
};
proto.getStatisticsInfo = function(){
var self = this;
return {
serverId: self.serverId,
connCount: self.connCount,
loginedCount: self.loginedCount,
logined: self.logined
};
}; | 3203317/st | server/lib/common/services/connectionService.js | JavaScript | bsd-3-clause | 1,457 |
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// GCC 5 does not evaluate static assertions dependent on a template parameter.
// UNSUPPORTED: gcc-5
// UNSUPPORTED: c++98, c++03
// <string>
// Test that hash specializations for <string> require "char_traits<_CharT>" not just any "_Trait".
#include <string>
template <class _CharT>
struct trait // copied from <__string>
{
typedef _CharT char_type;
typedef int int_type;
typedef std::streamoff off_type;
typedef std::streampos pos_type;
typedef std::mbstate_t state_type;
static inline void assign(char_type& __c1, const char_type& __c2) {
__c1 = __c2;
}
static inline bool eq(char_type __c1, char_type __c2) { return __c1 == __c2; }
static inline bool lt(char_type __c1, char_type __c2) { return __c1 < __c2; }
static int compare(const char_type* __s1, const char_type* __s2, size_t __n);
static size_t length(const char_type* __s);
static const char_type* find(const char_type* __s, size_t __n,
const char_type& __a);
static char_type* move(char_type* __s1, const char_type* __s2, size_t __n);
static char_type* copy(char_type* __s1, const char_type* __s2, size_t __n);
static char_type* assign(char_type* __s, size_t __n, char_type __a);
static inline int_type not_eof(int_type __c) {
return eq_int_type(__c, eof()) ? ~eof() : __c;
}
static inline char_type to_char_type(int_type __c) { return char_type(__c); }
static inline int_type to_int_type(char_type __c) { return int_type(__c); }
static inline bool eq_int_type(int_type __c1, int_type __c2) {
return __c1 == __c2;
}
static inline int_type eof() { return int_type(EOF); }
};
template <class CharT>
void test() {
typedef std::basic_string<CharT, trait<CharT> > str_t;
std::hash<str_t>
h; // expected-error-re 4 {{{{call to implicitly-deleted default constructor of 'std::hash<str_t>'|implicit instantiation of undefined template}} {{.+}}}}}}
(void)h;
}
int main(int, char**) {
test<char>();
test<wchar_t>();
test<char16_t>();
test<char32_t>();
return 0;
}
| endlessm/chromium-browser | third_party/llvm/libcxx/test/std/strings/basic.string.hash/char_type_hash.fail.cpp | C++ | bsd-3-clause | 2,504 |
module Watir
module RowContainer
# Returns a row in the table
# * index - the index of the row
def [](index)
assert_exists
TableRow.new(self, :ole_object, @o.rows.item(index))
end
def strings
assert_exists
rows_memo = []
@o.rows.each do |row|
cells_memo = []
row.cells.each do |cell|
cells_memo << TableCell.new(self, :ole_object, cell).text
end
rows_memo << cells_memo
end
rows_memo
end
end
# This class is used for dealing with tables.
# Normally a user would not need to create this object as it is returned by the Watir::Container#table method
#
# many of the methods available to this object are inherited from the Element class
#
class Table < NonControlElement
include RowContainer
# override the highlight method, as if the tables rows are set to have a background color,
# this will override the table background color, and the normal flash method won't work
def highlight(set_or_clear)
if set_or_clear == :set
begin
@original_border = @o.border.to_i
if @o.border.to_i==1
@o.border = 2
else
@o.border = 1
end
rescue
@original_border = nil
end
else
begin
@o.border= @original_border unless @original_border == nil
@original_border = nil
rescue
# we could be here for a number of reasons...
ensure
@original_border = nil
end
end
super
end
# this method is used to populate the properties in the to_s method
def table_string_creator
n = []
n << "rows:".ljust(TO_S_SIZE) + self.row_count.to_s
n << "cols:".ljust(TO_S_SIZE) + self.column_count.to_s
return n
end
private :table_string_creator
# returns the properties of the object in a string
# raises an ObjectNotFound exception if the object cannot be found
def to_s
assert_exists
r = string_creator
r += table_string_creator
return r.join("\n")
end
# iterates through the rows in the table. Yields a TableRow object
def each
assert_exists
@o.rows.each do |row|
yield TableRow.new(self, :ole_object, row)
end
end
# Returns the number of rows inside the table, including rows in nested tables.
def row_count
assert_exists
rows.length
end
# This method returns the number of columns in a row of the table.
# Raises an UnknownObjectException if the table doesn't exist.
# * index - the index of the row
def column_count(index=0)
assert_exists
row[index].cells.length
end
# Returns an array containing all the text values in the specified column
# Raises an UnknownCellException if the specified column does not exist in every
# Raises an UnknownObjectException if the table doesn't exist.
# row of the table
# * columnnumber - column index to extract values from
def column_values(columnnumber)
return (0..row_count - 1).collect {|i| self[i][columnnumber].text}
end
# Returns an array containing all the text values in the specified row
# Raises an UnknownObjectException if the table doesn't exist.
# * rownumber - row index to extract values from
def row_values(rownumber)
return (0..column_count(rownumber) - 1).collect {|i| self[rownumber][i].text}
end
def hashes
assert_exists
headers = []
@o.rows.item(0).cells.each do |cell|
headers << TableCell.new(self, :ole_object, cell).text
end
rows_memo = []
i = 0
@o.rows.each do |row|
next if row.uniqueID == @o.rows.item(0).uniqueID
cells_memo = {}
cells = row.cells
raise "row at index #{i} has #{cells.length} cells, expected #{headers.length}" if cells.length < headers.length
j = 0
cells.each do |cell|
cells_memo[headers[j]] = TableCell.new(self, :ole_object, cell).text
j += 1
end
rows_memo << cells_memo
i += 1
end
rows_memo
end
end
class TableSection < NonControlElement
include RowContainer
Watir::Container.module_eval do
def tbody(how={}, what=nil)
how = {how => what} if what
TableSection.new(self, how.merge(:tag_name => "tbody"), nil)
end
def tbodys(how={}, what=nil)
how = {how => what} if what
TableSectionCollection.new(self, how.merge(:tag_name => "tbody"), nil)
end
def thead(how={}, what=nil)
how = {how => what} if what
TableSection.new(self, how.merge(:tag_name => "thead"), nil)
end
def theads(how={}, what=nil)
how = {how => what} if what
TableSectionCollection.new(self, how.merge(:tag_name => "thead"), nil)
end
def tfoot(how={}, what=nil)
how = {how => what} if what
TableSection.new(self, how.merge(:tag_name => "tfoot"), nil)
end
def tfoots(how={}, what=nil)
how = {how => what} if what
TableSectionCollection.new(self, how.merge(:tag_name => "tfoot"), nil)
end
end
end
class TableRow < NonControlElement
TAG = "TR"
# this method iterates through each of the cells in the row. Yields a TableCell object
def each
locate
cells.each {|cell| yield cell}
end
# Returns an element from the row as a TableCell object
def [](index)
assert_exists
if cells.length <= index
raise UnknownCellException, "Unable to locate a cell at index #{index}"
end
return cells[index]
end
# defaults all missing methods to the array of elements, to be able to
# use the row as an array
# def method_missing(aSymbol, *args)
# return @o.send(aSymbol, *args)
# end
def column_count
locate
cells.length
end
Watir::Container.module_eval do
def row(how={}, what=nil)
TableRow.new(self, how, what)
end
alias_method :tr, :row
def rows(how={}, what=nil)
TableRows.new(self, how, what)
end
alias_method :trs, :rows
end
end
# this class is a table cell - when called via the Table object
class TableCell < NonControlElement
TAGS = ["TH", "TD"]
alias to_s text
def colspan
locate
@o.colSpan
end
Watir::Container.module_eval do
def cell(how={}, what=nil)
TableCell.new(self, how, what)
end
alias_method :td, :cell
def cells(how={}, what=nil)
TableCells.new(self, how, what)
end
alias_method :tds, :cells
end
end
end
| jarib/watir | watir/lib/watir/table.rb | Ruby | bsd-3-clause | 6,849 |
<?php
namespace PragmaRX\Health\Checkers;
use GuzzleHttp\Client as Guzzle;
use Illuminate\Support\Str;
use PragmaRX\Health\Support\LocallyProtected;
use PragmaRX\Health\Support\Result;
class ServerVars extends Base
{
protected $response;
protected $errors;
/**
* Check resource.
*
* @return Result
*/
public function check()
{
$this->requestServerVars();
collect($this->target->config['vars'])->each(function ($var) {
$this->checkVar($var);
});
return blank($this->errors)
? $this->makeHealthyResult()
: $this->makeResult(false, sprintf($this->target->resource->errorMessage, implode('; ', $this->errors)));
}
public function requestServerVars()
{
$url = $this->makeUrl();
$bearer = (new LocallyProtected())->protect($this->target->config['cache_timeout'] ?? 60);
$guzze = new Guzzle($this->getAuthorization());
$response = $guzze->request('GET', $url, [
'headers' => ['API-Token' => $bearer],
]);
if (($code = $response->getStatusCode()) !== 200) {
throw new \Exception("Request to {$url} returned a status code {$code}");
}
$this->response = json_decode((string) $response->getBody(), true);
}
public function checkVar($var)
{
if (blank($this->response[$var['name']] ?? null)) {
if ($var['mandatory']) {
$this->errors[] = "{$var['name']} is empty";
}
return;
}
$got = $this->response[$var['name']];
$expected = $var['value'];
if (! $this->compare($var, $expected, $got)) {
$this->errors[] = "{$var['name']}: expected '{$expected}' but got '{$got}'";
}
}
public function compare($var, $expected, $got)
{
$operator = $var['operator'] ?? 'equals';
$strict = $var['strict'] ?? true;
if ($operator === 'equals') {
return $strict ? $expected === $got : $expected == $got;
}
if ($operator === 'contains') {
return Str::contains($got, $expected);
}
throw new \Exception("Operator '$operator' is not supported.");
}
public function makeUrl()
{
$url = route($this->target->config['route']);
if ($queryString = $this->target->config['query_string']) {
$url .= "?$queryString";
}
return $url;
}
public function getAuthorization()
{
if (blank($auth = $this->target->config['auth'] ?? null)) {
return [];
}
return ['auth' => [$auth['username'], $auth['password']]];
}
}
| antonioribeiro/health | src/Checkers/ServerVars.php | PHP | bsd-3-clause | 2,717 |
<aside class="main-sidebar">
<section class="sidebar">
<?= dmstr\widgets\Menu::widget(
[
'options' => ['class' => 'sidebar-menu'],
'items' => [
['label' => 'Menu', 'options' => ['class' => 'header']],
['label' => 'Home', 'icon' => 'fa fa-area-chart', 'url' => ['/site/index']],
['label' => 'Login', 'url' => ['site/login'], 'visible' => Yii::$app->user->isGuest],
[
'label' => 'Lesson',
'icon' => 'fa fa-book',
'url' => '#',
'items' => [
['label' => 'Index', 'icon' => 'fa fa-th-list', 'url' => ['/lesson/index'],],
['label' => 'Create', 'icon' => 'fa fa-edit', 'url' => ['/lesson/create'],],
],
],
[
'label' => 'App User',
'icon' => 'fa fa-group',
'url' => '#',
'items' => [
['label' => 'Points', 'icon' => 'fa fa-dollar', 'url' => ['/user-earned-point/index'],],
['label' => 'Score', 'icon' => 'fa fa-graduation-cap', 'url' => ['/user-score/index'],],
],
],
],
]
) ?>
</section>
</aside>
| mehdihasan/new_english | admin/layouts/left.php | PHP | bsd-3-clause | 1,482 |
// Copyright 2019 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/optimization_guide/optimization_guide_web_contents_observer.h"
#include "chrome/browser/optimization_guide/chrome_hints_manager.h"
#include "chrome/browser/optimization_guide/optimization_guide_keyed_service.h"
#include "chrome/browser/optimization_guide/optimization_guide_keyed_service_factory.h"
#include "chrome/browser/prefetch/no_state_prefetch/no_state_prefetch_manager_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "components/no_state_prefetch/browser/no_state_prefetch_manager.h"
#include "components/optimization_guide/core/hints_fetcher.h"
#include "components/optimization_guide/core/hints_processing_util.h"
#include "components/optimization_guide/core/optimization_guide_enums.h"
#include "components/optimization_guide/core/optimization_guide_features.h"
#include "components/optimization_guide/proto/hints.pb.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/web_contents.h"
namespace {
bool IsValidOptimizationGuideNavigation(
content::NavigationHandle* navigation_handle) {
if (!navigation_handle->IsInPrimaryMainFrame())
return false;
if (!navigation_handle->GetURL().SchemeIsHTTPOrHTTPS())
return false;
// Now check if this is a NSP navigation. NSP is not a valid navigation.
prerender::NoStatePrefetchManager* no_state_prefetch_manager =
prerender::NoStatePrefetchManagerFactory::GetForBrowserContext(
navigation_handle->GetWebContents()->GetBrowserContext());
if (!no_state_prefetch_manager) {
// Not a NSP navigation if there is no NSP manager.
return true;
}
return !(no_state_prefetch_manager->IsWebContentsPrerendering(
navigation_handle->GetWebContents()));
}
} // namespace
OptimizationGuideWebContentsObserver::OptimizationGuideWebContentsObserver(
content::WebContents* web_contents)
: content::WebContentsObserver(web_contents) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
optimization_guide_keyed_service_ =
OptimizationGuideKeyedServiceFactory::GetForProfile(
Profile::FromBrowserContext(web_contents->GetBrowserContext()));
}
OptimizationGuideWebContentsObserver::~OptimizationGuideWebContentsObserver() =
default;
OptimizationGuideNavigationData* OptimizationGuideWebContentsObserver::
GetOrCreateOptimizationGuideNavigationData(
content::NavigationHandle* navigation_handle) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
DCHECK_EQ(web_contents(), navigation_handle->GetWebContents());
NavigationHandleData* navigation_handle_data =
NavigationHandleData::GetOrCreateForNavigationHandle(*navigation_handle);
OptimizationGuideNavigationData* navigation_data =
navigation_handle_data->GetOptimizationGuideNavigationData();
if (!navigation_data) {
// We do not have one already - create one.
navigation_handle_data->SetOptimizationGuideNavigationData(
std::make_unique<OptimizationGuideNavigationData>(
navigation_handle->GetNavigationId(),
navigation_handle->NavigationStart()));
navigation_data =
navigation_handle_data->GetOptimizationGuideNavigationData();
}
DCHECK(navigation_data);
return navigation_data;
}
void OptimizationGuideWebContentsObserver::DidStartNavigation(
content::NavigationHandle* navigation_handle) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (!IsValidOptimizationGuideNavigation(navigation_handle))
return;
if (!optimization_guide_keyed_service_)
return;
OptimizationGuideNavigationData* navigation_data =
GetOrCreateOptimizationGuideNavigationData(navigation_handle);
navigation_data->set_navigation_url(navigation_handle->GetURL());
optimization_guide_keyed_service_->OnNavigationStartOrRedirect(
navigation_data);
}
void OptimizationGuideWebContentsObserver::DidRedirectNavigation(
content::NavigationHandle* navigation_handle) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (!IsValidOptimizationGuideNavigation(navigation_handle))
return;
if (!optimization_guide_keyed_service_)
return;
OptimizationGuideNavigationData* navigation_data =
GetOrCreateOptimizationGuideNavigationData(navigation_handle);
navigation_data->set_navigation_url(navigation_handle->GetURL());
optimization_guide_keyed_service_->OnNavigationStartOrRedirect(
navigation_data);
}
void OptimizationGuideWebContentsObserver::DidFinishNavigation(
content::NavigationHandle* navigation_handle) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (!IsValidOptimizationGuideNavigation(navigation_handle))
return;
// Note that a lot of Navigations (same document, non-committed, etc.) might
// not have navigation data associated with them, but we reduce likelihood of
// future leaks by always trying to remove the data.
NavigationHandleData* navigation_handle_data =
NavigationHandleData::GetForNavigationHandle(*navigation_handle);
if (!navigation_handle_data)
return;
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(
&OptimizationGuideWebContentsObserver::NotifyNavigationFinish,
weak_factory_.GetWeakPtr(),
navigation_handle_data->TakeOptimizationGuideNavigationData(),
navigation_handle->GetRedirectChain()));
}
void OptimizationGuideWebContentsObserver::PostFetchHintsUsingManager(
content::RenderFrameHost* render_frame_host) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (!render_frame_host->GetLastCommittedURL().SchemeIsHTTPOrHTTPS())
return;
if (!optimization_guide_keyed_service_)
return;
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(
&OptimizationGuideWebContentsObserver::FetchHintsUsingManager,
weak_factory_.GetWeakPtr(),
optimization_guide_keyed_service_->GetHintsManager(),
web_contents()->GetPrimaryPage().GetWeakPtr()));
}
void OptimizationGuideWebContentsObserver::FetchHintsUsingManager(
optimization_guide::ChromeHintsManager* hints_manager,
base::WeakPtr<content::Page> page) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
DCHECK(hints_manager);
if (!page)
return;
PageData& page_data = GetPageData(*page);
page_data.set_sent_batched_hints_request();
hints_manager->FetchHintsForURLs(
page_data.GetHintsTargetUrls(),
optimization_guide::proto::CONTEXT_BATCH_UPDATE_GOOGLE_SRP);
}
void OptimizationGuideWebContentsObserver::NotifyNavigationFinish(
std::unique_ptr<OptimizationGuideNavigationData> navigation_data,
const std::vector<GURL>& navigation_redirect_chain) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (optimization_guide_keyed_service_) {
optimization_guide_keyed_service_->OnNavigationFinish(
navigation_redirect_chain);
}
// We keep the navigation data in the PageData around to keep track of events
// happening for the navigation that can happen after commit, such as a fetch
// for the navigation successfully completing (which is not guaranteed to come
// back before commit, if at all).
PageData& page_data = GetPageData(web_contents()->GetPrimaryPage());
page_data.SetNavigationData(std::move(navigation_data));
}
void OptimizationGuideWebContentsObserver::FlushLastNavigationData() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
PageData& page_data = GetPageData(web_contents()->GetPrimaryPage());
page_data.SetNavigationData(nullptr);
}
void OptimizationGuideWebContentsObserver::AddURLsToBatchFetchBasedOnPrediction(
std::vector<GURL> urls,
content::WebContents* web_contents) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (!this->web_contents())
return;
DCHECK_EQ(this->web_contents(), web_contents);
PageData& page_data = GetPageData(web_contents->GetPrimaryPage());
if (page_data.is_sent_batched_hints_request())
return;
page_data.InsertHintTargetUrls(urls);
PostFetchHintsUsingManager(web_contents->GetMainFrame());
}
OptimizationGuideWebContentsObserver::PageData&
OptimizationGuideWebContentsObserver::GetPageData(content::Page& page) {
return *PageData::GetOrCreateForPage(page);
}
OptimizationGuideWebContentsObserver::PageData::PageData(content::Page& page)
: PageUserData(page) {}
OptimizationGuideWebContentsObserver::PageData::~PageData() = default;
void OptimizationGuideWebContentsObserver::PageData::InsertHintTargetUrls(
const std::vector<GURL>& urls) {
DCHECK(!sent_batched_hints_request_);
for (const GURL& url : urls)
hints_target_urls_.insert(url);
}
std::vector<GURL>
OptimizationGuideWebContentsObserver::PageData::GetHintsTargetUrls() {
std::vector<GURL> target_urls = std::move(hints_target_urls_.vector());
hints_target_urls_.clear();
return target_urls;
}
OptimizationGuideWebContentsObserver::NavigationHandleData::
NavigationHandleData(content::NavigationHandle&) {}
OptimizationGuideWebContentsObserver::NavigationHandleData::
~NavigationHandleData() = default;
PAGE_USER_DATA_KEY_IMPL(OptimizationGuideWebContentsObserver::PageData);
NAVIGATION_HANDLE_USER_DATA_KEY_IMPL(
OptimizationGuideWebContentsObserver::NavigationHandleData);
WEB_CONTENTS_USER_DATA_KEY_IMPL(OptimizationGuideWebContentsObserver);
| nwjs/chromium.src | chrome/browser/optimization_guide/optimization_guide_web_contents_observer.cc | C++ | bsd-3-clause | 9,522 |
// GLFW Engine.
// -----------------------------------------------------------------------------
// Copyright (C) 2011, ZEUS project (See authors)
//
// This program is open source and distributed under the New BSD License. See
// license for more detail.
// -----------------------------------------------------------------------------
#include <Core/GLFWEngine.h>
#include <Devices/GLFWKeyboard.h>
#include <Devices/GLFWMouse.h>
#include <Display/Camera.h>
#include <Display/GLFWWindow.h>
#include <Math/Vector.h>
#include <GL/glfw.h>
#include <stdlib.h>
using namespace ZEUS::Display;
using namespace ZEUS::Devices;
using namespace ZEUS::Math;
namespace ZEUS {
namespace Core {
GLFWEngine::GLFWEngine()
: IEngine() {
if (!glfwInit()) exit(EXIT_FAILURE);
Vector<2, unsigned int> res(800, 600);
window = new Display::GLFWWindow(res);
IKeyboard::Add<GLFWKeyboard>();
IMouse::Add<GLFWMouse>();
}
GLFWEngine::~GLFWEngine(){
glfwTerminate();
}
GLFWEngine* GLFWEngine::CreateEngine(){
GLFWEngine* tmp = new GLFWEngine();
engine = tmp;
return tmp;
}
void GLFWEngine::Initialize(){
glfwSetTime(0.0);
}
double GLFWEngine::GetImplTime(){
return glfwGetTime();
}
}
}
| papaboo/The-ZEUS-Project | extensions/GLFW/Core/GLFWEngine.cpp | C++ | bsd-3-clause | 1,427 |
#include "farversion.hpp"
#define PLUGIN_BUILD 37
#define PLUGIN_DESC L"File names case conversion for Far Manager"
#define PLUGIN_NAME L"FileCase"
#define PLUGIN_FILENAME L"FileCase.dll"
#define PLUGIN_AUTHOR FARCOMPANYNAME
#define PLUGIN_VERSION MAKEFARVERSION(FARMANAGERVERSION_MAJOR,FARMANAGERVERSION_MINOR,FARMANAGERVERSION_REVISION,PLUGIN_BUILD,VS_RELEASE)
| data-man/FarAS | plugins/filecase/version.hpp | C++ | bsd-3-clause | 364 |
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/renderer_host/pepper/device_id_fetcher.h"
#include "base/file_util.h"
#include "base/prefs/pref_service.h"
#include "base/strings/string_number_conversions.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/pref_names.h"
#if defined(OS_CHROMEOS)
#include "chromeos/cryptohome/cryptohome_library.h"
#endif
#include "components/user_prefs/pref_registry_syncable.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_ppapi_host.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_process_host.h"
#include "crypto/encryptor.h"
#include "crypto/random.h"
#include "crypto/sha2.h"
#if defined(ENABLE_RLZ)
#include "rlz/lib/machine_id.h"
#endif
using content::BrowserPpapiHost;
using content::BrowserThread;
using content::RenderProcessHost;
namespace chrome {
namespace {
const char kDRMIdentifierFile[] = "Pepper DRM ID.0";
const uint32_t kSaltLength = 32;
void GetMachineIDAsync(const DeviceIDFetcher::IDCallback& callback) {
std::string result;
#if defined(OS_WIN) && defined(ENABLE_RLZ)
rlz_lib::GetMachineId(&result);
#elif defined(OS_CHROMEOS)
result = chromeos::CryptohomeLibrary::Get()->GetSystemSalt();
if (result.empty()) {
// cryptohome must not be running; re-request after a delay.
const int64 kRequestSystemSaltDelayMs = 500;
base::MessageLoop::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&GetMachineIDAsync, callback),
base::TimeDelta::FromMilliseconds(kRequestSystemSaltDelayMs));
return;
}
#else
// Not implemented for other platforms.
NOTREACHED();
#endif
callback.Run(result);
}
} // namespace
DeviceIDFetcher::DeviceIDFetcher(int render_process_id)
: in_progress_(false),
render_process_id_(render_process_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
}
DeviceIDFetcher::~DeviceIDFetcher() {
}
bool DeviceIDFetcher::Start(const IDCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
if (in_progress_)
return false;
in_progress_ = true;
callback_ = callback;
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&DeviceIDFetcher::CheckPrefsOnUIThread, this));
return true;
}
// static
void DeviceIDFetcher::RegisterProfilePrefs(
user_prefs::PrefRegistrySyncable* prefs) {
prefs->RegisterBooleanPref(prefs::kEnableDRM,
true,
user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
prefs->RegisterStringPref(
prefs::kDRMSalt,
"",
user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
}
// static
base::FilePath DeviceIDFetcher::GetLegacyDeviceIDPath(
const base::FilePath& profile_path) {
return profile_path.AppendASCII(kDRMIdentifierFile);
}
void DeviceIDFetcher::CheckPrefsOnUIThread() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
Profile* profile = NULL;
RenderProcessHost* render_process_host =
RenderProcessHost::FromID(render_process_id_);
if (render_process_host && render_process_host->GetBrowserContext()) {
profile = Profile::FromBrowserContext(
render_process_host->GetBrowserContext());
}
if (!profile ||
profile->IsOffTheRecord() ||
!profile->GetPrefs()->GetBoolean(prefs::kEnableDRM)) {
RunCallbackOnIOThread(std::string());
return;
}
// Check if the salt pref is set. If it isn't, set it.
std::string salt = profile->GetPrefs()->GetString(prefs::kDRMSalt);
if (salt.empty()) {
uint8_t salt_bytes[kSaltLength];
crypto::RandBytes(salt_bytes, arraysize(salt_bytes));
// Since it will be stored in a string pref, convert it to hex.
salt = base::HexEncode(salt_bytes, arraysize(salt_bytes));
profile->GetPrefs()->SetString(prefs::kDRMSalt, salt);
}
#if defined(OS_CHROMEOS)
// Try the legacy path first for ChromeOS. We pass the new salt in as well
// in case the legacy id doesn't exist.
BrowserThread::PostBlockingPoolTask(
FROM_HERE,
base::Bind(&DeviceIDFetcher::LegacyComputeOnBlockingPool,
this,
profile->GetPath(), salt));
#else
// Get the machine ID and call ComputeOnUIThread with salt + machine_id.
GetMachineIDAsync(base::Bind(&DeviceIDFetcher::ComputeOnUIThread,
this, salt));
#endif
}
void DeviceIDFetcher::ComputeOnUIThread(const std::string& salt,
const std::string& machine_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (machine_id.empty()) {
LOG(ERROR) << "Empty machine id";
RunCallbackOnIOThread(std::string());
return;
}
// Build the identifier as follows:
// SHA256(machine-id||service||SHA256(machine-id||service||salt))
std::vector<uint8> salt_bytes;
if (!base::HexStringToBytes(salt, &salt_bytes))
salt_bytes.clear();
if (salt_bytes.size() != kSaltLength) {
LOG(ERROR) << "Unexpected salt bytes length: " << salt_bytes.size();
RunCallbackOnIOThread(std::string());
return;
}
char id_buf[256 / 8]; // 256-bits for SHA256
std::string input = machine_id;
input.append(kDRMIdentifierFile);
input.append(salt_bytes.begin(), salt_bytes.end());
crypto::SHA256HashString(input, &id_buf, sizeof(id_buf));
std::string id = StringToLowerASCII(
base::HexEncode(reinterpret_cast<const void*>(id_buf), sizeof(id_buf)));
input = machine_id;
input.append(kDRMIdentifierFile);
input.append(id);
crypto::SHA256HashString(input, &id_buf, sizeof(id_buf));
id = StringToLowerASCII(base::HexEncode(
reinterpret_cast<const void*>(id_buf),
sizeof(id_buf)));
RunCallbackOnIOThread(id);
}
// TODO(raymes): This is temporary code to migrate ChromeOS devices to the new
// scheme for generating device IDs. Delete this once we are sure most ChromeOS
// devices have been migrated.
void DeviceIDFetcher::LegacyComputeOnBlockingPool(
const base::FilePath& profile_path,
const std::string& salt) {
std::string id;
// First check if the legacy device ID file exists on ChromeOS. If it does, we
// should just return that.
base::FilePath id_path = GetLegacyDeviceIDPath(profile_path);
if (base::PathExists(id_path)) {
if (base::ReadFileToString(id_path, &id) && !id.empty()) {
RunCallbackOnIOThread(id);
return;
}
}
// If we didn't find an ID, get the machine ID and call the new code path to
// generate an ID.
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&GetMachineIDAsync,
base::Bind(&DeviceIDFetcher::ComputeOnUIThread,
this, salt)));
}
void DeviceIDFetcher::RunCallbackOnIOThread(const std::string& id) {
if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) {
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&DeviceIDFetcher::RunCallbackOnIOThread, this, id));
return;
}
in_progress_ = false;
callback_.Run(id);
}
} // namespace chrome
| mogoweb/chromium-crosswalk | chrome/browser/renderer_host/pepper/device_id_fetcher.cc | C++ | bsd-3-clause | 7,226 |
"""
Room Typeclasses for the TutorialWorld.
This defines special types of Rooms available in the tutorial. To keep
everything in one place we define them together with the custom
commands needed to control them. Those commands could also have been
in a separate module (e.g. if they could have been re-used elsewhere.)
"""
from __future__ import print_function
import random
from evennia import TICKER_HANDLER
from evennia import CmdSet, Command, DefaultRoom
from evennia import utils, create_object, search_object
from evennia import syscmdkeys, default_cmds
from evennia.contrib.tutorial_world.objects import LightSource
# the system error-handling module is defined in the settings. We load the
# given setting here using utils.object_from_module. This way we can use
# it regardless of if we change settings later.
from django.conf import settings
_SEARCH_AT_RESULT = utils.object_from_module(settings.SEARCH_AT_RESULT)
# -------------------------------------------------------------
#
# Tutorial room - parent room class
#
# This room is the parent of all rooms in the tutorial.
# It defines a tutorial command on itself (available to
# all those who are in a tutorial room).
#
# -------------------------------------------------------------
#
# Special command available in all tutorial rooms
class CmdTutorial(Command):
"""
Get help during the tutorial
Usage:
tutorial [obj]
This command allows you to get behind-the-scenes info
about an object or the current location.
"""
key = "tutorial"
aliases = ["tut"]
locks = "cmd:all()"
help_category = "TutorialWorld"
def func(self):
"""
All we do is to scan the current location for an Attribute
called `tutorial_info` and display that.
"""
caller = self.caller
if not self.args:
target = self.obj # this is the room the command is defined on
else:
target = caller.search(self.args.strip())
if not target:
return
helptext = target.db.tutorial_info
if helptext:
caller.msg("|G%s|n" % helptext)
else:
caller.msg("|RSorry, there is no tutorial help available here.|n")
# for the @detail command we inherit from MuxCommand, since
# we want to make use of MuxCommand's pre-parsing of '=' in the
# argument.
class CmdTutorialSetDetail(default_cmds.MuxCommand):
"""
sets a detail on a room
Usage:
@detail <key> = <description>
@detail <key>;<alias>;... = description
Example:
@detail walls = The walls are covered in ...
@detail castle;ruin;tower = The distant ruin ...
This sets a "detail" on the object this command is defined on
(TutorialRoom for this tutorial). This detail can be accessed with
the TutorialRoomLook command sitting on TutorialRoom objects (details
are set as a simple dictionary on the room). This is a Builder command.
We custom parse the key for the ;-separator in order to create
multiple aliases to the detail all at once.
"""
key = "@detail"
locks = "cmd:perm(Builder)"
help_category = "TutorialWorld"
def func(self):
"""
All this does is to check if the object has
the set_detail method and uses it.
"""
if not self.args or not self.rhs:
self.caller.msg("Usage: @detail key = description")
return
if not hasattr(self.obj, "set_detail"):
self.caller.msg("Details cannot be set on %s." % self.obj)
return
for key in self.lhs.split(";"):
# loop over all aliases, if any (if not, this will just be
# the one key to loop over)
self.obj.set_detail(key, self.rhs)
self.caller.msg("Detail set: '%s': '%s'" % (self.lhs, self.rhs))
class CmdTutorialLook(default_cmds.CmdLook):
"""
looks at the room and on details
Usage:
look <obj>
look <room detail>
look *<account>
Observes your location, details at your location or objects
in your vicinity.
Tutorial: This is a child of the default Look command, that also
allows us to look at "details" in the room. These details are
things to examine and offers some extra description without
actually having to be actual database objects. It uses the
return_detail() hook on TutorialRooms for this.
"""
# we don't need to specify key/locks etc, this is already
# set by the parent.
help_category = "TutorialWorld"
def func(self):
"""
Handle the looking. This is a copy of the default look
code except for adding in the details.
"""
caller = self.caller
args = self.args
if args:
# we use quiet=True to turn off automatic error reporting.
# This tells search that we want to handle error messages
# ourself. This also means the search function will always
# return a list (with 0, 1 or more elements) rather than
# result/None.
looking_at_obj = caller.search(args,
# note: excludes room/room aliases
candidates=caller.location.contents + caller.contents,
use_nicks=True, quiet=True)
if len(looking_at_obj) != 1:
# no target found or more than one target found (multimatch)
# look for a detail that may match
detail = self.obj.return_detail(args)
if detail:
self.caller.msg(detail)
return
else:
# no detail found, delegate our result to the normal
# error message handler.
_SEARCH_AT_RESULT(None, caller, args, looking_at_obj)
return
else:
# we found a match, extract it from the list and carry on
# normally with the look handling.
looking_at_obj = looking_at_obj[0]
else:
looking_at_obj = caller.location
if not looking_at_obj:
caller.msg("You have no location to look at!")
return
if not hasattr(looking_at_obj, 'return_appearance'):
# this is likely due to us having an account instead
looking_at_obj = looking_at_obj.character
if not looking_at_obj.access(caller, "view"):
caller.msg("Could not find '%s'." % args)
return
# get object's appearance
caller.msg(looking_at_obj.return_appearance(caller))
# the object's at_desc() method.
looking_at_obj.at_desc(looker=caller)
return
class TutorialRoomCmdSet(CmdSet):
"""
Implements the simple tutorial cmdset. This will overload the look
command in the default CharacterCmdSet since it has a higher
priority (ChracterCmdSet has prio 0)
"""
key = "tutorial_cmdset"
priority = 1
def at_cmdset_creation(self):
"""add the tutorial-room commands"""
self.add(CmdTutorial())
self.add(CmdTutorialSetDetail())
self.add(CmdTutorialLook())
class TutorialRoom(DefaultRoom):
"""
This is the base room type for all rooms in the tutorial world.
It defines a cmdset on itself for reading tutorial info about the location.
"""
def at_object_creation(self):
"""Called when room is first created"""
self.db.tutorial_info = "This is a tutorial room. It allows you to use the 'tutorial' command."
self.cmdset.add_default(TutorialRoomCmdSet)
def at_object_receive(self, new_arrival, source_location):
"""
When an object enter a tutorial room we tell other objects in
the room about it by trying to call a hook on them. The Mob object
uses this to cheaply get notified of enemies without having
to constantly scan for them.
Args:
new_arrival (Object): the object that just entered this room.
source_location (Object): the previous location of new_arrival.
"""
if new_arrival.has_account and not new_arrival.is_superuser:
# this is a character
for obj in self.contents_get(exclude=new_arrival):
if hasattr(obj, "at_new_arrival"):
obj.at_new_arrival(new_arrival)
def return_detail(self, detailkey):
"""
This looks for an Attribute "obj_details" and possibly
returns the value of it.
Args:
detailkey (str): The detail being looked at. This is
case-insensitive.
"""
details = self.db.details
if details:
return details.get(detailkey.lower(), None)
def set_detail(self, detailkey, description):
"""
This sets a new detail, using an Attribute "details".
Args:
detailkey (str): The detail identifier to add (for
aliases you need to add multiple keys to the
same description). Case-insensitive.
description (str): The text to return when looking
at the given detailkey.
"""
if self.db.details:
self.db.details[detailkey.lower()] = description
else:
self.db.details = {detailkey.lower(): description}
# -------------------------------------------------------------
#
# Weather room - room with a ticker
#
# -------------------------------------------------------------
# These are rainy weather strings
WEATHER_STRINGS = (
"The rain coming down from the iron-grey sky intensifies.",
"A gust of wind throws the rain right in your face. Despite your cloak you shiver.",
"The rainfall eases a bit and the sky momentarily brightens.",
"For a moment it looks like the rain is slowing, then it begins anew with renewed force.",
"The rain pummels you with large, heavy drops. You hear the rumble of thunder in the distance.",
"The wind is picking up, howling around you, throwing water droplets in your face. It's cold.",
"Bright fingers of lightning flash over the sky, moments later followed by a deafening rumble.",
"It rains so hard you can hardly see your hand in front of you. You'll soon be drenched to the bone.",
"Lightning strikes in several thundering bolts, striking the trees in the forest to your west.",
"You hear the distant howl of what sounds like some sort of dog or wolf.",
"Large clouds rush across the sky, throwing their load of rain over the world.")
class WeatherRoom(TutorialRoom):
"""
This should probably better be called a rainy room...
This sets up an outdoor room typeclass. At irregular intervals,
the effects of weather will show in the room. Outdoor rooms should
inherit from this.
"""
def at_object_creation(self):
"""
Called when object is first created.
We set up a ticker to update this room regularly.
Note that we could in principle also use a Script to manage
the ticking of the room; the TickerHandler works fine for
simple things like this though.
"""
super(WeatherRoom, self).at_object_creation()
# subscribe ourselves to a ticker to repeatedly call the hook
# "update_weather" on this object. The interval is randomized
# so as to not have all weather rooms update at the same time.
self.db.interval = random.randint(50, 70)
TICKER_HANDLER.add(interval=self.db.interval, callback=self.update_weather, idstring="tutorial")
# this is parsed by the 'tutorial' command on TutorialRooms.
self.db.tutorial_info = \
"This room has a Script running that has it echo a weather-related message at irregular intervals."
def update_weather(self, *args, **kwargs):
"""
Called by the tickerhandler at regular intervals. Even so, we
only update 20% of the time, picking a random weather message
when we do. The tickerhandler requires that this hook accepts
any arguments and keyword arguments (hence the *args, **kwargs
even though we don't actually use them in this example)
"""
if random.random() < 0.2:
# only update 20 % of the time
self.msg_contents("|w%s|n" % random.choice(WEATHER_STRINGS))
SUPERUSER_WARNING = "\nWARNING: You are playing as a superuser ({name}). Use the {quell} command to\n" \
"play without superuser privileges (many functions and puzzles ignore the \n" \
"presence of a superuser, making this mode useful for exploring things behind \n" \
"the scenes later).\n" \
# ------------------------------------------------------------
#
# Intro Room - unique room
#
# This room marks the start of the tutorial. It sets up properties on
# the player char that is needed for the tutorial.
#
# -------------------------------------------------------------
class IntroRoom(TutorialRoom):
"""
Intro room
properties to customize:
char_health - integer > 0 (default 20)
"""
def at_object_creation(self):
"""
Called when the room is first created.
"""
super(IntroRoom, self).at_object_creation()
self.db.tutorial_info = "The first room of the tutorial. " \
"This assigns the health Attribute to "\
"the account."
def at_object_receive(self, character, source_location):
"""
Assign properties on characters
"""
# setup character for the tutorial
health = self.db.char_health or 20
if character.has_account:
character.db.health = health
character.db.health_max = health
if character.is_superuser:
string = "-" * 78 + SUPERUSER_WARNING + "-" * 78
character.msg("|r%s|n" % string.format(name=character.key, quell="|w@quell|r"))
# -------------------------------------------------------------
#
# Bridge - unique room
#
# Defines a special west-eastward "bridge"-room, a large room that takes
# several steps to cross. It is complete with custom commands and a
# chance of falling off the bridge. This room has no regular exits,
# instead the exitings are handled by custom commands set on the account
# upon first entering the room.
#
# Since one can enter the bridge room from both ends, it is
# divided into five steps:
# westroom <- 0 1 2 3 4 -> eastroom
#
# -------------------------------------------------------------
class CmdEast(Command):
"""
Go eastwards across the bridge.
Tutorial info:
This command relies on the caller having two Attributes
(assigned by the room when entering):
- east_exit: a unique name or dbref to the room to go to
when exiting east.
- west_exit: a unique name or dbref to the room to go to
when exiting west.
The room must also have the following Attributes
- tutorial_bridge_posistion: the current position on
on the bridge, 0 - 4.
"""
key = "east"
aliases = ["e"]
locks = "cmd:all()"
help_category = "TutorialWorld"
def func(self):
"""move one step eastwards"""
caller = self.caller
bridge_step = min(5, caller.db.tutorial_bridge_position + 1)
if bridge_step > 4:
# we have reached the far east end of the bridge.
# Move to the east room.
eexit = search_object(self.obj.db.east_exit)
if eexit:
caller.move_to(eexit[0])
else:
caller.msg("No east exit was found for this room. Contact an admin.")
return
caller.db.tutorial_bridge_position = bridge_step
# since we are really in one room, we have to notify others
# in the room when we move.
caller.location.msg_contents("%s steps eastwards across the bridge." % caller.name, exclude=caller)
caller.execute_cmd("look")
# go back across the bridge
class CmdWest(Command):
"""
Go westwards across the bridge.
Tutorial info:
This command relies on the caller having two Attributes
(assigned by the room when entering):
- east_exit: a unique name or dbref to the room to go to
when exiting east.
- west_exit: a unique name or dbref to the room to go to
when exiting west.
The room must also have the following property:
- tutorial_bridge_posistion: the current position on
on the bridge, 0 - 4.
"""
key = "west"
aliases = ["w"]
locks = "cmd:all()"
help_category = "TutorialWorld"
def func(self):
"""move one step westwards"""
caller = self.caller
bridge_step = max(-1, caller.db.tutorial_bridge_position - 1)
if bridge_step < 0:
# we have reached the far west end of the bridge.
# Move to the west room.
wexit = search_object(self.obj.db.west_exit)
if wexit:
caller.move_to(wexit[0])
else:
caller.msg("No west exit was found for this room. Contact an admin.")
return
caller.db.tutorial_bridge_position = bridge_step
# since we are really in one room, we have to notify others
# in the room when we move.
caller.location.msg_contents("%s steps westwards across the bridge." % caller.name, exclude=caller)
caller.execute_cmd("look")
BRIDGE_POS_MESSAGES = ("You are standing |wvery close to the the bridge's western foundation|n."
" If you go west you will be back on solid ground ...",
"The bridge slopes precariously where it extends eastwards"
" towards the lowest point - the center point of the hang bridge.",
"You are |whalfways|n out on the unstable bridge.",
"The bridge slopes precariously where it extends westwards"
" towards the lowest point - the center point of the hang bridge.",
"You are standing |wvery close to the bridge's eastern foundation|n."
" If you go east you will be back on solid ground ...")
BRIDGE_MOODS = ("The bridge sways in the wind.", "The hanging bridge creaks dangerously.",
"You clasp the ropes firmly as the bridge sways and creaks under you.",
"From the castle you hear a distant howling sound, like that of a large dog or other beast.",
"The bridge creaks under your feet. Those planks does not seem very sturdy.",
"Far below you the ocean roars and throws its waves against the cliff,"
" as if trying its best to reach you.",
"Parts of the bridge come loose behind you, falling into the chasm far below!",
"A gust of wind causes the bridge to sway precariously.",
"Under your feet a plank comes loose, tumbling down. For a moment you dangle over the abyss ...",
"The section of rope you hold onto crumble in your hands,"
" parts of it breaking apart. You sway trying to regain balance.")
FALL_MESSAGE = "Suddenly the plank you stand on gives way under your feet! You fall!" \
"\nYou try to grab hold of an adjoining plank, but all you manage to do is to " \
"divert your fall westwards, towards the cliff face. This is going to hurt ... " \
"\n ... The world goes dark ...\n\n"
class CmdLookBridge(Command):
"""
looks around at the bridge.
Tutorial info:
This command assumes that the room has an Attribute
"fall_exit", a unique name or dbref to the place they end upp
if they fall off the bridge.
"""
key = 'look'
aliases = ["l"]
locks = "cmd:all()"
help_category = "TutorialWorld"
def func(self):
"""Looking around, including a chance to fall."""
caller = self.caller
bridge_position = self.caller.db.tutorial_bridge_position
# this command is defined on the room, so we get it through self.obj
location = self.obj
# randomize the look-echo
message = "|c%s|n\n%s\n%s" % (location.key,
BRIDGE_POS_MESSAGES[bridge_position],
random.choice(BRIDGE_MOODS))
chars = [obj for obj in self.obj.contents_get(exclude=caller) if obj.has_account]
if chars:
# we create the You see: message manually here
message += "\n You see: %s" % ", ".join("|c%s|n" % char.key for char in chars)
self.caller.msg(message)
# there is a chance that we fall if we are on the western or central
# part of the bridge.
if bridge_position < 3 and random.random() < 0.05 and not self.caller.is_superuser:
# we fall 5% of time.
fall_exit = search_object(self.obj.db.fall_exit)
if fall_exit:
self.caller.msg("|r%s|n" % FALL_MESSAGE)
self.caller.move_to(fall_exit[0], quiet=True)
# inform others on the bridge
self.obj.msg_contents("A plank gives way under %s's feet and "
"they fall from the bridge!" % self.caller.key)
# custom help command
class CmdBridgeHelp(Command):
"""
Overwritten help command while on the bridge.
"""
key = "help"
aliases = ["h", "?"]
locks = "cmd:all()"
help_category = "Tutorial world"
def func(self):
"""Implements the command."""
string = "You are trying hard not to fall off the bridge ..." \
"\n\nWhat you can do is trying to cross the bridge |weast|n" \
" or try to get back to the mainland |wwest|n)."
self.caller.msg(string)
class BridgeCmdSet(CmdSet):
"""This groups the bridge commands. We will store it on the room."""
key = "Bridge commands"
priority = 1 # this gives it precedence over the normal look/help commands.
def at_cmdset_creation(self):
"""Called at first cmdset creation"""
self.add(CmdTutorial())
self.add(CmdEast())
self.add(CmdWest())
self.add(CmdLookBridge())
self.add(CmdBridgeHelp())
BRIDGE_WEATHER = (
"The rain intensifies, making the planks of the bridge even more slippery.",
"A gust of wind throws the rain right in your face.",
"The rainfall eases a bit and the sky momentarily brightens.",
"The bridge shakes under the thunder of a closeby thunder strike.",
"The rain pummels you with large, heavy drops. You hear the distinct howl of a large hound in the distance.",
"The wind is picking up, howling around you and causing the bridge to sway from side to side.",
"Some sort of large bird sweeps by overhead, giving off an eery screech. Soon it has disappeared in the gloom.",
"The bridge sways from side to side in the wind.",
"Below you a particularly large wave crashes into the rocks.",
"From the ruin you hear a distant, otherwordly howl. Or maybe it was just the wind.")
class BridgeRoom(WeatherRoom):
"""
The bridge room implements an unsafe bridge. It also enters the player into
a state where they get new commands so as to try to cross the bridge.
We want this to result in the account getting a special set of
commands related to crossing the bridge. The result is that it
will take several steps to cross it, despite it being represented
by only a single room.
We divide the bridge into steps:
self.db.west_exit - - | - - self.db.east_exit
0 1 2 3 4
The position is handled by a variable stored on the character
when entering and giving special move commands will
increase/decrease the counter until the bridge is crossed.
We also has self.db.fall_exit, which points to a gathering
location to end up if we happen to fall off the bridge (used by
the CmdLookBridge command).
"""
def at_object_creation(self):
"""Setups the room"""
# this will start the weather room's ticker and tell
# it to call update_weather regularly.
super(BridgeRoom, self).at_object_creation()
# this identifies the exits from the room (should be the command
# needed to leave through that exit). These are defaults, but you
# could of course also change them after the room has been created.
self.db.west_exit = "cliff"
self.db.east_exit = "gate"
self.db.fall_exit = "cliffledge"
# add the cmdset on the room.
self.cmdset.add_default(BridgeCmdSet)
# since the default Character's at_look() will access the room's
# return_description (this skips the cmdset) when
# first entering it, we need to explicitly turn off the room
# as a normal view target - once inside, our own look will
# handle all return messages.
self.locks.add("view:false()")
def update_weather(self, *args, **kwargs):
"""
This is called at irregular intervals and makes the passage
over the bridge a little more interesting.
"""
if random.random() < 80:
# send a message most of the time
self.msg_contents("|w%s|n" % random.choice(BRIDGE_WEATHER))
def at_object_receive(self, character, source_location):
"""
This hook is called by the engine whenever the player is moved
into this room.
"""
if character.has_account:
# we only run this if the entered object is indeed a player object.
# check so our east/west exits are correctly defined.
wexit = search_object(self.db.west_exit)
eexit = search_object(self.db.east_exit)
fexit = search_object(self.db.fall_exit)
if not (wexit and eexit and fexit):
character.msg("The bridge's exits are not properly configured. "
"Contact an admin. Forcing west-end placement.")
character.db.tutorial_bridge_position = 0
return
if source_location == eexit[0]:
# we assume we enter from the same room we will exit to
character.db.tutorial_bridge_position = 4
else:
# if not from the east, then from the west!
character.db.tutorial_bridge_position = 0
character.execute_cmd("look")
def at_object_leave(self, character, target_location):
"""
This is triggered when the player leaves the bridge room.
"""
if character.has_account:
# clean up the position attribute
del character.db.tutorial_bridge_position
# -------------------------------------------------------------------------------
#
# Dark Room - a room with states
#
# This room limits the movemenets of its denizens unless they carry an active
# LightSource object (LightSource is defined in
# tutorialworld.objects.LightSource)
#
# -------------------------------------------------------------------------------
DARK_MESSAGES = ("It is pitch black. You are likely to be eaten by a grue.",
"It's pitch black. You fumble around but cannot find anything.",
"You don't see a thing. You feel around, managing to bump your fingers hard against something. Ouch!",
"You don't see a thing! Blindly grasping the air around you, you find nothing.",
"It's totally dark here. You almost stumble over some un-evenness in the ground.",
"You are completely blind. For a moment you think you hear someone breathing nearby ... "
"\n ... surely you must be mistaken.",
"Blind, you think you find some sort of object on the ground, but it turns out to be just a stone.",
"Blind, you bump into a wall. The wall seems to be covered with some sort of vegetation,"
" but its too damp to burn.",
"You can't see anything, but the air is damp. It feels like you are far underground.")
ALREADY_LIGHTSOURCE = "You don't want to stumble around in blindness anymore. You already " \
"found what you need. Let's get light already!"
FOUND_LIGHTSOURCE = "Your fingers bump against a splinter of wood in a corner." \
" It smells of resin and seems dry enough to burn! " \
"You pick it up, holding it firmly. Now you just need to" \
" |wlight|n it using the flint and steel you carry with you."
class CmdLookDark(Command):
"""
Look around in darkness
Usage:
look
Look around in the darkness, trying
to find something.
"""
key = "look"
aliases = ["l", 'feel', 'search', 'feel around', 'fiddle']
locks = "cmd:all()"
help_category = "TutorialWorld"
def func(self):
"""
Implement the command.
This works both as a look and a search command; there is a
random chance of eventually finding a light source.
"""
caller = self.caller
if random.random() < 0.8:
# we don't find anything
caller.msg(random.choice(DARK_MESSAGES))
else:
# we could have found something!
if any(obj for obj in caller.contents if utils.inherits_from(obj, LightSource)):
# we already carry a LightSource object.
caller.msg(ALREADY_LIGHTSOURCE)
else:
# don't have a light source, create a new one.
create_object(LightSource, key="splinter", location=caller)
caller.msg(FOUND_LIGHTSOURCE)
class CmdDarkHelp(Command):
"""
Help command for the dark state.
"""
key = "help"
locks = "cmd:all()"
help_category = "TutorialWorld"
def func(self):
"""
Replace the the help command with a not-so-useful help
"""
string = "Can't help you until you find some light! Try looking/feeling around for something to burn. " \
"You shouldn't give up even if you don't find anything right away."
self.caller.msg(string)
class CmdDarkNoMatch(Command):
"""
This is a system command. Commands with special keys are used to
override special sitations in the game. The CMD_NOMATCH is used
when the given command is not found in the current command set (it
replaces Evennia's default behavior or offering command
suggestions)
"""
key = syscmdkeys.CMD_NOMATCH
locks = "cmd:all()"
def func(self):
"""Implements the command."""
self.caller.msg("Until you find some light, there's not much you can do. Try feeling around.")
class DarkCmdSet(CmdSet):
"""
Groups the commands of the dark room together. We also import the
default say command here so that players can still talk in the
darkness.
We give the cmdset the mergetype "Replace" to make sure it
completely replaces whichever command set it is merged onto
(usually the default cmdset)
"""
key = "darkroom_cmdset"
mergetype = "Replace"
priority = 2
def at_cmdset_creation(self):
"""populate the cmdset."""
self.add(CmdTutorial())
self.add(CmdLookDark())
self.add(CmdDarkHelp())
self.add(CmdDarkNoMatch())
self.add(default_cmds.CmdSay)
class DarkRoom(TutorialRoom):
"""
A dark room. This tries to start the DarkState script on all
objects entering. The script is responsible for making sure it is
valid (that is, that there is no light source shining in the room).
The is_lit Attribute is used to define if the room is currently lit
or not, so as to properly echo state changes.
Since this room (in the tutorial) is meant as a sort of catch-all,
we also make sure to heal characters ending up here, since they
may have been beaten up by the ghostly apparition at this point.
"""
def at_object_creation(self):
"""
Called when object is first created.
"""
super(DarkRoom, self).at_object_creation()
self.db.tutorial_info = "This is a room with custom command sets on itself."
# the room starts dark.
self.db.is_lit = False
self.cmdset.add(DarkCmdSet, permanent=True)
def at_init(self):
"""
Called when room is first recached (such as after a reload)
"""
self.check_light_state()
def _carries_light(self, obj):
"""
Checks if the given object carries anything that gives light.
Note that we do NOT look for a specific LightSource typeclass,
but for the Attribute is_giving_light - this makes it easy to
later add other types of light-giving items. We also accept
if there is a light-giving object in the room overall (like if
a splinter was dropped in the room)
"""
return obj.is_superuser or obj.db.is_giving_light or any(o for o in obj.contents if o.db.is_giving_light)
def _heal(self, character):
"""
Heal a character.
"""
health = character.db.health_max or 20
character.db.health = health
def check_light_state(self, exclude=None):
"""
This method checks if there are any light sources in the room.
If there isn't it makes sure to add the dark cmdset to all
characters in the room. It is called whenever characters enter
the room and also by the Light sources when they turn on.
Args:
exclude (Object): An object to not include in the light check.
"""
if any(self._carries_light(obj) for obj in self.contents if obj != exclude):
self.locks.add("view:all()")
self.cmdset.remove(DarkCmdSet)
self.db.is_lit = True
for char in (obj for obj in self.contents if obj.has_account):
# this won't do anything if it is already removed
char.msg("The room is lit up.")
else:
# noone is carrying light - darken the room
self.db.is_lit = False
self.locks.add("view:false()")
self.cmdset.add(DarkCmdSet, permanent=True)
for char in (obj for obj in self.contents if obj.has_account):
if char.is_superuser:
char.msg("You are Superuser, so you are not affected by the dark state.")
else:
# put players in darkness
char.msg("The room is completely dark.")
def at_object_receive(self, obj, source_location):
"""
Called when an object enters the room.
"""
if obj.has_account:
# a puppeted object, that is, a Character
self._heal(obj)
# in case the new guy carries light with them
self.check_light_state()
def at_object_leave(self, obj, target_location):
"""
In case people leave with the light, we make sure to clear the
DarkCmdSet if necessary. This also works if they are
teleported away.
"""
# since this hook is called while the object is still in the room,
# we exclude it from the light check, to ignore any light sources
# it may be carrying.
self.check_light_state(exclude=obj)
# -------------------------------------------------------------
#
# Teleport room - puzzles solution
#
# This is a sort of puzzle room that requires a certain
# attribute on the entering character to be the same as
# an attribute of the room. If not, the character will
# be teleported away to a target location. This is used
# by the Obelisk - grave chamber puzzle, where one must
# have looked at the obelisk to get an attribute set on
# oneself, and then pick the grave chamber with the
# matching imagery for this attribute.
#
# -------------------------------------------------------------
class TeleportRoom(TutorialRoom):
"""
Teleporter - puzzle room.
Important attributes (set at creation):
puzzle_key - which attr to look for on character
puzzle_value - what char.db.puzzle_key must be set to
success_teleport_to - where to teleport in case if success
success_teleport_msg - message to echo while teleporting to success
failure_teleport_to - where to teleport to in case of failure
failure_teleport_msg - message to echo while teleporting to failure
"""
def at_object_creation(self):
"""Called at first creation"""
super(TeleportRoom, self).at_object_creation()
# what character.db.puzzle_clue must be set to, to avoid teleportation.
self.db.puzzle_value = 1
# target of successful teleportation. Can be a dbref or a
# unique room name.
self.db.success_teleport_msg = "You are successful!"
self.db.success_teleport_to = "treasure room"
# the target of the failure teleportation.
self.db.failure_teleport_msg = "You fail!"
self.db.failure_teleport_to = "dark cell"
def at_object_receive(self, character, source_location):
"""
This hook is called by the engine whenever the player is moved into
this room.
"""
if not character.has_account:
# only act on player characters.
return
# determine if the puzzle is a success or not
is_success = str(character.db.puzzle_clue) == str(self.db.puzzle_value)
teleport_to = self.db.success_teleport_to if is_success else self.db.failure_teleport_to
# note that this returns a list
results = search_object(teleport_to)
if not results or len(results) > 1:
# we cannot move anywhere since no valid target was found.
character.msg("no valid teleport target for %s was found." % teleport_to)
return
if character.is_superuser:
# superusers don't get teleported
character.msg("Superuser block: You would have been teleported to %s." % results[0])
return
# perform the teleport
if is_success:
character.msg(self.db.success_teleport_msg)
else:
character.msg(self.db.failure_teleport_msg)
# teleport quietly to the new place
character.move_to(results[0], quiet=True, move_hooks=False)
# we have to call this manually since we turn off move_hooks
# - this is necessary to make the target dark room aware of an
# already carried light.
results[0].at_object_receive(character, self)
# -------------------------------------------------------------
#
# Outro room - unique exit room
#
# Cleans up the character from all tutorial-related properties.
#
# -------------------------------------------------------------
class OutroRoom(TutorialRoom):
"""
Outro room.
Called when exiting the tutorial, cleans the
character of tutorial-related attributes.
"""
def at_object_creation(self):
"""
Called when the room is first created.
"""
super(OutroRoom, self).at_object_creation()
self.db.tutorial_info = "The last room of the tutorial. " \
"This cleans up all temporary Attributes " \
"the tutorial may have assigned to the "\
"character."
def at_object_receive(self, character, source_location):
"""
Do cleanup.
"""
if character.has_account:
del character.db.health_max
del character.db.health
del character.db.last_climbed
del character.db.puzzle_clue
del character.db.combat_parry_mode
del character.db.tutorial_bridge_position
for obj in character.contents:
if obj.typeclass_path.startswith("evennia.contrib.tutorial_world"):
obj.delete()
character.tags.clear(category="tutorial_world")
| feend78/evennia | evennia/contrib/tutorial_world/rooms.py | Python | bsd-3-clause | 40,655 |
<?php
namespace asdfstudio\admin\helpers;
use Yii;
use asdfstudio\admin\Module;
use asdfstudio\admin\base\Admin;
use yii\db\ActiveRecord;
class AdminHelper
{
/**
* @param string $entity Admin class name or Id
* @return Admin|null
*/
public static function getEntity($entity)
{
/* @var Module $module */
$module = Yii::$app->controller->module;
if (isset($module->entities[$entity])) {
return $module->entities[$entity];
} elseif (isset($module->entitiesClasses[$entity])) {
return static::getEntity($module->entitiesClasses[$entity]);
}
return null;
}
/**
* Return value of nested attribute.
*
* ```php
* // e.g. $post is Post model. We need to get a name of owmer. Owner is related model.
*
* AdminHelper::resolveAttribute('owner.username', $post); // it returns username from owner attribute
* ```
*
* @param string $attribute
* @param ActiveRecord $model
* @return string
*/
public static function resolveAttribute($attribute, $model)
{
$path = explode('.', $attribute);
$attr = $model;
foreach ($path as $a) {
$attr = $attr->{$a};
}
return $attr;
}
}
| Tecnoready/yii2-admin-module | helpers/AdminHelper.php | PHP | bsd-3-clause | 1,294 |
package tools;
/*
* Extremely Compiler Collection
* Copyright (c) 2015-2020, Jianping Zeng.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
* This owns the files read by a parser, handles include stacks,
* and handles diagnostic wrangling.
*
* @author Jianping Zeng
* @version 0.4
*/
public final class SourceMgr {
public enum DiagKind {
DK_Error,
DK_Warning,
DK_Remark,
DK_Note
}
private DiagKind getDiagKindByName(String name) {
switch (name) {
case "error":
return DiagKind.DK_Error;
case "warning":
return DiagKind.DK_Warning;
case "remark":
return DiagKind.DK_Remark;
case "note":
return DiagKind.DK_Note;
default:
Util.assertion("Unknown diagnostic kind!");
return null;
}
}
public static class SMLoc {
private MemoryBuffer buffer;
private int startPos;
@Override
public boolean equals(Object obj) {
if (obj == null) return false;
if (this == obj) return true;
if (getClass() != obj.getClass())
return false;
SMLoc loc = (SMLoc) obj;
return loc.buffer.equals(buffer) && startPos == loc.startPos;
}
public static SMLoc get(MemoryBuffer buf, int start) {
SMLoc loc = new SMLoc();
loc.buffer = buf;
loc.startPos = start;
return loc;
}
public static SMLoc get(MemoryBuffer buf) {
SMLoc loc = new SMLoc();
loc.buffer = buf;
loc.startPos = buf.getBufferStart();
return loc;
}
public boolean isValid() {
return buffer != null;
}
public int getPointer() {
return startPos;
}
}
static class SrcBuffer {
MemoryBuffer buffer;
/**
* This is the location of the parent include, or
* null if it is in the top level.
*/
SMLoc includeLoc;
}
private static class LineNoCache {
int lastQueryBufferID;
MemoryBuffer lastQuery;
int lineNoOfQuery;
}
/**
* This is all of the buffers that we are reading from.
*/
private ArrayList<SrcBuffer> buffers = new ArrayList<>();
/**
* This is the list of directories we should search for
* include files in.
*/
private LinkedList<String> includeDirs;
/**
* This s cache for line number queries.
*/
private LineNoCache lineNoCache;
public void setIncludeDirs(List<String> dirs) {
includeDirs = new LinkedList<>(dirs);
}
public SrcBuffer getBufferInfo(int i) {
Util.assertion(i >= 0 && i < buffers.size(), "Invalid buffer ID!");
return buffers.get(i);
}
public MemoryBuffer getMemoryBuffer(int i) {
Util.assertion(i >= 0 && i < buffers.size(), "Invalid buffer ID!");
return buffers.get(i).buffer;
}
public SMLoc getParentIncludeLoc(int i) {
Util.assertion(i >= 0 && i < buffers.size(), "Invalid buffer ID!");
return buffers.get(i).includeLoc;
}
public int addNewSourceBuffer(MemoryBuffer buf, SMLoc includeLoc) {
SrcBuffer buffer = new SrcBuffer();
buffer.buffer = buf;
buffer.includeLoc = includeLoc;
buffers.add(buffer);
return buffers.size() - 1;
}
/**
* Search for a file with the specified name in the current directory or
* in one of the {@linkplain #includeDirs}. If no such file found, this return
* ~0, otherwise it returns the buffer ID of the stacked file.
*
* @param filename
* @param includeLoc
* @return
*/
public int addIncludeFile(String filename, SMLoc includeLoc) {
MemoryBuffer newBuf = MemoryBuffer.getFile(filename);
for (int i = 0, e = includeDirs.size(); i < e && newBuf == null; i++) {
String incFile = includeDirs.get(i) + "/" + filename;
newBuf = MemoryBuffer.getFile(incFile);
}
if (newBuf == null)
return ~0;
return addNewSourceBuffer(newBuf, includeLoc);
}
/**
* Return the ID of the buffer containing the specified location, return -1
* if not found.
*
* @param loc
* @return
*/
public int findBufferContainingLoc(SMLoc loc) {
for (int i = 0, e = buffers.size(); i < e; i++) {
MemoryBuffer buf = buffers.get(i).buffer;
if (buf.contains(loc.buffer))
return i;
}
return ~0;
}
/**
* Find the line number for the specified location in the specified file.
*
* @param loc
* @param bufferID
* @return
*/
public int findLineNumber(SMLoc loc, int bufferID) {
if (bufferID == -1) bufferID = findBufferContainingLoc(loc);
Util.assertion(bufferID != -1, "Invalid location!");
int lineNo = 1;
MemoryBuffer buf = getBufferInfo(bufferID).buffer;
if (lineNoCache != null) {
if (lineNoCache.lastQueryBufferID == bufferID
&& lineNoCache.lastQuery.getCharBuffer().equals(buf.getCharBuffer())
&& lineNoCache.lastQuery.getBufferStart() <= buf.getBufferStart()) {
buf = lineNoCache.lastQuery;
lineNo = lineNoCache.lineNoOfQuery;
}
}
for (; !SMLoc.get(buf).equals(loc); buf.advance()) {
if (buf.getCurChar() == '\n')
++lineNo;
}
if (lineNoCache == null)
lineNoCache = new LineNoCache();
lineNoCache.lastQueryBufferID = bufferID;
lineNoCache.lastQuery = buf;
lineNoCache.lineNoOfQuery = lineNo;
return lineNo;
}
public int findLineNumber(SMLoc loc) {
return findLineNumber(loc, -1);
}
/**
* Emit a message about the specified location with the specified string.
* This method is deprecated, you should use {@linkplain Error#printMessage(SMLoc, String, DiagKind)} instead.
*
* @param loc
* @param msg
* @param type If not null, it specified the kind of message to be emitted (e.g. "error")
* which is prefixed to the message.
*/
@Deprecated
public void printMessage(SMLoc loc, String msg, String type) {
Error.printMessage(loc, msg, getDiagKindByName(type));
}
/**
* Return an SMDiagnostic at the specified location with the specified string.
*
* @param loc
* @param msg
* @param kind If not null, it specified the kind of message to be emitted (e.g. "error")
* which is prefixed to the message.
* @return
*/
public SMDiagnostic getMessage(SMLoc loc, String msg, DiagKind kind) {
int curBuf = findBufferContainingLoc(loc);
Util.assertion(curBuf != -1, "Invalid or unspecified location!");
MemoryBuffer curMB = getBufferInfo(curBuf).buffer;
Util.assertion(curMB.getCharBuffer() == loc.buffer.getCharBuffer());
int columnStart = loc.getPointer();
while (columnStart >= curMB.getBufferStart()
&& curMB.getCharAt(columnStart) != '\n'
&& curMB.getCharAt(columnStart) != '\r')
--columnStart;
int columnEnd = loc.getPointer();
while (columnEnd < curMB.length()
&& curMB.getCharAt(columnEnd) != '\n'
&& curMB.getCharAt(columnEnd) != '\r')
++columnEnd;
String printedMsg = "";
switch (kind) {
case DK_Error:
printedMsg = "error: ";
break;
case DK_Remark:
printedMsg = "remark: ";
break;
case DK_Note:
printedMsg = "note: ";
break;
case DK_Warning:
printedMsg = "warning: ";
break;
}
printedMsg += msg;
return new SMDiagnostic(curMB.getBufferIdentifier(), findLineNumber(loc, curBuf),
curMB.getBufferStart() - columnStart, printedMsg,
curMB.getSubString(columnStart, columnEnd));
}
private void printIncludeStack(SMLoc includeLoc, PrintStream os) {
// Top stack.
if (includeLoc.buffer == null) return;
int curBuf = findBufferContainingLoc(includeLoc);
Util.assertion(curBuf != -1, "Invalid or unspecified location!");
printIncludeStack(getBufferInfo(curBuf).includeLoc, os);
os.printf("Included from %s:%d:\n", getBufferInfo(curBuf).buffer.getBufferIdentifier(),
findLineNumber(includeLoc, curBuf));
}
}
| JianpingZeng/xcc | xcc/java/tools/SourceMgr.java | Java | bsd-3-clause | 8,511 |
package com.logicalpractice.collections;
import static org.junit.Assert.*;
import static org.hamcrest.Matchers.* ;
import org.junit.Test;
public class ExpressionTest {
@Test
public void script1() throws Exception {
Person billy = new Person("Billy", "Smith");
Expression<Person,String> testObject = new Expression<Person,String>(){{
each(Person.class).getFirstName();
}};
String result = testObject.apply(billy);
assertThat(result, equalTo("Billy"));
}
}
| tempredirect/lps-collections | src/test/java/com/logicalpractice/collections/ExpressionTest.java | Java | bsd-3-clause | 534 |
<?php
declare(strict_types=1);
namespace LizardsAndPumpkins\Context\Country;
use LizardsAndPumpkins\Context\ContextPartBuilder;
class IntegrationTestContextCountry implements ContextPartBuilder
{
private $defaultCountryCode = 'DE';
/**
* @param mixed[] $inputDataSet
* @return string
*/
public function getValue(array $inputDataSet) : string
{
if (isset($inputDataSet[Country::CONTEXT_CODE])) {
return (string) $inputDataSet[Country::CONTEXT_CODE];
}
return $this->defaultCountryCode;
}
public function getCode() : string
{
return Country::CONTEXT_CODE;
}
}
| lizards-and-pumpkins/catalog | tests/Integration/Util/Context/Country/IntegrationTestContextCountry.php | PHP | bsd-3-clause | 660 |
const initialState = {
country: 'es',
language: 'es-ES'
}
const settings = (state = initialState, action) => {
switch (action.type) {
default:
return state
}
}
export default settings
| emoriarty/podcaster | src/reducers/settings.js | JavaScript | bsd-3-clause | 200 |
// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Justin Madsen
// =============================================================================
//
// model a single track chain system, as part of a tracked vehicle.
// TODO: read in subsystem data w/ JSON input files
//
// =============================================================================
#include <cstdio>
#include <sstream>
#include "subsys/trackSystem/TrackSystem.h"
namespace chrono {
// -----------------------------------------------------------------------------
// Static variables
// idler, right side
const ChVector<> TrackSystem::m_idlerPos(-2.1904, -0.1443, 0.2447); // relative to local csys
const ChQuaternion<> TrackSystem::m_idlerRot(QUNIT);
// drive gear, right side
const ChVector<> TrackSystem::m_gearPos(1.7741, -0.0099, 0.2447); // relative to local csys
const ChQuaternion<> TrackSystem::m_gearRot(QUNIT);
// suspension
const int TrackSystem::m_numSuspensions = 5;
TrackSystem::TrackSystem(const std::string& name, int track_idx, const double idler_preload)
: m_track_idx(track_idx), m_name(name), m_idler_preload(idler_preload) {
// FILE* fp = fopen(filename.c_str(), "r");
// char readBuffer[65536];
// fclose(fp);
Create(track_idx);
}
// Create: 1) load/set the subsystem data, resize vectors 2) BuildSubsystems()
// TODO: replace hard-coded junk with JSON input files for each subsystem
void TrackSystem::Create(int track_idx) {
/*
// read idler info
assert(d.HasMember("Idler"));
m_idlerMass = d["Idler"]["Mass"].GetDouble();
m_idlerPos = loadVector(d["Idler"]["Location"]);
m_idlerInertia = loadVector(d["Idler"]["Inertia"]);
m_idlerRadius = d["Spindle"]["Radius"].GetDouble();
m_idlerWidth = d["Spindle"]["Width"].GetDouble();
m_idler_K = d["Idler"]["SpringK"].GetDouble();
m_idler_C = d["Idler"]["SpringC"].GetDouble();
*/
/*
// Read Drive Gear data
assert(d.HasMember("Drive Gear"));
assert(d["Drive Gear"].IsObject());
m_gearMass = d["Drive Gear"]["Mass"].GetDouble();
m_gearPos = loadVector(d["Drive Gear"]["Location"]);
m_gearInertia = loadVector(d["Drive Gear"]["Inertia"]);
m_gearRadius = d["Drive Gear"]["Radius"].GetDouble();
m_gearWidth = d["Drive Gear"]["Width"].GetDouble();
// Read Suspension data
assert(d.HasMember("Suspension"));
assert(d["Suspension"].IsObject());
assert(d["Suspension"]["Location"].IsArray() );
m_suspensionFilename = d["Suspension"]["Input File"].GetString();
m_NumSuspensions = d["Suspension"]["Location"].Size();
*/
m_suspensions.resize(m_numSuspensions);
m_suspensionLocs.resize(m_numSuspensions);
// hard-code positions relative to trackSystem csys. Start w/ one nearest sprocket
m_suspensionLocs[0] = ChVector<>(1.3336, 0, 0);
m_suspensionLocs[1] = ChVector<>(0.6668, 0, 0);
// trackSystem c-sys aligned with middle suspension subsystem arm/chassis revolute constraint position
m_suspensionLocs[2] = ChVector<>(0, 0, 0);
m_suspensionLocs[3] = ChVector<>(-0.6682, 0, 0);
m_suspensionLocs[4] = ChVector<>(-1.3368, 0, 0);
/*
for(int j = 0; j < m_numSuspensions; j++)
{
m_suspensionLocs[j] = loadVector(d["Suspension"]["Locaiton"][j]);
}
// Read Track Chain data
assert(d.HasMember("Track Chain"));
assert(d["Track Chain"].IsObject());
m_trackChainFilename = d["Track Chain"]["Input File"].GetString()
*/
// create the various subsystems, from the hardcoded static variables in each subsystem class
BuildSubsystems();
}
void TrackSystem::BuildSubsystems() {
std::stringstream gearName;
gearName << "drive gear " << m_track_idx;
// build one of each of the following subsystems. VisualizationType and CollisionType defaults are PRIMITIVES
m_driveGear = ChSharedPtr<DriveGear>(new DriveGear(gearName.str(), VisualizationType::Mesh,
// CollisionType::Primitives) );
// VisualizationType::Primitives,
CollisionType::CallbackFunction));
std::stringstream idlerName;
idlerName << "idler " << m_track_idx;
m_idler =
ChSharedPtr<IdlerSimple>(new IdlerSimple(idlerName.str(), VisualizationType::Mesh, CollisionType::Primitives));
std::stringstream chainname;
chainname << "chain " << m_track_idx;
m_chain = ChSharedPtr<TrackChain>(new TrackChain(chainname.str(),
// VisualizationType::Primitives,
VisualizationType::CompoundPrimitives, CollisionType::Primitives));
// CollisionType::CompoundPrimitives) );
// build suspension/road wheel subsystems
for (int i = 0; i < m_numSuspensions; i++) {
std::stringstream susp_name;
susp_name << "suspension " << i << ", chain " << m_track_idx;
m_suspensions[i] = ChSharedPtr<TorsionArmSuspension>(
new TorsionArmSuspension(susp_name.str(), VisualizationType::Primitives, CollisionType::Primitives,
0, i ));
}
}
void TrackSystem::Initialize(ChSharedPtr<ChBodyAuxRef> chassis,
const ChVector<>& local_pos,
ChTrackVehicle* vehicle,
double pin_damping) {
m_local_pos = local_pos;
m_gearPosRel = m_gearPos;
m_idlerPosRel = m_idlerPos;
// if we're on the left side of the vehicle, switch lateral z-axis on all relative positions
if (m_local_pos.z < 0) {
m_gearPosRel.z *= -1;
m_idlerPosRel.z *= -1;
}
// Create list of the center location of the rolling elements and their clearance.
// Clearance is a sphere shaped envelope at each center location, where it can
// be guaranteed that the track chain geometry will not penetrate the sphere.
std::vector<ChVector<> > rolling_elem_locs; // w.r.t. chassis ref. frame
std::vector<double> clearance; // 1 per rolling elem
std::vector<ChVector<> > rolling_elem_spin_axis; /// w.r.t. abs. frame
// initialize 1 of each of the following subsystems.
// will use the chassis ref frame to do the transforms, since the TrackSystem
// local ref. frame has same rot (just difference in position)
// NOTE: move drive Gear Init() AFTER the chain of shoes is created, since
// need the list of shoes to be passed in to create custom collision w/ gear
// HOWEVER, still add the info to the rolling element lists passed into TrackChain Init().
// drive sprocket is First added to the lists passed into TrackChain Init()
rolling_elem_locs.push_back(m_local_pos + Get_gearPosRel());
clearance.push_back(m_driveGear->GetRadius());
rolling_elem_spin_axis.push_back(m_driveGear->GetBody()->GetRot().GetZaxis());
// initialize the torsion arm suspension subsystems
for (int s_idx = 0; s_idx < m_suspensionLocs.size(); s_idx++) {
m_suspensions[s_idx]->Initialize(chassis, chassis->GetFrame_REF_to_abs(),
ChCoordsys<>(m_local_pos + m_suspensionLocs[s_idx], QUNIT));
// add to the lists passed into the track chain, find location of each wheel center w.r.t. chassis coords.
rolling_elem_locs.push_back(m_local_pos + m_suspensionLocs[s_idx] + m_suspensions[s_idx]->GetWheelPosRel());
clearance.push_back(m_suspensions[s_idx]->GetWheelRadius());
rolling_elem_spin_axis.push_back(m_suspensions[s_idx]->GetWheelBody()->GetRot().GetZaxis());
}
// last control point: the idler body
m_idler->Initialize(chassis, chassis->GetFrame_REF_to_abs(),
ChCoordsys<>(m_local_pos + Get_idlerPosRel(), Q_from_AngAxis(CH_C_PI, VECT_Z)),
m_idler_preload);
// add to the lists passed into the track chain Init()
rolling_elem_locs.push_back(m_local_pos + Get_idlerPosRel());
clearance.push_back(m_idler->GetRadius());
rolling_elem_spin_axis.push_back(m_idler->GetBody()->GetRot().GetZaxis());
// After all rolling elements have been initialized, now able to setup the TrackChain.
// Assumed that start_pos is between idler and gear control points, e.g., on the top
// of the track chain.
ChVector<> start_pos = (rolling_elem_locs.front() + rolling_elem_locs.back()) / 2.0;
start_pos.y += (clearance.front() + clearance.back()) / 2.0;
// Assumption: start_pos should lie close to where the actual track chain would
// pass between the idler and driveGears.
// MUST be on the top part of the chain so the chain wrap rotation direction can be assumed.
m_chain->Initialize(chassis, chassis->GetFrame_REF_to_abs(), rolling_elem_locs, clearance, rolling_elem_spin_axis,
start_pos);
// add some initial damping to the inter-shoe pin joints
if (pin_damping > 0)
m_chain->Set_pin_friction(pin_damping);
// chain of shoes available for gear init
m_driveGear->Initialize(chassis, chassis->GetFrame_REF_to_abs(),
ChCoordsys<>(m_local_pos + Get_gearPosRel(), QUNIT), m_chain->GetShoeBody(), vehicle);
}
const ChVector<> TrackSystem::Get_idler_spring_react() {
return m_idler->m_shock->Get_react_force();
}
} // end namespace chrono
| jcmadsen/chrono | src/demos/trackVehicle/subsys/trackSystem/TrackSystem.cpp | C++ | bsd-3-clause | 9,871 |
<?php
// uncomment the following to define a path alias
// Yii::setPathOfAlias('local','path/to/local-folder');
// This is the main Web application configuration. Any writable
// CWebApplication properties can be configured here.
return array(
'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',
'name'=>'Plataforma LAEL',
'language'=>'es',
'sourceLanguage'=>'en',
'charset'=>'utf-8',
'theme'=>'classic',
// preloading 'log' component
'preload'=>array('log'),
// autoloading model and component classes
'import'=>array(
'application.models.*',
'application.components.*',
),
'modules'=>array(
// uncomment the following to enable the Gii tool
/*
'gii'=>array(
'class'=>'system.gii.GiiModule',
'password'=>'Enter Your Password Here',
// If removed, Gii defaults to localhost only. Edit carefully to taste.
'ipFilters'=>array('127.0.0.1','::1'),
),
*/
),
// application components
'components'=>array(
'user'=>array(
// enable cookie-based authentication
'allowAutoLogin'=>true,
),
// uncomment the following to enable URLs in path-format
/*
'urlManager'=>array(
'urlFormat'=>'path',
'rules'=>array(
'<controller:\w+>/<id:\d+>'=>'<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',
'<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
),
),
*/
'db'=>array(
'connectionString' => 'sqlite:'.dirname(__FILE__).'/../data/testdrive.db',
),
// uncomment the following to use a MySQL database
/*
'db'=>array(
'connectionString' => 'mysql:host=localhost;dbname=testdrive',
'emulatePrepare' => true,
'username' => 'root',
'password' => '',
'charset' => 'utf8',
),
*/
'errorHandler'=>array(
// use 'site/error' action to display errors
'errorAction'=>'site/error',
),
'log'=>array(
'class'=>'CLogRouter',
'routes'=>array(
array(
'class'=>'CFileLogRoute',
'levels'=>'error, warning',
),
// uncomment the following to show log messages on web pages
/*
array(
'class'=>'CWebLogRoute',
),
*/
),
),
),
// application-level parameters that can be accessed
// using Yii::app()->params['paramName']
'params'=>array(
// this is used in contact page
'adminEmail'=>'webmaster@example.com',
),
); | phghost/plataformaeducativalael-1 | protected/config/main.php | PHP | bsd-3-clause | 2,340 |
/**
Copyright (c) 2014, Nathan Carver
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. Neither the name of the copyright holder nor the names of its contributors may be used to endorse
or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file Code to run the TEETH Smart Toothbrush Holder on Intel Edison board.
*
* Code is maintained at https://github.com/ncarver/TEETH-IotToothbrushHolder.
*
* All code and modules are defined in this file, main.js.
*
* @author Nathan Carver
* @copyright Nathan Carver 2014
* @version 0.0.1
*/
/*
* Required libraries
*
* You will need these libraries to interface with the services and hardware.
*/
var MRAA = require('mraa'); //require MRAA for communicating with hardware pins
var LCD = require('jsupm_i2clcd'); //require LCD libraries for signaling the LCD screen
var LED = require('jsupm_grove'); //require SEEED Grove library for photoresister
var BUZZ = require("jsupm_buzzer"); //require SEEED Grove library for buzzer
var MAILER = require('nodemailer'); //require for sending emails over SMTP
var NET = require('net'); //require for sending cloud data to Edison service on TCP
/**
* Change the constants properties to customize the operation of the TEETH Smart Toothbrush Timer
* @global
*/
var constants = {
'LOG_LEVEL': 3, //Change this value to limit loggin output: 0-none, 1-err, 2-warn, 3-info, 4-debug, 5-all
'USE_SOUND': true,
'PINS': { //Change these values to match the pins on your Edison build
'brushSwitch': [8, 4], //digital pins monitoring switches for toothbrushes
'buzzer': 3, //digital pin for signaling the buzzer
'roomLightSensor': 0, //analog pin for getting room light readings from photoresister on 10K external pullup
'roomLightThreshold' : 80 //value that indicates that room is dark
},
'MAIL': { //Change these values based on documentation at nodemailer to use your SMTP account
'service': 'Gmail', //Account service name, ex. "Gmail"
'user': 'your.name@gmail.com', //user name to login to your service
'pass': 'pass****', //password to login to your service
'from': 'TEETH <teeth@server.com>', //appears in the "From:" section of your emails
'brushTo': ['brush.1@gmail.com', 'brush.2@gmail.com'], //email value for each toothbrush
'subject': 'Great job on TEETH!', //appears as the subject of your emails
'body': 'You met the goal today. Way to go!' //the body text of your emails
},
'METRICS': { //Change these values to match the custom components of your Intel Cloud Analytics
'brushComponent': ['brush1', 'brush2'] //component value for each toothbrush
},
'SCREEN_MSG': { //Messages that appear on the LCD screen during the timer prep and countdown
'ready': '...get ready', //message to display during start of prep time
'set': '.....get set', //message to display last five seconds of prep time
'countdown': 'Countdown:', //message to display during countdown
'percent25': '...almost there!', //message to display 25% of the way through countdown
'percent50': 'good...halfway ', //message to display 50% of the way through countdown
'percent75': 'you\'re doing it ', //message to display 75% of the way through countdown
'finish': 'GREAT JOB!', //message to display at the end of countdown
'brushName': ['Nathan', 'Sarah'] //name to display during countdwon, one value for each toothbrush
},
'TIME': { //Time focused constants for timer, buzzer sounds
'brushPreptime': [10, 30], //seconds of prep time for each toothbrush
'brushGoaltime': [30, 120], //seconds of countdown time for each toothbrush
'buzzDuration': 20, //milliseconds of buzzer time for start and stop sounds
'buzzInterval': 150 //milliseconds between buzzer sounds for start and stop signals
},
'COLOR': { //Colors to use on the LCD screen
'off': [ 0, 0, 0], //black - use when LCD is off
'ready': [100, 100, 100], //light grey - use during prep time
'percent0': [255, 68, 29], //red - use at start of countdown
'percent25': [232, 114, 12], //brown - use when countdown is 25% finished
'percent50': [255, 179, 0], //orange - use when countdown is 50% finished
'percent75': [232, 211, 12], //yellow - use when countdown is 75% finished
'finish': [ 89, 132, 13], //green - use when countdown is finished
'colorFadeDuration': 1000, //milliseconds to fade to new color during countdown mode
'fadeSteps': 100 //number of fading steps to take during colorFadeDuration
}
};
/**
* These values hold the setTimeout and setInterval handles so they can be cleared as part of a timer interuption
* @global
*/
var timers = {
'fadeColor': null, //timer fading the color on the LCD screen
'buzzerPlay': null, //timer playing the buzzer sounds
'buzzerWait': null, //timer waiting in between buzzer sounds
'prepCountdown': null, //timer for the main prep time
'startCountdown': null, //timer for the last five seconds of prep time
'countdown': null, //timer for the main countdown
'lightsOut': null //timer lookin for "lights out" interuption
};
/**
* Creates a new Logger object and the helper methods used to send messages to console.
* Highest level of logging, ERR (1), only outputs errors during code execution.
* Lowest level DEBUG (4) outputs all logging messages.
*
* @see constants.LOG_LEVEL Use the constant constants.LOG_LEVEL to adjust the level of output.
* @class
*/
var Logger = function () {
this.ERR = 1;
this.WARN = 2;
this.INFO = 3;
this.DEBUG = 4;
/**
* @private
*/
var logLevels = ['', 'err', 'warn', 'info', 'debug'];
/**
* @param {string} msg message to send to logger
* @param {int} level log level for this message
* @public
*/
this.it = function (msg, level) {
if (constants.LOG_LEVEL >= level || level === undefined) {
console.log('%s - %s: %s', new Date(), logLevels[level], msg);
}
};
/*
* @param {string} msg message to send to logger at log level ERR (1)
* @public
*/
this.err = function (msg) {
this.it(msg, this.ERR);
};
/*
* @param {string} msg message to send to logger at log level WARN (2)
* @public
*/
this.warn = function (msg) {
this.it(msg, this.WARN);
};
/*
* @param {string} msg message to send to logger at log level INFO (3)
* @public
*/
this.info = function (msg) {
this.it(msg, this.INFO);
};
/*
* @param {string} msg message to send to logger at log level DEBUG (4)
* @public
*/
this.debug = function (msg) {
this.it(msg, this.DEBUG);
};
};
/**
* Creates a new Sensors object to monitor the hardware connected to the Edison
* @requires mraa:Gpio
* @requires mraa:Aio
* @param {Logger} log object for logging output
* @see constants.PINS Use the constant constants.PINS to identify the hardware connections
* @class
*/
var Sensors = function (log) {
log.info('instatiate Sensors');
/**
* @private
*/
var i;
/**
* the array of switches associated with each toothbrush are initialized
* as INPUT pins during instatiation.
* @public
*/
this.brushSwitch = [];
for (i = 0; i < constants.PINS.brushSwitch.length; i = i + 1) {
this.brushSwitch[i] = new MRAA.Gpio(constants.PINS.brushSwitch[i]);
this.brushSwitch[i].dir(MRAA.DIR_IN);
}
/**
* the analog pin for monitoring the phototransister is initialized
* during instatiation. Expected that this photo cell will have a 10K
* external pulldown resistor.
* @public
*/
// this.roomLightSensor = new MRAA.Aio(constants.PINS.roomLightSensor);
};
/**
* Creates a new Buzzer object to play a sound on the buzzer connected to the Edison
* @requires jsupm_buzzer:Buzzer
* @param {Logger} log object for logging output
* @see constants.TIME Use the properties of constants.TIME to adjust the buzzer sounds
* @class
*/
var Buzzer = function (log) {
log.info('instatiate Buzzer');
var buzzer = new BUZZ.Buzzer(constants.PINS.buzzer);
/**
* play calls the playSound method of the low-level buzzer class for a simple tone value
* @private
*/
function play(buzzingTime) {
log.debug('(buzzer.play for ' + buzzingTime + ')');
if (!constants.USE_SOUND) {
return;
}
buzzer.playSound(BUZZ.DO, 5000);
timers.buzzerPlay = setTimeout(function () {
buzzer.playSound(BUZZ.DO, 0);
}, buzzingTime);
}
/**
* plays the standard sound for the buzz duration, then waits, and plays again
* expected to be called at the beginning of the countdown
* @public
*/
this.playStartSound = function () {
log.info('buzzer.playStartSound');
play(constants.TIME.buzzDuration);
timers.buzzerWait = setTimeout(function () {
play(constants.TIME.buzzDuration);
}, constants.TIME.buzzInterval);
};
/**
* plays the standard sound for the buzz duration, then waits, and plays again
* expected to be called at the end of the countdown
* @public
*/
this.playStopSound = function () {
log.info('buzzer.playStopSound');
play(constants.TIME.buzzDuration);
timers.buzzerWait = setTimeout(function () {
play(constants.TIME.buzzDuration);
}, constants.TIME.buzzInterval);
};
};
/**
* Creates a new Screen object to display messages and colors RGB LCD connected to the Edison over I2C
* @requires jsupm_i2clcd:Jhd1313m1
* @param {Logger} log object for logging output
* @see constants.COLOR Use the properties of constants.COLOR to adjust the screen background colors
* @see constants.SCREEN_MSG Use the properties of constants.SCREEN_MSG to change the messages displayed on screen
* @class
*/
var Screen = function (log) {
log.info('instatiate Screen');
/**
* Instance variables to connect to LCD screen and manage the color fading
* @private
*/
var lcd = new LCD.Jhd1313m1(6, 0x3E, 0x62), //standard I2C bus
interval = constants.COLOR.colorFadeDuration / constants.COLOR.fadeSteps,
lastColor = constants.COLOR.off,
steps = constants.COLOR.fadeSteps;
/**
* getRemainingSteps identifies how many more steps are needed before fade is finished
* @returns {int} number of steps remaining
* @private
*/
function getRemainingSteps() {
log.debug('(screen.getRemainingSteps)');
return steps;
}
/**
* setRemainingSteps sets how many more steps are needed before fade is finished
* @params {int} remainingSteps new number of steps remaining
* @private
*/
function setRemainingSteps(remainingSteps) {
log.debug('(screen.setRemainingSteps: ' + remainingSteps + ')');
steps = remainingSteps;
}
/**
* setScreen color calls low-level methods to set RGB values of screen background
* also sets the instance variable "lastColor" to help with fade control
* @param {array} colorArray array of decimal color values in Red Green Blue order [r,g,b]
* @private
*/
function setScreenColor(colorArray) {
log.debug('(screen.setScreenColor to ' + colorArray + ')');
lcd.setColor(colorArray[0], colorArray[1], colorArray[2]);
lastColor = colorArray;
}
/**
* Inner method called by timeouts to fade background color from current color to the
* updated color passed RGB color array
* @private
*/
function _fadeColor(colorArray) {
log.debug('(screen._fadeColor: ' + colorArray + ')');
var step = getRemainingSteps();
if (step > 0) {
var diffRed = colorArray[0] - lastColor[0],
diffGrn = colorArray[1] - lastColor[1],
diffBlu = colorArray[2] - lastColor[2],
stepRed = parseInt(diffRed / step, 10),
stepGrn = parseInt(diffGrn / step, 10),
stepBlu = parseInt(diffBlu / step, 10),
nextRed = lastColor[0] + stepRed,
nextGrn = lastColor[1] + stepGrn,
nextBlu = lastColor[2] + stepBlu;
setScreenColor([nextRed, nextGrn, nextBlu]);
setRemainingSteps(step - 1);
timers.fadeColor = setTimeout(function () {
_fadeColor(colorArray);
}, interval);
}
}
/**
* Starts a timout sequence to slowy change the LCD RGB screen background from its current
* color to the one passed in the parameters. The speed and number of steps used for fading
* are controlled by the constants.
*
* @param {array} colorArray a 3-member array of decimal numbers describing the color to display
* on the screen background: [r,g,b]
* @public
*/
this.fadeColor = function (colorArray) {
log.info('screen.fadeColor: ' + colorArray);
setRemainingSteps(constants.COLOR.fadeSteps);
_fadeColor(colorArray);
};
/**
* Helper method combines clearing the screen of all text content and returning the cursor
* position back to the top left.
* @public
*/
this.reset = function () {
log.info('screen.reset');
lcd.clear();
lcd.setCursor(0, 0);
};
/**
* Helper method combines reseting the screen and returning the screen color to "off"
* @public
*/
this.resetAndTurnOff = function () {
log.info('screen.resetAndTurnOff');
this.reset();
setScreenColor(constants.COLOR.off);
};
/**
* Turns the screen on and displays the "ready" message defined in constants for the given toothbrush
*
* @param {int} componentIndex identifies the toothbrush by it's array index
* @public
*/
this.displayReady = function (componentIndex) {
log.info('screen.displayReady for ' + componentIndex);
lcd.clear();
setScreenColor(constants.COLOR.ready);
this.write(constants.SCREEN_MSG.brushName[componentIndex], 0, 0);
this.write(constants.SCREEN_MSG.ready, 1, 0);
};
/**
* Changes the "ready" message to the "set" message defined in constants for the given toothbrush
*
* @param {int} componentIndex identifies the toothbrush by it's array index
* @public
*/
this.displaySet = function (componentIndex) {
log.info('screen.displaySet for ' + componentIndex);
this.write(constants.SCREEN_MSG.set, 1, 0);
};
/**
* Helper message combines writing the given message to the screen at (optional) given coordinates
*
* @param {string} msg the string to ouput to the screen
* @param {int} col (optional) 0-indexed column number to set the cursor
* @param {int} row (optional) 0-indexed row number to set the cursor
* @public
*/
this.write = function (msg, col, row) {
//log.info('screen.write msg ' + msg);
var i;
if (!(col === undefined || row === undefined)) {
lcd.setCursor(col, row);
for (i = 0; i < 10000000; i = i + 1) {
//wait for slow LCD
}
}
lcd.write(msg);
};
//initialize the LCD screen during instatiation
this.resetAndTurnOff();
};
/**
* Creates a new Mailer object to send mail over SMTP
* @requires nodemailer
* @param {Logger} log object for logging output
* @see constants.MAIL Use the properties of constants.MAIL to configure your SMTP service
* @class
*/
var Mailer = function (log) {
log.info('instatiate Mailer');
/**
* Instance options taken from constants.MAIL are used by createTransport to authenticate SMTP
* @private
*/
var mailOptions = {
from: constants.MAIL.from, // sender address
to: constants.MAIL.brushTo[0], // list of receivers
subject: constants.MAIL.subject, // Subject line
text: constants.MAIL.body, // plaintext body
html: constants.MAIL.body // html body
},
transporter = MAILER.createTransport({
service: constants.MAIL.service,
auth: {
user: constants.MAIL.user,
pass: constants.MAIL.pass
}
});
/**
* Sends the message defined in constants.MAIL for the given toothbrush.
* Errors are sent to the log Logger object.
* @param {int} componentIndex identifies the toothbrush by it's array index in constants
* @public
*/
this.sendCongratsEmail = function (componentIndex) {
log.info('mailer.sendCongratsEmail for ' + componentIndex);
mailOptions.to = constants.MAIL.brushTo[componentIndex];
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
log.err('mail error ' + error + '.');
} else {
log.info('mail sent.');
}
});
};
};
/**
* Creates a new Metrics object to connect to Intel Cloud Analytics over TCP
* @requires net:socket
* @param {Logger} log object for logging output
* @class
*/
var Metrics = function (log) {
log.info('instatiate metrics');
/**
* instance objects and options to connect over TCP to Edison iot-agent
* @private
*/
var client = new NET.Socket(),
options = {
host : 'localhost', //use the Intel analytics client running locally on the Edison
port : 7070 //on default TCP port
};
/**
* sendObservation concatenates the string expected by cloud analytics based on the parameter values
* @param {string} name custom component name registered with Intel analytics
* @param {float} value data value to send to cloud
* @private
*/
function sendObservation(name, value) {
log.debug('(metrics.sendObservation for ' + name + ', ' + value + ')');
var msg = JSON.stringify({
n: name,
v: value
}),
sentMsg = msg.length + "#" + msg; //syntax for Intel analytics
client.write(sentMsg);
}
/**
* Method combines the activity of connecting to the Edision service and then sending data to the cloud
* @param {int} itemIndex array index of component names registered with Intel analytics
* @param {float} timeValue data value to send to cloud, expecting fractional number of seconds
* @public
*/
this.addDataToCloud = function (itemIndex, timeValue) {
log.info('metrics.addDataToCloud for ' + itemIndex + ', ' + timeValue);
client.on('error', function () {
log.err('Could not connect to cloud');
});
client.connect(options.port, options.host, function () {
sendObservation(constants.METRICS.brushComponent[itemIndex], timeValue);
});
};
};
/**
* Creates a new Teeth object to manage the countdown timer
* @param {Logger} log object for logging output
* @param {Sensors} sensor object for listening to hardware sensors
* @param {Buzzer} buzzer object for controlling the sounds
* @param {Screen} screen object for display on the RGB LCD screen
* @param {Mailer} mailer object for sending email
* @param {Metrics} metrics object for sending data to cloud
* @see constants.TIME Use the properties of constants.TIME to adjust the length of the countdown
* @class
*/
var Teeth = function (log, sensors, buzzer, lcdScreen, mailer, metrics) {
log.info('instatiate teeth');
/**
* flags to make sure fadeColor only called once for each color
* @private
*/
var fades = [],
currentComponent = -1,
timeSpent = 0;
/**
* clearAllTimers loops through all timers in constants to clear them and set to null
* @private
*/
function clearAllTimers() {
log.debug('(teeth.clearAllTimers)');
var key,
timer;
for (key in timers) {
if (timers.hasOwnProperty(key)) {
timer = timers[key];
if (timer !== null) {
clearTimeout(timer);
timer = null;
}
}
}
fades = [];
currentComponent = -1;
}
/**
* finishCountdown clears the screen, plays the stop sound, and starts the waiting process again
* @param {int} componentIndex array index number of the toothbrush that is finishing the countdown
* @private
*/
function finishCountdown(componentIndex) {
log.debug('(teeth.finishCountdown for ' + componentIndex + ')');
clearAllTimers();
lcdScreen.reset();
buzzer.playStopSound();
mailer.sendCongratsEmail(componentIndex);
lcdScreen.write(constants.SCREEN_MSG.finish);
metrics.addDataToCloud(componentIndex, constants.TIME.brushGoaltime[componentIndex]);
setTimeout(function () {
lcdScreen.resetAndTurnOff();
wait();
}, 1000);
}
/**
* countdown generates messages and colors to the screen during the countdown,
* called continuously until time is over
* @param {int} componentIndex array index number of the toothbrush that is in the middle of the countdown
* @param {int} timeRemaining the amount of time remaining in seconds before the countdown is over
* @private
*/
function countdown(componentIndex, timeRemaining) {
log.debug('(teeth.countdown for ' + componentIndex + ': ' + timeRemaining + ')');
var originalValue = constants.TIME.brushGoaltime[componentIndex];
timeSpent = originalValue - timeRemaining;
if (timeRemaining > 0) {
lcdScreen.write(constants.SCREEN_MSG.countdown + timeRemaining + ' ', 0, 0);
if (timeRemaining <= (0.25 * originalValue)) {
lcdScreen.write(constants.SCREEN_MSG.percent25, 1, 0);
if (fades[constants.COLOR.percent25] !== 1) {
lcdScreen.fadeColor(constants.COLOR.percent25);
fades[constants.COLOR.percent25] = 1;
}
} else if (timeRemaining <= (0.5 * originalValue)) {
lcdScreen.write(constants.SCREEN_MSG.percent50, 1, 0);
if (fades[constants.COLOR.percent50] !== 1) {
lcdScreen.fadeColor(constants.COLOR.percent50);
fades[constants.COLOR.percent50] = 1;
}
} else if (timeRemaining <= (0.75 * originalValue)) {
lcdScreen.write(constants.SCREEN_MSG.percent75, 1, 0);
if (fades[constants.COLOR.percent75] !== 1) {
lcdScreen.fadeColor(constants.COLOR.percent75);
fades[constants.COLOR.percent75] = 1;
}
}
timers.countdown = setTimeout(function () {
countdown(componentIndex, timeRemaining - 1);
}, 1000);
} else {
finishCountdown(componentIndex);
}
}
/**
* startCountdown plays the sound and begins the first call to countdown
* @param {int} componentIndex array index number of the toothbrush that is starting the countdown
* @private
*/
function startCountdown(componentIndex) {
log.info('(teeth.startCountdown for ' + componentIndex + ')');
buzzer.playStartSound();
lcdScreen.reset();
currentComponent = componentIndex;
countdown(componentIndex, constants.TIME.brushGoaltime[componentIndex]);
}
/**
* prepCountdown prepares the screen and waits for real countdown to begin, displays
* an additional warning with five seconds to go
* @param {int} componentIndex array index number of the toothbrush that is starting the countdown
* @private
*/
function prepCountdown(componentIndex) {
log.debug('(teeth.prepCountdown for ' + componentIndex + ')');
lcdScreen.displayReady(componentIndex);
var prepTime = constants.TIME.brushPreptime[componentIndex];
timers.prepCountdown = setTimeout(function () {
log.debug('setTimeout: prepCountdown');
lcdScreen.displaySet(componentIndex);
}, (prepTime - 5) * 1000);
timers.startCountdown = setTimeout(function () {
log.debug('setTimeout: startCountdown');
startCountdown(componentIndex);
}, prepTime * 1000);
}
/**
* watchForLightsOut polls the photoresistor to see if the room is dark, then stops all activity
* @private
*/
function watchForLightsOut() {
//do not log.debug >> called every 50ms
return;
var val = sensors.roomLightSensor.read();
if (val < constants.PINS.roomLightThreshold) {
log.info('Trigger for lights out: Stop Timer (early) then wait 5 seconds to start again');
if (currentComponent >= 0) {
metrics.addDataToCloud(currentComponent, timeSpent);
}
clearAllTimers();
lcdScreen.resetAndTurnOff();
setTimeout(wait, 5000);
}
}
/**
* wait is the main entry to this class, it polls the switches regularly to see if it should start the countdown
* @private
*/
function wait() {
//do not log.debug >> called every 100ms
var i,
val;
for (i = 0; i < sensors.brushSwitch.length; i = i + 1) {
val = sensors.brushSwitch[i].read();
if (val === 0) { //0 for NO (normally open switch), 1 for NC (normally closed)
log.info('Trigger for toothbrush ' + i + ': Start Timer');
prepCountdown(i);
timers.lightsOut = setInterval(watchForLightsOut, 50);
break;
}
}
if (i >= sensors.brushSwitch.length) {
setTimeout(wait, 100);
}
}
/**
* Entry point to Teeth, the start command initiates the Smart Toothbrush Holder and begins the process of waiting for a countdown
* @public
*/
this.start = function () {
log.info('Teeth.start waiting for toothbrush events');
wait();
};
};
/* Create instance objects of the classes needed by TEETH */
var log = new Logger(),
sensors = new Sensors(log),
buzzer = new Buzzer(log),
lcdScreen = new Screen(log),
mailer = new Mailer(log),
metrics = new Metrics(log),
teeth = new Teeth(log, sensors, buzzer, lcdScreen, mailer, metrics);
/* Get the code running by invoking the start method of the Teeth controller */
teeth.start();
| ncarver/TEETH | main.js | JavaScript | bsd-3-clause | 28,665 |
<?php
use app\core\helpers\Html;
use app\core\helpers\Url;
$this->title = '权限管理 在此页面添加名修改权限项注释';
$this->params['breadcrumbs'][] = $this->title;
?>
<style type="text/css">
.nopad{padding-left: 0}
.panel-default>.panel-heading{
padding: 10px 15px;
background-color: #f5f5f5;
border-color: #ddd;
}
</style>
<div class="page-content">
<!-- /section:settings.box -->
<div class="page-content-area">
<div class="page-header">
<h1>
<small>
<a data-loading-text="数据更新中, 请稍后..." href="<?=Url::toRoute('sync')?>" class="btn btn-danger auth-sync">权限初始化</a>
</small>
<?= $this->render('@app/modules/sys/views/admin/layout/_nav.php') ?>
</h1>
</div><!-- /.page-header -->
<div class="row">
<div class="col-md-12">
<?php foreach ($classes as $key => $value):?>
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<?=$key;?>
</h4>
</div>
<div class="panel-body">
<?php foreach ($value as $ke => $val):?>
<dl class="col-md-12 col-sm-12 nopad">
<dt><?php echo $ke;?> </dt>
<?php foreach ($val as $k => $v):?>
<dd class="col-md-3 nopad">
<span class="lbl ">
<?php echo $k?>
<input value="<?= $v['title']?>" class="action_des input-small form-control" key="<?=$v['name']?>" />
</span>
</dd>
<?php endforeach;?>
</dl>
<hr/>
<?php endforeach;?>
</div>
</div>
<?php endforeach;?>
</div>
</div><!-- /.row -->
</div><!-- /.page-content-area -->
</div><!-- /.page-content -->
<?php $this->beginBlock('auth') ?>
$(function(){
$('.auth-sync').click(function(e){
e.preventDefault();
var btn = $(this).button('loading');
$.get($(this).attr('href'),null,function(xhr){
if (xhr.status) {
location.reload();
};
btn.button('reset');
},'json');
});
$('.action_des').change(function(e){
e.preventDefault();
var url = "<?=Url::toRoute('title')?>";
var csrf = $('meta[name=csrf-token]').attr('content');
var data = {name:$(this).attr('key'), title:$(this).val(), _csrf:csrf};
$.post(url, data, function(xhr){
if (!xhr.status) {
alert(xhr.info);
};
},'json');
});
})
<?php $this->endBlock() ?>
<?php $this->registerJs($this->blocks['auth'], \yii\web\View::POS_END); ?>
| cboy868/lion2 | modules/sys/views/admin/auth-permission/index.php | PHP | bsd-3-clause | 3,238 |