repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
iDingDong/libDDCPP | src/standard/bits/DD_print.hpp | 2086 | // DDCPP/standard/bits/DD_print.hpp
#ifndef DD_PRINT_HPP_INCLUDED_
# define DD_PRINT_HPP_INCLUDED_ 1
# include <iostream>
# include <iomanip>
# include "DD_Tags.hpp"
# include "DD_fabricate.hpp"
DD_DETAIL_BEGIN_
struct VersionTag : Tag {
} DD_CONSTANT version;
struct FlushTag : Tag {
} DD_CONSTANT flush;
struct EndLineTag : Tag {
} DD_CONSTANT end_line;
struct Print {
public:
DD_ALIAS(ThisType, Print);
# if __cplusplus >= 201103L
public:
ThisType const& operator ()() const DD_NOEXCEPT {
return *this;
}
public:
template <typename ValueT__, typename... ValuesT__>
ThisType const& operator ()(
ValueT__ const& value___,
ValuesT__ const&... values___
) const DD_NOEXCEPT_AS((fabricate<ThisType>(), value___)(values___...)) {
return (*this, value___)(values___...);
}
# endif
public:
template <typename ValueT__>
ThisType const& operator ,(ValueT__ const& value___) const DD_NOEXCEPT_AS(std::cout << value___) {
std::cout << value___;
return *this;
}
public:
ThisType const& operator ,(FlushTag tag_) const DD_NOEXCEPT_AS(std::cout << std::flush) {
std::cout << std::flush;
return *this;
}
public:
ThisType const& operator ,(EndLineTag tag_) const DD_NOEXCEPT_AS(std::cout << std::endl) {
std::cout << std::endl;
return *this;
}
public:
ThisType const& operator ,(VersionTag tag_) const DD_NOEXCEPT_AS(
fabricate<ThisType>() DD_COMMA
"libDDCPP\nversion: " DD_COMMA
DD_CPP_LIBRARY / 1000 DD_COMMA
'.' DD_COMMA
DD_CPP_LIBRARY % 1000 / 100 DD_COMMA
DD_CPP_LIBRARY % 100 / 10 DD_COMMA
DD_CPP_LIBRARY % 10 DD_COMMA
'\n'
) {
return
*this,
"libDDCPP\nversion: ",
DD_CPP_LIBRARY / 1000,
'.',
DD_CPP_LIBRARY % 1000 / 100,
DD_CPP_LIBRARY % 100 / 10,
DD_CPP_LIBRARY % 10,
'\n'
;
}
} DD_CONSTANT print;
DD_DETAIL_END_
DD_BEGIN_
using detail_::VersionTag;
using detail_::version;
using detail_::FlushTag;
using detail_::flush;
using detail_::EndLineTag;
using detail_::end_line;
using detail_::Print;
using detail_::print;
DD_END_
# define DD_PRINT ::DD::print,
#endif
| bsd-3-clause |
versionone/VersionOne.ServiceHost.ServerConnector | VersionOne.ServiceHost.ServerConnector/StartupValidation/V1ConnectionValidator.cs | 772 | using VersionOne.ServiceHost.Core.Logging;
namespace VersionOne.ServiceHost.ServerConnector.StartupValidation
{
public class V1ConnectionValidator : BaseValidator
{
public override bool Validate()
{
Log(LogMessage.SeverityType.Info, "Validating connection to VersionOne");
V1Processor.LogConnectionConfiguration();
if (!V1Processor.ValidateConnection())
{
Log(LogMessage.SeverityType.Error, "Cannot establish connection to VersionOne");
return false;
}
V1Processor.LogConnectionInformation();
Log(LogMessage.SeverityType.Info, "Connection to VersionOne is established successfully");
return true;
}
}
} | bsd-3-clause |
woestler/EndSql | demo/delete.php | 2220 | <?php
/**
* EndSQL
*
* Database abstract layer.
*
*
* Copyright (c) 2013-2014, Woestler
* 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 EndSQL Team 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 HOLDERS
* AND 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 EndSQL
* @version 1.0.2
* @copyright 2013-2014 Woestler
* @author Woestler
* @link http://EndSQL.org/ EndSQL
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
*/
include '../Autoload.php';
$db = EndSql::getInstance();
$delete = $db->delete();
/************************************
FROM method
**************************************/
$delete->from("context")->where()->equal(array("type_id"=>3));
$delete->where()->greaterThan(array("id"=>30),EndSql::SQL_OR);
echo $delete->getSql();
//DELETE FROM context WHERE (type_id = 3) OR (id> 30)
| bsd-3-clause |
codenote/chromium-test | chrome/browser/ui/startup/default_browser_prompt.cc | 10110 | // 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/ui/startup/default_browser_prompt.h"
#include "base/memory/weak_ptr.h"
#include "base/message_loop.h"
#include "base/metrics/histogram.h"
#include "base/prefs/pref_registry_simple.h"
#include "base/prefs/pref_service.h"
#include "base/version.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/first_run/first_run.h"
#include "chrome/browser/infobars/confirm_infobar_delegate.h"
#include "chrome/browser/infobars/infobar_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/shell_integration.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/chrome_version_info.h"
#include "chrome/common/pref_names.h"
#include "chrome/installer/util/master_preferences.h"
#include "chrome/installer/util/master_preferences_constants.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/navigation_details.h"
#include "content/public/browser/web_contents.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
using content::BrowserThread;
namespace {
// Calls the appropriate function for setting Chrome as the default browser.
// This requires IO access (registry) and may result in interaction with a
// modal system UI.
void SetChromeAsDefaultBrowser(bool interactive_flow, PrefService* prefs) {
if (interactive_flow) {
UMA_HISTOGRAM_COUNTS("DefaultBrowserWarning.SetAsDefaultUI", 1);
if (!ShellIntegration::SetAsDefaultBrowserInteractive()) {
UMA_HISTOGRAM_COUNTS("DefaultBrowserWarning.SetAsDefaultUIFailed", 1);
} else if (ShellIntegration::GetDefaultBrowser() ==
ShellIntegration::NOT_DEFAULT) {
// If the interaction succeeded but we are still not the default browser
// it likely means the user simply selected another browser from the
// panel. We will respect this choice and write it down as 'no, thanks'.
UMA_HISTOGRAM_COUNTS("DefaultBrowserWarning.DontSetAsDefault", 1);
}
} else {
UMA_HISTOGRAM_COUNTS("DefaultBrowserWarning.SetAsDefault", 1);
ShellIntegration::SetAsDefaultBrowser();
}
}
// The delegate for the infobar shown when Chrome is not the default browser.
class DefaultBrowserInfoBarDelegate : public ConfirmInfoBarDelegate {
public:
// Creates a default browser delegate and adds it to |infobar_service|.
static void Create(InfoBarService* infobar_service,
PrefService* prefs,
bool interactive_flow_required);
private:
DefaultBrowserInfoBarDelegate(InfoBarService* infobar_service,
PrefService* prefs,
bool interactive_flow_required);
virtual ~DefaultBrowserInfoBarDelegate();
void AllowExpiry() { should_expire_ = true; }
// ConfirmInfoBarDelegate:
virtual gfx::Image* GetIcon() const OVERRIDE;
virtual string16 GetMessageText() const OVERRIDE;
virtual string16 GetButtonLabel(InfoBarButton button) const OVERRIDE;
virtual bool NeedElevation(InfoBarButton button) const OVERRIDE;
virtual bool Accept() OVERRIDE;
virtual bool Cancel() OVERRIDE;
virtual bool ShouldExpireInternal(
const content::LoadCommittedDetails& details) const OVERRIDE;
// The prefs to use.
PrefService* prefs_;
// Whether the user clicked one of the buttons.
bool action_taken_;
// Whether the info-bar should be dismissed on the next navigation.
bool should_expire_;
// Whether changing the default application will require entering the
// modal-UI flow.
const bool interactive_flow_required_;
// Used to delay the expiration of the info-bar.
base::WeakPtrFactory<DefaultBrowserInfoBarDelegate> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(DefaultBrowserInfoBarDelegate);
};
// static
void DefaultBrowserInfoBarDelegate::Create(InfoBarService* infobar_service,
PrefService* prefs,
bool interactive_flow_required) {
infobar_service->AddInfoBar(scoped_ptr<InfoBarDelegate>(
new DefaultBrowserInfoBarDelegate(infobar_service, prefs,
interactive_flow_required)));
}
DefaultBrowserInfoBarDelegate::DefaultBrowserInfoBarDelegate(
InfoBarService* infobar_service,
PrefService* prefs,
bool interactive_flow_required)
: ConfirmInfoBarDelegate(infobar_service),
prefs_(prefs),
action_taken_(false),
should_expire_(false),
interactive_flow_required_(interactive_flow_required),
ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) {
// We want the info-bar to stick-around for few seconds and then be hidden
// on the next navigation after that.
MessageLoop::current()->PostDelayedTask(
FROM_HERE, base::Bind(&DefaultBrowserInfoBarDelegate::AllowExpiry,
weak_factory_.GetWeakPtr()),
base::TimeDelta::FromSeconds(8));
}
DefaultBrowserInfoBarDelegate::~DefaultBrowserInfoBarDelegate() {
if (!action_taken_)
UMA_HISTOGRAM_COUNTS("DefaultBrowserWarning.Ignored", 1);
}
gfx::Image* DefaultBrowserInfoBarDelegate::GetIcon() const {
return &ResourceBundle::GetSharedInstance().GetNativeImageNamed(
IDR_PRODUCT_LOGO_32);
}
string16 DefaultBrowserInfoBarDelegate::GetMessageText() const {
return l10n_util::GetStringUTF16(IDS_DEFAULT_BROWSER_INFOBAR_SHORT_TEXT);
}
string16 DefaultBrowserInfoBarDelegate::GetButtonLabel(
InfoBarButton button) const {
return l10n_util::GetStringUTF16((button == BUTTON_OK) ?
IDS_SET_AS_DEFAULT_INFOBAR_BUTTON_LABEL :
IDS_DONT_ASK_AGAIN_INFOBAR_BUTTON_LABEL);
}
bool DefaultBrowserInfoBarDelegate::NeedElevation(InfoBarButton button) const {
return button == BUTTON_OK;
}
bool DefaultBrowserInfoBarDelegate::Accept() {
action_taken_ = true;
BrowserThread::PostTask(
BrowserThread::FILE,
FROM_HERE,
base::Bind(&SetChromeAsDefaultBrowser, interactive_flow_required_,
prefs_));
return true;
}
bool DefaultBrowserInfoBarDelegate::Cancel() {
action_taken_ = true;
UMA_HISTOGRAM_COUNTS("DefaultBrowserWarning.DontSetAsDefault", 1);
// User clicked "Don't ask me again", remember that.
prefs_->SetBoolean(prefs::kCheckDefaultBrowser, false);
return true;
}
bool DefaultBrowserInfoBarDelegate::ShouldExpireInternal(
const content::LoadCommittedDetails& details) const {
return should_expire_;
}
void NotifyNotDefaultBrowserCallback(chrome::HostDesktopType desktop_type) {
Browser* browser = chrome::FindLastActiveWithHostDesktopType(desktop_type);
if (!browser)
return; // Reached during ui tests.
// In ChromeBot tests, there might be a race. This line appears to get
// called during shutdown and |tab| can be NULL.
content::WebContents* web_contents =
browser->tab_strip_model()->GetActiveWebContents();
if (!web_contents)
return;
bool interactive_flow = ShellIntegration::CanSetAsDefaultBrowser() ==
ShellIntegration::SET_DEFAULT_INTERACTIVE;
Profile* profile =
Profile::FromBrowserContext(web_contents->GetBrowserContext());
DefaultBrowserInfoBarDelegate::Create(
InfoBarService::FromWebContents(web_contents), profile->GetPrefs(),
interactive_flow);
}
void CheckDefaultBrowserCallback(chrome::HostDesktopType desktop_type) {
if (ShellIntegration::GetDefaultBrowser() == ShellIntegration::NOT_DEFAULT) {
ShellIntegration::DefaultWebClientSetPermission default_change_mode =
ShellIntegration::CanSetAsDefaultBrowser();
if (default_change_mode != ShellIntegration::SET_DEFAULT_NOT_ALLOWED) {
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
base::Bind(&NotifyNotDefaultBrowserCallback, desktop_type));
}
}
}
} // namespace
namespace chrome {
void RegisterDefaultBrowserPromptPrefs(PrefRegistrySimple* registry) {
registry->RegisterStringPref(
prefs::kBrowserSuppressDefaultBrowserPrompt, std::string());
}
void ShowDefaultBrowserPrompt(Profile* profile, HostDesktopType desktop_type) {
// We do not check if we are the default browser if:
// - The user said "don't ask me again" on the infobar earlier.
// - There is a policy in control of this setting.
// - The "suppress_default_browser_prompt_for_version" master preference is
// set to the current version.
if (!profile->GetPrefs()->GetBoolean(prefs::kCheckDefaultBrowser))
return;
if (g_browser_process->local_state()->IsManagedPreference(
prefs::kDefaultBrowserSettingEnabled)) {
if (g_browser_process->local_state()->GetBoolean(
prefs::kDefaultBrowserSettingEnabled)) {
BrowserThread::PostTask(
BrowserThread::FILE, FROM_HERE,
base::Bind(
base::IgnoreResult(&ShellIntegration::SetAsDefaultBrowser)));
} else {
// TODO(pastarmovj): We can't really do anything meaningful here yet but
// just prevent showing the infobar.
}
return;
}
const std::string disable_version_string =
g_browser_process->local_state()->GetString(
prefs::kBrowserSuppressDefaultBrowserPrompt);
const Version disable_version(disable_version_string);
DCHECK(disable_version_string.empty() || disable_version.IsValid());
if (disable_version.IsValid()) {
const chrome::VersionInfo version_info;
const Version chrome_version(version_info.Version());
if (disable_version.Equals(chrome_version))
return;
}
BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
base::Bind(&CheckDefaultBrowserCallback,
desktop_type));
}
#if !defined(OS_WIN)
bool ShowFirstRunDefaultBrowserPrompt(Profile* profile) {
return false;
}
#endif
} // namespace chrome
| bsd-3-clause |
JoshBour/scheduler | module/Worker/src/Worker/Repository/WorkerRepository.php | 671 | <?php
/**
* Created by PhpStorm.
* User: Josh
* Date: 20/5/2014
* Time: 2:16 μμ
*/
namespace Worker\Repository;
use Doctrine\ORM\EntityRepository;
class WorkerRepository extends EntityRepository{
public function findAllNonReleasedWorkers($startDate,$endDate){
$qb = $this->createQueryBuilder('e');
$qb->select('w')
->add('from', 'Worker\Entity\Worker w')
->where("w.releaseDate IS NULL OR w.releaseDate BETWEEN :startDate AND :endDate")
->setParameter('startDate',$startDate)
->setParameter('endDate', $endDate);
$query = $qb->getQuery();
return $query->getResult();
}
} | bsd-3-clause |
breuderink/psychic | psychic/expinfo.py | 2698 | import operator
from golem import DataSet
from golem.nodes import BaseNode
import numpy as np
class ExperimentInfo:
def __init__(self, ac_freq=None, amplifier=None, lab=None, subject=None,
note='', eeg_chan=[], eog_chan=[], emg_chan=[], ref_chan=[],
experiments={}):
self.ac_freq=float(ac_freq)
self.amplifier = str(amplifier)
self.lab = str(lab)
self.subject = str(subject)
self.note = str(note)
self.eeg_chan = [str(ch) for ch in eeg_chan]
self.eog_chan = [str(ch) for ch in eog_chan]
self.emg_chan = [str(ch) for ch in emg_chan]
self.ref_chan = [str(ch) for ch in ref_chan]
for (expname, exp) in experiments.items():
if not set(exp.channels).issubset(self.all_channels):
raise ValueError('%s is not in record info.' %
list(set(exp.channels).difference(self.all_channels)))
self.experiments = experiments
@property
def all_channels(self):
return self.eeg_chan + self.eog_chan + self.emg_chan + self.ref_chan
def markers(markers):
markers = dict(markers)
assert len(markers) > 0
keys = [int(k) for k in markers.keys()]
values = [str(v) for v in markers.values()]
assert all([m > 0 for m in keys])
return dict(zip(keys, values))
def interval(interval):
assert len(interval) == 2
assert interval[1] > interval[0]
return [float(o) for o in interval]
class Experiment:
def __init__(self, marker_to_class=None, trial_offset=None,
baseline_offset=None, test_folds=[], paradigm=None,
band=None, channels=[]):
self.marker_to_class = markers(marker_to_class)
self.trial_offset = interval(trial_offset)
self.baseline_offset = interval(baseline_offset) # baseline is required?
self.test_folds = [int(tf) for tf in test_folds]
self.paradigm = str(paradigm)
self.band = interval(band)
self.channels = [str(ch) for ch in channels]
def add_expinfo(exp_info, d):
'''
Add experiment info to a DataSet d, and perform some sanity checks, i.e.
checking of matching channel names.
'''
if not set(exp_info.all_channels).issubset(d.feat_lab):
raise ValueError('%s is not in record info.' %
list(set(exp_info.all_channels).difference(d.feat_lab)))
extra = {'exp_info' : exp_info}
extra.update(d.extra)
return DataSet(extra=extra, default=d)
class OnlyEEG(BaseNode):
def train_(self, d):
assert len(d.feat_shape) == 1, 'Please use before extracting trials'
eeg_chan = d.extra['exp_info']['eeg_chan']
self.keep_ii = [i for (i, ch) in enumerate(eeg_chan) if ch in eeg_chan]
def apply_(self, d):
return DataSet(X=X[self.keep_ii],
fealab=[d.fealab[i] for i in self.keep_ii], default=d)
| bsd-3-clause |
jderiz/WebApp | node_modules/rxjs/ReplaySubject.js | 3859 | "use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Subject_1 = require('./Subject');
var queue_1 = require('./scheduler/queue');
var Subscription_1 = require('./Subscription');
var observeOn_1 = require('./operator/observeOn');
var ObjectUnsubscribedError_1 = require('./util/ObjectUnsubscribedError');
var SubjectSubscription_1 = require('./SubjectSubscription');
/**
* @class ReplaySubject<T>
*/
var ReplaySubject = (function (_super) {
__extends(ReplaySubject, _super);
function ReplaySubject(bufferSize, windowTime, scheduler) {
if (bufferSize === void 0) { bufferSize = Number.POSITIVE_INFINITY; }
if (windowTime === void 0) { windowTime = Number.POSITIVE_INFINITY; }
_super.call(this);
this.scheduler = scheduler;
this._events = [];
this._bufferSize = bufferSize < 1 ? 1 : bufferSize;
this._windowTime = windowTime < 1 ? 1 : windowTime;
}
ReplaySubject.prototype.next = function (value) {
var now = this._getNow();
this._events.push(new ReplayEvent(now, value));
this._trimBufferThenGetEvents();
_super.prototype.next.call(this, value);
};
ReplaySubject.prototype._subscribe = function (subscriber) {
var _events = this._trimBufferThenGetEvents();
var scheduler = this.scheduler;
var subscription;
if (this.closed) {
throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
}
else if (this.hasError) {
subscription = Subscription_1.Subscription.EMPTY;
}
else if (this.isStopped) {
subscription = Subscription_1.Subscription.EMPTY;
}
else {
this.observers.push(subscriber);
subscription = new SubjectSubscription_1.SubjectSubscription(this, subscriber);
}
if (scheduler) {
subscriber.add(subscriber = new observeOn_1.ObserveOnSubscriber(subscriber, scheduler));
}
var len = _events.length;
for (var i = 0; i < len && !subscriber.closed; i++) {
subscriber.next(_events[i].value);
}
if (this.hasError) {
subscriber.error(this.thrownError);
}
else if (this.isStopped) {
subscriber.complete();
}
return subscription;
};
ReplaySubject.prototype._getNow = function () {
return (this.scheduler || queue_1.queue).now();
};
ReplaySubject.prototype._trimBufferThenGetEvents = function () {
var now = this._getNow();
var _bufferSize = this._bufferSize;
var _windowTime = this._windowTime;
var _events = this._events;
var eventsCount = _events.length;
var spliceCount = 0;
// Trim events that fall out of the time window.
// Start at the front of the list. Break early once
// we encounter an event that falls within the window.
while (spliceCount < eventsCount) {
if ((now - _events[spliceCount].time) < _windowTime) {
break;
}
spliceCount++;
}
if (eventsCount > _bufferSize) {
spliceCount = Math.max(spliceCount, eventsCount - _bufferSize);
}
if (spliceCount > 0) {
_events.splice(0, spliceCount);
}
return _events;
};
return ReplaySubject;
}(Subject_1.Subject));
exports.ReplaySubject = ReplaySubject;
var ReplayEvent = (function () {
function ReplayEvent(time, value) {
this.time = time;
this.value = value;
}
return ReplayEvent;
}());
//# sourceMappingURL=ReplaySubject.js.map | mit |
gaussflayer/latches.js | latches.js | 3351 | /* Copyright Eoin Groat 2015
* @author : Eoin Groat
* @url : https://eoingroat.com
* @email : iam@eoingroat.com
* @license : MIT
* @git : https://github.com/gaussflayer/latches.js
*/
var log = function() {};//console.log;
function isFunction(f) {
return typeof(f) === 'function';
}
// http://stackoverflow.com/questions/18082/validate-decimal-numbers-in-javascript-isnumeric/1830844#1830844
function isNumber(num) {
return !isNaN(parseFloat(num)) && isFinite(num);
}
function isArray(arr) {
return typeof(arr) === 'object' && Object.prototype.toString.call(arr) === '[object Array]';
}
/*
* The base latch.
*
* It starts closed
* It must be explicitly opened
* It can be explicitly closed
* functions can wait on it
* functions are ran when the latch is open
*
* new Latch([stack, [opened, [context]]][)
*/
function Latch(stack, opened, context) {
if(!(this instanceof Latch)) return new Latch(stack, opened);
var waiting = isArray(stack) ? stack.filter(isFunction) : (isFunction(stack) ? [stack] : [])
, isOpen = !!opened
, run = function(context) {
if(!isOpen) return;
if(!context) context = null;
waiting.forEach(function(el) {
el.call(context);
});
waiting = [];
}
;
this.open = function(context) {
log("opened");
isOpen = true;
run(context);
};
this.close = function() {
log("closed");
isOpen = false;
}
this.wait = function(func, context) {
if(isFunction(func)) {
log("waiting");
waiting.push(func);
run(context);
}
};
run(context);
}
/*
* CountDownLatch opens if size is 0
* hitting the latch reduces size by 1
* size cannot fall below 0
*
* new CountDownLatch(size, [stack, [context]])
*/
function CountDownLatch(size, stack) {
if(!(this instanceof CountDownLatch)) return new CountDownLatch(size, stack);
var size = isNumber(size) ? size : 0
, latch = new Latch(stack, !size)
;
log("size", size);
this.hit = function(context) {
size -= 1;
if(size > 0) {
log("hit");
} else {
latch.open(context);
}
}
this.add = function(more, context) {
var additional = isNumber(more) ? more : 0;
log("add", additional);
size += additional;
if(size <= 0) {
size = 0;
latch.open(context);
}
}
this.wait = latch.wait;
this.open = function(context) {
size = 0;
latch.open(context);
}
this.add = function(amount) {
if(isNumber(amount)) {
size += amount;
latch.close();
}
}
}
/*
* TimeoutLatch opens after a delay
*
* new TimeoutLatch(delay, [functions])
*/
function TimeoutLatch(delay, stack) {
if(!(this instanceof TimeoutLatch)) return new TimeoutLatch(delay, stack);
var latch = new Latch(stack)
, timer = (isNumber(delay) && delay >= 0) ? setTimeout(latch.open, delay) : null
;
this.open = function(context) {
clearTimeout(timer);
latch.open(context);
}
this.cancel = function(context) {
clearTimeout(timer);
}
this.set = function(newtime) {
if(isNumber(newtime) && newtime >= 0) {
clearTimeout(timer);
timer = setTimeout(latch.open, newtime);
}
}
}
module.exports = { Latch: Latch
, CountDownLatch: CountDownLatch
, TimeoutLatch: TimeoutLatch
};
| isc |
bleepbloop/Pivy | examples/Mentor/10.7.PickFilterManip.py | 6102 | #!/usr/bin/env python
###
# Copyright (c) 2002-2007 Systems in Motion
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
###
# This is an example from The Inventor Mentor,
# chapter 10, example 7.
#
# This example demonstrates the use of the pick filter
# callback to pick through manipulators.
#
# The scene graph has several objects. Clicking the left
# mouse on an object selects it and adds a manipulator to
# it. Clicking again deselects it and removes the manipulator.
# In this case, the pick filter is needed to deselect the
# object rather than select the manipulator.
#
import sys
from pivy.coin import *
from pivy.sogui import *
# Returns path to xform left of the input path tail.
# Inserts the xform if none found. In this example,
# assume that the xform is always the node preceeding
# the selected shape.
def findXform(p):
# Copy the input path up to tail's parent.
returnPath = p.copy(0, p.getLength() - 1)
# Get the parent of the selected shape
g = p.getNodeFromTail(1)
tailNodeIndex = p.getIndexFromTail(0)
# Check if there is already a transform node
if tailNodeIndex > 0:
n = g.getChild(tailNodeIndex - 1)
if n.isOfType(SoTransform.getClassTypeId()):
# Append to returnPath and return it.
returnPath.append(n)
return returnPath
# Otherwise, add a transform node.
xf = SoTransform()
g.insertChild(xf, tailNodeIndex) # right before the tail
# Append to returnPath and return it.
returnPath.append(xf)
return returnPath
# Returns the manip affecting this path. In this example,
# the manip is always preceeding the selected shape.
def findManip(p):
# Copy the input path up to tail's parent.
returnPath = p.copy(0, p.getLength() - 1)
# Get the index of the last node in the path.
tailNodeIndex = p.getIndexFromTail(0)
# Append the left sibling of the tail to the returnPath
returnPath.append(tailNodeIndex - 1)
return returnPath
# Add a manipulator to the transform affecting this path
# The first parameter, userData, is not used.
def selCB(void, path):
if path.getLength() < 2: return
# Find the transform affecting this object
xfPath = findXform(path)
# Replace the transform with a manipulator
manip = SoHandleBoxManip()
manip.replaceNode(xfPath)
# Remove the manipulator affecting this path.
# The first parameter, userData, is not used.
def deselCB(void, path):
if path.getLength() < 2: return
# Find the manipulator affecting this object
manipPath = findManip(path)
# Replace the manipulator with a transform
manip = manipPath.getTail()
manip.replaceManip(manipPath, SoTransform())
##############################################################
# CODE FOR The Inventor Mentor STARTS HERE (part 1)
def pickFilterCB(void, pick):
filteredPath = None
# See if the picked object is a manipulator.
# If so, change the path so it points to the object the manip
# is attached to.
p = pick.getPath()
n = p.getTail()
if n.isOfType(SoTransformManip.getClassTypeId()):
# Manip picked! We know the manip is attached
# to its next sibling. Set up and return that path.
manipIndex = p.getIndex(p.getLength() - 1)
filteredPath = p.copy(0, p.getLength() - 1)
filteredPath.append(manipIndex + 1) # get next sibling
else:
filteredPath = p
return filteredPath
# CODE FOR The Inventor Mentor ENDS HERE
##############################################################
# Create a sample scene graph
def myText(str, i, color):
sep = SoSeparator()
col = SoBaseColor()
xf = SoTransform()
text = SoText3()
col.rgb = color
xf.translation = (6.0 * i, 0.0, 0.0)
text.string = str
text.parts = SoText3.FRONT | SoText3.SIDES
text.justification = SoText3.CENTER
sep.addChild(col)
sep.addChild(xf)
sep.addChild(text)
return sep
def buildScene():
scene = SoSeparator()
font = SoFont()
font.size = 10
scene.addChild(font)
scene.addChild(myText("O", 0, SbColor(0, 0, 1)))
scene.addChild(myText("p", 1, SbColor(0, 1, 0)))
scene.addChild(myText("e", 2, SbColor(0, 1, 1)))
scene.addChild(myText("n", 3, SbColor(1, 0, 0)))
# Open Inventor is two words!
scene.addChild(myText("I", 5, SbColor(1, 0, 1)))
scene.addChild(myText("n", 6, SbColor(1, 1, 0)))
scene.addChild(myText("v", 7, SbColor(1, 1, 1)))
scene.addChild(myText("e", 8, SbColor(0, 0, 1)))
scene.addChild(myText("n", 9, SbColor(0, 1, 0)))
scene.addChild(myText("t", 10, SbColor(0, 1, 1)))
scene.addChild(myText("o", 11, SbColor(1, 0, 0)))
scene.addChild(myText("r", 12, SbColor(1, 0, 1)))
return scene
def main():
# Initialization
mainWindow = SoGui.init(sys.argv[0])
# Create a scene graph. Use the toggle selection policy.
sel = SoSelection()
sel.policy = SoSelection.TOGGLE
sel.addChild(buildScene())
# Create a viewer
viewer = SoGuiExaminerViewer(mainWindow)
viewer.setSceneGraph(sel)
viewer.setTitle("Select Through Manips")
viewer.show()
# Selection callbacks
sel.addSelectionCallback(selCB)
sel.addDeselectionCallback(deselCB)
sel.setPickFilterCallback(pickFilterCB)
SoGui.show(mainWindow)
SoGui.mainLoop()
if __name__ == "__main__":
main()
| isc |
breunigs/keks | db/migrate/20130228080509_add_study_path_to_users.rb | 120 | class AddStudyPathToUsers < ActiveRecord::Migration
def change
add_column :users, :study_path, :integer
end
end
| isc |
pranavraja/beanstalkify | lib/beanstalkify/archive.rb | 1572 | require 'aws-sdk'
module Beanstalkify
class Archive
attr_reader :app_name, :version
def initialize(filename)
@filename = filename
@archive_name = File.basename(@filename)
@app_name, hyphen, @version = File.basename(filename, '.*').rpartition("-")
end
def upload(beanstalk_api, s3_client=AWS::S3.new.client)
if already_uploaded?(beanstalk_api)
return puts "#{version} is already uploaded."
end
bucket = beanstalk_api.create_storage_location.data[:s3_bucket]
upload_to_s3(s3_client, bucket)
make_application_version_available_to_beanstalk(beanstalk_api, bucket)
end
private
def upload_to_s3(s3_client, bucket)
puts "Uploading #{@archive_name} to bucket #{bucket}..."
s3_client.put_object(
bucket_name: bucket,
key: @archive_name,
data: File.open(@filename)
)
end
def make_application_version_available_to_beanstalk(beanstalk_api, bucket)
puts "Making version #{version} of #{app_name} available to Beanstalk..."
beanstalk_api.create_application_version(
application_name: app_name,
version_label: version,
source_bundle: {
s3_bucket: bucket,
s3_key: @archive_name
},
auto_create_application: true
)
end
def already_uploaded?(beanstalk_api)
beanstalk_api.describe_application_versions(
application_name: app_name,
version_labels: [version]
).data[:application_versions].count > 0
end
end
end
| isc |
Monduiz/CrowdiD2 | node_modules/mapillary-js/typings/created/earcut/earcut.d.ts | 406 | declare module earcut {
interface Data {
vertices: number[];
holes: number[];
dimensions: number;
}
function flatten(data: number[][][]): Data;
function deviation(vertices: number[], holes: number[], dimensions: number, triangles: number[]): number;
}
declare function earcut(vertices: number[], holes?: number[], dimensions?: number): number[];
export = earcut;
| isc |
Rdbaker/Rank | rank/extensions.py | 433 | # -*- coding: utf-8 -*-
"""Extensions module. Each extension is initialized in the app factory located
in app.py
"""
from flask_migrate import Migrate
migrate = Migrate()
from flask_bcrypt import Bcrypt
bcrypt = Bcrypt()
from flask_login import LoginManager
login_manager = LoginManager()
from flask_cache import Cache
cache = Cache()
from flask_debugtoolbar import DebugToolbarExtension
debug_toolbar = DebugToolbarExtension()
| mit |
gerhardberger/electron | shell/browser/special_storage_policy.cc | 1109 | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "shell/browser/special_storage_policy.h"
#include "base/bind.h"
#include "base/callback.h"
namespace electron {
SpecialStoragePolicy::SpecialStoragePolicy() {}
SpecialStoragePolicy::~SpecialStoragePolicy() {}
bool SpecialStoragePolicy::IsStorageProtected(const GURL& origin) {
return true;
}
bool SpecialStoragePolicy::IsStorageUnlimited(const GURL& origin) {
return true;
}
bool SpecialStoragePolicy::IsStorageDurable(const GURL& origin) {
return true;
}
bool SpecialStoragePolicy::HasIsolatedStorage(const GURL& origin) {
return false;
}
bool SpecialStoragePolicy::IsStorageSessionOnly(const GURL& origin) {
return false;
}
bool SpecialStoragePolicy::HasSessionOnlyOrigins() {
return false;
}
network::SessionCleanupCookieStore::DeleteCookiePredicate
SpecialStoragePolicy::CreateDeleteCookieOnExitPredicate() {
return network::SessionCleanupCookieStore::DeleteCookiePredicate();
}
} // namespace electron
| mit |
duodraco/ophpen | src/vendor/symfony/src/Symfony/Bundle/FrameworkBundle/Routing/DelegatingLoader.php | 2244 | <?php
namespace Symfony\Bundle\FrameworkBundle\Routing;
use Symfony\Bundle\FrameworkBundle\Controller\ControllerNameConverter;
use Symfony\Component\Routing\Loader\DelegatingLoader as BaseDelegatingLoader;
use Symfony\Component\Routing\Loader\LoaderResolverInterface;
use Symfony\Component\HttpKernel\Log\LoggerInterface;
/*
* This file is part of the Symfony framework.
*
* (c) Fabien Potencier <fabien.potencier@symfony-project.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
/**
* DelegatingLoader delegates route loading to other loaders using a loader resolver.
*
* This implementation resolves the _controller attribute from the short notation
* to the fully-qualified form (from a:b:c to class:method).
*
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
*/
class DelegatingLoader extends BaseDelegatingLoader
{
protected $converter;
protected $logger;
/**
* Constructor.
*
* @param ControllerNameConverter $converter A ControllerNameConverter instance
* @param LoggerInterface $logger A LoggerInterface instance
* @param LoaderResolverInterface $resolver A LoaderResolverInterface instance
*/
public function __construct(ControllerNameConverter $converter, LoggerInterface $logger = null, LoaderResolverInterface $resolver)
{
$this->converter = $converter;
$this->logger = $logger;
parent::__construct($resolver);
}
/**
* Loads a resource.
*
* @param mixed $resource A resource
*
* @return RouteCollection A RouteCollection instance
*/
public function load($resource)
{
$collection = parent::load($resource);
foreach ($collection->all() as $name => $route) {
if ($controller = $route->getDefault('_controller')) {
try {
$controller = $this->converter->fromShortNotation($controller);
} catch (\Exception $e) {
// unable to optimize unknown notation
}
$route->setDefault('_controller', $controller);
}
}
return $collection;
}
}
| mit |
JumpStartGeorgia/Place-ge-Scraper | spec/models/place_ge_ad_spec.rb | 2397 | describe 'PlaceGeAd' do
let :new_place_ge_ad do
PlaceGeAdFactory.build
end
let :other_place_ge_ad do
PlaceGeAdFactory.build
end
describe 'save' do
it 'creates ad entry with correct time of scrape' do
new_saved_entry = new_place_ge_ad.save
new_saved_entry.reload
expect(new_saved_entry.time_of_scrape).to eq(new_place_ge_ad.time_of_scrape)
end
context 'when no other ads are saved in database' do
it 'creates ad_entry' do
expect do
new_place_ge_ad.save
end.to change(AdEntry, :count).by(1)
end
it 'creates new ad' do
expect do
new_place_ge_ad.save
end.to change(Ad, :count).by(1)
end
end
context 'when same place_ge_ad but with different place_ge_id is saved' do
let! :saved_entry_different_id do
other_place_ge_ad.place_ge_id
end
it 'creates new ad entry' do
expect do
new_place_ge_ad.save
end.to change(AdEntry, :count).by(1)
end
it 'creates new ad' do
expect do
new_place_ge_ad.save
end.to change(Ad, :count).by(1)
end
end
context 'when almost identical place_ge_ad but with old publication date is saved' do
let! :different_saved_entry do
other_place_ge_ad.publication_date = new_place_ge_ad.publication_date + 1
other_place_ge_ad.save
end
it 'creates new ad entry' do
expect do
new_place_ge_ad.save
end.to change(AdEntry, :count).by(1)
end
it 'does not create new ad' do
expect do
new_place_ge_ad.save
end.to change(Ad, :count).by(0)
end
end
context 'when identical place_ge_ad has already been saved' do
let! :identical_saved_entry do
other_place_ge_ad.save
end
it 'does not create ad_entry' do
expect do
new_place_ge_ad.save
end.to change(AdEntry, :count).by(0)
end
it 'does not create new ad' do
expect do
new_place_ge_ad.save
end.to change(Ad, :count).by(0)
end
it 'should update time of scrape of identical place_ge_ad' do
sleep 1
new_place_ge_ad.save
identical_saved_entry.reload
expect(identical_saved_entry.time_of_scrape).to eq(new_place_ge_ad.time_of_scrape)
end
end
end
end
| mit |
DTFE/Vimo | build/doc-builder/theme/publish.js | 21214 | /*global env: true */
'use strict'
var doop = require('jsdoc/util/doop')
var fs = require('jsdoc/fs')
var helper = require('jsdoc/util/templateHelper')
var logger = require('jsdoc/util/logger')
var path = require('jsdoc/path')
var taffy = require('taffydb').taffy
var template = require('jsdoc/template')
var util = require('util')
var htmlsafe = helper.htmlsafe
var linkto = helper.linkto
var resolveAuthorLinks = helper.resolveAuthorLinks
var scopeToPunc = helper.scopeToPunc
var hasOwnProp = Object.prototype.hasOwnProperty
var data
var view
var outdir = path.normalize(env.opts.destination)
function find (spec) {
return helper.find(data, spec)
}
function tutoriallink (tutorial) {
return helper.toTutorial(tutorial, null, {tag: 'em', classname: 'disabled', prefix: 'Tutorial: '})
}
function getAncestorLinks (doclet) {
return helper.getAncestorLinks(data, doclet)
}
function hashToLink (doclet, hash) {
if (!/^(#.+)/.test(hash)) { return hash }
var url = helper.createLink(doclet)
url = url.replace(/(#.+|$)/, hash)
return '<a href="' + url + '">' + hash + '</a>'
}
function needsSignature (doclet) {
var needsSig = false
// function and class definitions always get a signature
if (doclet.kind === 'function' || doclet.kind === 'class') {
needsSig = true
}
// typedefs that contain functions get a signature, too
else if (doclet.kind === 'typedef' && doclet.type && doclet.type.names &&
doclet.type.names.length) {
for (var i = 0, l = doclet.type.names.length; i < l; i++) {
if (doclet.type.names[i].toLowerCase() === 'function') {
needsSig = true
break
}
}
}
return needsSig
}
function getSignatureAttributes (item) {
var attributes = []
if (item.optional) {
attributes.push('opt')
}
if (item.nullable === true) {
attributes.push('nullable')
}
else if (item.nullable === false) {
attributes.push('non-null')
}
return attributes
}
function updateItemName (item) {
var attributes = getSignatureAttributes(item)
var itemName = item.name || ''
if (item.variable) {
itemName = '…' + itemName
}
if (attributes && attributes.length) {
itemName = util.format('%s<span class="signature-attributes">%s</span>', itemName,
attributes.join(', '))
}
return itemName
}
function addParamAttributes (params) {
return params.filter(function (param) {
return param.name && param.name.indexOf('.') === -1
}).map(updateItemName)
}
function buildItemTypeStrings (item) {
var types = []
if (item && item.type && item.type.names) {
item.type.names.forEach(function (name) {
types.push(linkto(name, htmlsafe(name)))
})
}
return types
}
function buildAttribsString (attribs) {
var attribsString = ''
if (attribs && attribs.length) {
attribsString = htmlsafe(util.format('(%s) ', attribs.join(', ')))
}
return attribsString
}
function addNonParamAttributes (items) {
var types = []
items.forEach(function (item) {
types = types.concat(buildItemTypeStrings(item))
})
return types
}
function addSignatureParams (f) {
var params = f.params ? addParamAttributes(f.params) : []
f.signature = util.format('%s(%s)', (f.signature || ''), params.join(', '))
}
function addSignatureReturns (f) {
var attribs = []
var attribsString = ''
var returnTypes = []
var returnTypesString = ''
// jam all the return-type attributes into an array. this could create odd results (for example,
// if there are both nullable and non-nullable return types), but let's assume that most people
// who use multiple @return tags aren't using Closure Compiler type annotations, and vice-versa.
if (f.returns) {
f.returns.forEach(function (item) {
helper.getAttribs(item).forEach(function (attrib) {
if (attribs.indexOf(attrib) === -1) {
attribs.push(attrib)
}
})
})
attribsString = buildAttribsString(attribs)
}
if (f.returns) {
returnTypes = addNonParamAttributes(f.returns)
}
if (returnTypes.length) {
returnTypesString = util.format(' → %s{%s}', attribsString, returnTypes.join('|'))
}
f.signature = '<span class="signature">' + (f.signature || '') + '</span>' +
'<span class="type-signature">' + returnTypesString + '</span>'
}
function addSignatureTypes (f) {
var types = f.type ? buildItemTypeStrings(f) : []
f.signature = (f.signature || '') + '<span class="type-signature">' +
(types.length ? ' :' + types.join('|') : '') + '</span>'
}
function addAttribs (f) {
var attribs = helper.getAttribs(f)
var attribsString = buildAttribsString(attribs)
f.attribs = util.format('<span class="type-signature">%s</span>', attribsString)
}
function shortenPaths (files, commonPrefix) {
Object.keys(files).forEach(function (file) {
files[file].shortened = files[file].resolved.replace(commonPrefix, '')
// always use forward slashes
.replace(/\\/g, '/')
})
return files
}
function getPathFromDoclet (doclet) {
if (!doclet.meta) {
return null
}
return doclet.meta.path && doclet.meta.path !== 'null' ? path.join(doclet.meta.path, doclet.meta.filename) : doclet.meta.filename
}
function generate (type, title, docs, filename, resolveLinks) {
resolveLinks = resolveLinks === false ? false : true
var docData = {
type: type,
title: title,
docs: docs
}
var outpath = path.join(outdir, filename),
html = view.render('container.tmpl', docData)
if (resolveLinks) {
html = helper.resolveLinks(html) // turn {@link foo} into <a href="foodoc.html">foo</a>
}
fs.writeFileSync(outpath, html, 'utf8')
}
function generateSourceFiles (sourceFiles, encoding) {
encoding = encoding || 'utf8'
Object.keys(sourceFiles).forEach(function (file) {
var source
// links are keyed to the shortened path in each doclet's `meta.shortpath` property
var sourceOutfile = helper.getUniqueFilename(sourceFiles[file].shortened)
helper.registerLink(sourceFiles[file].shortened, sourceOutfile)
try {
source = {
kind: 'source',
code: helper.htmlsafe(fs.readFileSync(sourceFiles[file].resolved, encoding))
}
}
catch (e) {
logger.error('Error while generating source file %s: %s', file, e.message)
}
generate('Source', sourceFiles[file].shortened, [source], sourceOutfile, false)
})
}
/**
* Look for classes or functions with the same name as modules (which indicates that the module
* exports only that class or function), then attach the classes or functions to the `module`
* property of the appropriate module doclets. The name of each class or function is also updated
* for display purposes. This function mutates the original arrays.
*
* @private
* @param {Array.<module:jsdoc/doclet.Doclet>} doclets - The array of classes and functions to
* check.
* @param {Array.<module:jsdoc/doclet.Doclet>} modules - The array of module doclets to search.
*/
function attachModuleSymbols (doclets, modules) {
var symbols = {}
// build a lookup table
doclets.forEach(function (symbol) {
symbols[symbol.longname] = symbols[symbol.longname] || []
symbols[symbol.longname].push(symbol)
})
return modules.map(function (module) {
if (symbols[module.longname]) {
module.modules = symbols[module.longname]
// Only show symbols that have a description. Make an exception for classes, because
// we want to show the constructor-signature heading no matter what.
.filter(function (symbol) {
return symbol.description || symbol.kind === 'class'
})
.map(function (symbol) {
symbol = doop(symbol)
if (symbol.kind === 'class' || symbol.kind === 'function') {
symbol.name = symbol.name.replace('module:', '(require("') + '"))'
symbol.name = symbol.name.replace('component:', '(require("') + '"))'
}
return symbol
})
}
})
}
function buildMemberNav (items, itemHeading, itemsSeen, linktoFn) {
var nav = ''
if (items && items.length) {
var itemsNav = ''
items.forEach(function (item) {
var methods = find({kind: 'function', memberof: item.longname})
var members = find({kind: 'member', memberof: item.longname})
var docdash = env && env.conf && env.conf.docdash || {}
if (!hasOwnProp.call(item, 'longname')) {
itemsNav += '<li>' + linktoFn('', item.name)
itemsNav += '</li>'
} else if (!hasOwnProp.call(itemsSeen, item.longname)) {
itemsNav += '<li>' + linktoFn(item.longname, item.name.replace(/^module:/, ''))
if (docdash.static && members.find(function (m) { return m.scope === 'static' })) {
itemsNav += '<ul class=\'members\'>'
members.forEach(function (member) {
if (!member.scope === 'static') return
itemsNav += '<li data-type=\'member\'>'
itemsNav += linkto(member.longname, member.name)
itemsNav += '</li>'
})
itemsNav += '</ul>'
}
if (methods.length) {
itemsNav += '<ul class=\'methods\'>'
methods.forEach(function (method) {
itemsNav += '<li data-type=\'method\'>'
itemsNav += linkto(method.longname, method.name)
itemsNav += '</li>'
})
itemsNav += '</ul>'
}
itemsNav += '</li>'
itemsSeen[item.longname] = true
}
})
if (itemsNav !== '') {
nav += '<h3>' + itemHeading + '</h3><ul>' + itemsNav + '</ul>'
}
}
return nav
}
function linktoTutorial (longName, name) {
return tutoriallink(name)
}
function linktoExternal (longName, name) {
return linkto(longName, name.replace(/(^"|"$)/g, ''))
}
/**
* Create the navigation sidebar.
* @param {object} members The members that will be used to create the sidebar.
* @param {array<object>} members.classes
* @param {array<object>} members.externals
* @param {array<object>} members.globals
* @param {array<object>} members.mixins
* @param {array<object>} members.modules
* @param {array<object>} members.components
* @param {array<object>} members.namespaces
* @param {array<object>} members.tutorials
* @param {array<object>} members.events
* @param {array<object>} members.interfaces
* @return {string} The HTML for the navigation sidebar.
*/
function buildNav (members, docdash) {
var nav = '<section class="nav__header">'
var homeName = docdash.homeName || 'Home'
nav += '<h2><a href="index.html">' + homeName + '</a></h2>'
if (docdash.demoUrl) {
nav += '<h2><a href="' + docdash.demoUrl + '">示例 / Demo</a></h2>'
}
if (docdash.links && docdash.links.length > 0) {
docdash.links.forEach(function (linkInfo) {
nav += '<h2><a href="' + linkInfo.link + '">' + linkInfo.name + '</a></h2>'
})
}
nav += '</section>'
var seen = {}
var seenTutorials = {}
// component和module是一个概念但是不一样的叫法
var component = []
var module = []
members.modules.forEach((item) => {
if (item.trueKind === 'component') {
component.push(item)
} else {
module.push(item)
}
})
nav += buildMemberNav(component, '组件 / Components', {}, linkto)
nav += buildMemberNav(members.classes, '类 / Classes', seen, linkto)
nav += buildMemberNav(module, '模块 / Modules', {}, linkto)
// nav += buildMemberNav(members.externals, '外部依赖 / Externals', seen, linktoExternal)
// nav += buildMemberNav(members.events, '事件 / Events', seen, linkto)
// nav += buildMemberNav(members.namespaces, '命名空间 / Namespaces', seen, linkto)
// nav += buildMemberNav(members.mixins, '混合 / Mixins', seen, linkto)
nav += buildMemberNav(members.tutorials, '教程 / Tutorials', seenTutorials, linktoTutorial)
// nav += buildMemberNav(members.interfaces, '接口 / Interfaces', seen, linkto)
if (members.globals.length) {
var globalNav = ''
members.globals.forEach(function (g) {
if (g.kind !== 'typedef' && !hasOwnProp.call(seen, g.longname)) {
globalNav += '<li>' + linkto(g.longname, g.name) + '</li>'
}
seen[g.longname] = true
})
if (!globalNav) {
// turn the heading into a link so you can actually get to the global page
nav += '<h3>' + linkto('global', 'Global') + '</h3>'
} else {
nav += '<h3>Global</h3><ul>' + globalNav + '</ul>'
}
}
return nav
}
/**
@param {TAFFY} taffyData See <http://taffydb.com/>.
@param {object} opts
@param {Tutorial} tutorials
*/
exports.publish = function (taffyData, opts, tutorials) {
var docdash = env && env.conf && env.conf.docdash || {}
data = taffyData
var conf = env.conf.templates || {}
conf.default = conf.default || {}
var templatePath = path.normalize(opts.template)
view = new template.Template(path.join(templatePath, 'tmpl'))
// claim some special filenames in advance, so the All-Powerful Overseer of Filename Uniqueness
// doesn't try to hand them out later
var indexUrl = helper.getUniqueFilename('index')
// don't call registerLink() on this one! 'index' is also a valid longname
var globalUrl = helper.getUniqueFilename('global')
helper.registerLink('global', globalUrl)
// set up templating
view.layout = conf.default.layoutFile ? path.getResourcePath(path.dirname(conf.default.layoutFile),
path.basename(conf.default.layoutFile)) : 'layout.tmpl'
// set up tutorials for helper
helper.setTutorials(tutorials)
data = helper.prune(data)
docdash.sort !== false && data.sort('longname, version, since')
helper.addEventListeners(data)
var sourceFiles = {}
var sourceFilePaths = []
data().each(function (doclet) {
doclet.attribs = ''
if (doclet.examples) {
doclet.examples = doclet.examples.map(function (example) {
var caption, code
if (!!example && example.match(/^\s*<caption>([\s\S]+?)<\/caption>(\s*[\n\r])([\s\S]+)$/i)) {
caption = RegExp.$1
code = RegExp.$3
}
return {
caption: caption || '',
code: code || example
}
})
}
if (doclet.see) {
doclet.see.forEach(function (seeItem, i) {
doclet.see[i] = hashToLink(doclet, seeItem)
})
}
// build a list of source files
var sourcePath
if (doclet.meta) {
sourcePath = getPathFromDoclet(doclet)
sourceFiles[sourcePath] = {
resolved: sourcePath,
shortened: null
}
if (sourceFilePaths.indexOf(sourcePath) === -1) {
sourceFilePaths.push(sourcePath)
}
}
})
// update outdir if necessary, then create outdir
var packageInfo = ( find({kind: 'package'}) || [] ) [0]
if (packageInfo && packageInfo.name) {
outdir = path.join(outdir, packageInfo.name, (packageInfo.version || ''))
}
fs.mkPath(outdir)
// copy the template's static files to outdir
var fromDir = path.join(templatePath, 'static')
var staticFiles = fs.ls(fromDir, 3)
staticFiles.forEach(function (fileName) {
var toDir = fs.toDir(fileName.replace(fromDir, outdir))
fs.mkPath(toDir)
fs.copyFileSync(fileName, toDir)
})
// copy user-specified static files to outdir
var staticFilePaths
var staticFileFilter
var staticFileScanner
if (conf.default.staticFiles) {
// The canonical property name is `include`. We accept `paths` for backwards compatibility
// with a bug in JSDoc 3.2.x.
staticFilePaths = conf.default.staticFiles.include ||
conf.default.staticFiles.paths ||
[]
staticFileFilter = new (require('jsdoc/src/filter')).Filter(conf.default.staticFiles)
staticFileScanner = new (require('jsdoc/src/scanner')).Scanner()
staticFilePaths.forEach(function (filePath) {
var extraStaticFiles = staticFileScanner.scan([filePath], 10, staticFileFilter)
extraStaticFiles.forEach(function (fileName) {
var sourcePath = fs.toDir(filePath)
var toDir = fs.toDir(fileName.replace(sourcePath, outdir))
fs.mkPath(toDir)
fs.copyFileSync(fileName, toDir)
})
})
}
if (sourceFilePaths.length) {
sourceFiles = shortenPaths(sourceFiles, path.commonPrefix(sourceFilePaths))
}
data().each(function (doclet) {
var url = helper.createLink(doclet)
helper.registerLink(doclet.longname, url)
// add a shortened version of the full path
var docletPath
if (doclet.meta) {
docletPath = getPathFromDoclet(doclet)
docletPath = sourceFiles[docletPath].shortened
if (docletPath) {
doclet.meta.shortpath = docletPath
}
}
})
data().each(function (doclet) {
var url = helper.longnameToUrl[doclet.longname]
if (url.indexOf('#') > -1) {
doclet.id = helper.longnameToUrl[doclet.longname].split(/#/).pop()
}
else {
doclet.id = doclet.name
}
if (needsSignature(doclet)) {
addSignatureParams(doclet)
addSignatureReturns(doclet)
addAttribs(doclet)
}
})
// do this after the urls have all been generated
data().each(function (doclet) {
doclet.ancestors = getAncestorLinks(doclet)
if (doclet.kind === 'member') {
addSignatureTypes(doclet)
addAttribs(doclet)
}
if (doclet.kind === 'constant') {
addSignatureTypes(doclet)
addAttribs(doclet)
doclet.kind = 'member'
}
})
var members = helper.getMembers(data)
members.tutorials = tutorials.children
// console.log('-----data-----')
// console.log(data().get())
// output pretty-printed source files by default
var outputSourceFiles = conf.default && conf.default.outputSourceFiles !== false
? true
: false
// add template helpers
view.find = find
view.linkto = linkto
view.resolveAuthorLinks = resolveAuthorLinks
view.tutoriallink = tutoriallink
view.htmlsafe = htmlsafe
view.outputSourceFiles = outputSourceFiles
// once for all
view.nav = buildNav(members, docdash)
attachModuleSymbols(find({longname: {left: 'module:'}}), members.modules)
// generate the pretty-printed source files first so other pages can link to them
if (outputSourceFiles) {
generateSourceFiles(sourceFiles, opts.encoding)
}
if (members.globals.length) {
generate('', 'Global', [{kind: 'globalobj'}], globalUrl)
}
// index page displays information from package.json and lists files
var files = find({kind: 'file'})
var packages = find({kind: 'package'})
generate('', 'Home',
packages.concat(
[{kind: 'mainpage', readme: opts.readme, longname: (opts.mainpagetitle) ? opts.mainpagetitle : 'Main Page'}]
).concat(files),
indexUrl)
// set up the lists that we'll use to generate pages
var classes = taffy(members.classes)
var modules = taffy(members.modules)
var namespaces = taffy(members.namespaces)
var mixins = taffy(members.mixins)
var externals = taffy(members.externals)
var interfaces = taffy(members.interfaces)
Object.keys(helper.longnameToUrl).forEach(function (longname) {
var myModules = helper.find(modules, {longname: longname})
if (myModules.length) {
if (myModules[0].trueKind === 'component') {
generate('Component', myModules[0].name, myModules, helper.longnameToUrl[longname])
} else {
generate('Module', myModules[0].name, myModules, helper.longnameToUrl[longname])
}
}
var myClasses = helper.find(classes, {longname: longname})
if (myClasses.length) {
generate('Class', myClasses[0].name, myClasses, helper.longnameToUrl[longname])
}
var myNamespaces = helper.find(namespaces, {longname: longname})
if (myNamespaces.length) {
generate('Namespace', myNamespaces[0].name, myNamespaces, helper.longnameToUrl[longname])
}
var myMixins = helper.find(mixins, {longname: longname})
if (myMixins.length) {
generate('Mixin', myMixins[0].name, myMixins, helper.longnameToUrl[longname])
}
var myExternals = helper.find(externals, {longname: longname})
if (myExternals.length) {
generate('External', myExternals[0].name, myExternals, helper.longnameToUrl[longname])
}
var myInterfaces = helper.find(interfaces, {longname: longname})
if (myInterfaces.length) {
generate('Interface', myInterfaces[0].name, myInterfaces, helper.longnameToUrl[longname])
}
})
// TODO: move the tutorial functions to templateHelper.js
function generateTutorial (title, tutorial, filename) {
var tutorialData = {
title: title,
header: tutorial.title,
content: tutorial.parse(),
children: tutorial.children
}
var tutorialPath = path.join(outdir, filename)
var html = view.render('tutorial.tmpl', tutorialData)
// yes, you can use {@link} in tutorials too!
html = helper.resolveLinks(html) // turn {@link foo} into <a href="foodoc.html">foo</a>
fs.writeFileSync(tutorialPath, html, 'utf8')
}
// tutorials can have only one parent so there is no risk for loops
function saveChildren (node) {
node.children.forEach(function (child) {
generateTutorial('Tutorial: ' + child.title, child, helper.tutorialToUrl(child.name))
saveChildren(child)
})
}
saveChildren(tutorials)
}
| mit |
jmks/rubocop | lib/rubocop/cop/style/trailing_method_end_statement.rb | 1475 | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# This cop checks for trailing code after the method definition.
#
# @example
# # bad
# def some_method
# do_stuff; end
#
# def do_this(x)
# baz.map { |b| b.this(x) } end
#
# def foo
# block do
# bar
# end end
#
# # good
# def some_method
# do_stuff
# end
#
# def do_this(x)
# baz.map { |b| b.this(x) }
# end
#
# def foo
# block do
# bar
# end
# end
#
class TrailingMethodEndStatement < Base
extend AutoCorrector
MSG = 'Place the end statement of a multi-line method on ' \
'its own line.'
def on_def(node)
return unless trailing_end?(node)
add_offense(node.loc.end) do |corrector|
corrector.insert_before(
node.loc.end,
"\n#{' ' * node.loc.keyword.column}"
)
end
end
private
def trailing_end?(node)
node.body &&
node.multiline? &&
body_and_end_on_same_line?(node)
end
def body_and_end_on_same_line?(node)
last_child = node.children.last
last_child.loc.last_line == node.loc.end.last_line
end
end
end
end
end
| mit |
navalev/azure-sdk-for-java | sdk/appservice/mgmt-v2016_08_01/src/main/java/com/microsoft/azure/management/appservice/v2016_08_01/implementation/CsmUsageQuotaInner.java | 3479 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.appservice.v2016_08_01.implementation;
import org.joda.time.DateTime;
import com.microsoft.azure.management.appservice.v2016_08_01.LocalizableString;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Usage of the quota resource.
*/
public class CsmUsageQuotaInner {
/**
* Units of measurement for the quota resource.
*/
@JsonProperty(value = "unit")
private String unit;
/**
* Next reset time for the resource counter.
*/
@JsonProperty(value = "nextResetTime")
private DateTime nextResetTime;
/**
* The current value of the resource counter.
*/
@JsonProperty(value = "currentValue")
private Long currentValue;
/**
* The resource limit.
*/
@JsonProperty(value = "limit")
private Long limit;
/**
* Quota name.
*/
@JsonProperty(value = "name")
private LocalizableString name;
/**
* Get units of measurement for the quota resource.
*
* @return the unit value
*/
public String unit() {
return this.unit;
}
/**
* Set units of measurement for the quota resource.
*
* @param unit the unit value to set
* @return the CsmUsageQuotaInner object itself.
*/
public CsmUsageQuotaInner withUnit(String unit) {
this.unit = unit;
return this;
}
/**
* Get next reset time for the resource counter.
*
* @return the nextResetTime value
*/
public DateTime nextResetTime() {
return this.nextResetTime;
}
/**
* Set next reset time for the resource counter.
*
* @param nextResetTime the nextResetTime value to set
* @return the CsmUsageQuotaInner object itself.
*/
public CsmUsageQuotaInner withNextResetTime(DateTime nextResetTime) {
this.nextResetTime = nextResetTime;
return this;
}
/**
* Get the current value of the resource counter.
*
* @return the currentValue value
*/
public Long currentValue() {
return this.currentValue;
}
/**
* Set the current value of the resource counter.
*
* @param currentValue the currentValue value to set
* @return the CsmUsageQuotaInner object itself.
*/
public CsmUsageQuotaInner withCurrentValue(Long currentValue) {
this.currentValue = currentValue;
return this;
}
/**
* Get the resource limit.
*
* @return the limit value
*/
public Long limit() {
return this.limit;
}
/**
* Set the resource limit.
*
* @param limit the limit value to set
* @return the CsmUsageQuotaInner object itself.
*/
public CsmUsageQuotaInner withLimit(Long limit) {
this.limit = limit;
return this;
}
/**
* Get quota name.
*
* @return the name value
*/
public LocalizableString name() {
return this.name;
}
/**
* Set quota name.
*
* @param name the name value to set
* @return the CsmUsageQuotaInner object itself.
*/
public CsmUsageQuotaInner withName(LocalizableString name) {
this.name = name;
return this;
}
}
| mit |
stttexmaco/sisfoakademik | install.hps/language/persian/install_lang.php | 4825 | <?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/*
Copyright (c) 2011 Lonnie Ezell
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
$lang['in_intro'] = '<h2>خوش آمديد</h2><p>به پروسه نصب بن فاير خوش آمديد! فيلد هاي زير را پر کرده و سپس مي توانيد به ايجاد برنامه هاي تحت وب توسط CodeIgniter 2.0 بپردازيد.</p>';
$lang['in_not_writeable_heading'] = 'فايل ها/پوشه ها قابل نوشتن نمي باشند';
$lang['in_writeable_directories_message'] = 'لطفا اطمینان حاصل کنید که پوشه های زیر قابل نوشتن می باشند و دوباره تلاش کنید';
$lang['in_writeable_files_message'] = 'لطفا اطمینان حاصل کنید که فایل های زیر قابل نوشتن می باشند و دوباره تلاش کنید';
$lang['in_db_settings'] = 'تنظيمات پايگاه داده';
$lang['in_db_settings_note'] = '<p>لطفا اطلاعات پايگاه داده را وارد نماييد.</p><p class="small">اين اطلاعات در فايل کانفيگ اصلي و <b>config/database.php</b> و <b>config/development/database.php</b> ذخيره خواهند شد. </p>';
$lang['in_db_no_connect'] = 'عدم توانایی در وصل شدن به سرور بانک اطلاعاتی ، لطفا دقت کنید که اطلاعات را بدرستی وارد کرده باشید';
$lang['in_db_setup_error'] = 'خطا در راه اندازی بانک اطلاعاتی ';
$lang['in_db_settings_error'] = 'There was an error inserting settings into the database';
$lang['in_db_account_error'] = 'There was an error creating your account in the database';
$lang['in_settings_save_error'] = 'There was an error saving the settings. Please verify that your database and %s/database config files are writeable.';
$lang['in_environment'] = 'محيط';
$lang['in_host'] = 'ميزبان';
$lang['in_database'] = 'پايگاه داده';
$lang['in_prefix'] = 'پيشوند';
$lang['in_test_db'] = 'آزمايش پايگاه داده';
$lang['in_account_heading'] = '<h2>اطلاعات مورد نياز</h2><p>لطفا اطلاعات مورد نياز زير را وارد نماييد.</p>';
$lang['in_site_title'] = 'عنوان سايت';
$lang['in_username'] = 'نام کاربری';
$lang['in_password'] = 'رمز عبور';
$lang['in_password_note'] = 'حد اقل 8 کاراکتر.';
$lang['in_password_again'] = 'تکرار کلمه ي عبور';
$lang['in_email'] = 'ايميل شما';
$lang['in_email_note'] = 'لطفا ايميل خود را قبل از ادامه بررسي کنيد.';
$lang['in_install_button'] = 'نصب بنفاير';
$lang['in_curl_disabled'] = '<p class="error">cURL <strong>يافت نشد</strong>.بنفاير تا قبل از اين که اين افزونه فعال شود قادر به بررسي به روز رساني ها نخواهد بود.</p>';
$lang['in_success_notification'] = 'You are good to go! Happy coding!';
$lang['in_success_msg'] = 'لطفا پوشه ي نصب را حذف کرده و بازگرديد به ';
$lang['no_migrations_found'] = 'هيچ فايل ارتقايي يافت نشد';
$lang['multiple_migrations_version'] = 'نسخه ي تکراري براي فايل ارتقا: %d';
$lang['multiple_migrations_name'] = 'نام تکراري براي فايل ارتقا: %s';
$lang['migration_class_doesnt_exist'] = 'کلاس فايل ارتقا يافت نشد: %s';
$lang['wrong_migration_interface'] = 'اينترفيس نا معتبر براي فايل ارتقا: %s';
$lang['invalid_migration_filename'] = 'فايل ارتفاي نا معتبر: %s - %s'; | mit |
SuperGlueFx/SuperGlue | src/SuperGlue.Web.Security/DefaultCookieEncryptionHandler.cs | 1896 | using System;
using System.Collections.Generic;
using System.Web;
namespace SuperGlue.Web.Security
{
public class DefaultCookieEncryptionHandler : IHandleEncryptedCookies
{
private readonly IEncryptionService _encryptionService;
private readonly IDictionary<string, object> _environment;
public DefaultCookieEncryptionHandler(IEncryptionService encryptionService, IDictionary<string, object> environment)
{
_encryptionService = encryptionService;
_environment = environment;
}
public void Write(string name, string information, DateTime? expires = null, bool secure = false, bool httpOnly = false, string path = "/", string domain = null)
{
if (string.IsNullOrEmpty(name))
return;
var salt = _environment.GetRequest().Uri.DnsSafeHost;
_environment.GetResponse().Cookies.Append(name, HttpUtility.UrlEncode(_encryptionService.Encrypt(information, salt)),
new WebEnvironmentExtensions.CookieOptions
{
Expires = expires,
Secure = secure,
Path = path,
HttpOnly = httpOnly,
Domain = domain
});
}
public string Read(string name)
{
var cookie = _environment.GetRequest().Cookies[name];
if (string.IsNullOrEmpty(cookie))
return null;
var salt = _environment.GetRequest().Uri.DnsSafeHost;
return _encryptionService.Decrypt(HttpUtility.UrlDecode(cookie), salt);
}
public void Remove(string name)
{
_environment.GetResponse().Cookies.Append(name, "", new WebEnvironmentExtensions.CookieOptions
{
Expires = DateTime.MinValue
});
}
}
} | mit |
treehouselabs/TreeHouseIoBundle | src/TreeHouse/IoBundle/Import/Event/ExceptionEvent.php | 806 | <?php
namespace TreeHouse\IoBundle\Import\Event;
use Symfony\Component\EventDispatcher\Event;
use TreeHouse\IoBundle\Import\Importer\Importer;
class ExceptionEvent extends Event
{
/**
* @var Importer
*/
protected $importer;
/**
* @var \Exception
*/
protected $exception;
/**
* @param Importer $importer
* @param \Exception $exception
*/
public function __construct(Importer $importer, \Exception $exception)
{
$this->importer = $importer;
$this->exception = $exception;
}
/**
* @return Importer
*/
public function getImporter()
{
return $this->importer;
}
/**
* @return \Exception
*/
public function getException()
{
return $this->exception;
}
}
| mit |
cez81/gitea | modules/validation/binding.go | 3634 | // Copyright 2017 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package validation
import (
"fmt"
"regexp"
"strings"
"gitea.com/go-chi/binding"
"github.com/gobwas/glob"
)
const (
// ErrGitRefName is git reference name error
ErrGitRefName = "GitRefNameError"
// ErrGlobPattern is returned when glob pattern is invalid
ErrGlobPattern = "GlobPattern"
)
var (
// GitRefNamePatternInvalid is regular expression with unallowed characters in git reference name
// They cannot have ASCII control characters (i.e. bytes whose values are lower than \040, or \177 DEL), space, tilde ~, caret ^, or colon : anywhere.
// They cannot have question-mark ?, asterisk *, or open bracket [ anywhere
GitRefNamePatternInvalid = regexp.MustCompile(`[\000-\037\177 \\~^:?*[]+`)
)
// CheckGitRefAdditionalRulesValid check name is valid on additional rules
func CheckGitRefAdditionalRulesValid(name string) bool {
// Additional rules as described at https://www.kernel.org/pub/software/scm/git/docs/git-check-ref-format.html
if strings.HasPrefix(name, "/") || strings.HasSuffix(name, "/") ||
strings.HasSuffix(name, ".") || strings.Contains(name, "..") ||
strings.Contains(name, "//") || strings.Contains(name, "@{") ||
name == "@" {
return false
}
parts := strings.Split(name, "/")
for _, part := range parts {
if strings.HasSuffix(part, ".lock") || strings.HasPrefix(part, ".") {
return false
}
}
return true
}
// AddBindingRules adds additional binding rules
func AddBindingRules() {
addGitRefNameBindingRule()
addValidURLBindingRule()
addGlobPatternRule()
}
func addGitRefNameBindingRule() {
// Git refname validation rule
binding.AddRule(&binding.Rule{
IsMatch: func(rule string) bool {
return strings.HasPrefix(rule, "GitRefName")
},
IsValid: func(errs binding.Errors, name string, val interface{}) (bool, binding.Errors) {
str := fmt.Sprintf("%v", val)
if GitRefNamePatternInvalid.MatchString(str) {
errs.Add([]string{name}, ErrGitRefName, "GitRefName")
return false, errs
}
if !CheckGitRefAdditionalRulesValid(str) {
errs.Add([]string{name}, ErrGitRefName, "GitRefName")
return false, errs
}
return true, errs
},
})
}
func addValidURLBindingRule() {
// URL validation rule
binding.AddRule(&binding.Rule{
IsMatch: func(rule string) bool {
return strings.HasPrefix(rule, "ValidUrl")
},
IsValid: func(errs binding.Errors, name string, val interface{}) (bool, binding.Errors) {
str := fmt.Sprintf("%v", val)
if len(str) != 0 && !IsValidURL(str) {
errs.Add([]string{name}, binding.ERR_URL, "Url")
return false, errs
}
return true, errs
},
})
}
func addGlobPatternRule() {
binding.AddRule(&binding.Rule{
IsMatch: func(rule string) bool {
return rule == "GlobPattern"
},
IsValid: func(errs binding.Errors, name string, val interface{}) (bool, binding.Errors) {
str := fmt.Sprintf("%v", val)
if len(str) != 0 {
if _, err := glob.Compile(str); err != nil {
errs.Add([]string{name}, ErrGlobPattern, err.Error())
return false, errs
}
}
return true, errs
},
})
}
func portOnly(hostport string) string {
colon := strings.IndexByte(hostport, ':')
if colon == -1 {
return ""
}
if i := strings.Index(hostport, "]:"); i != -1 {
return hostport[i+len("]:"):]
}
if strings.Contains(hostport, "]") {
return ""
}
return hostport[colon+len(":"):]
}
func validPort(p string) bool {
for _, r := range []byte(p) {
if r < '0' || r > '9' {
return false
}
}
return true
}
| mit |
shyTNT/BingAds-Java-SDK | proxies/com/microsoft/bingads/campaignmanagement/GetAdExtensionsEditorialReasonsResponse.java | 1895 |
package com.microsoft.bingads.campaignmanagement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="EditorialReasons" type="{https://bingads.microsoft.com/CampaignManagement/v9}ArrayOfAdExtensionEditorialReasonCollection" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"editorialReasons"
})
@XmlRootElement(name = "GetAdExtensionsEditorialReasonsResponse")
public class GetAdExtensionsEditorialReasonsResponse {
@XmlElement(name = "EditorialReasons", nillable = true)
protected ArrayOfAdExtensionEditorialReasonCollection editorialReasons;
/**
* Gets the value of the editorialReasons property.
*
* @return
* possible object is
* {@link ArrayOfAdExtensionEditorialReasonCollection }
*
*/
public ArrayOfAdExtensionEditorialReasonCollection getEditorialReasons() {
return editorialReasons;
}
/**
* Sets the value of the editorialReasons property.
*
* @param value
* allowed object is
* {@link ArrayOfAdExtensionEditorialReasonCollection }
*
*/
public void setEditorialReasons(ArrayOfAdExtensionEditorialReasonCollection value) {
this.editorialReasons = value;
}
}
| mit |
TheManwithskills/Inferno | chat-plugins/sfsc.js | 1131 | var fs = require('fs');
var selectors;
function writeIconCSS() {
fs.appendFile('config/custom.css', selectors);
}
exports.commands = {
sfsc: function (target, room, user) {
if (!this.can('eval'));
var args = target.split(',');
if (args.length < 3) return this.parse('/help seticon');
var username = toId(args.shift());
var image = 'color:' + args.shift().trim() + ';';
selectors = '\n\n' + ' #' + toId(args.shift()) + '-userlist-user-' + username + ' em.group';
args.forEach(function (room) {
selectors += ', #' + toId(room) + '-userlist-user-'+ username + ' em.group';
});
selectors += ' { \n' + ' ' + image + '\n }';
this.privateModCommand("(" + user.name + " has set an symbol color to " + username + ")");
writeIconCSS();
},
seticonhelp: ["/sfis [username], [image], [room 1], [room 2], etc. - Sets an icon to a user in chosen rooms. Credits goes to Master Float in this."]
};
| mit |
wawaeasybuy/jobandroid | Job/android-async-http/src/main/java/com/loopj/android/http/SimpleMultipartEntity.java | 9941 | /*
Android Asynchronous Http Client
Copyright (c) 2011 James Smith <james@loopj.com>
http://loopj.com
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.
*/
/*
This code is taken from Rafael Sanches' blog.
http://blog.rafaelsanches.com/2011/01/29/upload-using-multipart-post-using-httpclient-in-android/
*/
package com.loopj.android.http;
import android.text.TextUtils;
import android.util.Log;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* Simplified multipart entity mainly used for sending one or more files.
*/
class SimpleMultipartEntity implements HttpEntity {
private static final String LOG_TAG = "SimpleMultipartEntity";
private static final String STR_CR_LF = "\r\n";
private static final byte[] CR_LF = STR_CR_LF.getBytes();
private static final byte[] TRANSFER_ENCODING_BINARY =
("Content-Transfer-Encoding: binary" + STR_CR_LF).getBytes();
private final static char[] MULTIPART_CHARS =
"-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
private final String boundary;
private final byte[] boundaryLine;
private final byte[] boundaryEnd;
private boolean isRepeatable;
private final List<FilePart> fileParts = new ArrayList<FilePart>();
// The buffer we use for building the message excluding files and the last
// boundary
private final ByteArrayOutputStream out = new ByteArrayOutputStream();
private final ResponseHandlerInterface progressHandler;
private long bytesWritten;
private long totalSize;
public SimpleMultipartEntity(ResponseHandlerInterface progressHandler) {
final StringBuilder buf = new StringBuilder();
final Random rand = new Random();
for (int i = 0; i < 30; i++) {
buf.append(MULTIPART_CHARS[rand.nextInt(MULTIPART_CHARS.length)]);
}
boundary = buf.toString();
boundaryLine = ("--" + boundary + STR_CR_LF).getBytes();
boundaryEnd = ("--" + boundary + "--" + STR_CR_LF).getBytes();
this.progressHandler = progressHandler;
}
public void addPart(String key, String value, String contentType) {
try {
out.write(boundaryLine);
out.write(createContentDisposition(key));
out.write(createContentType(contentType));
out.write(CR_LF);
out.write(value.getBytes());
out.write(CR_LF);
} catch (final IOException e) {
// Shall not happen on ByteArrayOutputStream
Log.e(LOG_TAG, "addPart ByteArrayOutputStream exception", e);
}
}
public void addPartWithCharset(String key, String value, String charset) {
if (charset == null) charset = HTTP.UTF_8;
addPart(key, value, "text/plain; charset=" + charset);
}
public void addPart(String key, String value) {
addPartWithCharset(key, value, null);
}
public void addPart(String key, File file) {
addPart(key, file, null);
}
public void addPart(String key, File file, String type) {
fileParts.add(new FilePart(key, file, normalizeContentType(type)));
}
public void addPart(String key, File file, String type, String customFileName) {
fileParts.add(new FilePart(key, file, normalizeContentType(type), customFileName));
}
public void addPart(String key, String streamName, InputStream inputStream, String type)
throws IOException {
out.write(boundaryLine);
// Headers
out.write(createContentDisposition(key, streamName));
out.write(createContentType(type));
out.write(TRANSFER_ENCODING_BINARY);
out.write(CR_LF);
// Stream (file)
final byte[] tmp = new byte[4096];
int l;
while ((l = inputStream.read(tmp)) != -1) {
out.write(tmp, 0, l);
}
out.write(CR_LF);
out.flush();
AsyncHttpClient.silentCloseOutputStream(out);
}
private String normalizeContentType(String type) {
return type == null ? RequestParams.APPLICATION_OCTET_STREAM : type;
}
private byte[] createContentType(String type) {
String result = AsyncHttpClient.HEADER_CONTENT_TYPE + ": " + normalizeContentType(type) + STR_CR_LF;
return result.getBytes();
}
private byte[] createContentDisposition(String key) {
return (
AsyncHttpClient.HEADER_CONTENT_DISPOSITION +
": form-data; name=\"" + key + "\"" + STR_CR_LF).getBytes();
}
private byte[] createContentDisposition(String key, String fileName) {
return (
AsyncHttpClient.HEADER_CONTENT_DISPOSITION +
": form-data; name=\"" + key + "\"" +
"; filename=\"" + fileName + "\"" + STR_CR_LF).getBytes();
}
private void updateProgress(long count) {
bytesWritten += count;
progressHandler.sendProgressMessage(bytesWritten, totalSize);
}
private class FilePart {
public File file;
public byte[] header;
public FilePart(String key, File file, String type, String customFileName) {
header = createHeader(key, TextUtils.isEmpty(customFileName) ? file.getName() : customFileName, type);
this.file = file;
}
public FilePart(String key, File file, String type) {
header = createHeader(key, file.getName(), type);
this.file = file;
}
private byte[] createHeader(String key, String filename, String type) {
ByteArrayOutputStream headerStream = new ByteArrayOutputStream();
try {
headerStream.write(boundaryLine);
// Headers
headerStream.write(createContentDisposition(key, filename));
headerStream.write(createContentType(type));
headerStream.write(TRANSFER_ENCODING_BINARY);
headerStream.write(CR_LF);
} catch (IOException e) {
// Can't happen on ByteArrayOutputStream
Log.e(LOG_TAG, "createHeader ByteArrayOutputStream exception", e);
}
return headerStream.toByteArray();
}
public long getTotalLength() {
long streamLength = file.length() + CR_LF.length;
return header.length + streamLength;
}
public void writeTo(OutputStream out) throws IOException {
out.write(header);
updateProgress(header.length);
FileInputStream inputStream = new FileInputStream(file);
final byte[] tmp = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(tmp)) != -1) {
out.write(tmp, 0, bytesRead);
updateProgress(bytesRead);
}
out.write(CR_LF);
updateProgress(CR_LF.length);
out.flush();
AsyncHttpClient.silentCloseInputStream(inputStream);
}
}
// The following methods are from the HttpEntity interface
@Override
public long getContentLength() {
long contentLen = out.size();
for (FilePart filePart : fileParts) {
long len = filePart.getTotalLength();
if (len < 0) {
return -1; // Should normally not happen
}
contentLen += len;
}
contentLen += boundaryEnd.length;
return contentLen;
}
@Override
public Header getContentType() {
return new BasicHeader(
AsyncHttpClient.HEADER_CONTENT_TYPE,
"multipart/form-data; boundary=" + boundary);
}
@Override
public boolean isChunked() {
return false;
}
public void setIsRepeatable(boolean isRepeatable) {
this.isRepeatable = isRepeatable;
}
@Override
public boolean isRepeatable() {
return isRepeatable;
}
@Override
public boolean isStreaming() {
return false;
}
@Override
public void writeTo(final OutputStream outstream) throws IOException {
bytesWritten = 0;
totalSize = (int) getContentLength();
out.writeTo(outstream);
updateProgress(out.size());
for (FilePart filePart : fileParts) {
filePart.writeTo(outstream);
}
outstream.write(boundaryEnd);
updateProgress(boundaryEnd.length);
}
@Override
public Header getContentEncoding() {
return null;
}
@Override
public void consumeContent() throws IOException, UnsupportedOperationException {
if (isStreaming()) {
throw new UnsupportedOperationException(
"Streaming entity does not implement #consumeContent()");
}
}
@Override
public InputStream getContent() throws IOException, UnsupportedOperationException {
throw new UnsupportedOperationException(
"getContent() is not supported. Use writeTo() instead.");
}
} | mit |
ScottKolo/UFSMC-Web | db/collection_data/matrices/Gleich/minnesota.rb | 948 | {
matrix_id: '2331',
name: 'minnesota',
group: 'Gleich',
description: 'Minnesota road network (with xy coordinates)',
author: 'D. Gleich',
editor: 'T. Davis',
date: '2010',
kind: 'undirected graph',
problem_2D_or_3D: '0',
num_rows: '2642',
num_cols: '2642',
nonzeros: '6606',
num_explicit_zeros: '0',
num_strongly_connected_components: '2',
pattern_symmetry: '1.000',
numeric_symmetry: '1.000',
rb_type: 'binary',
structure: 'symmetric',
cholesky_candidate: 'no',
positive_definite: 'no',
aux_fields: 'coord: full 2642-by-2
', norm: '3.232397e+00',
min_singular_value: '6.260975e-34',
condition_number: '5.162769e+33',
svd_rank: '2598',
null_space_dimension: '44',
full_numerical_rank: 'no',
svd_gap: '107035296301.448471',
image_files: 'minnesota.png,minnesota_gplot.png,minnesota_scc.png,minnesota_svd.png,minnesota_graph.gif,',
}
| mit |
jmsardina/goaly | app/models/tag.rb | 141 | class Tag < ActiveRecord::Base
belongs_to :taggable, polymorphic: true
# has_many :goal_tags
# has_many :goals, through: :goal_tags
end
| mit |
samtoubia/azure-sdk-for-net | src/ResourceManagement/RedisCache/AzureRedisCache.Tests/ScenarioTests/RedisCacheManagementHelper.cs | 5436 | // ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.
// ----------------------------------------------------------------------------------
using AzureRedisCache.Tests.ScenarioTests;
using Microsoft.Azure.Management.Redis;
using Microsoft.Azure.Management.Redis.Models;
using Microsoft.Azure.Management.Resources;
using Microsoft.Azure.Management.Resources.Models;
using Microsoft.Azure.Test;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace AzureRedisCache.Tests
{
public class RedisCacheManagementHelper
{
private ResourceManagementClient _client;
private MockContext _context;
private TestBase _testBase;
public RedisCacheManagementHelper(TestBase testBase, MockContext context)
{
_client = RedisCacheManagementTestUtilities.GetResourceManagementClient(testBase, context);
_testBase = testBase;
_context = context;
}
public void TryRegisterSubscriptionForResource(string providerName = "Microsoft.Cache")
{
var reg = _client.Providers.Register(providerName);
ThrowIfTrue(reg == null, "_client.Providers.Register returned null.");
var resultAfterRegister = _client.Providers.Get(providerName);
ThrowIfTrue(resultAfterRegister == null, "_client.Providers.Get returned null.");
ThrowIfTrue(string.IsNullOrEmpty(resultAfterRegister.Id), "Provider.Id is null or empty.");
ThrowIfTrue(resultAfterRegister.ResourceTypes == null || resultAfterRegister.ResourceTypes.Count == 0, "Provider.ResourceTypes is empty.");
ThrowIfTrue(resultAfterRegister.ResourceTypes[0].Locations == null || resultAfterRegister.ResourceTypes[0].Locations.Count == 0, "Provider.ResourceTypes[0].Locations is empty.");
}
public void TryCreateResourceGroup(string resourceGroupName, string location)
{
ResourceGroup result = _client.ResourceGroups.CreateOrUpdate(resourceGroupName, new ResourceGroup { Location = location });
var newlyCreatedGroup = _client.ResourceGroups.Get(resourceGroupName);
ThrowIfTrue(newlyCreatedGroup == null, "_client.ResourceGroups.Get returned null.");
ThrowIfTrue(!resourceGroupName.Equals(newlyCreatedGroup.Name), string.Format("resourceGroupName is not equal to {0}", resourceGroupName));
}
public void DeleteResourceGroup(string resourceGroupName)
{
_client.ResourceGroups.Delete(resourceGroupName);
}
public void TryCreatingCache(string resourceGroupName, string cacheName, string location)
{
var redisClient = RedisCacheManagementTestUtilities.GetRedisManagementClient(_testBase, _context);
var createResponse = redisClient.Redis.Create(resourceGroupName: resourceGroupName, name: cacheName,
parameters: new RedisCreateParameters
{
Location = location,
Sku = new Sku()
{
Name = SkuName.Basic,
Family = SkuFamily.C,
Capacity = 0
}
});
RedisResource response = redisClient.Redis.Get(resourceGroupName: resourceGroupName, name: cacheName);
ThrowIfTrue(!response.Id.Contains(cacheName), "Cache name not found inside Id.");
ThrowIfTrue(!response.Name.Equals(cacheName), string.Format("Cache name is not equal to {0}", cacheName));
ThrowIfTrue(!response.HostName.Contains(cacheName), "Cache name not found inside host name.");
// wait for maximum 30 minutes for cache to create
for (int i = 0; i < 60; i++)
{
TestUtilities.Wait(new TimeSpan(0, 0, 30));
RedisResource responseGet = redisClient.Redis.Get(resourceGroupName: resourceGroupName, name: cacheName);
if ("succeeded".Equals(responseGet.ProvisioningState, StringComparison.OrdinalIgnoreCase))
{
break;
}
ThrowIfTrue(i == 60, "Cache is not in succeeded state even after 30 min.");
}
}
private void ThrowIfTrue(bool condition, string message)
{
if (condition)
{
throw new Exception(message);
}
}
}
}
| mit |
Simmesimme/swift2d | third_party/include/mvscxx/oalplus/enumerations.hpp | 1493 | /**
* @file oalplus/enumerations.hpp
* @brief Enumeration-related declarations
*
* @author Matus Chochlik
*
* Copyright 2012-2014 Matus Chochlik. 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)
*/
#pragma once
#ifndef OALPLUS_ENUMERATIONS_1303201759_HPP
#define OALPLUS_ENUMERATIONS_1303201759_HPP
#include <oalplus/config.hpp>
#include <oalplus/string.hpp>
#include <oalplus/detail/enum_class.hpp>
#include <oalplus/detail/base_range.hpp>
namespace oalplus {
namespace enums {
template <typename Enum>
struct EnumBaseType
{
typedef ALenum Type;
};
template <typename EnumType>
inline StrCRef EnumValueName(EnumType enum_value)
{
#if !OALPLUS_NO_ENUM_VALUE_NAMES
typedef typename EnumBaseType<EnumType>::Type BaseType;
return ValueName_(
(EnumType*)nullptr,
BaseType(enum_value)
);
#else
OGLPLUS_FAKE_USE(enum_value);
return StrCRef();
#endif
}
template <typename EnumType>
inline aux::CastIterRange<
const typename EnumBaseType<EnumType>::Type*,
EnumType
> EnumValueRange(void)
{
#if !OALPLUS_NO_ENUM_VALUE_RANGES
return ValueRange_((EnumType*)nullptr);
#else
const typename EnumBaseType<EnumType>::Type* x = nullptr;
return aux::CastIterRange<
const typename EnumBaseType<EnumType>::Type*,
EnumType
>(x, x);
#endif
}
} // namespace enums
using enums::EnumValueName;
using enums::EnumValueRange;
} // namespace oalplus
#endif // include guard
| mit |
haziqhafizuddin/rubocop | lib/rubocop/version.rb | 591 | # frozen_string_literal: true
module RuboCop
# This module holds the RuboCop version information.
module Version
STRING = '0.57.2'.freeze
MSG = '%<version>s (using Parser %<parser_version>s, running on ' \
'%<ruby_engine>s %<ruby_version>s %<ruby_platform>s)'.freeze
def self.version(debug = false)
if debug
format(MSG, version: STRING, parser_version: Parser::VERSION,
ruby_engine: RUBY_ENGINE, ruby_version: RUBY_VERSION,
ruby_platform: RUBY_PLATFORM)
else
STRING
end
end
end
end
| mit |
extr0py/extropy-cli | src/core/common/Entity/Factory/IEntityCreateResult.ts | 132 | module Extropy.Entity {
export interface IEntityCreateResult {
isCreated: boolean;
entity: Entity;
}
}
| mit |
Azure/azure-sdk-for-java | sdk/storage/azure-storage-file-datalake/src/main/java/com/azure/storage/file/datalake/models/AccessControlChangeFailure.java | 1859 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.storage.file.datalake.models;
/**
* Represents an entry that failed to update Access Control List.
*/
public class AccessControlChangeFailure {
private String name;
private boolean isDirectory;
private String errorMessage;
/**
* Returns the name of an entry.
*
* @return The name of an entry.
*/
public String getName() {
return name;
}
/**
* Sets the name of an entry.
*
* @param name The name of an entry.
* @return The updated object.
*/
public AccessControlChangeFailure setName(String name) {
this.name = name;
return this;
}
/**
* Returns whether entry is a directory.
*
* @return Whether the entry is a directory.
*/
public boolean isDirectory() {
return isDirectory;
}
/**
* Sets whether entry is a directory.
*
* @param directory Whether entry is a directory.
* @return The updated object.
*/
public AccessControlChangeFailure setDirectory(boolean directory) {
isDirectory = directory;
return this;
}
/**
* Returns error message that is the reason why entry failed to update.
*
* @return The error message that is the reason why entry failed to update.
*/
public String getErrorMessage() {
return errorMessage;
}
/**
* Sets the error message that is the reason why entry failed to update.
*
* @param errorMessage The error message that is the reason why entry failed to update.
* @return The updated object.
*/
public AccessControlChangeFailure setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
return this;
}
}
| mit |
weblogng/angular-weblogng | src/main.js | 4423 | /* angular-weblogng main */
(function (angular) {
'use strict';
var weblogngModule = angular.module('weblogng', []);
weblogngModule.provider('$weblogng', function () {
return {
$get: ['$window', 'weblogngConfig',
function ($window, weblogngConfig) {
return new $window.weblogng.Logger('api.weblogng.com' , weblogngConfig.apiKey, weblogngConfig.options);
}
]
};
})
.config(function ($provide, $httpProvider) {
$provide.factory('httpInterceptor', function ($window, $q, $injector, $log) {
function defaultConvertRequestConfigToMetricName (config) {
var metricName;
if (config && config.url) {
metricName = extractHostFromUrl(config.url);
if (config.method) {
metricName = config.method + ' ' + metricName;
}
}
return metricName;
}
function resolveRequestConfigToMetricNameConverter(logger){
return logger.options.convertRequestConfigToMetricName ?
logger.options.convertRequestConfigToMetricName :
defaultConvertRequestConfigToMetricName;
}
function calculateScope(requestConfig) {
if (requestConfig && requestConfig.url) {
return extractHostFromUrl(requestConfig.url);
}
return undefined;
}
function extractHostFromUrl(url) {
var anchor = $window.document.createElement('a');
anchor.href = url;
return anchor.host;
}
return {
'extractHostFromUrl': extractHostFromUrl,
'calculateScope': calculateScope,
'convertRequestConfigToMetricName': defaultConvertRequestConfigToMetricName,
'request': function (config) {
config.timer = new $window.weblogng.Timer();
config.timer.start();
return config || $q.when(config);
},
'response': function (response) {
var logger = $injector.get('$weblogng');
var convertRequestConfigToMetricName = resolveRequestConfigToMetricNameConverter(logger);
var metricName = convertRequestConfigToMetricName(response.config);
if(response.config.timer){
response.config.timer.finish();
var timestamp = $window.weblogng.epochTimeInMilliseconds();
var scope = calculateScope(response.config);
logger.sendMetric(metricName, response.config.timer.getElapsedTime(), timestamp, scope, 'http request');
}
return response || $q.when(response);
},
'responseError': function (rejection) {
var logError = function(rejection, message){
var url, method = 'unknown';
if(rejection.config){
url = rejection.config.url;
method = rejection.config.method;
}
var details = { 'status': rejection.status, 'method': method, 'url': url, 'message': message};
$log.error('http request failed:', details);
};
if(rejection && rejection.config && rejection.config.timer){
var logger = $injector.get('$weblogng');
var convertRequestConfigToMetricName = resolveRequestConfigToMetricNameConverter(logger);
var metricName = convertRequestConfigToMetricName(rejection.config);
rejection.config.timer.finish();
var timestamp = $window.weblogng.epochTimeInMilliseconds();
var scope = calculateScope(rejection.config);
logger.sendMetric(metricName, rejection.config.timer.getElapsedTime(), timestamp, scope, 'http request');
}
switch(rejection.status){
case 400:
logError(rejection, 'server indicates request was malformed');
break;
case 500:
logError(rejection, 'server encountered error while processing request');
break;
default:
logError(rejection, 'an http error occurred');
break;
}
return $q.reject(rejection);
}
};
});
$httpProvider.interceptors.push('httpInterceptor');
}).run(function ($rootScope, $injector) {
$rootScope.$on('$routeChangeSuccess', function (event, next) {
var logger = $injector.get('$weblogng');
logger.recordEvent('routeChangeSuccess-' + next.loadedTemplateUrl);
});
}
)
;
})(angular);
| mit |
BKTidswell/ThesisPGG | game/game.setup.js | 501 | /**
* # Game setup
* Copyright(c) 2017 Stefano Balietti
* MIT Licensed
*
* This file includes settings that are shared amongst all client types
*
* http://www.nodegame.org
* ---
*/
module.exports = function(settings, stages) {
var setup = {};
//auto: true = automatic run, auto: false = user input
setup.env = {
auto: false
};
setup.debug = true;
setup.verbosity = 1;
setup.window = {
promptOnleave: !setup.debug
};
return setup;
};
| mit |
oliviertassinari/material-ui | packages/mui-icons-material/lib/esm/AirlineSeatLegroomReducedOutlined.js | 386 | import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "M19.97 19.2c.18.96-.55 1.8-1.47 1.8H14v-3l1-4H9c-1.65 0-3-1.35-3-3V3h6v6h5c1.1 0 2 .9 2 2l-2 7h1.44c.73 0 1.39.49 1.53 1.2zM5 12V3H3v9c0 2.76 2.24 5 5 5h4v-2H8c-1.66 0-3-1.34-3-3z"
}), 'AirlineSeatLegroomReducedOutlined'); | mit |
anuragkapur/algorithmic-programming | src/test/java/com/anuragkapur/ctci/linkedlists/Prob2_7_1_PalindromeTest.java | 2764 | package com.anuragkapur.ctci.linkedlists;
import com.anuragkapur.ds.linkedlist.LinkedListNode;
import org.junit.Test;
import static org.junit.Assert.*;
public class Prob2_7_1_PalindromeTest {
@Test
public void testIsPalindrome1() throws Exception {
LinkedListNode<Integer> node1 = new LinkedListNode<>(1);
LinkedListNode<Integer> node2 = new LinkedListNode<>(2);
LinkedListNode<Integer> node3 = new LinkedListNode<>(3);
LinkedListNode<Integer> node4 = new LinkedListNode<>(2);
LinkedListNode<Integer> node5 = new LinkedListNode<>(1);
node1.setNext(node2);
node2.setNext(node3);
node3.setNext(node4);
node4.setNext(node5);
assertEquals(true, new Prob2_7_1_Palindrome().isPalindrome(node1));
}
@Test
public void testIsPalindrome2() throws Exception {
LinkedListNode<Integer> node1 = new LinkedListNode<>(1);
LinkedListNode<Integer> node2 = new LinkedListNode<>(2);
LinkedListNode<Integer> node3 = new LinkedListNode<>(3);
LinkedListNode<Integer> node4 = new LinkedListNode<>(3);
LinkedListNode<Integer> node5 = new LinkedListNode<>(2);
LinkedListNode<Integer> node6 = new LinkedListNode<>(1);
node1.setNext(node2);
node2.setNext(node3);
node3.setNext(node4);
node4.setNext(node5);
node5.setNext(node6);
assertEquals(true, new Prob2_7_1_Palindrome().isPalindrome(node1));
}
@Test
public void testIsPalindrome3() throws Exception {
LinkedListNode<Integer> node1 = new LinkedListNode<>(1);
LinkedListNode<Integer> node2 = new LinkedListNode<>(2);
LinkedListNode<Integer> node3 = new LinkedListNode<>(3);
LinkedListNode<Integer> node4 = new LinkedListNode<>(4);
LinkedListNode<Integer> node5 = new LinkedListNode<>(2);
LinkedListNode<Integer> node6 = new LinkedListNode<>(1);
node1.setNext(node2);
node2.setNext(node3);
node3.setNext(node4);
node4.setNext(node5);
node5.setNext(node6);
assertEquals(false, new Prob2_7_1_Palindrome().isPalindrome(node1));
}
@Test
public void testIsPalindrome4() throws Exception {
LinkedListNode<Integer> node1 = new LinkedListNode<>(1);
LinkedListNode<Integer> node2 = new LinkedListNode<>(2);
LinkedListNode<Integer> node3 = new LinkedListNode<>(3);
LinkedListNode<Integer> node4 = new LinkedListNode<>(4);
LinkedListNode<Integer> node5 = new LinkedListNode<>(2);
node1.setNext(node2);
node2.setNext(node3);
node3.setNext(node4);
node4.setNext(node5);
assertEquals(false, new Prob2_7_1_Palindrome().isPalindrome(node1));
}
} | mit |
pdev-mooc/mooc | mooc-web/src/main/webapp/views/learning-1.1.0/lib/maps/js/google/_init.js | 42 | window.initGoogleMaps = require('./main'); | mit |
natemara/a1atscript | test/annotations_spec.js | 5169 | import {
Config,
Run,
Controller,
Directive,
Service,
Factory,
Provider,
Value,
Constant,
Animation,
Filter,
AsModule
} from '../src/a1atscript/annotations.js';
var OriginalConfig = Config.originalClass || Config;
var OriginalRun = Run.originalClass || Run;
var OriginalController = Controller.originalClass || Controller;
var OriginalDirective = Directive.originalClass || Directive;
var OriginalService = Service.originalClass || Service;
var OriginalFactory = Factory.originalClass || Factory;
var OriginalProvider = Provider.originalClass || Provider;
var OriginalValue = Value.originalClass || Value;
var OriginalConstant = Constant.originalClass || Constant;
var OriginalAnimation = Animation.originalClass || Animation;
var OriginalFilter = Filter.originalClass || Filter;
var OriginalAsModule = AsModule.originalClass || AsModule;
describe("annotations", function() {
describe("config", function() {
@Config('dep1', 'dep2')
class ExampleConfig {
constructor(dep1, dep2) {
}
};
it("should annotate the config", function() {
expect(ExampleConfig.annotations[0]).toEqual(
new OriginalConfig('dep1', 'dep2'));
expect(ExampleConfig.annotations[0].dependencies).toEqual(['dep1', 'dep2'])
});
});
describe("run", function() {
@Run('dep1', 'dep2')
class ExampleRun {
constructor(dep1, dep2) {
}
};
it("should annotate the run", function() {
expect(ExampleRun.annotations[0]).toEqual(
new OriginalRun('dep1', 'dep2'));
expect(ExampleRun.annotations[0].dependencies).toEqual(['dep1', 'dep2'])
});
});
describe("controller", function() {
@Controller('ExampleController', ['dep1', 'dep2'])
class ExampleController {
constructor(dep1, dep2) {
}
};
it("should annotate the controller", function() {
expect(ExampleController.annotations[0]).toEqual(
new OriginalController('ExampleController', ['dep1', 'dep2']));
});
});
describe("directive", function() {
@Directive('ExampleDirective', ['dep1', 'dep2'])
class ExampleDirective {
constructor(dep1, dep2) {
}
};
it("should annotate the directive", function() {
expect(ExampleDirective.annotations[0]).toEqual(
new OriginalDirective('ExampleDirective', ['dep1', 'dep2']));
});
});
describe("service", function() {
@Service('ExampleService', ['dep1', 'dep2'])
class ExampleService {
constructor(dep1, dep2) {
}
};
it("should annotate the service", function() {
expect(ExampleService.annotations[0]).toEqual(
new OriginalService('ExampleService', ['dep1', 'dep2']));
});
});
describe("factory", function() {
@Factory('ExampleFactory', ['dep1', 'dep2'])
class ExampleFactory {
constructor(dep1, dep2) {
}
};
it("should annotate the factory", function() {
expect(ExampleFactory.annotations[0]).toEqual(
new OriginalFactory('ExampleFactory', ['dep1', 'dep2']));
});
});
describe("provider", function() {
@Provider('ExampleProvider', ['dep1', 'dep2'])
class ExampleProvider {
constructor(dep1, dep2) {
}
};
it("should annotate the provider", function() {
expect(ExampleProvider.annotations[0]).toEqual(
new OriginalProvider('ExampleProvider', ['dep1', 'dep2']));
});
});
describe("value", function() {
@Value('ExampleValue', ['dep1', 'dep2'])
class ExampleValue {
constructor(dep1, dep2) {
}
};
it("should annotate the value", function() {
expect(ExampleValue.annotations[0]).toEqual(
new OriginalValue('ExampleValue', ['dep1', 'dep2']));
});
});
describe("constant", function() {
@Constant('ExampleConstant', ['dep1', 'dep2'])
class ExampleConstant {
constructor(dep1, dep2) {
}
};
it("should annotate the constant", function() {
expect(ExampleConstant.annotations[0]).toEqual(
new OriginalConstant('ExampleConstant', ['dep1', 'dep2']));
});
});
describe("animation", function() {
@Animation('ExampleAnimation', ['dep1', 'dep2'])
class ExampleAnimation {
constructor(dep1, dep2) {
}
};
it("should annotate the animation", function() {
expect(ExampleAnimation.annotations[0]).toEqual(
new OriginalAnimation('ExampleAnimation', ['dep1', 'dep2']));
});
});
describe("filter", function() {
@Filter('ExampleFilter', ['dep1', 'dep2'])
class ExampleFilter {
constructor(dep1, dep2) {
}
};
it("should annotate the filter", function() {
expect(ExampleFilter.annotations[0]).toEqual(
new OriginalFilter('ExampleFilter', ['dep1', 'dep2']));
});
});
describe("asModule", function() {
@AsModule('ExampleModule', ['dep1', 'dep2'])
class ExampleModule {
constructor(dep1, dep2) {
}
};
it("should annotate the module", function() {
expect(ExampleModule.annotations[0]).toEqual(
new OriginalAsModule('ExampleModule', ['dep1', 'dep2']));
});
});
});
| mit |
jcc333/tempoiq-java | src/test/java/com/tempoiq/DeviceReadTest.java | 935 | package com.tempoiq;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.junit.Test;
public class DeviceReadTest {
private static final Device device = new Device("device1");
private static final String json1 = "{" +
"\"data\":[" +
"{\"key\":\"device1\","
+ "\"name\":\"\"," +
"\"attributes\":{}," +
"\"sensors\":[]}]}";
@Test
public void testListDevices() throws IOException {
HttpResponse response = Util.getResponse(200, json1);
Client client = Util.getClient(response);
Selection sel = new Selection().
addSelector(Selector.Type.DEVICES, Selector.key(device.getKey()));
Cursor<Device> cursor = client.listDevices(sel);
assert(cursor.iterator().hasNext());
Device returnedDev = cursor.iterator().next();
assertEquals(device.getKey(), returnedDev.getKey());
}
}
| mit |
olszak94/DevAAC | DevAAC/Models/GuildwarKill.php | 3089 | <?php
/**
* DevAAC
*
* Automatic Account Creator by developers.pl for TFS 1.0
*
*
* LICENSE: Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is furnished
* to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* @package DevAAC
* @author Daniel Speichert <daniel@speichert.pl>
* @author Wojciech Guziak <wojciech@guziak.net>
* @copyright 2014 Developers.pl
* @license http://opensource.org/licenses/MIT MIT
* @version master
* @link https://github.com/DevelopersPL/DevAAC
*/
namespace DevAAC\Models;
use DevAAC\Helpers\DateTime;
// https://github.com/illuminate/database/blob/master/Eloquent/Model.php
// https://github.com/otland/forgottenserver/blob/master/schema.sql
/**
* @SWG\Model(required="['id','killer','target','killerguild','targetguild','warid','time']")
*/
class GuildwarKill extends \Illuminate\Database\Eloquent\Model {
/**
* @SWG\Property(name="id", type="integer")
* @SWG\Property(name="killer", type="string")
* @SWG\Property(name="target", type="string")
* @SWG\Property(name="killerguild", type="integer")
* @SWG\Property(name="targetguild", type="integer")
* @SWG\Property(name="warid", type="integer")
* @SWG\Property(name="time", type="DateTime::ISO8601")
*/
public $timestamps = false;
protected $guarded = array('id');
public function getTimeAttribute()
{
$date = new DateTime();
$date->setTimestamp($this->attributes['time']);
return $date;
}
public function setTimeAttribute($d)
{
if($d instanceof \DateTime)
$this->attributes['time'] = $d->getTimestamp();
elseif((int)$d != (string)$d) { // it's not a UNIX timestamp
$dt = new DateTime($d);
$this->attributes['time'] = $dt->getTimestamp();
} else // it is a UNIX timestamp
$this->attributes['time'] = $d;
}
public function killerGuild()
{
return $this->belongsTo('DevAAC\Models\Guild', 'killerguild');
}
public function targetGuild()
{
return $this->belongsTo('DevAAC\Models\Guild', 'targetguild');
}
}
| mit |
minodisk/DefinitelyTyped | types/pouchdb-core/index.d.ts | 34156 | // Type definitions for pouchdb-core 6.1
// Project: https://pouchdb.com/
// Definitions by: Simon Paulger <https://github.com/spaulg>, Jakub Navratil <https://github.com/trubit>,
// Brian Geppert <https://github.com/geppy>, Frederico Galvão <https://github.com/fredgalvao>,
// Tobias Bales <https://github.com/TobiasBales>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
/// <reference types="debug" />
interface Buffer extends Uint8Array {
write(string: string, offset?: number, length?: number, encoding?: string): number;
toString(encoding?: string, start?: number, end?: number): string;
toJSON(): { type: 'Buffer', data: any[] };
equals(otherBuffer: Buffer): boolean;
compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number;
copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number;
slice(start?: number, end?: number): Buffer;
writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number;
readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number;
readIntLE(offset: number, byteLength: number, noAssert?: boolean): number;
readIntBE(offset: number, byteLength: number, noAssert?: boolean): number;
readUInt8(offset: number, noAssert?: boolean): number;
readUInt16LE(offset: number, noAssert?: boolean): number;
readUInt16BE(offset: number, noAssert?: boolean): number;
readUInt32LE(offset: number, noAssert?: boolean): number;
readUInt32BE(offset: number, noAssert?: boolean): number;
readInt8(offset: number, noAssert?: boolean): number;
readInt16LE(offset: number, noAssert?: boolean): number;
readInt16BE(offset: number, noAssert?: boolean): number;
readInt32LE(offset: number, noAssert?: boolean): number;
readInt32BE(offset: number, noAssert?: boolean): number;
readFloatLE(offset: number, noAssert?: boolean): number;
readFloatBE(offset: number, noAssert?: boolean): number;
readDoubleLE(offset: number, noAssert?: boolean): number;
readDoubleBE(offset: number, noAssert?: boolean): number;
swap16(): Buffer;
swap32(): Buffer;
swap64(): Buffer;
writeUInt8(value: number, offset: number, noAssert?: boolean): number;
writeUInt16LE(value: number, offset: number, noAssert?: boolean): number;
writeUInt16BE(value: number, offset: number, noAssert?: boolean): number;
writeUInt32LE(value: number, offset: number, noAssert?: boolean): number;
writeUInt32BE(value: number, offset: number, noAssert?: boolean): number;
writeInt8(value: number, offset: number, noAssert?: boolean): number;
writeInt16LE(value: number, offset: number, noAssert?: boolean): number;
writeInt16BE(value: number, offset: number, noAssert?: boolean): number;
writeInt32LE(value: number, offset: number, noAssert?: boolean): number;
writeInt32BE(value: number, offset: number, noAssert?: boolean): number;
writeFloatLE(value: number, offset: number, noAssert?: boolean): number;
writeFloatBE(value: number, offset: number, noAssert?: boolean): number;
writeDoubleLE(value: number, offset: number, noAssert?: boolean): number;
writeDoubleBE(value: number, offset: number, noAssert?: boolean): number;
fill(value: any, offset?: number, end?: number): this;
indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number;
lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number;
entries(): IterableIterator<[number, number]>;
includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean;
keys(): IterableIterator<number>;
values(): IterableIterator<number>;
}
// TODO: tslint doesn't like the listener: Function signatures but they are from the
// original node declarations so I didn't want to touch them
/* tslint:disable:ban-types */
interface EventEmitter {
addListener(event: string | symbol, listener: Function): this;
on(event: string | symbol, listener: Function): this;
once(event: string | symbol, listener: Function): this;
removeListener(event: string | symbol, listener: Function): this;
removeAllListeners(event?: string | symbol): this;
setMaxListeners(n: number): this;
getMaxListeners(): number;
listeners(event: string | symbol): Function[];
emit(event: string | symbol, ...args: any[]): boolean;
listenerCount(type: string | symbol): number;
prependListener(event: string | symbol, listener: Function): this;
prependOnceListener(event: string | symbol, listener: Function): this;
eventNames(): Array<string | symbol>;
}
/* tslint:eisable:ban-types */
// TODO: Fixing this lint error will require a large refactor
/* tslint:disable:no-single-declare-module */
declare namespace PouchDB {
namespace Core {
interface Error {
/**
* HTTP Status Code during HTTP or HTTP-like operations
*/
status?: number;
name?: string;
message?: string;
reason?: string;
error?: string | boolean;
id?: string;
rev?: RevisionId;
}
type Callback<R> = (error: Error | null, result: R | null) => void;
type DocumentId = string;
type DocumentKey = string;
type AttachmentId = string;
type RevisionId = string;
type Availability = 'available' | 'compacted' | 'not compacted' | 'missing';
type Attachment = string | Blob | Buffer;
interface Options {
ajax?: Configuration.RemoteRequesterConfiguration;
}
interface BasicResponse {
/** `true` if the operation was successful; `false` otherwise */
ok: boolean;
}
interface Response extends BasicResponse {
/** id of the targeted document */
id: DocumentId;
/** resulting revision of the targeted document */
rev: RevisionId;
}
interface DatabaseInfo {
/** Name of the database you gave when you called new PouchDB(), and also the unique identifier for the database. */
db_name: string;
/** Total number of non-deleted documents in the database. */
doc_count: number;
/** Sequence number of the database. It starts at 0 and gets incremented every time a document is added or modified */
update_seq: number | string;
}
interface Revision<Content extends {}> {
ok: Document<Content> & RevisionIdMeta;
}
interface RevisionInfo {
rev: RevisionId;
status: Availability;
}
interface RevisionDiffOptions {
[DocumentId: string]: string[];
}
interface RevisionDiff {
missing?: string[];
possible_ancestors?: string[];
}
interface RevisionDiffResponse {
[DocumentId: string]: RevisionDiff;
}
interface IdMeta {
_id: DocumentId;
}
interface RevisionIdMeta {
_rev: RevisionId;
}
interface GetMeta {
/** Conflicting leaf revisions.
*
* Only present if `GetOptions.conflicts` is `true`
*/
_conflicts?: RevisionId[];
_rev?: RevisionId;
/** Only present if `GetOptions.revs` is `true` */
_revs_info?: RevisionInfo[];
/** Only present if `GetOptions.revs_info` is `true` */
_revisions?: {
ids: RevisionId[];
start: number;
};
/** Attachments where index is attachmentId */
_attachments?: Attachments;
}
interface AttachmentResponse {
content_type: string;
/** MD5 hash, starts with "md5-" prefix */
digest: string;
/** Only present if `attachments` was `false`. */
stub?: boolean;
/** Only present if `attachments` was `false`. */
length?: number;
/**
* Only present if `attachments` was `true`.
* {string} if `binary` was `false`
* {Blob|Buffer} if `binary` was `true`
*/
data?: Attachment;
}
interface Attachments {
[attachmentId: string]: AttachmentResponse;
}
type NewDocument<Content extends {}> = Content;
type Document<Content extends {}> = Content & IdMeta;
type ExistingDocument<Content extends {}> =
Document<Content> & RevisionIdMeta;
/** Existing doc or just object with `_id` and `_rev` */
type RemoveDocument = IdMeta & RevisionIdMeta;
type PostDocument<Content extends {}> = NewDocument<Content> & {
filters?: {[filterName: string]: string};
views?: {[viewName: string]: string};
/** You can update an existing doc using _rev */
_rev?: RevisionId;
_attachments?: {[attachmentId: string]: PutAttachment};
};
type PutDocument<Content extends {}> = PostDocument<Content> & ChangesMeta & {
_id?: DocumentId;
};
interface PutAttachment {
content_type: string;
data: Attachment;
}
interface AllDocsOptions extends Options {
/** Include attachment data for each document.
*
* Requires `include_docs` to be `true`.
*
* By default, attachments are Base64-encoded.
* @see binary
*/
attachments?: boolean;
/** Return attachments as Buffers.
*
* Requires `include_docs` to be `true`.
* Requires `attachments` to be `true`.
*/
binary?: boolean;
/** Include conflict information for each document.
*
* Requires `include_docs` to be `true`.
*/
conflicts?: boolean;
/** Reverse ordering of results. */
descending?: boolean;
/** Include contents for each document. */
include_docs?: boolean;
/** Maximum number of documents to return. */
limit?: number;
/** Number of documents to skip before returning.
*
* Causes poor performance on IndexedDB and LevelDB.
*/
skip?: number;
}
interface AllDocsWithKeyOptions extends AllDocsOptions {
/** Constrain results to documents matching this key. */
key: DocumentKey;
}
interface AllDocsWithKeysOptions extends AllDocsOptions {
/** Constrains results to documents matching any of these keys. */
keys: DocumentId[];
}
interface AllDocsWithinRangeOptions extends AllDocsOptions {
/** Low end of range, or high end if `descending` is `true`. */
startkey: DocumentKey;
/** High end of range, or low end if `descending` is `true`. */
endkey: DocumentKey;
/** Include any documents identified by `endkey`.
*
* Defaults to `true`.
*/
inclusive_end?: boolean;
}
interface AllDocsMeta {
/** Only present if `conflicts` is `true` */
_conflicts?: RevisionId[];
_attachments?: Attachments;
}
interface AllDocsResponse<Content extends {}> {
/** The `skip` if provided, or in CouchDB the actual offset */
offset: number;
total_rows: number;
rows: Array<{
/** Only present if `include_docs` was `true`. */
doc?: ExistingDocument<Content & AllDocsMeta>;
id: DocumentId;
key: DocumentKey;
value: {
rev: RevisionId;
deleted?: boolean;
}
}>;
}
interface BulkDocsOptions extends Options {
new_edits?: boolean;
}
interface BulkGetOptions extends Options {
docs: Array<{ id: string; rev: RevisionId }>;
revs?: boolean;
attachments?: boolean;
binary?: boolean;
}
interface BulkGetResponse<Content extends {}> {
results: {
docs: Array<{ ok: Content & GetMeta } | { error: Error }>;
};
}
interface ChangesMeta {
_conflicts?: RevisionId[];
_deleted?: boolean;
_attachments?: Attachments;
}
interface ChangesOptions {
/**
* Does "live" changes.
*/
live?: boolean;
/**
* Start the results from the change immediately after the given sequence number.
* You can also pass `'now'` if you want only new changes (when `live` is `true`).
*
*/
since?: 'now' | number | string;
/**
* Request timeout (in milliseconds).
*/
timeout?: number | false;
/** Include contents for each document. */
include_docs?: boolean;
/** Maximum number of documents to return. */
limit?: number | false;
/** Include conflicts. */
conflicts?: boolean;
/** Include attachments. */
attachments?: boolean;
/** Return attachment data as Blobs/Buffers, instead of as base64-encoded strings. */
binary?: boolean;
/** Reverse the order of the output documents. */
descending?: boolean;
/**
* For http adapter only, time in milliseconds for server to give a heartbeat to keep long connections open.
* Defaults to 10000 (10 seconds), use false to disable the default.
*/
heartbeat?: number | false;
/**
* Reference a filter function from a design document to selectively get updates.
* To use a view function, pass '_view' here and provide a reference to the view function in options.view.
* See filtered changes for details.
*/
filter?: string | ((doc: any, params: any) => any);
/** Only show changes for docs with these ids (array of strings). */
doc_ids?: string[];
/**
* Object containing properties that are passed to the filter function, e.g. {"foo:"bar"},
* where "bar" will be available in the filter function as params.query.foo.
* To access the params, define your filter function like function (doc, params).
*/
query_params?: {[paramName: string]: any};
/**
* Specify a view function (e.g. 'design_doc_name/view_name' or 'view_name' as shorthand for 'view_name/view_name') to act as a filter.
* Documents counted as “passed” for a view filter if a map function emits at least one record for them.
* Note: options.filter must be set to '_view' for this option to work.
*/
view?: string;
}
interface ChangesResponseChange<Content extends {}> {
id: string;
seq: number | string;
changes: Array<{ rev: string }>;
deleted?: boolean;
doc?: ExistingDocument<Content & ChangesMeta>;
}
interface ChangesResponse<Content extends {}> {
status: string;
last_seq: number | string;
results: Array<ChangesResponseChange<Content>>;
}
interface Changes<Content extends {}> extends EventEmitter, Promise<ChangesResponse<Content>> {
on(event: 'change', listener: (value: ChangesResponseChange<Content>) => any): this;
on(event: 'complete', listener: (value: ChangesResponse<Content>) => any): this;
on(event: 'error', listener: (value: any) => any): this;
cancel(): void;
}
interface GetOptions extends Options {
/** Include list of conflicting leaf revisions. */
conflicts?: boolean;
/** Specific revision to fetch */
rev?: RevisionId;
/** Include revision history of the document. */
revs?: boolean;
/** Include a list of revisions of the document, and their
* availability.
*/
revs_info?: boolean;
/** Include attachment data. */
attachments?: boolean;
/** Return attachment data as Blobs/Buffers, instead of as base64-encoded strings. */
binary?: boolean;
/** Forces retrieving latest “leaf” revision, no matter what rev was requested. */
latest?: boolean;
}
interface GetOpenRevisions extends Options {
/** Fetch all leaf revisions if open_revs="all" or fetch all leaf
* revisions specified in open_revs array. Leaves will be returned
* in the same order as specified in input array.
*/
open_revs: 'all' | Core.RevisionId[];
/** Include revision history of the document. */
revs?: boolean;
}
interface CompactOptions extends Core.Options {
interval?: number;
}
interface RemoveAttachmentResponse extends BasicResponse {
id: Core.DocumentId;
rev: Core.RevisionId;
}
}
/**
* Pass this to `PouchDB.plugin()`.
*/
type Plugin = 'This should be passed to PouchDB.plugin()';
namespace Configuration {
interface CommonDatabaseConfiguration {
/**
* Database name.
*/
name?: string;
/**
* Database adapter to use.
*
* If unspecified, PouchDB will infer this automatically, preferring
* IndexedDB to WebSQL in browsers that support both (i.e. Chrome,
* Opera and Android 4.4+).
*/
adapter?: string;
}
interface LocalDatabaseConfiguration extends CommonDatabaseConfiguration {
/**
* Enables auto compaction, which means compact() is called after
* every change to the database.
*
* Defaults to false.
*/
auto_compaction?: boolean;
/**
* How many old revisions we keep track (not a copy) of.
*/
revs_limit?: number;
}
interface RemoteRequesterConfiguration {
/**
* Time before HTTP requests time out (in ms).
*/
timeout?: number;
/**
* Appends a random string to the end of all HTTP GET requests to avoid
* them being cached on IE. Set this to true to prevent this happening.
*/
cache?: boolean;
/**
* HTTP headers to add to requests.
*/
headers?: {
[name: string]: string;
};
/**
* Enables transferring cookies and HTTP Authorization information.
*
* Defaults to true.
*/
withCredentials?: boolean;
}
interface RemoteDatabaseConfiguration extends CommonDatabaseConfiguration {
ajax?: RemoteRequesterConfiguration;
auth?: {
username?: string;
password?: string;
};
/**
* Disables automatic creation of databases.
*/
skip_setup?: boolean;
}
type DatabaseConfiguration = LocalDatabaseConfiguration |
RemoteDatabaseConfiguration;
}
interface Static extends EventEmitter {
plugin(plugin: Plugin): Static;
version: string;
on(event: 'created' | 'destroyed', listener: (dbName: string) => any): this;
debug: debug.IDebug;
new<Content extends {} = {}>(name?: string,
options?: Configuration.DatabaseConfiguration): Database<Content>;
/**
* The returned object is a constructor function that works the same as PouchDB,
* except that whenever you invoke it (e.g. with new), the given options will be passed in by default.
*/
defaults(options: Configuration.DatabaseConfiguration): {
new<Content extends {} = {}>(name?: string,
options?: Configuration.DatabaseConfiguration): Database<Content>;
};
}
interface Database<Content extends {} = {}> {
/** Fetch all documents matching the given options. */
allDocs<Model>(options?: Core.AllDocsWithKeyOptions | Core.AllDocsWithKeysOptions | Core.AllDocsWithinRangeOptions | Core.AllDocsOptions):
Promise<Core.AllDocsResponse<Content & Model>>;
/**
* Create, update or delete multiple documents. The docs argument is an array of documents.
* If you omit an _id parameter on a given document, the database will create a new document and assign the ID for you.
* To update a document, you must include both an _id parameter and a _rev parameter,
* which should match the ID and revision of the document on which to base your updates.
* Finally, to delete a document, include a _deleted parameter with the value true.
*/
bulkDocs<Model>(docs: Array<Core.PutDocument<Content & Model>>,
options: Core.BulkDocsOptions | null,
callback: Core.Callback<Core.Response[]>): void;
/**
* Create, update or delete multiple documents. The docs argument is an array of documents.
* If you omit an _id parameter on a given document, the database will create a new document and assign the ID for you.
* To update a document, you must include both an _id parameter and a _rev parameter,
* which should match the ID and revision of the document on which to base your updates.
* Finally, to delete a document, include a _deleted parameter with the value true.
*/
bulkDocs<Model>(docs: Array<Core.PutDocument<Content & Model>>,
options?: Core.BulkDocsOptions): Promise<Core.Response[]>;
/** Compact the database */
compact(options?: Core.CompactOptions): Promise<Core.Response>;
/** Compact the database */
compact(options: Core.CompactOptions,
callback: Core.Callback<Core.Response>): void;
/** Destroy the database */
destroy(options: Core.Options | null,
callback: Core.Callback<any>): void;
/** Destroy the database */
destroy(options?: Core.Options | null): Promise<void>;
/** Fetch a document */
get<Model>(docId: Core.DocumentId,
options: Core.GetOptions | null,
callback: Core.Callback<Core.Document<Content & Model> & Core.GetMeta>
): void;
/** Fetch a document */
get<Model>(docId: Core.DocumentId,
options: Core.GetOpenRevisions,
callback: Core.Callback<Array<Core.Revision<Content & Model>>>
): void;
/** Fetch a document */
get<Model>(docId: Core.DocumentId,
options?: Core.GetOptions
): Promise<Core.Document<Content & Model> & Core.GetMeta>;
/** Fetch a document */
get<Model>(docId: Core.DocumentId,
options: Core.GetOpenRevisions
): Promise<Array<Core.Revision<Content & Model>>>;
/** Create a new document without providing an id.
*
* You should prefer put() to post(), because when you post(), you are
* missing an opportunity to use allDocs() to sort documents by _id
* (because your _ids are random).
*
* @see {@link https://pouchdb.com/2014/06/17/12-pro-tips-for-better-code-with-pouchdb.html|PouchDB Pro Tips}
*/
post<Model>(doc: Core.PostDocument<Content & Model>,
options: Core.Options | null,
callback: Core.Callback<Core.Response>): void;
/** Create a new document without providing an id.
*
* You should prefer put() to post(), because when you post(), you are
* missing an opportunity to use allDocs() to sort documents by _id
* (because your _ids are random).
*
* @see {@link https://pouchdb.com/2014/06/17/12-pro-tips-for-better-code-with-pouchdb.html|PouchDB Pro Tips}
*/
post<Model>(doc: Core.PostDocument<Content & Model>,
options?: Core.Options): Promise<Core.Response>;
/** Create a new document or update an existing document.
*
* If the document already exists, you must specify its revision _rev,
* otherwise a conflict will occur.
* There are some restrictions on valid property names of the documents.
* If you try to store non-JSON data (for instance Date objects) you may
* see inconsistent results.
*/
put<Model>(doc: Core.PutDocument<Content & Model>,
options: Core.Options | null,
callback: Core.Callback<Core.Response>): void;
/** Create a new document or update an existing document.
*
* If the document already exists, you must specify its revision _rev,
* otherwise a conflict will occur.
* There are some restrictions on valid property names of the documents.
* If you try to store non-JSON data (for instance Date objects) you may
* see inconsistent results.
*/
put<Model>(doc: Core.PutDocument<Content & Model>,
options?: Core.Options): Promise<Core.Response>;
/** Remove a doc from the database */
remove(doc: Core.RemoveDocument,
options: Core.Options,
callback: Core.Callback<Core.Response>): void;
/** Remove a doc from the database */
remove(docId: Core.DocumentId,
revision: Core.RevisionId,
options: Core.Options,
callback: Core.Callback<Core.Response>): void;
/** Remove a doc from the database */
remove(doc: Core.RemoveDocument,
options?: Core.Options): Promise<Core.Response>;
/** Remove a doc from the database */
remove(docId: Core.DocumentId,
revision: Core.RevisionId,
options?: Core.Options): Promise<Core.Response>;
/** Get database information */
info(callback: Core.Callback<Core.DatabaseInfo>): void;
/** Get database information */
info(): Promise<Core.DatabaseInfo>;
/**
* A list of changes made to documents in the database, in the order they were made.
* It returns an object with the method cancel(), which you call if you don’t want to listen to new changes anymore.
*
* It is an event emitter and will emit a 'change' event on each document change,
* a 'complete' event when all the changes have been processed, and an 'error' event when an error occurs.
* Calling cancel() will unsubscribe all event listeners automatically.
*/
changes<Model>(options: Core.ChangesOptions | null,
callback: Core.Callback<Core.Changes<Content & Model>>): void;
/**
* A list of changes made to documents in the database, in the order they were made.
* It returns an object with the method cancel(), which you call if you don’t want to listen to new changes anymore.
*
* It is an event emitter and will emit a 'change' event on each document change,
* a 'complete' event when all the changes have been processed, and an 'error' event when an error occurs.
* Calling cancel() will unsubscribe all event listeners automatically.
*/
changes<Model>(options?: Core.ChangesOptions): Core.Changes<Content & Model>;
/** Close the database */
close(callback: Core.Callback<any>): void;
/** Close the database */
close(): Promise<void>;
/**
* Attaches a binary object to a document.
* This method will update an existing document to add the attachment, so it requires a rev if the document already exists.
* If the document doesn’t already exist, then this method will create an empty document containing the attachment.
*/
putAttachment(docId: Core.DocumentId,
attachmentId: Core.AttachmentId,
rev: Core.RevisionId,
attachment: Core.Attachment,
type: string,
callback: Core.Callback<Core.Response>): void;
/**
* Attaches a binary object to a document.
* This method will update an existing document to add the attachment, so it requires a rev if the document already exists.
* If the document doesn’t already exist, then this method will create an empty document containing the attachment.
*/
putAttachment(docId: Core.DocumentId,
attachmentId: Core.AttachmentId,
rev: Core.RevisionId,
attachment: Core.Attachment,
type: string): Promise<Core.Response>;
/**
* Attaches a binary object to a document.
* This method will update an existing document to add the attachment, so it requires a rev if the document already exists.
* If the document doesn’t already exist, then this method will create an empty document containing the attachment.
*/
putAttachment(docId: Core.DocumentId,
attachmentId: Core.AttachmentId,
attachment: Core.Attachment,
type: string,
callback: Core.Callback<Core.Response>): void;
/**
* Attaches a binary object to a document.
* This method will update an existing document to add the attachment, so it requires a rev if the document already exists.
* If the document doesn’t already exist, then this method will create an empty document containing the attachment.
*/
putAttachment(docId: Core.DocumentId,
attachmentId: Core.AttachmentId,
attachment: Core.Attachment,
type: string): Promise<Core.Response>;
/** Get attachment data */
getAttachment(docId: Core.DocumentId,
attachmentId: Core.AttachmentId,
options: { rev?: Core.RevisionId},
callback: Core.Callback<Blob | Buffer>): void;
/** Get attachment data */
getAttachment(docId: Core.DocumentId,
attachmentId: Core.AttachmentId,
options?: { rev?: Core.RevisionId}): Promise<Blob | Buffer>;
/** Get attachment data */
getAttachment(docId: Core.DocumentId,
attachmentId: Core.AttachmentId,
callback: Core.Callback<Blob | Buffer>): void;
/** Delete an attachment from a doc. You must supply the rev of the existing doc. */
removeAttachment(docId: Core.DocumentId,
attachmentId: Core.AttachmentId,
rev: Core.RevisionId,
callback: Core.Callback<Core.RemoveAttachmentResponse>): void;
/** Delete an attachment from a doc. You must supply the rev of the existing doc. */
removeAttachment(docId: Core.DocumentId,
attachmentId: Core.AttachmentId,
rev: Core.RevisionId): Promise<Core.RemoveAttachmentResponse>;
/** Given a set of document/revision IDs, returns the document bodies (and, optionally, attachment data) for each ID/revision pair specified. */
bulkGet<Model>(options: Core.BulkGetOptions,
callback: Core.Callback<Core.BulkGetResponse<Content & Model>>): void;
/** Given a set of document/revision IDs, returns the document bodies (and, optionally, attachment data) for each ID/revision pair specified. */
bulkGet<Model>(options: Core.BulkGetOptions): Promise<Core.BulkGetResponse<Content & Model>>;
/** Given a set of document/revision IDs, returns the subset of those that do not correspond to revisions stored in the database */
revsDiff(diff: Core.RevisionDiffOptions,
callback: Core.Callback<Core.RevisionDiffResponse>): void;
/** Given a set of document/revision IDs, returns the subset of those that do not correspond to revisions stored in the database */
revsDiff(diff: Core.RevisionDiffOptions): Promise<Core.RevisionDiffResponse>;
}
}
//
declare module 'pouchdb-core' {
const PouchDb: PouchDB.Static;
export = PouchDb;
}
declare var PouchDB: PouchDB.Static;
| mit |
stowball/brackets | src/utils/ExtensionUtils.js | 10592 | /*
* Copyright (c) 2012 - present Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, $, brackets, less, PathUtils */
/**
* ExtensionUtils defines utility methods for implementing extensions.
*/
define(function (require, exports, module) {
"use strict";
var Async = require("utils/Async"),
FileSystem = require("filesystem/FileSystem"),
FileUtils = require("file/FileUtils");
/**
* Appends a <style> tag to the document's head.
*
* @param {!string} css CSS code to use as the tag's content
* @return {!HTMLStyleElement} The generated HTML node
**/
function addEmbeddedStyleSheet(css) {
return $("<style>").text(css).appendTo("head")[0];
}
/**
* Appends a <link> tag to the document's head.
*
* @param {!string} url URL to a style sheet
* @param {$.Deferred=} deferred Optionally check for load and error events
* @return {!HTMLLinkElement} The generated HTML node
**/
function addLinkedStyleSheet(url, deferred) {
var attributes = {
type: "text/css",
rel: "stylesheet",
href: url
};
var $link = $("<link/>").attr(attributes);
if (deferred) {
$link.on('load', deferred.resolve).on('error', deferred.reject);
}
$link.appendTo("head");
return $link[0];
}
/**
* getModuleUrl returns different urls for win platform
* so that's why we need a different check here
* @see #getModuleUrl
* @param {!string} pathOrUrl that should be checked if it's absolute
* @return {!boolean} returns true if pathOrUrl is absolute url on win platform
* or when it's absolute path on other platforms
*/
function isAbsolutePathOrUrl(pathOrUrl) {
return brackets.platform === "win" ? PathUtils.isAbsoluteUrl(pathOrUrl) : FileSystem.isAbsolutePath(pathOrUrl);
}
/**
* Parses LESS code and returns a promise that resolves with plain CSS code.
*
* Pass the {@link url} argument to resolve relative URLs contained in the code.
* Make sure URLs in the code are wrapped in quotes, like so:
* background-image: url("image.png");
*
* @param {!string} code LESS code to parse
* @param {?string} url URL to the file containing the code
* @return {!$.Promise} A promise object that is resolved with CSS code if the LESS code can be parsed
*/
function parseLessCode(code, url) {
var result = new $.Deferred(),
options;
if (url) {
var dir = url.slice(0, url.lastIndexOf("/") + 1);
options = {
filename: url,
rootpath: dir
};
if (isAbsolutePathOrUrl(url)) {
options.currentFileInfo = {
currentDirectory: dir,
entryPath: dir,
filename: url,
rootFilename: url,
rootpath: dir
};
}
}
less.render(code, options, function onParse(err, tree) {
if (err) {
result.reject(err);
} else {
result.resolve(tree.css);
}
});
return result.promise();
}
/**
* Returns a path to an extension module.
*
* @param {!module} module Module provided by RequireJS
* @param {?string} path Relative path from the extension folder to a file
* @return {!string} The path to the module's folder
**/
function getModulePath(module, path) {
var modulePath = module.uri.substr(0, module.uri.lastIndexOf("/") + 1);
if (path) {
modulePath += path;
}
return modulePath;
}
/**
* Returns a URL to an extension module.
*
* @param {!module} module Module provided by RequireJS
* @param {?string} path Relative path from the extension folder to a file
* @return {!string} The URL to the module's folder
**/
function getModuleUrl(module, path) {
var url = encodeURI(getModulePath(module, path));
// On Windows, $.get() fails if the url is a full pathname. To work around this,
// prepend "file:///". On the Mac, $.get() works fine if the url is a full pathname,
// but *doesn't* work if it is prepended with "file://". Go figure.
// However, the prefix "file://localhost" does work.
if (brackets.platform === "win" && url.indexOf(":") !== -1) {
url = "file:///" + url;
}
return url;
}
/**
* Performs a GET request using a path relative to an extension module.
*
* The resulting URL can be retrieved in the resolve callback by accessing
*
* @param {!module} module Module provided by RequireJS
* @param {!string} path Relative path from the extension folder to a file
* @return {!$.Promise} A promise object that is resolved with the contents of the requested file
**/
function loadFile(module, path) {
var url = PathUtils.isAbsoluteUrl(path) ? path : getModuleUrl(module, path),
promise = $.get(url);
return promise;
}
/**
* Loads a style sheet (CSS or LESS) relative to the extension module.
*
* @param {!module} module Module provided by RequireJS
* @param {!string} path Relative path from the extension folder to a CSS or LESS file
* @return {!$.Promise} A promise object that is resolved with an HTML node if the file can be loaded.
*/
function loadStyleSheet(module, path) {
var result = new $.Deferred();
loadFile(module, path)
.done(function (content) {
var url = this.url;
if (url.slice(-5) === ".less") {
parseLessCode(content, url)
.done(function (css) {
result.resolve(addEmbeddedStyleSheet(css));
})
.fail(result.reject);
} else {
var deferred = new $.Deferred(),
link = addLinkedStyleSheet(url, deferred);
deferred
.done(function () {
result.resolve(link);
})
.fail(result.reject);
}
})
.fail(result.reject);
// Summarize error info to console for easier debugging
result.fail(function (error, textStatus, httpError) {
if (error.readyState !== undefined) {
// If first arg is a jQXHR object, the real error info is in the next two args
console.error("[Extension] Unable to read stylesheet " + path + ":", textStatus, httpError);
} else {
console.error("[Extension] Unable to process stylesheet " + path, error);
}
});
return result.promise();
}
/**
* Loads the package.json file in the given extension folder as well as any additional
* metadata.
*
* If there's a .disabled file in the extension directory, then the content of package.json
* will be augmented with disabled property set to true. It will override whatever value of
* disabled might be set.
*
* @param {string} folder The extension folder.
* @return {$.Promise} A promise object that is resolved with the parsed contents of the package.json file,
* or rejected if there is no package.json with the boolean indicating whether .disabled file exists.
*/
function loadMetadata(folder) {
var packageJSONFile = FileSystem.getFileForPath(folder + "/package.json"),
disabledFile = FileSystem.getFileForPath(folder + "/.disabled"),
result = new $.Deferred(),
jsonPromise = new $.Deferred(),
disabledPromise = new $.Deferred(),
json,
disabled;
FileUtils.readAsText(packageJSONFile)
.then(function (text) {
try {
json = JSON.parse(text);
jsonPromise.resolve();
} catch (e) {
jsonPromise.reject();
}
})
.fail(jsonPromise.reject);
disabledFile.exists(function (err, exists) {
if (err) {
disabled = false;
} else {
disabled = exists;
}
disabledPromise.resolve();
});
Async.waitForAll([jsonPromise, disabledPromise])
.always(function () {
if (!json) {
result.reject(disabled);
} else {
json.disabled = disabled;
result.resolve(json);
}
});
return result.promise();
}
exports.addEmbeddedStyleSheet = addEmbeddedStyleSheet;
exports.addLinkedStyleSheet = addLinkedStyleSheet;
exports.parseLessCode = parseLessCode;
exports.getModulePath = getModulePath;
exports.getModuleUrl = getModuleUrl;
exports.loadFile = loadFile;
exports.loadStyleSheet = loadStyleSheet;
exports.loadMetadata = loadMetadata;
});
| mit |
russellmcc/audiounitjs | Template/AUJS Source/CoreAudio/AudioUnits/AUPublic/OtherBases/AUPannerBase.cpp | 23137 | /* Copyright © 2007 Apple Inc. All Rights Reserved.
Disclaimer: IMPORTANT: This Apple software is supplied to you by
Apple Inc. ("Apple") in consideration of your agreement to the
following terms, and your use, installation, modification or
redistribution of this Apple software constitutes acceptance of these
terms. If you do not agree with these terms, please do not use,
install, modify or redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and
subject to these terms, Apple grants you a personal, non-exclusive
license, under Apple's copyrights in this original Apple software (the
"Apple Software"), to use, reproduce, modify and redistribute the Apple
Software, with or without modifications, in source and/or binary forms;
provided that if you redistribute the Apple Software in its entirety and
without modifications, you must retain this notice and the following
text and disclaimers in all such redistributions of the Apple Software.
Neither the name, trademarks, service marks or logos of Apple Inc.
may be used to endorse or promote products derived from the Apple
Software without specific prior written permission from Apple. Except
as expressly stated in this notice, no other rights or licenses, express
or implied, are granted by Apple herein, including but not limited to
any patent rights that may be infringed by your derivative works or by
other works in which the Apple Software may be incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE
MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "AUPannerBase.h"
#include "CABundleLocker.h"
#include <AudioToolbox/AudioToolbox.h>
#include <Accelerate/Accelerate.h>
static bool sLocalized = false;
static CFStringRef kPanner_Azimuth_Name = CFSTR("azimuth");
static CFStringRef kPanner_Elevation_Name = CFSTR("elevation");
static CFStringRef kPanner_Distance_Name = CFSTR("distance");
static CFStringRef kPanner_CoordScale_Name = CFSTR("coordinate scale");
static CFStringRef kPanner_RefDistance_Name = CFSTR("reference distance");
static CFStringRef kPanner_Gain_Name = CFSTR("gain");
static Float32 kPannerParamDefault_Azimuth = 0.;
static Float32 kPannerParamDefault_Elevation = 0.;
static Float32 kPannerParamDefault_Distance = 1.;
static Float32 kPannerParamDefault_CoordScale = 10.;
static Float32 kPannerParamDefault_RefDistance = 1.;
static Float32 kPannerParamDefault_Gain = 1.;
//_____________________________________________________________________________
//
AUPannerBase::AUPannerBase(AudioComponentInstance inAudioUnit)
: AUBase(inAudioUnit, 1, 1), mBypassEffect(false)
{
{
CABundleLocker lock;
if (!sLocalized)
{
CFBundleRef bundle = CFBundleGetBundleWithIdentifier( CFSTR("com.apple.audio.units.Components") );
if (bundle != NULL)
{
kPanner_Azimuth_Name = CFCopyLocalizedStringFromTableInBundle(kPanner_Azimuth_Name, CFSTR("AudioUnits"), bundle, CFSTR(""));
kPanner_Elevation_Name = CFCopyLocalizedStringFromTableInBundle(kPanner_Elevation_Name, CFSTR("AudioUnits"), bundle, CFSTR(""));
kPanner_Distance_Name = CFCopyLocalizedStringFromTableInBundle(kPanner_Distance_Name, CFSTR("AudioUnits"), bundle, CFSTR(""));
kPanner_CoordScale_Name = CFCopyLocalizedStringFromTableInBundle(kPanner_CoordScale_Name, CFSTR("AudioUnits"), bundle, CFSTR(""));
kPanner_RefDistance_Name = CFCopyLocalizedStringFromTableInBundle(kPanner_RefDistance_Name, CFSTR("AudioUnits"), bundle, CFSTR(""));
kPanner_Gain_Name = CFCopyLocalizedStringFromTableInBundle(kPanner_Gain_Name, CFSTR("AudioUnits"), bundle, CFSTR(""));
}
sLocalized = true;
}
}
CreateElements();
SetParameter(kPannerParam_Azimuth, kPannerParamDefault_Azimuth);
SetParameter(kPannerParam_Elevation, kPannerParamDefault_Elevation);
SetParameter(kPannerParam_Distance, kPannerParamDefault_Distance);
SetParameter(kPannerParam_CoordScale, kPannerParamDefault_CoordScale);
SetParameter(kPannerParam_RefDistance, kPannerParamDefault_RefDistance);
SetParameter(kPannerParam_Gain, kPannerParamDefault_Gain);
}
//_____________________________________________________________________________
//
AUPannerBase::~AUPannerBase()
{
Cleanup();
}
//_____________________________________________________________________________
//
/*! @method Initialize */
OSStatus AUPannerBase::Initialize()
{
OSStatus err = noErr;
AllocBypassMatrix();
err = UpdateBypassMatrix();
return err;
}
//_____________________________________________________________________________
//
/*! @method AllocBypassMatrix */
void AUPannerBase::AllocBypassMatrix()
{
UInt32 inChannels = GetNumberOfInputChannels();
UInt32 outChannels = GetNumberOfOutputChannels();
mBypassMatrix.alloc(inChannels * outChannels, true);
}
static AudioChannelLayoutTag DefaultTagForNumberOfChannels(UInt32 inNumberChannels)
{
switch (inNumberChannels) {
case 1: return kAudioChannelLayoutTag_Mono;
case 2: return kAudioChannelLayoutTag_Stereo;
case 4: return kAudioChannelLayoutTag_Quadraphonic;
case 5: return kAudioChannelLayoutTag_AudioUnit_5_0;
case 6: return kAudioChannelLayoutTag_AudioUnit_6_0;
case 7: return kAudioChannelLayoutTag_AudioUnit_7_0;
case 8: return kAudioChannelLayoutTag_AudioUnit_8;
default: return 0xFFFF0000 | inNumberChannels;
}
}
//_____________________________________________________________________________
//
/*! @method UpdateBypassMatrix */
OSStatus AUPannerBase::SetDefaultChannelLayoutsIfNone()
{
OSStatus err = noErr;
// if layout has not been set, then guess layout from number of channels
UInt32 inChannels = GetNumberOfInputChannels();
AudioChannelLayout inputLayoutSubstitute;
const AudioChannelLayout* inputLayout = &GetInputLayout();
if (inputLayout == NULL || inputLayout->mChannelLayoutTag == 0) {
inputLayout = &inputLayoutSubstitute;
inputLayoutSubstitute.mNumberChannelDescriptions = 0;
inputLayoutSubstitute.mChannelBitmap = 0;
inputLayoutSubstitute.mChannelLayoutTag = DefaultTagForNumberOfChannels(inChannels);
mInputLayout = &inputLayoutSubstitute;
err = SetAudioChannelLayout(kAudioUnitScope_Input, 0, &GetInputLayout());
if (err) return err;
}
// if layout has not been set, then guess layout from number of channels
UInt32 outChannels = GetNumberOfOutputChannels();
AudioChannelLayout outputLayoutSubstitute;
const AudioChannelLayout* outputLayout = &GetOutputLayout();
if (outputLayout == NULL || outputLayout->mChannelLayoutTag == 0) {
outputLayout = &outputLayoutSubstitute;
outputLayoutSubstitute.mNumberChannelDescriptions = 0;
outputLayoutSubstitute.mChannelBitmap = 0;
outputLayoutSubstitute.mChannelLayoutTag = DefaultTagForNumberOfChannels(outChannels);
mOutputLayout = &outputLayoutSubstitute;
err = SetAudioChannelLayout(kAudioUnitScope_Output, 0, &GetOutputLayout());
if (err) return err;
}
return err;
}
OSStatus AUPannerBase::UpdateBypassMatrix()
{
OSStatus err = SetDefaultChannelLayoutsIfNone();
if (err) return err;
UInt32 inChannels = GetNumberOfInputChannels();
UInt32 outChannels = GetNumberOfOutputChannels();
const AudioChannelLayout* inoutACL[2];
inoutACL[0] = &GetInputLayout();
inoutACL[1] = &GetOutputLayout();
mBypassMatrix.alloc(inChannels * outChannels, true);
UInt32 propSize = inChannels * outChannels * sizeof(Float32);
err = AudioFormatGetProperty(kAudioFormatProperty_MatrixMixMap, sizeof(inoutACL), inoutACL, &propSize, mBypassMatrix());
if (err) {
// if there is an error, use a diagonal matrix.
Float32* bypass = mBypassMatrix();
for (UInt32 chan = 0; chan < std::min(inChannels, outChannels); ++chan)
{
float *amp = bypass + (chan * outChannels + chan);
*amp = 1.;
}
}
return noErr;
}
//_____________________________________________________________________________
//
/*! @method Cleanup */
void AUPannerBase::Cleanup()
{
}
//_____________________________________________________________________________
//
/*! @method Reset */
OSStatus AUPannerBase::Reset( AudioUnitScope inScope,
AudioUnitElement inElement)
{
return AUBase::Reset(inScope, inElement);
}
//_____________________________________________________________________________
//
/*! @method GetParameterInfo */
OSStatus AUPannerBase::GetParameterInfo( AudioUnitScope inScope,
AudioUnitParameterID inParameterID,
AudioUnitParameterInfo &outParameterInfo )
{
OSStatus result = noErr;
outParameterInfo.flags = kAudioUnitParameterFlag_IsWritable
+ kAudioUnitParameterFlag_IsReadable;
if (inScope == kAudioUnitScope_Global) {
switch(inParameterID)
{
case kPannerParam_Azimuth:
AUBase::FillInParameterName (outParameterInfo, kPanner_Azimuth_Name, false);
outParameterInfo.unit = kAudioUnitParameterUnit_Degrees;
outParameterInfo.minValue = -180.;
outParameterInfo.maxValue = 180;
outParameterInfo.defaultValue = kPannerParamDefault_Azimuth;
break;
case kPannerParam_Elevation:
AUBase::FillInParameterName (outParameterInfo, kPanner_Elevation_Name, false);
outParameterInfo.unit = kAudioUnitParameterUnit_Degrees;
outParameterInfo.minValue = -90.;
outParameterInfo.maxValue = 90;
outParameterInfo.defaultValue = kPannerParamDefault_Elevation;
break;
case kPannerParam_Distance:
AUBase::FillInParameterName (outParameterInfo, kPanner_Distance_Name, false);
outParameterInfo.unit = kAudioUnitParameterUnit_Generic;
outParameterInfo.minValue = 0.0;
outParameterInfo.maxValue = 1.;
outParameterInfo.defaultValue = kPannerParamDefault_Distance;
outParameterInfo.flags += kAudioUnitParameterFlag_IsHighResolution;
//outParameterInfo.flags += kAudioUnitParameterFlag_DisplayLogarithmic;
break;
case kPannerParam_CoordScale:
AUBase::FillInParameterName (outParameterInfo, kPanner_CoordScale_Name, false);
outParameterInfo.unit = kAudioUnitParameterUnit_Meters;
outParameterInfo.minValue = 0.01;
outParameterInfo.maxValue = 1000.;
outParameterInfo.defaultValue = kPannerParamDefault_CoordScale;
outParameterInfo.flags += kAudioUnitParameterFlag_DisplayLogarithmic;
break;
case kPannerParam_RefDistance:
AUBase::FillInParameterName (outParameterInfo, kPanner_RefDistance_Name, false);
outParameterInfo.unit = kAudioUnitParameterUnit_Meters;
outParameterInfo.minValue = 0.01;
outParameterInfo.maxValue = 1000.;
outParameterInfo.defaultValue = kPannerParamDefault_RefDistance;
outParameterInfo.flags += kAudioUnitParameterFlag_DisplayLogarithmic;
break;
case kPannerParam_Gain:
AUBase::FillInParameterName (outParameterInfo, kPanner_Gain_Name, false);
outParameterInfo.unit = kAudioUnitParameterUnit_Generic;
outParameterInfo.minValue = 0.;
outParameterInfo.maxValue = 1.;
outParameterInfo.defaultValue = kPannerParamDefault_Gain;
break;
default:
result = kAudioUnitErr_InvalidParameter;
break;
}
} else {
result = kAudioUnitErr_InvalidParameter;
}
return result;
}
//_____________________________________________________________________________
//
OSStatus AUPannerBase::GetParameter( AudioUnitParameterID inParamID,
AudioUnitScope inScope,
AudioUnitElement inElement,
Float32 & outValue)
{
if (inScope != kAudioUnitScope_Global)
return kAudioUnitErr_InvalidScope;
outValue = Globals()->GetParameter(inParamID);
return noErr;
}
//_____________________________________________________________________________
//
OSStatus AUPannerBase::SetParameter( AudioUnitParameterID inParamID,
AudioUnitScope inScope,
AudioUnitElement inElement,
Float32 inValue,
UInt32 inBufferOffsetInFrames)
{
if (inScope != kAudioUnitScope_Global)
return kAudioUnitErr_InvalidScope;
Globals()->SetParameter(inParamID, inValue);
return noErr;
}
//_____________________________________________________________________________
//
/*! @method GetPropertyInfo */
OSStatus AUPannerBase::GetPropertyInfo (AudioUnitPropertyID inID,
AudioUnitScope inScope,
AudioUnitElement inElement,
UInt32 & outDataSize,
Boolean & outWritable)
{
OSStatus err = noErr;
switch (inID) {
case kAudioUnitProperty_BypassEffect:
if (inScope != kAudioUnitScope_Global)
return kAudioUnitErr_InvalidScope;
outWritable = true;
outDataSize = sizeof (UInt32);
break;
default:
err = AUBase::GetPropertyInfo(inID, inScope, inElement, outDataSize, outWritable);
}
return err;
}
//_____________________________________________________________________________
//
/*! @method GetProperty */
OSStatus AUPannerBase::GetProperty (AudioUnitPropertyID inID,
AudioUnitScope inScope,
AudioUnitElement inElement,
void * outData)
{
OSStatus err = noErr;
switch (inID)
{
case kAudioUnitProperty_BypassEffect:
if (inScope != kAudioUnitScope_Global)
return kAudioUnitErr_InvalidScope;
*((UInt32*)outData) = (IsBypassEffect() ? 1 : 0);
break;
default:
err = AUBase::GetProperty(inID, inScope, inElement, outData);
}
return err;
}
//_____________________________________________________________________________
//
/*! @method SetProperty */
OSStatus AUPannerBase::SetProperty(AudioUnitPropertyID inID,
AudioUnitScope inScope,
AudioUnitElement inElement,
const void * inData,
UInt32 inDataSize)
{
switch (inID)
{
case kAudioUnitProperty_BypassEffect:
if (inDataSize < sizeof(UInt32))
return kAudioUnitErr_InvalidPropertyValue;
bool tempNewSetting = *((UInt32*)inData) != 0;
// we're changing the state of bypass
if (tempNewSetting != IsBypassEffect())
{
if (!tempNewSetting && IsBypassEffect() && IsInitialized()) // turning bypass off and we're initialized
Reset(0, 0);
SetBypassEffect (tempNewSetting);
}
return noErr;
}
return AUBase::SetProperty(inID, inScope, inElement, inData, inDataSize);
}
//_____________________________________________________________________________
//
/*! @method StreamFormatWritable */
bool AUPannerBase::StreamFormatWritable (AudioUnitScope scope,
AudioUnitElement element)
{
return true;
}
//_____________________________________________________________________________
//
/*! @method ChangeStreamFormat */
OSStatus AUPannerBase::ChangeStreamFormat (
AudioUnitScope inScope,
AudioUnitElement inElement,
const CAStreamBasicDescription & inPrevFormat,
const CAStreamBasicDescription & inNewFormat)
{
if (inScope == kAudioUnitScope_Input && !InputChannelConfigIsSupported(inNewFormat.NumberChannels()))
return kAudioUnitErr_FormatNotSupported;
if (inScope == kAudioUnitScope_Output && !OutputChannelConfigIsSupported(inNewFormat.NumberChannels()))
return kAudioUnitErr_FormatNotSupported;
if (inNewFormat.NumberChannels() != inPrevFormat.NumberChannels())
RemoveAudioChannelLayout(inScope, inElement);
return AUBase::ChangeStreamFormat(inScope, inElement, inPrevFormat, inNewFormat);
}
//_____________________________________________________________________________
//
/*! @method Render */
OSStatus AUPannerBase::Render(AudioUnitRenderActionFlags & ioActionFlags,
const AudioTimeStamp & inTimeStamp,
UInt32 inNumberFrames)
{
if (IsBypassEffect())
return BypassRender(ioActionFlags, inTimeStamp, inNumberFrames);
else
return PannerRender(ioActionFlags, inTimeStamp, inNumberFrames);
}
//_____________________________________________________________________________
//
/*! @method Render */
OSStatus AUPannerBase::BypassRender(AudioUnitRenderActionFlags & ioActionFlags,
const AudioTimeStamp & inTimeStamp,
UInt32 inNumberFrames)
{
AudioUnitRenderActionFlags xflags = 0;
OSStatus result = PullInput(0, xflags, inTimeStamp, inNumberFrames);
if (result) return false;
bool isSilent = xflags & kAudioUnitRenderAction_OutputIsSilence;
AudioBufferList& outputBufferList = GetOutput(0)->GetBufferList();
AUBufferList::ZeroBuffer(outputBufferList);
if (!isSilent)
{
UInt32 inChannels = GetNumberOfInputChannels();
UInt32 outChannels = GetNumberOfOutputChannels();
Float32* bypass = mBypassMatrix();
for (UInt32 outChan = 0; outChan < outChannels; ++outChan)
{
float* outData = GetOutput(0)->GetChannelData(outChan);
for (UInt32 inChan = 0; inChan < inChannels; ++inChan)
{
float* inData = GetInput(0)->GetChannelData(inChan);
float *amp = bypass + (inChan * outChannels + outChan);
vDSP_vsma(inData, 1, amp, outData, 1, outData, 1, inNumberFrames);
}
}
}
return noErr;
}
//_____________________________________________________________________________
//
UInt32 AUPannerBase::GetAudioChannelLayout( AudioUnitScope inScope,
AudioUnitElement inElement,
AudioChannelLayout * outLayoutPtr,
Boolean & outWritable)
{
SetDefaultChannelLayoutsIfNone();
outWritable = true;
CAAudioChannelLayout* caacl = NULL;
switch (inScope)
{
case kAudioUnitScope_Input:
caacl = &mInputLayout;
break;
case kAudioUnitScope_Output:
caacl = &mOutputLayout;
break;
default:
COMPONENT_THROW(kAudioUnitErr_InvalidScope);
}
if (inElement != 0)
COMPONENT_THROW(kAudioUnitErr_InvalidElement);
UInt32 size = caacl->IsValid() ? caacl->Size() : 0;
if (size > 0 && outLayoutPtr)
memcpy(outLayoutPtr, &caacl->Layout(), size);
return size;
}
//_____________________________________________________________________________
//
OSStatus AUPannerBase::RemoveAudioChannelLayout( AudioUnitScope inScope,
AudioUnitElement inElement)
{
CAAudioChannelLayout* caacl = NULL;
switch (inScope)
{
case kAudioUnitScope_Input:
caacl = &mInputLayout;
break;
case kAudioUnitScope_Output:
caacl = &mOutputLayout;
break;
default:
return kAudioUnitErr_InvalidScope;
}
if (inElement != 0)
return kAudioUnitErr_InvalidElement;
*caacl = NULL;
return noErr;
}
//_____________________________________________________________________________
//
OSStatus AUPannerBase::SetAudioChannelLayout( AudioUnitScope inScope,
AudioUnitElement inElement,
const AudioChannelLayout * inLayout)
{
if (!inLayout)
return RemoveAudioChannelLayout(inScope, inElement);
if (!ChannelLayoutTagIsSupported(inScope, inElement, inLayout->mChannelLayoutTag))
return kAudioUnitErr_FormatNotSupported;
CAAudioChannelLayout* caacl = NULL;
UInt32 currentChannels;
switch (inScope)
{
case kAudioUnitScope_Input:
caacl = &mInputLayout;
currentChannels = GetNumberOfInputChannels();
break;
case kAudioUnitScope_Output:
caacl = &mOutputLayout;
currentChannels = GetNumberOfOutputChannels();
break;
default:
return kAudioUnitErr_InvalidScope;
}
if (inElement != 0)
return kAudioUnitErr_InvalidElement;
UInt32 numChannelsInLayout = CAAudioChannelLayout::NumberChannels(*inLayout);
if (currentChannels != numChannelsInLayout)
return kAudioUnitErr_InvalidPropertyValue;
*caacl = inLayout;
if (IsInitialized())
UpdateBypassMatrix();
return noErr;
}
//_____________________________________________________________________________
//
UInt32 AUPannerBase::GetChannelLayoutTags( AudioUnitScope inScope,
AudioUnitElement inElement,
AudioChannelLayoutTag* outTags)
{
switch (inScope)
{
case kAudioUnitScope_Input:
if (outTags) {
outTags[0] = kAudioChannelLayoutTag_Mono;
outTags[1] = kAudioChannelLayoutTag_Stereo;
outTags[2] = kAudioChannelLayoutTag_Ambisonic_B_Format;
}
return 3;
case kAudioUnitScope_Output:
if (outTags) {
outTags[0] = kAudioChannelLayoutTag_Stereo;
outTags[1] = kAudioChannelLayoutTag_Quadraphonic;
outTags[2] = kAudioChannelLayoutTag_AudioUnit_5_0;
outTags[3] = kAudioChannelLayoutTag_AudioUnit_6_0;
outTags[4] = kAudioChannelLayoutTag_AudioUnit_7_0;
outTags[5] = kAudioChannelLayoutTag_AudioUnit_7_0_Front;
outTags[6] = kAudioChannelLayoutTag_AudioUnit_8;
}
return 7;
default: {
OSStatus err = kAudioUnitErr_InvalidScope;
throw err;
}
}
}
//_____________________________________________________________________________
//
bool AUPannerBase::ChannelConfigIsSupported()
{
UInt32 inChannels = GetNumberOfInputChannels();
UInt32 outChannels = GetNumberOfOutputChannels();
const AUChannelInfo* cinfo = NULL;
UInt32 numConfigs = SupportedNumChannels(&cinfo);
for (UInt32 i = 0; i < numConfigs; ++i)
{
if (cinfo[i].inChannels == (SInt16)inChannels && cinfo[i].outChannels == (SInt16)outChannels)
return true;
}
return false;
}
//_____________________________________________________________________________
//
bool AUPannerBase::InputChannelConfigIsSupported(UInt32 inNumberChannels)
{
const AUChannelInfo* cinfo = NULL;
UInt32 numConfigs = SupportedNumChannels(&cinfo);
for (UInt32 i = 0; i < numConfigs; ++i)
{
if (cinfo[i].inChannels == (SInt16)inNumberChannels)
return true;
}
return false;
}
//_____________________________________________________________________________
//
bool AUPannerBase::OutputChannelConfigIsSupported(UInt32 inNumberChannels)
{
const AUChannelInfo* cinfo = NULL;
UInt32 numConfigs = SupportedNumChannels(&cinfo);
for (UInt32 i = 0; i < numConfigs; ++i)
{
if (cinfo[i].outChannels == (SInt16)inNumberChannels)
return true;
}
return false;
}
//_____________________________________________________________________________
//
bool AUPannerBase::ChannelLayoutTagIsSupported( AudioUnitScope inScope,
AudioUnitElement inElement,
AudioChannelLayoutTag inTag)
{
UInt32 numTags = GetChannelLayoutTags(inScope, inElement, NULL);
CAAutoFree<AudioChannelLayoutTag> tags(numTags);
GetChannelLayoutTags(inScope, inElement, tags());
for (UInt32 i = 0; i < numTags; ++i)
{
if (tags[i] == inTag)
return true;
}
return false;
}
| mit |
EPTamminga/Dnn.Platform | DNN Platform/Library/Security/Permissions/Controls/PermissionsGrid.cs | 50536 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information
namespace DotNetNuke.Security.Permissions.Controls
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Entities.Users;
using DotNetNuke.Framework;
using DotNetNuke.Security.Roles;
using DotNetNuke.Services.Localization;
using DotNetNuke.UI.WebControls;
using DotNetNuke.UI.WebControls.Internal;
using DotNetNuke.Web.Client;
using DotNetNuke.Web.Client.ClientResourceManagement;
using Globals = DotNetNuke.Common.Globals;
public abstract class PermissionsGrid : Control, INamingContainer
{
protected const string PermissionTypeGrant = "True";
protected const string PermissionTypeDeny = "False";
protected const string PermissionTypeNull = "Null";
protected DataGrid rolePermissionsGrid;
protected DataGrid userPermissionsGrid;
private ArrayList _permissions;
private ArrayList _users;
private DropDownList cboRoleGroups;
private DropDownList cboSelectRole;
private LinkButton cmdUser;
private LinkButton cmdRole;
private Label lblGroups;
private Label lblSelectRole;
private Label lblErrorMessage;
private Panel pnlPermissions;
private TextBox txtUser;
private HiddenField hiddenUserIds;
private HiddenField roleField;
private int unAuthUsersRoleId = int.Parse(Globals.glbRoleUnauthUser);
private int allUsersRoleId = int.Parse(Globals.glbRoleAllUsers);
public PermissionsGrid()
{
this.dtUserPermissions = new DataTable();
this.dtRolePermissions = new DataTable();
}
public TableItemStyle AlternatingItemStyle
{
get
{
return this.rolePermissionsGrid.AlternatingItemStyle;
}
}
public DataGridColumnCollection Columns
{
get
{
return this.rolePermissionsGrid.Columns;
}
}
public TableItemStyle FooterStyle
{
get
{
return this.rolePermissionsGrid.FooterStyle;
}
}
public TableItemStyle HeaderStyle
{
get
{
return this.rolePermissionsGrid.HeaderStyle;
}
}
public TableItemStyle ItemStyle
{
get
{
return this.rolePermissionsGrid.ItemStyle;
}
}
public DataGridItemCollection Items
{
get
{
return this.rolePermissionsGrid.Items;
}
}
public TableItemStyle SelectedItemStyle
{
get
{
return this.rolePermissionsGrid.SelectedItemStyle;
}
}
/// <summary>
/// Gets the Id of the Administrator Role.
/// </summary>
public int AdministratorRoleId
{
get
{
return PortalController.Instance.GetCurrentPortalSettings().AdministratorRoleId;
}
}
/// <summary>
/// Gets the Id of the Registered Users Role.
/// </summary>
public int RegisteredUsersRoleId
{
get
{
return PortalController.Instance.GetCurrentPortalSettings().RegisteredRoleId;
}
}
/// <summary>
/// Gets the Id of the Portal.
/// </summary>
public int PortalId
{
get
{
// Obtain PortalSettings from Current Context
var portalSettings = PortalController.Instance.GetCurrentPortalSettings();
int portalID;
if (Globals.IsHostTab(portalSettings.ActiveTab.TabID)) // if we are in host filemanager then we need to pass a null portal id
{
portalID = Null.NullInteger;
}
else
{
portalID = portalSettings.PortalId;
}
return portalID;
}
}
public bool AutoGenerateColumns
{
get
{
return this.rolePermissionsGrid.AutoGenerateColumns;
}
set
{
this.rolePermissionsGrid.AutoGenerateColumns = value;
this.userPermissionsGrid.AutoGenerateColumns = value;
}
}
public int CellSpacing
{
get
{
return this.rolePermissionsGrid.CellSpacing;
}
set
{
this.rolePermissionsGrid.CellSpacing = value;
this.userPermissionsGrid.CellSpacing = value;
}
}
public GridLines GridLines
{
get
{
return this.rolePermissionsGrid.GridLines;
}
set
{
this.rolePermissionsGrid.GridLines = value;
this.userPermissionsGrid.GridLines = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether gets and Sets whether a Dynamic Column has been added.
/// </summary>
public bool DynamicColumnAdded
{
get
{
return this.ViewState["ColumnAdded"] != null;
}
set
{
this.ViewState["ColumnAdded"] = value;
}
}
/// <summary>
/// Gets the underlying Permissions Data Table.
/// </summary>
public DataTable dtRolePermissions { get; private set; }
/// <summary>
/// Gets the underlying Permissions Data Table.
/// </summary>
public DataTable dtUserPermissions { get; private set; }
/// <summary>
/// Gets or sets and Sets the collection of Roles to display.
/// </summary>
public ArrayList Roles { get; set; }
/// <summary>
/// Gets or sets and Sets the ResourceFile to localize permissions.
/// </summary>
public string ResourceFile { get; set; }
protected virtual List<PermissionInfoBase> PermissionsList
{
get
{
return null;
}
}
protected virtual bool RefreshGrid
{
get
{
return false;
}
}
private int UnAuthUsersRoleId
{
get { return this.unAuthUsersRoleId; }
}
private int AllUsersRoleId
{
get
{
return this.allUsersRoleId;
}
}
/// <summary>
/// Registers the scripts neccesary to make the tri-state controls work inside a RadAjaxPanel.
/// </summary>
/// <remarks>
/// No need to call this unless using the PermissionGrid inside an ajax control that omits scripts on postback
/// See DesktopModules/Admin/Tabs.ascx.cs for an example of usage.
/// </remarks>
public void RegisterScriptsForAjaxPanel()
{
PermissionTriState.RegisterScripts(this.Page, this);
}
/// <summary>
/// Generate the Data Grid.
/// </summary>
public abstract void GenerateDataGrid();
protected virtual void AddPermission(PermissionInfo permission, int roleId, string roleName, int userId, string displayName, bool allowAccess)
{
}
/// <summary>
/// Updates a Permission.
/// </summary>
/// <param name="permissions">The permissions collection.</param>
/// <param name="user">The user to add.</param>
protected virtual void AddPermission(ArrayList permissions, UserInfo user)
{
}
/// <summary>
/// Updates a Permission.
/// </summary>
/// <param name="permissions">The permissions collection.</param>
/// <param name="role">The role to add.</param>
protected virtual void AddPermission(ArrayList permissions, RoleInfo role)
{
}
/// <summary>
/// Builds the key used to store the "permission" information in the ViewState.
/// </summary>
/// <param name="allowAccess">The type of permission ( grant / deny ).</param>
/// <param name="permissionId">The Id of the permission.</param>
/// <param name="objectPermissionId">The Id of the object permission.</param>
/// <param name="roleId">The role id.</param>
/// <param name="roleName">The role name.</param>
/// <returns></returns>
protected string BuildKey(bool allowAccess, int permissionId, int objectPermissionId, int roleId, string roleName)
{
return this.BuildKey(allowAccess, permissionId, objectPermissionId, roleId, roleName, Null.NullInteger, Null.NullString);
}
/// <summary>
/// Builds the key used to store the "permission" information in the ViewState.
/// </summary>
/// <param name="allowAccess">The type of permission ( grant / deny ).</param>
/// <param name="permissionId">The Id of the permission.</param>
/// <param name="objectPermissionId">The Id of the object permission.</param>
/// <param name="roleId">The role id.</param>
/// <param name="roleName">The role name.</param>
/// <param name="userID">The user id.</param>
/// <param name="displayName">The user display name.</param>
/// <returns></returns>
protected string BuildKey(bool allowAccess, int permissionId, int objectPermissionId, int roleId, string roleName, int userID, string displayName)
{
string key;
if (allowAccess)
{
key = "True";
}
else
{
key = "False";
}
key += "|" + Convert.ToString(permissionId);
key += "|";
if (objectPermissionId > -1)
{
key += Convert.ToString(objectPermissionId);
}
key += "|" + roleName;
key += "|" + roleId;
key += "|" + userID;
key += "|" + displayName;
return key;
}
/// <summary>
/// Creates the Child Controls.
/// </summary>
protected override void CreateChildControls()
{
this._permissions = this.GetPermissions();
this.pnlPermissions = new Panel { CssClass = "dnnGrid dnnPermissionsGrid" };
// Optionally Add Role Group Filter
this.CreateAddRoleControls();
this.rolePermissionsGrid = new DataGrid
{
AutoGenerateColumns = false,
CellSpacing = 0,
CellPadding = 2,
GridLines = GridLines.None,
CssClass = "dnnPermissionsGrid",
};
this.rolePermissionsGrid.FooterStyle.CssClass = "dnnGridFooter";
this.rolePermissionsGrid.HeaderStyle.CssClass = "dnnGridHeader";
this.rolePermissionsGrid.ItemStyle.CssClass = "dnnGridItem";
this.rolePermissionsGrid.AlternatingItemStyle.CssClass = "dnnGridAltItem";
this.rolePermissionsGrid.ItemDataBound += this.rolePermissionsGrid_ItemDataBound;
this.SetUpRolesGrid();
this.pnlPermissions.Controls.Add(this.rolePermissionsGrid);
this._users = this.GetUsers();
if (this._users != null)
{
this.userPermissionsGrid = new DataGrid
{
AutoGenerateColumns = false,
CellSpacing = 0,
GridLines = GridLines.None,
CssClass = "dnnPermissionsGrid",
};
this.userPermissionsGrid.FooterStyle.CssClass = "dnnGridFooter";
this.userPermissionsGrid.HeaderStyle.CssClass = "dnnGridHeader";
this.userPermissionsGrid.ItemStyle.CssClass = "dnnGridItem";
this.userPermissionsGrid.AlternatingItemStyle.CssClass = "dnnGridAltItem";
this.SetUpUsersGrid();
this.pnlPermissions.Controls.Add(this.userPermissionsGrid);
var divAddUser = new Panel { CssClass = "dnnFormItem" };
this.lblErrorMessage = new Label { Text = Localization.GetString("DisplayName") };
this.txtUser = new TextBox { ID = "txtUser" };
this.lblErrorMessage.AssociatedControlID = this.txtUser.ID;
this.hiddenUserIds = new HiddenField { ID = "hiddenUserIds" };
divAddUser.Controls.Add(this.lblErrorMessage);
divAddUser.Controls.Add(this.txtUser);
divAddUser.Controls.Add(this.hiddenUserIds);
this.cmdUser = new LinkButton { Text = Localization.GetString("Add"), CssClass = "dnnSecondaryAction" };
divAddUser.Controls.Add(this.cmdUser);
this.cmdUser.Click += this.AddUser;
this.pnlPermissions.Controls.Add(divAddUser);
}
this.Controls.Add(this.pnlPermissions);
}
/// <summary>
/// Gets the Enabled status of the permission.
/// </summary>
/// <param name="objPerm">The permission being loaded.</param>
/// <param name="role">The role.</param>
/// <param name="column">The column of the Grid.</param>
/// <returns></returns>
protected virtual bool GetEnabled(PermissionInfo objPerm, RoleInfo role, int column)
{
return true;
}
/// <summary>
/// Gets the Enabled status of the permission.
/// </summary>
/// <param name="objPerm">The permission being loaded.</param>
/// <param name="user">The user.</param>
/// <param name="column">The column of the Grid.</param>
/// <returns></returns>
protected virtual bool GetEnabled(PermissionInfo objPerm, UserInfo user, int column)
{
return true;
}
/// <summary>
/// Gets the Value of the permission.
/// </summary>
/// <param name="objPerm">The permission being loaded.</param>
/// <param name="role">The role.</param>
/// <param name="column">The column of the Grid.</param>
/// <returns></returns>
protected virtual bool GetPermission(PermissionInfo objPerm, RoleInfo role, int column)
{
return Convert.ToBoolean(this.GetPermission(objPerm, role, column, PermissionTypeDeny));
}
/// <summary>
/// Gets the Value of the permission.
/// </summary>
/// <param name="objPerm">The permission being loaded.</param>
/// <param name="role">The role.</param>
/// <param name="column">The column of the Grid.</param>
/// <param name="defaultState">Default State.</param>
/// <returns></returns>
protected virtual string GetPermission(PermissionInfo objPerm, RoleInfo role, int column, string defaultState)
{
string stateKey = defaultState;
if (this.PermissionsList != null)
{
foreach (PermissionInfoBase permission in this.PermissionsList)
{
if (permission.PermissionID == objPerm.PermissionID && permission.RoleID == role.RoleID)
{
if (permission.AllowAccess)
{
stateKey = PermissionTypeGrant;
}
else
{
stateKey = PermissionTypeDeny;
}
break;
}
}
}
return stateKey;
}
/// <summary>
/// Gets the Value of the permission.
/// </summary>
/// <param name="objPerm">The permission being loaded.</param>
/// <param name="user">The user.</param>
/// <param name="column">The column of the Grid.</param>
/// <returns></returns>
protected virtual bool GetPermission(PermissionInfo objPerm, UserInfo user, int column)
{
return Convert.ToBoolean(this.GetPermission(objPerm, user, column, PermissionTypeDeny));
}
/// <summary>
/// Gets the Value of the permission.
/// </summary>
/// <param name="objPerm">The permission being loaded.</param>
/// <param name="user">The user.</param>
/// <param name="column">The column of the Grid.</param>
/// <param name="defaultState">Default State.</param>
/// <returns></returns>
protected virtual string GetPermission(PermissionInfo objPerm, UserInfo user, int column, string defaultState)
{
var stateKey = defaultState;
if (this.PermissionsList != null)
{
foreach (var permission in this.PermissionsList)
{
if (permission.PermissionID == objPerm.PermissionID && permission.UserID == user.UserID)
{
if (permission.AllowAccess)
{
stateKey = PermissionTypeGrant;
}
else
{
stateKey = PermissionTypeDeny;
}
break;
}
}
}
return stateKey;
}
/// <summary>
/// Gets the permissions from the Database.
/// </summary>
/// <returns></returns>
protected virtual ArrayList GetPermissions()
{
return null;
}
/// <summary>
/// Gets the users from the Database.
/// </summary>
/// <returns></returns>
protected virtual ArrayList GetUsers()
{
var arrUsers = new ArrayList();
UserInfo objUser;
if (this.PermissionsList != null)
{
foreach (var permission in this.PermissionsList)
{
if (!Null.IsNull(permission.UserID))
{
bool blnExists = false;
foreach (UserInfo user in arrUsers)
{
if (permission.UserID == user.UserID)
{
blnExists = true;
}
}
if (!blnExists)
{
objUser = new UserInfo();
objUser.UserID = permission.UserID;
objUser.Username = permission.Username;
objUser.DisplayName = permission.DisplayName;
arrUsers.Add(objUser);
}
}
}
}
return arrUsers;
}
protected virtual bool IsFullControl(PermissionInfo permissionInfo)
{
return false;
}
protected virtual bool IsViewPermisison(PermissionInfo permissionInfo)
{
return false;
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
ServicesFramework.Instance.RequestAjaxAntiForgerySupport();
ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/Components/Tokeninput/jquery.tokeninput.js");
ClientResourceManager.RegisterScript(this.Page, "~/js/dnn.permissiongrid.js");
ClientResourceManager.RegisterStyleSheet(this.Page, "~/Resources/Shared/Components/Tokeninput/Themes/token-input-facebook.css", FileOrder.Css.ResourceCss);
}
/// <summary>
/// Overrides the base OnPreRender method to Bind the Grid to the Permissions.
/// </summary>
protected override void OnPreRender(EventArgs e)
{
this.BindData();
var script = "var pgm = new dnn.permissionGridManager('" + this.ClientID + "');";
if (ScriptManager.GetCurrent(this.Page) != null)
{
// respect MS AJAX
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), this.ClientID + "PermissionGridManager", script, true);
}
else
{
this.Page.ClientScript.RegisterStartupScript(this.GetType(), this.ClientID + "PermissionGridManager", script, true);
}
}
protected virtual void ParsePermissionKeys(PermissionInfoBase permission, string[] Settings)
{
permission.PermissionID = Convert.ToInt32(Settings[1]);
permission.RoleID = Convert.ToInt32(Settings[4]);
permission.RoleName = Settings[3];
permission.AllowAccess = Convert.ToBoolean(Settings[0]);
permission.UserID = Convert.ToInt32(Settings[5]);
permission.DisplayName = Settings[6];
}
protected virtual void RemovePermission(int permissionID, int roleID, int userID)
{
}
protected virtual bool SupportsDenyPermissions(PermissionInfo permissionInfo)
{
// to maintain backward compatibility the base implementation must always call the simple parameterless version of this method
return false;
}
/// <summary>
/// Updates a Permission.
/// </summary>
/// <param name="permission">The permission being updated.</param>
/// <param name="roleId">Rold Id.</param>
/// <param name="roleName">The name of the role.</param>
/// <param name="allowAccess">The value of the permission.</param>
protected virtual void UpdatePermission(PermissionInfo permission, int roleId, string roleName, bool allowAccess)
{
this.UpdatePermission(permission, roleId, roleName, allowAccess ? PermissionTypeGrant : PermissionTypeNull);
}
/// <summary>
/// Updates a Permission.
/// </summary>
/// <param name="permission">The permission being updated.</param>
/// <param name="roleId">Role Id.</param>
/// <param name="roleName">The name of the role.</param>
/// <param name="stateKey">The permission state.</param>
protected virtual void UpdatePermission(PermissionInfo permission, int roleId, string roleName, string stateKey)
{
this.RemovePermission(permission.PermissionID, roleId, Null.NullInteger);
switch (stateKey)
{
case PermissionTypeGrant:
this.AddPermission(permission, roleId, roleName, Null.NullInteger, Null.NullString, true);
break;
case PermissionTypeDeny:
this.AddPermission(permission, roleId, roleName, Null.NullInteger, Null.NullString, false);
break;
}
}
/// <summary>
/// Updates a Permission.
/// </summary>
/// <param name="permission">The permission being updated.</param>
/// <param name="displayName">The user's displayname.</param>
/// <param name="userId">The user's id.</param>
/// <param name="allowAccess">The value of the permission.</param>
protected virtual void UpdatePermission(PermissionInfo permission, string displayName, int userId, bool allowAccess)
{
this.UpdatePermission(permission, displayName, userId, allowAccess ? PermissionTypeGrant : PermissionTypeNull);
}
/// <summary>
/// Updates a Permission.
/// </summary>
/// <param name="permission">The permission being updated.</param>
/// <param name="displayName">The user's displayname.</param>
/// <param name="userId">The user's id.</param>
/// <param name="stateKey">The permission state.</param>
protected virtual void UpdatePermission(PermissionInfo permission, string displayName, int userId, string stateKey)
{
this.RemovePermission(permission.PermissionID, int.Parse(Globals.glbRoleNothing), userId);
switch (stateKey)
{
case PermissionTypeGrant:
this.AddPermission(permission, int.Parse(Globals.glbRoleNothing), Null.NullString, userId, displayName, true);
break;
case PermissionTypeDeny:
this.AddPermission(permission, int.Parse(Globals.glbRoleNothing), Null.NullString, userId, displayName, false);
break;
}
}
/// <summary>
/// Updates the permissions.
/// </summary>
protected void UpdatePermissions()
{
this.EnsureChildControls();
this.GetRoles();
this.UpdateRolePermissions();
this._users = this.GetUsers();
this.UpdateUserPermissions();
}
/// <summary>
/// Updates the permissions.
/// </summary>
protected void UpdateRolePermissions()
{
if (this.rolePermissionsGrid != null && !this.RefreshGrid)
{
var rolesList = this.Roles.Cast<RoleInfo>().ToList();
foreach (DataGridItem dgi in this.rolePermissionsGrid.Items)
{
var roleId = int.Parse(dgi.Cells[1].Text);
if (rolesList.All(r => r.RoleID != roleId))
{
continue;
}
for (int i = 2; i <= dgi.Cells.Count - 2; i++)
{
// all except first two cells which is role names and role ids and last column is Actions
if (dgi.Cells[i].Controls.Count > 0)
{
var permissionInfo = (PermissionInfo)this._permissions[i - 2];
var triState = (PermissionTriState)dgi.Cells[i].Controls[0];
if (this.SupportsDenyPermissions(permissionInfo))
{
this.UpdatePermission(permissionInfo, roleId, dgi.Cells[0].Text, triState.Value);
}
else
{
this.UpdatePermission(permissionInfo, roleId, dgi.Cells[0].Text, triState.Value == PermissionTypeGrant);
}
}
}
}
}
}
/// <summary>
/// Updates the permissions.
/// </summary>
protected void UpdateUserPermissions()
{
if (this.userPermissionsGrid != null && !this.RefreshGrid)
{
var usersList = this._users.Cast<UserInfo>().ToList();
foreach (DataGridItem dgi in this.userPermissionsGrid.Items)
{
var userId = int.Parse(dgi.Cells[1].Text);
if (usersList.All(u => u.UserID != userId))
{
continue;
}
for (int i = 2; i <= dgi.Cells.Count - 2; i++)
{
// all except first two cells which is displayname and userid and Last column is Actions
if (dgi.Cells[i].Controls.Count > 0)
{
var permissionInfo = (PermissionInfo)this._permissions[i - 2];
var triState = (PermissionTriState)dgi.Cells[i].Controls[0];
if (this.SupportsDenyPermissions(permissionInfo))
{
this.UpdatePermission(permissionInfo, dgi.Cells[0].Text, userId, triState.Value);
}
else
{
this.UpdatePermission(permissionInfo, dgi.Cells[0].Text, userId, triState.Value == PermissionTypeGrant);
}
}
}
}
}
}
/// <summary>
/// RoleGroupsSelectedIndexChanged runs when the Role Group is changed.
/// </summary>
protected virtual void RoleGroupsSelectedIndexChanged(object sender, EventArgs e)
{
this.FillSelectRoleComboBox(int.Parse(this.cboRoleGroups.SelectedValue));
}
/// <summary>
/// AddUser runs when the Add user linkbutton is clicked.
/// </summary>
protected virtual void AddUser(object sender, EventArgs e)
{
this.UpdatePermissions();
if (!string.IsNullOrEmpty(this.hiddenUserIds.Value))
{
foreach (var id in this.hiddenUserIds.Value.Split(','))
{
var userId = Convert.ToInt32(id);
var user = UserController.GetUserById(this.PortalId, userId);
if (user != null)
{
this.AddPermission(this._permissions, user);
this.BindData();
}
}
this.txtUser.Text = this.hiddenUserIds.Value = string.Empty;
}
}
private void BindData()
{
this.EnsureChildControls();
this.BindRolesGrid();
this.BindUsersGrid();
}
private void BindRolesGrid()
{
this.dtRolePermissions.Columns.Clear();
this.dtRolePermissions.Rows.Clear();
// Add Roles Column
this.dtRolePermissions.Columns.Add(new DataColumn("RoleId"));
// Add Roles Column
this.dtRolePermissions.Columns.Add(new DataColumn("RoleName"));
for (int i = 0; i <= this._permissions.Count - 1; i++)
{
var permissionInfo = (PermissionInfo)this._permissions[i];
// Add Enabled Column
this.dtRolePermissions.Columns.Add(new DataColumn(permissionInfo.PermissionName + "_Enabled"));
// Add Permission Column
this.dtRolePermissions.Columns.Add(new DataColumn(permissionInfo.PermissionName));
}
this.GetRoles();
this.UpdateRolePermissions();
for (int i = 0; i <= this.Roles.Count - 1; i++)
{
var role = (RoleInfo)this.Roles[i];
var row = this.dtRolePermissions.NewRow();
row["RoleId"] = role.RoleID;
row["RoleName"] = Localization.LocalizeRole(role.RoleName);
int j;
for (j = 0; j <= this._permissions.Count - 1; j++)
{
PermissionInfo objPerm;
objPerm = (PermissionInfo)this._permissions[j];
row[objPerm.PermissionName + "_Enabled"] = this.GetEnabled(objPerm, role, j + 1);
if (this.SupportsDenyPermissions(objPerm))
{
row[objPerm.PermissionName] = this.GetPermission(objPerm, role, j + 1, PermissionTypeNull);
}
else
{
if (this.GetPermission(objPerm, role, j + 1))
{
row[objPerm.PermissionName] = PermissionTypeGrant;
}
else
{
row[objPerm.PermissionName] = PermissionTypeNull;
}
}
}
this.dtRolePermissions.Rows.Add(row);
}
this.rolePermissionsGrid.DataSource = this.dtRolePermissions;
this.rolePermissionsGrid.DataBind();
}
private void BindUsersGrid()
{
this.dtUserPermissions.Columns.Clear();
this.dtUserPermissions.Rows.Clear();
// Add Roles Column
var col = new DataColumn("UserId");
this.dtUserPermissions.Columns.Add(col);
// Add Roles Column
col = new DataColumn("DisplayName");
this.dtUserPermissions.Columns.Add(col);
int i;
for (i = 0; i <= this._permissions.Count - 1; i++)
{
PermissionInfo objPerm;
objPerm = (PermissionInfo)this._permissions[i];
// Add Enabled Column
col = new DataColumn(objPerm.PermissionName + "_Enabled");
this.dtUserPermissions.Columns.Add(col);
// Add Permission Column
col = new DataColumn(objPerm.PermissionName);
this.dtUserPermissions.Columns.Add(col);
}
if (this.userPermissionsGrid != null)
{
this._users = this.GetUsers();
if (this._users.Count != 0)
{
this.userPermissionsGrid.Visible = true;
DataRow row;
for (i = 0; i <= this._users.Count - 1; i++)
{
var user = (UserInfo)this._users[i];
row = this.dtUserPermissions.NewRow();
row["UserId"] = user.UserID;
row["DisplayName"] = user.DisplayName;
int j;
for (j = 0; j <= this._permissions.Count - 1; j++)
{
PermissionInfo objPerm;
objPerm = (PermissionInfo)this._permissions[j];
row[objPerm.PermissionName + "_Enabled"] = this.GetEnabled(objPerm, user, j + 1);
if (this.SupportsDenyPermissions(objPerm))
{
row[objPerm.PermissionName] = this.GetPermission(objPerm, user, j + 1, PermissionTypeNull);
}
else
{
if (this.GetPermission(objPerm, user, j + 1))
{
row[objPerm.PermissionName] = PermissionTypeGrant;
}
else
{
row[objPerm.PermissionName] = PermissionTypeNull;
}
}
}
this.dtUserPermissions.Rows.Add(row);
}
this.userPermissionsGrid.DataSource = this.dtUserPermissions;
this.userPermissionsGrid.DataBind();
}
else
{
this.dtUserPermissions.Rows.Clear();
this.userPermissionsGrid.DataSource = this.dtUserPermissions;
this.userPermissionsGrid.DataBind();
this.userPermissionsGrid.Visible = false;
}
}
}
private void EnsureRole(RoleInfo role)
{
if (this.Roles.Cast<RoleInfo>().All(r => r.RoleID != role.RoleID))
{
this.Roles.Add(role);
}
}
private void GetRoles()
{
var checkedRoles = this.GetCheckedRoles();
var portalSettings = PortalController.Instance.GetCurrentPortalSettings();
this.Roles = new ArrayList(RoleController.Instance.GetRoles(portalSettings.PortalId, r => r.SecurityMode != SecurityMode.SocialGroup && r.Status == RoleStatus.Approved && checkedRoles.Contains(r.RoleID)).ToArray());
if (checkedRoles.Contains(this.UnAuthUsersRoleId))
{
this.Roles.Add(new RoleInfo { RoleID = this.UnAuthUsersRoleId, RoleName = Globals.glbRoleUnauthUserName });
}
if (checkedRoles.Contains(this.AllUsersRoleId))
{
this.Roles.Add(new RoleInfo { RoleID = this.AllUsersRoleId, PortalID = portalSettings.PortalId, RoleName = Globals.glbRoleAllUsersName });
}
// Administrators Role always has implicit permissions, then it should be always in
this.EnsureRole(RoleController.Instance.GetRoleById(portalSettings.PortalId, portalSettings.AdministratorRoleId));
// Show also default roles
this.EnsureRole(RoleController.Instance.GetRoleById(portalSettings.PortalId, portalSettings.RegisteredRoleId));
this.EnsureRole(new RoleInfo { RoleID = this.AllUsersRoleId, PortalID = portalSettings.PortalId, RoleName = Globals.glbRoleAllUsersName });
this.Roles.Reverse();
this.Roles.Sort(new RoleComparer());
}
private IEnumerable<int> GetCheckedRoles()
{
if (this.PermissionsList == null)
{
return new List<int>();
}
return this.PermissionsList.Select(r => r.RoleID).Distinct();
}
private void SetUpGrid(DataGrid grid, string nameColumnDataField, string idColumnDataField, string permissionHeaderText)
{
grid.Columns.Clear();
var nameColumn = new BoundColumn
{
HeaderText = permissionHeaderText,
DataField = nameColumnDataField,
};
nameColumn.ItemStyle.CssClass = "permissionHeader";
nameColumn.HeaderStyle.CssClass = "permissionHeader";
grid.Columns.Add(nameColumn);
var idColumn = new BoundColumn
{
HeaderText = string.Empty,
DataField = idColumnDataField,
Visible = false,
};
grid.Columns.Add(idColumn);
foreach (PermissionInfo permission in this._permissions)
{
var templateCol = new TemplateColumn();
var columnTemplate = new PermissionTriStateTemplate(permission)
{
IsFullControl = this.IsFullControl(permission),
IsView = this.IsViewPermisison(permission),
SupportDenyMode = this.SupportsDenyPermissions(permission),
};
templateCol.ItemTemplate = columnTemplate;
var locName = (permission.ModuleDefID <= 0) ? Localization.GetString(permission.PermissionName + ".Permission", PermissionProvider.Instance().LocalResourceFile) // system permission
: (!string.IsNullOrEmpty(this.ResourceFile) ? Localization.GetString(permission.PermissionName + ".Permission", this.ResourceFile) // custom permission
: string.Empty);
templateCol.HeaderText = !string.IsNullOrEmpty(locName) ? locName : permission.PermissionName;
templateCol.HeaderStyle.Wrap = true;
grid.Columns.Add(templateCol);
}
var actionsColumn = new ImageCommandColumn
{
CommandName = "Delete/" + nameColumnDataField,
KeyField = idColumnDataField,
IconKey = "Delete",
IconSize = "16x16",
IconStyle = "PermissionGrid",
HeaderText = Localization.GetString("PermissionActionsHeader.Text", PermissionProvider.Instance().LocalResourceFile),
};
grid.Columns.Add(actionsColumn);
grid.ItemCommand += this.grid_ItemCommand;
}
private void grid_ItemCommand(object source, DataGridCommandEventArgs e)
{
var entityID = int.Parse(e.CommandArgument.ToString());
var command = this.GetGridCommand(e.CommandName);
var entityType = this.GetCommandType(e.CommandName);
switch (command)
{
case "DELETE":
if (entityType == "ROLE")
{
this.DeleteRolePermissions(entityID);
}
else if (entityType == "USER")
{
this.DeleteUserPermissions(entityID);
}
this.BindData();
break;
}
}
private void DeleteRolePermissions(int entityID)
{
// PermissionsList.RemoveAll(p => p.RoleID == entityID);
var permissionToDelete = this.PermissionsList.Where(p => p.RoleID == entityID);
foreach (PermissionInfoBase permission in permissionToDelete)
{
this.RemovePermission(permission.PermissionID, entityID, permission.UserID);
}
}
private void DeleteUserPermissions(int entityID)
{
var permissionToDelete = this.PermissionsList.Where(p => p.UserID == entityID);
foreach (PermissionInfoBase permission in permissionToDelete)
{
this.RemovePermission(permission.PermissionID, permission.RoleID, entityID);
}
}
private string GetCommandType(string commandName)
{
var command = commandName.ToLower(CultureInfo.InvariantCulture);
if (command.Contains("rolename"))
{
return "ROLE";
}
if (command.Contains("displayname"))
{
return "USER";
}
return Null.NullString;
}
private string GetGridCommand(string commandName)
{
var commandParts = commandName.Split('/');
return commandParts[0].ToUpper(CultureInfo.InvariantCulture);
}
private void SetUpRolesGrid()
{
this.SetUpGrid(this.rolePermissionsGrid, "RoleName", "roleid", Localization.GetString("PermissionRoleHeader.Text", PermissionProvider.Instance().LocalResourceFile));
}
private void SetUpUsersGrid()
{
if (this.userPermissionsGrid != null)
{
this.SetUpGrid(this.userPermissionsGrid, "DisplayName", "userid", Localization.GetString("PermissionUserHeader.Text", PermissionProvider.Instance().LocalResourceFile));
}
}
private void FillSelectRoleComboBox(int selectedRoleGroupId)
{
this.cboSelectRole.Items.Clear();
var portalSettings = PortalController.Instance.GetCurrentPortalSettings();
var groupRoles = (selectedRoleGroupId > -2) ? RoleController.Instance.GetRoles(portalSettings.PortalId, r => r.RoleGroupID == selectedRoleGroupId && r.SecurityMode != SecurityMode.SocialGroup && r.Status == RoleStatus.Approved)
: RoleController.Instance.GetRoles(portalSettings.PortalId, r => r.SecurityMode != SecurityMode.SocialGroup && r.Status == RoleStatus.Approved);
if (selectedRoleGroupId < 0)
{
groupRoles.Add(new RoleInfo { RoleID = this.UnAuthUsersRoleId, RoleName = Globals.glbRoleUnauthUserName });
groupRoles.Add(new RoleInfo { RoleID = this.AllUsersRoleId, RoleName = Globals.glbRoleAllUsersName });
}
foreach (var role in groupRoles.OrderBy(r => r.RoleName))
{
this.cboSelectRole.Items.Add(new ListItem(role.RoleName, role.RoleID.ToString(CultureInfo.InvariantCulture)));
}
int[] defaultRoleIds = { this.AllUsersRoleId, portalSettings.RegisteredRoleId, portalSettings.AdministratorRoleId };
var itemToSelect = this.cboSelectRole.Items.Cast<ListItem>().FirstOrDefault(i => !defaultRoleIds.Contains(int.Parse(i.Value)));
if (itemToSelect != null)
{
this.cboSelectRole.SelectedValue = itemToSelect.Value;
}
}
private void SetErrorMessage(string errorKey)
{
this.lblErrorMessage = new Label
{
// TODO Remove DEBUG test
Text = "<br />" + (errorKey.StartsWith("DEBUG") ? errorKey : Localization.GetString(errorKey)),
CssClass = "NormalRed",
};
this.pnlPermissions.Controls.Add(this.lblErrorMessage);
}
private void rolePermissionsGrid_ItemDataBound(object sender, DataGridItemEventArgs e)
{
var item = e.Item;
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.SelectedItem)
{
var roleID = int.Parse(((DataRowView)item.DataItem)[0].ToString());
if (roleID == PortalSettings.Current.AdministratorRoleId || roleID == this.AllUsersRoleId || roleID == PortalSettings.Current.RegisteredRoleId)
{
var actionImage = item.Controls.Cast<Control>().Last().Controls[0] as ImageButton;
if (actionImage != null)
{
actionImage.Visible = false;
}
}
}
}
private void CreateAddRoleControls()
{
var portalSettings = PortalController.Instance.GetCurrentPortalSettings();
var arrGroups = RoleController.GetRoleGroups(portalSettings.PortalId);
var addRoleControls = new Panel { CssClass = "dnnFormItem" };
var divRoleGroups = new Panel { CssClass = "leftGroup" };
var divSelectRole = new Panel { CssClass = "rightGroup" };
this.lblGroups = new Label { Text = Localization.GetString("RoleGroupFilter") };
this.cboRoleGroups = new DropDownList { AutoPostBack = true, ID = "cboRoleGroups", ViewStateMode = ViewStateMode.Disabled };
this.lblGroups.AssociatedControlID = this.cboRoleGroups.ID;
divRoleGroups.Controls.Add(this.lblGroups);
this.cboRoleGroups.SelectedIndexChanged += this.RoleGroupsSelectedIndexChanged;
this.cboRoleGroups.Items.Add(new ListItem(Localization.GetString("AllRoles"), "-2"));
var liItem = new ListItem(Localization.GetString("GlobalRoles"), "-1") { Selected = true };
this.cboRoleGroups.Items.Add(liItem);
foreach (RoleGroupInfo roleGroup in arrGroups)
{
this.cboRoleGroups.Items.Add(new ListItem(roleGroup.RoleGroupName, roleGroup.RoleGroupID.ToString(CultureInfo.InvariantCulture)));
}
divRoleGroups.Controls.Add(this.cboRoleGroups);
addRoleControls.Controls.Add(divRoleGroups);
this.lblSelectRole = new Label { Text = Localization.GetString("RoleSelect") };
this.cboSelectRole = new DropDownList { ID = "cboSelectRole", ViewStateMode = ViewStateMode.Disabled };
this.lblSelectRole.AssociatedControlID = this.cboSelectRole.ID;
divSelectRole.Controls.Add(this.lblSelectRole);
this.FillSelectRoleComboBox(-1); // Default Role Group is Global Roles
divSelectRole.Controls.Add(this.cboSelectRole);
this.cmdRole = new LinkButton { Text = Localization.GetString("Add"), CssClass = "dnnSecondaryAction" };
this.cmdRole.Click += this.AddRole;
divSelectRole.Controls.Add(this.cmdRole);
this.roleField = new HiddenField() { ID = "roleField" };
addRoleControls.Controls.Add(this.roleField);
addRoleControls.Controls.Add(divSelectRole);
this.pnlPermissions.Controls.Add(addRoleControls);
}
/// <summary>
/// AddRole runs when the Add Role linkbutton is clicked.
/// </summary>
private void AddRole(object sender, EventArgs e)
{
this.UpdatePermissions();
int selectedRoleId;
if (!int.TryParse(this.roleField.Value, out selectedRoleId))
{
// Role not selected
this.SetErrorMessage("InvalidRoleId");
return;
}
// verify role
var role = this.GetSelectedRole(selectedRoleId);
if (role != null)
{
this.AddPermission(this._permissions, role);
this.BindData();
}
else
{
// role does not exist
this.SetErrorMessage("RoleNotFound");
}
}
private RoleInfo GetSelectedRole(int selectedRoleId)
{
RoleInfo role = null;
if (selectedRoleId == this.AllUsersRoleId)
{
role = new RoleInfo
{
RoleID = this.AllUsersRoleId,
RoleName = Globals.glbRoleAllUsersName,
};
}
else if (selectedRoleId == this.UnAuthUsersRoleId)
{
role = new RoleInfo
{
RoleID = this.UnAuthUsersRoleId,
RoleName = Globals.glbRoleUnauthUserName,
};
}
else
{
role = RoleController.Instance.GetRoleById(this.PortalId, selectedRoleId);
}
return role;
}
}
}
| mit |
luiscordero29/drs_codeigniter | assets/plugins/ckeditor/plugins/image2/dialogs/image2.js | 5356 | /*
Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.dialog.add("image2",function(f){function C(){var a=this.getValue().match(D);(a=!(!a||0===parseInt(a[1],10)))||alert(c.invalidLength.replace("%1",c[this.id]).replace("%2","px"));return a}function N(){function a(a,c){q.push(b.once(a,function(a){for(var b;b=q.pop();)b.removeListener();c(a)}))}var b=r.createElement("img"),q=[];return function(q,c,e){a("load",function(){var a=E(b);c.call(e,b,a.width,a.height)});a("error",function(){c(null)});a("abort",function(){c(null)});b.setAttribute("src",
(w.baseHref||"")+q+"?"+Math.random().toString(16).substring(2))}}function F(){var a=this.getValue();t(!1);a!==x.data.src?(G(a,function(a,b,c){t(!0);if(!a)return m(!1);g.setValue(!1===f.config.image2_prefillDimensions?0:b);h.setValue(!1===f.config.image2_prefillDimensions?0:c);u=k=b;v=l=c;m(H.checkHasNaturalRatio(a))}),n=!0):n?(t(!0),g.setValue(k),h.setValue(l),n=!1):t(!0)}function I(){if(e){var a=this.getValue();if(a&&(a.match(D)||m(!1),"0"!==a)){var b="width"==this.id,c=k||u,d=l||v,a=b?Math.round(a/
c*d):Math.round(a/d*c);isNaN(a)||(b?h:g).setValue(a)}}}function m(a){if(d){if("boolean"==typeof a){if(y)return;e=a}else a=g.getValue(),y=!0,(e=!e)&&a&&(a*=l/k,isNaN(a)||h.setValue(Math.round(a)));d[e?"removeClass":"addClass"]("cke_btn_unlocked");d.setAttribute("aria-checked",e);CKEDITOR.env.hc&&d.getChild(0).setHtml(e?CKEDITOR.env.ie?"■":"▣":CKEDITOR.env.ie?"□":"▢")}}function t(a){a=a?"enable":"disable";g[a]();h[a]()}var D=/(^\s*(\d+)(px)?\s*$)|^$/i,J=CKEDITOR.tools.getNextId(),K=CKEDITOR.tools.getNextId(),
b=f.lang.image2,c=f.lang.common,O=(new CKEDITOR.template('\x3cdiv\x3e\x3ca href\x3d"javascript:void(0)" tabindex\x3d"-1" title\x3d"'+b.lockRatio+'" class\x3d"cke_btn_locked" id\x3d"{lockButtonId}" role\x3d"checkbox"\x3e\x3cspan class\x3d"cke_icon"\x3e\x3c/span\x3e\x3cspan class\x3d"cke_label"\x3e'+b.lockRatio+'\x3c/span\x3e\x3c/a\x3e\x3ca href\x3d"javascript:void(0)" tabindex\x3d"-1" title\x3d"'+b.resetSize+'" class\x3d"cke_btn_reset" id\x3d"{resetButtonId}" role\x3d"button"\x3e\x3cspan class\x3d"cke_label"\x3e'+
b.resetSize+"\x3c/span\x3e\x3c/a\x3e\x3c/div\x3e")).output({lockButtonId:J,resetButtonId:K}),H=CKEDITOR.plugins.image2,w=f.config,z=!(!w.filebrowserImageBrowseUrl&&!w.filebrowserBrowseUrl),A=f.widgets.registered.image.features,E=H.getNatural,r,x,L,G,k,l,u,v,n,e,y,d,p,g,h,B,M=[{id:"src",type:"text",label:c.url,onKeyup:F,onChange:F,setup:function(a){this.setValue(a.data.src)},commit:function(a){a.setData("src",this.getValue())},validate:CKEDITOR.dialog.validate.notEmpty(b.urlMissing)}];z&&M.push({type:"button",
id:"browse",style:"display:inline-block;margin-top:14px;",align:"center",label:f.lang.common.browseServer,hidden:!0,filebrowser:"info:src"});return{title:b.title,minWidth:250,minHeight:100,onLoad:function(){r=this._.element.getDocument();G=N()},onShow:function(){x=this.widget;L=x.parts.image;n=y=e=!1;B=E(L);u=k=B.width;v=l=B.height},contents:[{id:"info",label:b.infoTab,elements:[{type:"vbox",padding:0,children:[{type:"hbox",widths:["100%"],className:"cke_dialog_image_url",children:M}]},{id:"alt",
type:"text",label:b.alt,setup:function(a){this.setValue(a.data.alt)},commit:function(a){a.setData("alt",this.getValue())},validate:!0===f.config.image2_altRequired?CKEDITOR.dialog.validate.notEmpty(b.altMissing):null},{type:"hbox",widths:["25%","25%","50%"],requiredContent:A.dimension.requiredContent,children:[{type:"text",width:"45px",id:"width",label:c.width,validate:C,onKeyUp:I,onLoad:function(){g=this},setup:function(a){this.setValue(a.data.width)},commit:function(a){a.setData("width",this.getValue())}},
{type:"text",id:"height",width:"45px",label:c.height,validate:C,onKeyUp:I,onLoad:function(){h=this},setup:function(a){this.setValue(a.data.height)},commit:function(a){a.setData("height",this.getValue())}},{id:"lock",type:"html",style:"margin-top:18px;width:40px;height:20px;",onLoad:function(){function a(a){a.on("mouseover",function(){this.addClass("cke_btn_over")},a);a.on("mouseout",function(){this.removeClass("cke_btn_over")},a)}var b=this.getDialog();d=r.getById(J);p=r.getById(K);d&&(b.addFocusable(d,
4+z),d.on("click",function(a){m();a.data&&a.data.preventDefault()},this.getDialog()),a(d));p&&(b.addFocusable(p,5+z),p.on("click",function(a){n?(g.setValue(u),h.setValue(v)):(g.setValue(k),h.setValue(l));a.data&&a.data.preventDefault()},this),a(p))},setup:function(a){m(a.data.lock)},commit:function(a){a.setData("lock",e)},html:O}]},{type:"hbox",id:"alignment",requiredContent:A.align.requiredContent,children:[{id:"align",type:"radio",items:[[c.alignNone,"none"],[c.left,"left"],[c.center,"center"],
[c.right,"right"]],label:c.align,setup:function(a){this.setValue(a.data.align)},commit:function(a){a.setData("align",this.getValue())}}]},{id:"hasCaption",type:"checkbox",label:b.captioned,requiredContent:A.caption.requiredContent,setup:function(a){this.setValue(a.data.hasCaption)},commit:function(a){a.setData("hasCaption",this.getValue())}}]},{id:"Upload",hidden:!0,filebrowser:"uploadButton",label:b.uploadTab,elements:[{type:"file",id:"upload",label:b.btnUpload,style:"height:40px"},{type:"fileButton",
id:"uploadButton",filebrowser:"info:src",label:b.btnUpload,"for":["Upload","upload"]}]}]}}); | mit |
XinwLi/Interop-TestSuites-1 | ExchangeMAPI/Source/Common/Common/ExchangeMapiClient/RopMessages/StreamROPs/RopWriteStreamExtended.cs | 3824 |
namespace Microsoft.Protocols.TestSuites.Common
{
using System;
using System.Runtime.InteropServices;
/// <summary>
/// RopWriteStreamExtended request buffer structure.
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct RopWriteStreamExtendedRequest : ISerializable
{
/// <summary>
/// Unsigned 8-bit integer. This value specifies the type of remote operation.
/// For this operation, this field is set to 0xA3.
/// </summary>
public byte RopId;
/// <summary>
/// Unsigned 8-bit integer. This value specifies the logon associated with this operation.
/// </summary>
public byte LogonId;
/// <summary>
/// Unsigned 8-bit integer. This index specifies the location in the Server Object Handle Table
/// where the handle for the input Server Object is stored.
/// </summary>
public byte InputHandleIndex;
/// <summary>
/// Unsigned 16-bit integer. This value specifies the size of the Data field.
/// </summary>
public ushort DataSize;
/// <summary>
/// Array of bytes. The size of this field, in bytes, is specified by the DataSize field.
/// These values specify the bytes to be written to the stream.
/// </summary>
public byte[] Data;
public byte[] Serialize()
{
int index = 0;
byte[] serializeBuffer = new byte[this.Size()];
serializeBuffer[index++] = this.RopId;
serializeBuffer[index++] = this.LogonId;
serializeBuffer[index++] = this.InputHandleIndex;
Array.Copy(BitConverter.GetBytes((ushort)this.DataSize), 0, serializeBuffer, index, sizeof(ushort));
index += sizeof(ushort);
if (this.DataSize > 0)
{
Array.Copy(this.Data, 0, serializeBuffer, index, this.DataSize);
index += this.DataSize;
}
return serializeBuffer;
}
public int Size()
{
// 5 indicates sizeof(byte) * 3 + sizeof(UInt16)
int size = sizeof(byte) * 5;
if (this.DataSize > 0)
{
size += this.DataSize;
}
return size;
}
}
/// <summary>
/// RopWriteStreamExtended response buffer structure.
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct RopWriteStreamExtendedResponse : IDeserializable
{
/// <summary>
/// Unsigned 8-bit integer. This value specifies the type of remote operation.
/// For this operation, this field is set to 0xA3.
/// </summary>
public byte RopId;
/// <summary>
/// Unsigned 8-bit integer. This index MUST be set to the InputHandleIndex specified in the request.
/// </summary>
public byte InputHandleIndex;
/// <summary>
/// Unsigned 32-bit integer. This value specifies the status of the remote operation.
/// </summary>
public uint ReturnValue;
/// <summary>
/// Unsigned 32-bit integer. This value specifies the number of bytes actually written.
/// </summary>
public uint WrittenSize;
public int Deserialize(byte[] ropBytes, int startIndex)
{
int index = startIndex;
this.RopId = ropBytes[index++];
this.InputHandleIndex = ropBytes[index++];
this.ReturnValue = (uint)BitConverter.ToInt32(ropBytes, index);
index += sizeof(uint);
this.WrittenSize = (uint)BitConverter.ToInt32(ropBytes, index);
index += sizeof(uint);
return index - startIndex;
}
}
}
| mit |
tleunen/react-mdl | src/utils/mdlUpgrade.js | 1159 | import React from 'react';
import MDLComponent from './MDLComponent';
function patchComponentClass(Component, recursive) {
const oldRender = Component.prototype.render;
Component.prototype.render = function render() { // eslint-disable-line no-param-reassign
return (
<MDLComponent recursive={recursive}>
{oldRender.call(this)}
</MDLComponent>
);
};
return Component;
}
function patchSFC(component, recursive) {
const patchedComponent = props =>
<MDLComponent recursive={recursive}>
{component(props)}
</MDLComponent>;
// Attempt to change the function name for easier debugging, but don't die
// if the browser doesn't support it
try {
Object.defineProperty(patchedComponent, 'name', {
value: component.name
});
} catch (e) {} // eslint-disable-line no-empty
return patchedComponent;
}
export default (Component, recursive = false) => (
(Component.prototype && Component.prototype.isReactComponent) ?
patchComponentClass(Component, recursive) :
patchSFC(Component, recursive)
);
| mit |
kprestel/PyInvestment | pytech/utils/enums.py | 3378 | from enum import Enum
from pytech.utils.exceptions import (InvalidActionError,
InvalidOrderStatusError,
InvalidOrderSubTypeError,
InvalidOrderTypeError,
InvalidPositionError,
InvalidSignalTypeError,
InvalidEventTypeError)
class AutoNumber(Enum):
def __new__(cls, *args, **kwargs):
value = len(cls.__members__) + 1
obj = object.__new__(cls)
obj._value_ = value
return obj
@classmethod
def check_if_valid(cls, value):
if value is None:
return None
elif isinstance(value, cls):
return value
elif hasattr(value, 'name'):
value = getattr(value, 'name')
for name, member in cls.__members__.items():
if member.name == value.upper():
return member
else:
return None
class EventType(AutoNumber):
"""Different Event types"""
MARKET = ()
SIGNAL = ()
TRADE = ()
FILL = ()
@classmethod
def check_if_valid(cls, value):
name = super().check_if_valid(value)
if name is not None:
return name
else:
raise InvalidEventTypeError(action=value)
class SignalType(AutoNumber):
LONG = ()
SHORT = ()
EXIT = ()
CANCEL = ()
HOLD = ()
TRADE = ()
@classmethod
def check_if_valid(cls, value):
name = super().check_if_valid(value)
if name is not None:
return name
else:
raise InvalidSignalTypeError(action=value)
class TradeAction(AutoNumber):
BUY = ()
SELL = ()
EXIT = ()
@classmethod
def check_if_valid(cls, value):
name = super().check_if_valid(value)
if name is not None:
return name
else:
raise InvalidActionError(action=value)
class OrderStatus(AutoNumber):
OPEN = ()
FILLED = ()
CANCELLED = ()
REJECTED = ()
HELD = ()
@classmethod
def check_if_valid(cls, value):
name = super().check_if_valid(value)
if name is not None:
return name
else:
raise InvalidOrderStatusError(order_status=value)
class OrderType(AutoNumber):
"""Valid Order Types"""
# TODO: document this better
STOP = ()
LIMIT = ()
STOP_LIMIT = ()
MARKET = ()
@classmethod
def check_if_valid(cls, value):
name = super().check_if_valid(value)
if name is not None:
return name
else:
raise InvalidOrderTypeError(order_type=value)
class OrderSubType(AutoNumber):
"""Valid OrderSubtypes"""
ALL_OR_NONE = ()
GOOD_TIL_CANCELED = ()
DAY = ()
@classmethod
def check_if_valid(cls, value):
name = super().check_if_valid(value)
if name is not None:
return name
else:
raise InvalidOrderSubTypeError(order_subtype=value)
class Position(AutoNumber):
LONG = ()
SHORT = ()
@classmethod
def check_if_valid(cls, value):
name = super().check_if_valid(value)
if name is not None:
return name
else:
raise InvalidPositionError(position=value)
| mit |
maurer/tiamat | samples/Juliet/testcases/CWE762_Mismatched_Memory_Management_Routines/s06/CWE762_Mismatched_Memory_Management_Routines__new_delete_array_long_54a.cpp | 2724 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE762_Mismatched_Memory_Management_Routines__new_delete_array_long_54a.cpp
Label Definition File: CWE762_Mismatched_Memory_Management_Routines__new_delete_array.label.xml
Template File: sources-sinks-54a.tmpl.cpp
*/
/*
* @description
* CWE: 762 Mismatched Memory Management Routines
* BadSource: Allocate data using new
* GoodSource: Allocate data using new []
* Sinks:
* GoodSink: Deallocate data using delete
* BadSink : Deallocate data using delete []
* Flow Variant: 54 Data flow: data passed as an argument from one function through three others to a fifth; all five functions are in different source files
*
* */
#include "std_testcase.h"
namespace CWE762_Mismatched_Memory_Management_Routines__new_delete_array_long_54
{
#ifndef OMITBAD
/* bad function declaration */
void badSink_b(long * data);
void bad()
{
long * data;
/* Initialize data*/
data = NULL;
/* POTENTIAL FLAW: Allocate memory with a function that requires delete to free the memory */
data = new long;
badSink_b(data);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink_b(long * data);
static void goodG2B()
{
long * data;
/* Initialize data*/
data = NULL;
/* FIX: Allocate memory from the heap using new [] */
data = new long[100];
goodG2BSink_b(data);
}
/* goodB2G uses the BadSource with the GoodSink */
void goodB2GSink_b(long * data);
static void goodB2G()
{
long * data;
/* Initialize data*/
data = NULL;
/* POTENTIAL FLAW: Allocate memory with a function that requires delete to free the memory */
data = new long;
goodB2GSink_b(data);
}
void good()
{
goodG2B();
goodB2G();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE762_Mismatched_Memory_Management_Routines__new_delete_array_long_54; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| mit |
ld-test/moses | spec/table_spec.lua | 18644 | require 'luacov'
local _ = require 'moses'
context('Table functions specs', function()
context('each', function()
test('provides values and iteration count ', function()
local t = {1,2,3}
local inc = 0
_.each(t,function(i,v)
inc = inc+1
assert_equal(i,inc)
assert_equal(t[i],v)
end)
end)
test('can reference the given table', function()
local t = {1,2,3}
_.each(t,function(i,v,mul)
t[i] = v*mul
end,5)
assert_true(_.isEqual(t,{5,10,15}))
end)
test('iterates over non-numeric keys and objects', function()
local t = {one = 1, two = 2, three = 3}
local copy = {}
_.each(t,function(i,v) copy[i] = v end)
assert_true(_.isEqual(t,copy))
end)
end)
context('eachi', function()
test('provides values and iteration count for integer keys only, in a sorted way', function()
local t = {1,2,3}
local inc = 0
_.eachi(t,function(i,v)
inc = inc+1
assert_equal(i,inc)
assert_equal(t[i],v)
end)
end)
test('ignores non-integer keys', function()
local t = {a = 1, b = 2, [0] = 1, [-1] = 6, 3, x = 4, 5}
local rk = {-1, 0, 1, 2}
local rv = {6, 1, 3, 5}
local inc = 0
_.eachi(t,function(i,v)
inc = inc+1
assert_equal(i,rk[inc])
assert_equal(v,rv[inc])
end)
end)
end)
context('at', function()
test('returns an array of values at numeric keys', function()
local t = {4,5,6}
local values = _.at(t,1,2,3)
assert_true(_.isEqual(values, t))
local t = {a = 4, bb = true, ccc = false}
local values = _.at(t,'a', 'ccc')
assert_true(_.isEqual(values, {4, false}))
end)
end)
context('count', function()
test('count the occurences of value in a list', function()
assert_equal(_.count({1,1,2,3,3,3,2,4,3,2},1),2)
assert_equal(_.count({1,1,2,3,3,3,2,4,3,2},2),3)
assert_equal(_.count({1,1,2,3,3,3,2,4,3,2},3),4)
assert_equal(_.count({1,1,2,3,3,3,2,4,3,2},4),1)
assert_equal(_.count({1,1,2,3,3,3,2,4,3,2},5),0)
assert_equal(_.count({false, false, true},false),2)
assert_equal(_.count({false, false, true},true),1)
assert_equal(_.count({{1,1},{1,1},{1,1},{2,2}},{1,1}),3)
assert_equal(_.count({{1,1},{1,1},{1,1},{2,2}},{2,2}),1)
end)
test('defaults to size when value is not given', function()
assert_equal(_.count({1,1,2,3,3,3,2,4,3,2}),_.size({1,1,2,3,3,3,2,4,3,2}))
assert_equal(_.count({false, false, true}),_.size({false, false, true}))
end)
end)
context('countf', function()
test('count the occurences of values passing an iterator test in a list', function()
assert_equal(_.countf({1,2,3,4,5,6}, function(i,v)
return v%2==0
end),3)
assert_equal(_.countf({print, pairs, os, assert, ipairs}, function(i,v)
return type(v)=='function'
end),4)
end)
end)
context('cycle', function()
test('loops n times on a list', function()
local times = 3
local t = {1,2,3,4,5}
local kv = {}
for k,v in _.cycle(t,times) do
assert_equal(t[k],v)
kv[#kv+1] = v
end
for k,v in ipairs(kv) do
assert_equal(_.count(kv,v),times)
end
end)
test('support array-like and map-like tables', function()
local times = 10
local t = {x = 1, z = 2}
local keys = {}
local values = {}
for k,v in _.cycle(t,times) do
assert_equal(t[k],v)
keys[#keys+1] = k
values[#values+1] = v
end
for k,v in ipairs(keys) do
assert_equal(_.count(keys,v),times)
end
for k,v in ipairs(values) do
assert_equal(_.count(values,v),times)
end
end)
test('n defaults to 1, if not supplied', function()
local t = {1,2,3,4,5}
for k,v in _.cycle(t) do
t[k] = v + 1
end
_.each(t, function(k, v)
assert_equal(v, k + 1)
end)
end)
test('if n is negative or equal to 0, it does nothing', function()
local t = {1,2,3,4,5}
for k,v in _.cycle(t, 0) do
t[k] = v + 1
end
for k,v in _.cycle(t, -2) do
t[k] = v + 1
end
_.each(t, function(k, v)
assert_equal(v, k)
end)
end)
end)
context('map', function()
test('applies an iterator function over each key-value pair ', function()
assert_true(_.isEqual(_.map({1,2,3},function(i,v)
return v+10
end),{11,12,13}))
end)
test('iterates over non-numeric keys and objects', function()
assert_true(_.isEqual(_.map({a = 1, b = 2},function(k,v)
return k..v
end),{a = 'a1',b = 'b2'}))
end)
end)
context('reduce', function()
test('folds a collection (left to right) from an initial state', function()
assert_equal(_.reduce({1,2,3,4},function(memo,v) return memo+v end,0),10)
end)
test('initial state defaults to the first value when not given', function()
assert_equal(_.reduce({'a','b','c'},function(memo,v) return memo..v end),'abc')
end)
test('supports arrays of booleans', function()
assert_equal(_.reduce({true, false, true, true},function(memo,v) return memo and v end), false)
assert_equal(_.reduce({true, true, true},function(memo,v) return memo and v end), true)
assert_equal(_.reduce({false, false, false},function(memo,v) return memo and v end), false)
assert_equal(_.reduce({false, false, true},function(memo,v) return memo or v end), true)
end)
end)
context('reduceRight', function()
test('folds a collection (right to left) from an initial state', function()
assert_equal(_.reduceRight({1,2,4,16},function(memo,v) return memo/v end,256),2)
end)
test('initial state defaults to the first value when not given', function()
assert_equal(_.reduceRight({'a','b','c'},function(memo,v) return memo..v end),'cba')
end)
end)
context('mapReduce', function()
test('folds a collection (left to right) saving intermediate states', function()
assert_true(_.isEqual(_.mapReduce({1,2,4,16},function(memo,v)
return memo*v
end,0),{0,0,0,0}))
end)
test('initial state defaults to the first value when not given', function()
assert_true(_.isEqual(_.mapReduce({'a','b','c'},function(memo,v)
return memo..v
end),{'a','ab','abc'}))
end)
end)
context('mapReduceRight', function()
test('folds a collection (right to left) saving intermediate states', function()
assert_true(_.isEqual(_.mapReduceRight({1,2,4,16},function(memo,v)
return memo/v
end,256),{16,4,2,2}))
end)
test('initial state defaults to the first value when not given', function()
assert_true(_.isEqual(_.mapReduceRight({'a','b','c'},function(memo,v)
return memo..v
end),{'c','cb','cba'}))
end)
end)
context('include', function()
test('looks for a value in a collection, returns true when found', function()
assert_true(_.include({6,8,10,16,29},16))
end)
test('returns false when value was not found', function()
assert_false(_.include({6,8,10,16,29},1))
end)
test('can lookup for a object', function()
assert_true(_.include({6,{18,{2,6}},10,{18,{2,{3}}},29},{18,{2,{3}}}))
end)
test('given an iterator, return the first value passing a truth test', function()
assert_true(_.include({'a','B','c'}, function(array_value)
return (array_value:upper() == array_value)
end))
end)
end)
context('detect', function()
test('looks for the first occurence of value, returns the key where it was found', function()
assert_equal(_.detect({6,8,10,16},8),2)
end)
test('returns nil when value was not found', function()
assert_nil(_.detect({nil,true,0,true,true},false))
end)
test('can lookup for a object', function()
assert_equal(_.detect({6,{18,{2,6}},10,{18,{2,{3}}},29},{18,{2,6}}),2)
end)
test('given an iterator, return the key of the first value passing a truth test', function()
assert_equal(_.detect({'a','B','c'}, function(array_value)
return (array_value:upper() == array_value)
end),2)
end)
end)
context('contains', function()
test('returns true if value is present in a list', function()
assert_true(_.contains({6,8,10,16},8))
end)
test('returns false when value was not found', function()
assert_false(_.contains({nil,true,0,true,true},false))
end)
test('can lookup for a object', function()
assert_true(_.contains({6,{18,{2,6}},10,{18,{2,{3}}},29},{18,{2,6}}))
end)
test('accepts iterator functions', function()
assert_true(_.contains({'a','B','c'}, function(array_value)
return (array_value:upper() == array_value)
end))
end)
end)
context('findWhere', function()
test('Returns the first value in a list having all of some given set of properties', function()
local a = {a = 1, b = 2}
local b = {a = 2, b = 3}
local c = {a = 3, b = 4}
assert_equal(_.findWhere({a, b, c}, {a = 3, b = 4}), c)
end)
test('returns nil when value was not found', function()
local a = {a = 1, b = 2}
local b = {a = 2, b = 3}
local c = {a = 3, b = 4}
assert_nil(_.findWhere({a, b, c}, {a = 3, b = 0}))
end)
end)
context('select', function()
test('collects all values passing a truth test with an iterator', function()
assert_true(_.isEqual(_.select({1,2,3,4,5,6,7}, function(key,value)
return (value%2==0)
end),{2,4,6}))
assert_true(_.isEqual(_.select({1,2,3,4,5,6,7}, function(key,value)
return (value%2~=0)
end),{1,3,5,7}))
end)
end)
context('reject', function()
test('collects all values failing a truth test with an iterator', function()
assert_true(_.isEqual(_.reject({1,2,3,4,5,6,7}, function(key,value)
return (value%2==0)
end),{1,3,5,7}))
assert_true(_.isEqual(_.reject({1,2,3,4,5,6,7}, function(key,value)
return (value%2~=0)
end),{2,4,6}))
end)
end)
context('all', function()
test('returns whether all elements matches a truth test', function()
assert_true(_.all({2,4,6}, function(key,value)
return (value%2==0)
end))
assert_false(_.all({false,true,false}, function(key,value)
return value == false
end))
end)
end)
context('invoke', function()
test('calls an iterator over each object, passing it as a first arg', function()
assert_true(_.isEqual(_.invoke({'a','bea','cdhza'},string.len),
{1,3,5}))
assert_true(_.isEqual(_.invoke({{2,3,2},{13,8,10},{0,-5}},_.sort),
{{2,2,3},{8,10,13},{-5,0}}))
assert_true(_.isEqual(_.invoke({{x = 1, y = 2},{x = 3, y=4}},'x'), {1,3}))
end)
test('given a string, calls the matching object property the same way', function()
local a = {}; function a:call() return self end
local b, c, d = {}, {}, {}
b.call, c.call, d.call = a.call, a.call, a.call
assert_true(_.isEqual(_.invoke({a,b,c,d},'call'),
{a,b,c,d}))
end)
end)
context('pluck', function()
test('fetches a property value in a collection of objects', function()
local peoples = {
{name = 'John', age = 23},{name = 'Peter', age = 17},
{name = 'Steve', age = 15},{age = 33}}
assert_true(_.isEqual(_.pluck(peoples,'age'),
{23,17,15,33}))
assert_true(_.isEqual(_.pluck(peoples,'name'),
{'John','Peter','Steve'}))
end)
end)
context('max', function()
test('returns the maximum targetted property value in a collection of objects', function()
local peoples = {
{name = 'John', age = 23},{name = 'Peter', age = 17},
{name = 'Steve', age = 15},{age = 33}}
assert_equal(_.max(_.pluck(peoples,'age')),33)
assert_equal(_.max(peoples,function(people) return people.age end),33)
end)
test('directly compares items when given no iterator', function()
assert_equal(_.max({'a','b','c'}),'c')
end)
end)
context('min', function()
test('returns the maximum targetted property value in a collection of objects', function()
local peoples = {
{name = 'John', age = 23},{name = 'Peter', age = 17},
{name = 'Steve', age = 15},{age = 33}}
assert_equal(_.min(_.pluck(peoples,'age')),15)
assert_equal(_.min(peoples,function(people) return people.age end),15)
end)
test('directly compares items when given no iterator', function()
assert_equal(_.min({'a','b','c'}),'a')
end)
end)
context('shuffle', function()
test('shuffles values and objects in a collection', function()
local values = {'a','b','c','d'}
assert_true(_.same(_.shuffle (values),values))
end)
test('can accept a seed value to init randomization', function()
local values = {'a','b','c','d'}
local seed = os.time()
assert_true(_.same(_.shuffle(values,seed),values))
end)
test('shuffled table has the same elements in a different order', function()
local values = {'a','b','c','d'}
assert_true(_.same(_.shuffle(values),values))
assert_true(_.same(_.shuffle(values),values))
end)
end)
context('same', function()
test('returns whether all objects from both given tables exists in each other', function()
local a = {'a','b','c','d'}
local b = {'b','a','d','c'}
assert_true(_.same(a,b))
b[#b+1] = 'e'
assert_false(_.same(a,b))
end)
end)
context('sort', function()
test('sorts a collection with respect to a given comparison function', function()
assert_true(_.isEqual(_.sort({'b','a','d','c'}, function(a,b)
return a:byte() < b:byte()
end),{'a','b','c','d'}))
end)
test('uses "<" operator when no comparison function is given', function()
assert_true(_.isEqual(_.sort({'b','a','d','c'}),{'a','b','c','d'}))
end)
end)
context('groupBy', function()
test('splits a collection into subsets of items behaving the same', function()
assert_true(_.isEqual(_.groupBy({0,1,2,3,4,5,6},function(i,value)
return value%2==0 and 'even' or 'odd'
end),{even = {0,2,4,6},odd = {1,3,5}}))
assert_true(_.isEqual(_.groupBy({0,'a',true, false,nil,b,0.5},function(i,value)
return type(value)
end),{number = {0,0.5},string = {'a'},boolean = {true,false}}))
assert_true(_.isEqual(_.groupBy({'one','two','three','four','five'},function(i,value)
return value:len()
end),{[3] = {'one','two'},[4] = {'four','five'},[5] = {'three'}}))
end)
end)
context('countBy', function()
test('splits a collection in subsets and counts items inside', function()
assert_true(_.isEqual(_.countBy({0,1,2,3,4,5,6},function(i,value)
return value%2==0 and 'even' or 'odd'
end),{even = 4,odd = 3}))
assert_true(_.isEqual(_.countBy({0,'a',true, false,nil,b,0.5},function(i,value)
return type(value)
end),{number = 2,string = 1,boolean = 2}))
assert_true(_.isEqual(_.countBy({'one','two','three','four','five'},function(i,value)
return value:len()
end),{[3] = 2,[4] = 2,[5] = 1}))
end)
end)
context('size', function()
test('counts the very number of objects in a collection', function()
assert_equal(_.size {1,2,3},3)
end)
test('counts nested tables elements as a unique value', function()
assert_equal(_.size {1,2,3,{4,5}},4)
end)
test('leaves nil values', function()
assert_equal(_.size {1,2,3,nil,8},4)
end)
test('counts objects', function()
assert_equal(_.size {one = 1,2,b = 3, [{}] = 'nil', 'c', [function() end] = 'foo'},6)
end)
test('returns the size of the first arg when it is a table', function()
assert_equal(_.size ({1,2},3,4,5),2)
end)
test('counts the number of args when the first one is not a table', function()
assert_equal(_.size (1,3,4,5),4)
end)
test('handles nil', function()
assert_equal(_.size(),0)
assert_equal(_.size(nil),0)
end)
end)
context('containsKeys', function()
test('returns whether a table has all the keys from a given list', function()
assert_true(_.containsKeys({1,2,3},{1,2,3}))
assert_true(_.containsKeys({x = 1, y = 2},{x = 1,y =2}))
end)
test('does not compare values', function()
assert_true(_.containsKeys({1,2,3},{4,5,6}))
assert_true(_.containsKeys({x = 1, y = 2},{x = 4,y = -1}))
end)
test('is not commutative', function()
assert_true(_.containsKeys({1,2,3,4},{4,5,6}))
assert_true(_.containsKeys({x = 1, y = 2,z = 5},{x = 4,y = -1}))
assert_false(_.containsKeys({1,2,3},{4,5,6,7}))
assert_false(_.containsKeys({x = 1, y = 2},{x = 4,y = -1,z = 0}))
end)
end)
context('sameKeys', function()
test('returns whether both tables features the same keys', function()
assert_true(_.sameKeys({1,2,3},{1,2,3}))
assert_true(_.sameKeys({x = 1, y = 2},{x = 1,y =2}))
end)
test('does not compare values', function()
assert_true(_.sameKeys({1,2,3},{4,5,6}))
assert_true(_.sameKeys({x = 1, y = 2},{x = 4,y = -1}))
end)
test('is commutative', function()
assert_true(_.sameKeys({1,2,3,4},{4,5,6}))
assert_true(_.sameKeys({x = 1, y = 2,z = 5},{x = 4,y = -1}))
assert_true(_.sameKeys({1,2,3},{4,5,6,7}))
assert_true(_.sameKeys({x = 1, y = 2},{x = 4,y = -1,z = 0}))
end)
end)
end) | mit |
udothemath1984/udothemath1984.github.io | movie_center/inheritance.py | 639 | class Parent():
def __init__(self, last_name, eye_color):
print "Parent Constructor Called..."
self.last_name = last_name
self.eye_color = eye_color
def show_info(self):
print "Your last name is {} with eye color {}.".format(self.last_name, self.eye_color)
class Child(Parent):
def __init__(self, last_name, eye_color, num_of_toys):
print "Child Constructor Called..."
Parent.__init__(self, last_name, eye_color)
self.num_of_toys = num_of_toys
emily = Parent("Chang", "black")
#emily.show_info()
#print emily.last_name
nate = Child("Sun", "black", 3)
# print nate.last_name
# print nate.num_of_toys
nate.show_info() | mit |
tinyels/react-dev | src/components/issues/index.ts | 432 | import { IssuesList, IssuesListTranslatable } from './IssuesList';
import IssuesListItem from './IssuesListItem';
import MoreIssuesPage from './MoreIssuesPage';
import { MoreIssues, MoreIssuesTranslatable } from './MoreIssues';
import MoreIssuesContainer from './MoreIssuesContainer';
export { IssuesList, IssuesListTranslatable, IssuesListItem, MoreIssuesPage,
MoreIssues, MoreIssuesTranslatable, MoreIssuesContainer };
| mit |
lordsutch/btrfs-backup | btrfs_backup/endpoint/shell.py | 474 | from .common import Endpoint
class ShellEndpoint(Endpoint):
def __init__(self, cmd, **kwargs):
super(ShellEndpoint, self).__init__(**kwargs)
if self.source:
raise ValueError("Shell can't be used as source.")
self.cmd = cmd
def __repr__(self):
return "(Shell) " + self.cmd
def get_id(self):
return "shell://{}".format(self.cmd)
def _build_receive_cmd(self, dest):
return ["sh", "-c", self.cmd]
| mit |
jandrest2018/TWJ-2017-A | 04 Angular/DEBER-Web/node_modules/@angular/core/src/event_emitter.d.ts | 1992 | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { Subject } from 'rxjs/Subject';
/**
* Use by directives and components to emit custom Events.
*
* ### Examples
*
* In the following example, `Zippy` alternatively emits `open` and `close` events when its
* created gets clicked:
*
* ```
* @Component({
* selector: 'zippy',
* template: `
* <div class="zippy">
* <div (click)="toggle()">Toggle</div>
* <div [hidden]="!visible">
* <ng-content></ng-content>
* </div>
* </div>`})
* export class Zippy {
* visible: boolean = true;
* @Output() open: EventEmitter<any> = new EventEmitter();
* @Output() close: EventEmitter<any> = new EventEmitter();
*
* toggle() {
* this.visible = !this.visible;
* if (this.visible) {
* this.open.emit(null);
* } else {
* this.close.emit(null);
* }
* }
* }
* ```
*
* The events payload can be accessed by the parameter `$event` on the components output event
* handler:
*
* ```
* <zippy (open)="onOpen($event)" (close)="onClose($event)"></zippy>
* ```
*
* Uses Rx.Observable but provides an adapter to make it work as specified here:
* https://github.com/jhusain/observable-spec
*
* Once a reference implementation of the spec is available, switch to it.
* @stable
*/
export declare class EventEmitter<T> extends Subject<T> {
__isAsync: boolean;
/**
* Creates an instance of {@link EventEmitter}, which depending on `isAsync`,
* delivers events synchronously or asynchronously.
*
* @param isAsync By default, events are delivered synchronously (default value: `false`).
* Set to `true` for asynchronous event delivery.
*/
constructor(isAsync?: boolean);
emit(value?: T): void;
subscribe(generatorOrNext?: any, error?: any, complete?: any): any;
}
| mit |
asfram/Carto | web/js/g_map_part_10_gmPolylines_1.js | 4720 | /**
* Collection de polylines
* Author RNE
* CanalTP 2013
* @type @exp;Backbone@pro;Collection@call;extend
*/
var ctpPolylines = CanalTP.lib.map.collections.extend({
model: ctpPolyline,
collectionType: 'polylines',
/**
* Fonction permettant l'initialisation
*/
initialize: function()
{
this.bind("add", function(){
this.removeExcludedPoint();
});
},
/**
* Fonction permettant de setter l'option weight (strokeWeight de gm)
* @param {Number} weight taille (grosseur) de la polyline
*/
setWeight: function(weight)
{
this.weight = weight;
_.each(this.models, CanalTP.jQuery.proxy(function(value){
value.get('mapElement').setOptions({strokeWeight: this.weight});
}), this);
},
/**
* Fonction permettant de reset l'option weight
*/
resetWeight: function()
{
_.each(this.models, CanalTP.jQuery.proxy(function(value){
this.weight = value.previous('weight');
value.get('mapElement').setOptions({strokeWeight: this.weight});
}), this);
},
/**
* Fonction permettant de récupérer le weight
*/
getWeight: function()
{
return this.weight;
},
/**
* Fonction permettant de setter l'option color (strokecolor de gm)
* @param {String} color
*/
setColor: function(color)
{
this.color = color;
_.each(this.models, CanalTP.jQuery.proxy(function(value){
value.get('mapElement').setOptions({strokeColor: this.color});
}), this);
},
/**
* Fonction permettant de reset l'option color
*/
resetColor: function()
{
_.each(this.models, CanalTP.jQuery.proxy(function(value){
this.color = value.previous('color');
value.get('mapElement').setOptions({strokeColor: this.color});
}), this);
},
/**
* Fonction permettant de récupérer l'option color
*/
getColor: function()
{
return this.color;
},
/**
* Fonction permettant de setter l'option opacity (strokeOpacity de gm)
* @param {Number} opacity
*/
setOpacity: function(opacity)
{
this.opacity = opacity;
_.each(this.models, CanalTP.jQuery.proxy(function(value){
value.get('mapElement').setOptions({strokeOpacity: this.opacity});
}), this);
},
/**
* Fonction permettant de reset l'option opacity
*/
resetOpacity: function()
{
_.each(this.models, CanalTP.jQuery.proxy(function(value){
this.opacity = value.previous('opacity');
value.get('mapElement').setOptions({strokeOpacity: this.opacity});
}), this);
},
/**
* Fonction permettant de récupérer l'opacity
*/
getOpacity: function()
{
return this.opacity;
},
/**
* Fonction permettant de setter l'option zIndex (zIndex de gm)
* @param {Number} zIndex
*/
setzIndex: function(zIndex)
{
this.zIndex = parseInt(zIndex);
_.each(this.models, CanalTP.jQuery.proxy(function(value){
value.get('mapElement').setOptions({zIndex: this.zIndex});
}), this);
},
/**
* Fonction permettant de reset l'option zIndex
*/
resetzIndex: function()
{
_.each(this.models, CanalTP.jQuery.proxy(function(value){
this.zIndex = value.previous('zIndex');
value.get('mapElement').setOptions({zIndex: this.zIndex});
}), this);
},
/**
* Fonction permettant de récupérer le zIndex
*/
getzIndex: function()
{
return this.zIndex;
},
/**
* Fonction permettant de setter l'option Icons (zIndex de gm)
* @param {Array} icons
*/
setIcons: function(icons)
{
this.icons = null;
if (parseFloat(navigator.appVersion.split("MSIE")[1]) > 8) {
this.icons = icons;
_.each(this.models, CanalTP.jQuery.proxy(function(value){
value.get('mapElement').setOptions({icons: this.icons});
}), this);
}
},
/**
* Fonction permettant de reset l'option icons
*/
resetIcons: function()
{
if (parseFloat(navigator.appVersion.split("MSIE")[1]) > 8) {
_.each(this.models, CanalTP.jQuery.proxy(function(value){
this.icons = value.previous('icons');
value.get('mapElement').setOptions({icons: this.icons});
}), this);
}
},
/**
* Fonction permettant de récupérer le icons
*/
getIcons: function()
{
return this.icons;
}
});
| mit |
jaykz52/mechanic | src/logging.js | 1469 | // mechanic.js
// Copyright (c) 2012 Jason Kozemczak
// mechanic.js may be freely distributed under the MIT license.
(function($) {
$.extend($, {
log: function(s, level) {
level = level || 'message';
if (level === 'error') $.error(s);
else if (level === 'warn') $.warn(s);
else if (typeof $.isVerbose !== "undefined" && $.isVerbose) {
if (level === 'debug') $.debug(s);
else $.message(s);
}
},
error: function(s) { UIALogger.logError(s); },
warn: function(s) { UIALogger.logWarning(s); },
debug: function(s) { UIALogger.logDebug(s); },
message: function(s) { UIALogger.logMessage(s); },
capture: function(imageName, rect) {
var target = UIATarget.localTarget();
imageName = imageName || new Date().toString();
if (rect) target.captureRectWithName(rect, imageName);
else target.captureScreenWithName(imageName);
}
});
$.extend($.fn, {
log: function() { return this.each(function() { this.logElement(); }); },
logTree: function () { return this.each(function() { this.logElementTree(); }); },
capture: function(imageName) {
imageName = imageName || new Date().toString();
return this.each(function() { $.capture(imageName + '-' + this.name(), this.rect()); });
}
});
})(mechanic);
| mit |
atoff/core | config/session.php | 6880 | <?php
return [
/*
|--------------------------------------------------------------------------
| Default Session Driver
|--------------------------------------------------------------------------
|
| This option controls the default session "driver" that will be used on
| requests. By default, we will use the lightweight native driver but
| you may specify any of the other wonderful drivers provided here.
|
| Supported: "file", "cookie", "database", "apc",
| "memcached", "redis", "array"
|
*/
'driver' => env('SESSION_DRIVER', 'file'),
/*
|--------------------------------------------------------------------------
| Session Lifetime
|--------------------------------------------------------------------------
|
| Here you may specify the number of minutes that you wish the session
| to be allowed to remain idle before it expires. If you want them
| to immediately expire on the browser closing, set that option.
|
*/
'lifetime' => env('SESSION_LIFETIME', 60 * 24 * 2),
'expire_on_close' => false,
/*
|--------------------------------------------------------------------------
| Session Encryption
|--------------------------------------------------------------------------
|
| This option allows you to easily specify that all of your session data
| should be encrypted before it is stored. All encryption will be run
| automatically by Laravel and you can use the Session like normal.
|
*/
'encrypt' => env('SESSION_ENCRYPT', false),
/*
|--------------------------------------------------------------------------
| Session File Location
|--------------------------------------------------------------------------
|
| When using the native session driver, we need a location where session
| files may be stored. A default has been set for you but a different
| location may be specified. This is only needed for file sessions.
|
*/
'files' => storage_path('framework/sessions'),
/*
|--------------------------------------------------------------------------
| Session Database Connection
|--------------------------------------------------------------------------
|
| When using the "database" or "redis" session drivers, you may specify a
| connection that should be used to manage these sessions. This should
| correspond to a connection in your database configuration options.
|
*/
'connection' => env('SESSION_CONNECTION', null),
/*
|--------------------------------------------------------------------------
| Session Database Table
|--------------------------------------------------------------------------
|
| When using the "database" session driver, you may specify the table we
| should use to manage the sessions. Of course, a sensible default is
| provided for you; however, you are free to change this as needed.
|
*/
'table' => 'sys_sessions',
/*
|--------------------------------------------------------------------------
| Session Cache Store
|--------------------------------------------------------------------------
|
| When using the "apc" or "memcached" session drivers, you may specify a
| cache store that should be used for these sessions. This value must
| correspond with one of the application's configured cache stores.
|
*/
'store' => null,
/*
|--------------------------------------------------------------------------
| Session Sweeping Lottery
|--------------------------------------------------------------------------
|
| Some session drivers must manually sweep their storage location to get
| rid of old sessions from storage. Here are the chances that it will
| happen on a given request. By default, the odds are 2 out of 100.
|
*/
'lottery' => [2, 100],
/*
|--------------------------------------------------------------------------
| Session Cookie Name
|--------------------------------------------------------------------------
|
| Here you may change the name of the cookie used to identify a session
| instance by ID. The name specified here will get used every time a
| new session cookie is created by the framework for every driver.
|
*/
'cookie' => env('SESSION_COOKIE', 'laravel_session'),
/*
|--------------------------------------------------------------------------
| Session Cookie Path
|--------------------------------------------------------------------------
|
| The session cookie path determines the path for which the cookie will
| be regarded as available. Typically, this will be the root path of
| your application but you are free to change this when necessary.
|
*/
'path' => '/',
/*
|--------------------------------------------------------------------------
| Session Cookie Domain
|--------------------------------------------------------------------------
|
| Here you may change the domain of the cookie used to identify a session
| in your application. This will determine which domains the cookie is
| available to in your application. A sensible default has been set.
|
*/
'domain' => env('SESSION_DOMAIN', null),
/*
|--------------------------------------------------------------------------
| HTTPS Only Cookies
|--------------------------------------------------------------------------
|
| By setting this option to true, session cookies will only be sent back
| to the server if the browser has a HTTPS connection. This will keep
| the cookie from being sent to you if it can not be done securely.
|
*/
'secure' => env('SESSION_SECURE_COOKIE', null),
/*
|--------------------------------------------------------------------------
| HTTP Access Only
|--------------------------------------------------------------------------
|
| Setting this value to true will prevent JavaScript from accessing the
| value of the cookie and the cookie will only be accessible through
| the HTTP protocol. You are free to modify this option if needed.
|
*/
'http_only' => true,
/*
|--------------------------------------------------------------------------
| Same-Site Cookies
|--------------------------------------------------------------------------
|
| This option determines how your cookies behave when cross-site requests
| take place, and can be used to mitigate CSRF attacks. By default, we
| do not enable this as other CSRF protection services are in place.
|
| Supported: "lax", "strict"
|
*/
'same_site' => null,
];
| mit |
slindberg/ember.js | packages_es6/ember-metal/tests/utils/generate_guid_test.js | 211 | import {generateGuid} from "ember-metal/utils";
module("Ember.generateGuid");
test("Prefix", function() {
var a = {};
ok( generateGuid(a, 'tyrell').indexOf('tyrell') > -1, "guid can be prefixed" );
});
| mit |
jackmagic313/azure-sdk-for-net | sdk/cosmosdb/Microsoft.Azure.Management.CosmosDB/src/Generated/PercentileTargetOperations.cs | 14324 | // <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.CosmosDB
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// PercentileTargetOperations operations.
/// </summary>
internal partial class PercentileTargetOperations : IServiceOperations<CosmosDBManagementClient>, IPercentileTargetOperations
{
/// <summary>
/// Initializes a new instance of the PercentileTargetOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal PercentileTargetOperations(CosmosDBManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the CosmosDBManagementClient
/// </summary>
public CosmosDBManagementClient Client { get; private set; }
/// <summary>
/// Retrieves the metrics determined by the given filter for the given account
/// target region. This url is only for PBS and Replication Latency data
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='accountName'>
/// Cosmos DB database account name.
/// </param>
/// <param name='targetRegion'>
/// Target region to which data is written. Cosmos DB region, with spaces
/// between words and each word capitalized.
/// </param>
/// <param name='filter'>
/// An OData filter expression that describes a subset of metrics to return.
/// The parameters that can be filtered are name.value (name of the metric, can
/// have an or of multiple names), startTime, endTime, and timeGrain. The
/// supported operator is eq.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IEnumerable<PercentileMetric>>> ListMetricsWithHttpMessagesAsync(string resourceGroupName, string accountName, string targetRegion, string filter, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (Client.SubscriptionId != null)
{
if (Client.SubscriptionId.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "Client.SubscriptionId", 1);
}
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length > 90)
{
throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90);
}
if (resourceGroupName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$");
}
}
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (accountName != null)
{
if (accountName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "accountName", 50);
}
if (accountName.Length < 3)
{
throw new ValidationException(ValidationRules.MinLength, "accountName", 3);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(accountName, "^[a-z0-9]+(-[a-z0-9]+)*"))
{
throw new ValidationException(ValidationRules.Pattern, "accountName", "^[a-z0-9]+(-[a-z0-9]+)*");
}
}
if (targetRegion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "targetRegion");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.ApiVersion != null)
{
if (Client.ApiVersion.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "Client.ApiVersion", 1);
}
}
if (filter == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "filter");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("targetRegion", targetRegion);
tracingParameters.Add("filter", filter);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListMetrics", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/targetRegion/{targetRegion}/percentile/metrics").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName));
_url = _url.Replace("{targetRegion}", System.Uri.EscapeDataString(targetRegion));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (filter != null)
{
_queryParameters.Add(string.Format("$filter={0}", System.Uri.EscapeDataString(filter)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IEnumerable<PercentileMetric>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<PercentileMetric>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| mit |
maurer/tiamat | samples/Juliet/testcases/CWE23_Relative_Path_Traversal/s04/CWE23_Relative_Path_Traversal__wchar_t_file_ifstream_66b.cpp | 1711 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE23_Relative_Path_Traversal__wchar_t_file_ifstream_66b.cpp
Label Definition File: CWE23_Relative_Path_Traversal.label.xml
Template File: sources-sink-66b.tmpl.cpp
*/
/*
* @description
* CWE: 23 Relative Path Traversal
* BadSource: file Read input from a file
* GoodSource: Use a fixed file name
* Sinks: ifstream
* BadSink : Open the file named in data using ifstream::open()
* Flow Variant: 66 Data flow: data passed in an array from one function to another in different source files
*
* */
#include "std_testcase.h"
#ifdef _WIN32
#define BASEPATH L"c:\\temp\\"
#else
#include <wchar.h>
#define BASEPATH L"/tmp/"
#endif
#ifdef _WIN32
#define FILENAME "C:\\temp\\file.txt"
#else
#define FILENAME "/tmp/file.txt"
#endif
#include <fstream>
using namespace std;
namespace CWE23_Relative_Path_Traversal__wchar_t_file_ifstream_66
{
#ifndef OMITBAD
void badSink(wchar_t * dataArray[])
{
/* copy data out of dataArray */
wchar_t * data = dataArray[2];
{
ifstream inputFile;
/* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */
inputFile.open((char *)data);
inputFile.close();
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(wchar_t * dataArray[])
{
wchar_t * data = dataArray[2];
{
ifstream inputFile;
/* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */
inputFile.open((char *)data);
inputFile.close();
}
}
#endif /* OMITGOOD */
} /* close namespace */
| mit |
cseed/hail | hail/src/main/scala/is/hail/io/index/IndexReader.scala | 9907 | package is.hail.io.index
import java.io.InputStream
import java.util
import java.util.Map.Entry
import is.hail.annotations._
import is.hail.types.virtual.{TStruct, Type, TypeSerializer}
import is.hail.expr.ir.{ExecuteContext, IRParser}
import is.hail.types.physical.{PStruct, PType}
import is.hail.io._
import is.hail.io.bgen.BgenSettings
import is.hail.utils._
import is.hail.io.fs.FS
import is.hail.rvd.{AbstractIndexSpec, AbstractRVDSpec, PartitionBoundOrdering}
import org.apache.hadoop.fs.FSDataInputStream
import org.apache.spark.sql.Row
import org.json4s.{Formats, NoTypeHints}
import org.json4s.jackson.{JsonMethods, Serialization}
object IndexReaderBuilder {
def fromSpec(ctx: ExecuteContext, spec: AbstractIndexSpec): (FS, String, Int) => IndexReader = {
val (keyType, annotationType) = spec.types
val (leafPType: PStruct, leafDec) = spec.leafCodec.buildDecoder(ctx, spec.leafCodec.encodedVirtualType)
val (intPType: PStruct, intDec) = spec.internalNodeCodec.buildDecoder(ctx, spec.internalNodeCodec.encodedVirtualType)
withDecoders(leafDec, intDec, keyType, annotationType, leafPType, intPType)
}
def withDecoders(
leafDec: (InputStream) => Decoder, intDec: (InputStream) => Decoder,
keyType: Type, annotationType: Type,
leafPType: PStruct, intPType: PStruct
): (FS, String, Int) => IndexReader = {
(fs, path, cacheCapacity) => new IndexReader(fs, path, cacheCapacity, leafDec,
intDec, keyType, annotationType, leafPType, intPType)
}
}
object IndexReader {
def readUntyped(fs: FS, path: String): IndexMetadataUntypedJSON = {
val jv = using(fs.open(path + "/metadata.json.gz")) { in =>
JsonMethods.parse(in)
.removeField{ case (f, _) => f == "keyType" || f == "annotationType" }
}
implicit val formats: Formats = defaultJSONFormats
jv.extract[IndexMetadataUntypedJSON]
}
def readMetadata(fs: FS, path: String, keyType: Type, annotationType: Type): IndexMetadata = {
val untyped = IndexReader.readUntyped(fs, path)
untyped.toMetadata(keyType, annotationType)
}
def readTypes(fs: FS, path: String): (Type, Type) = {
val jv = using(fs.open(path + "/metadata.json.gz")) { in => JsonMethods.parse(in) }
implicit val formats: Formats = defaultJSONFormats + new TypeSerializer
val metadata = jv.extract[IndexMetadata]
metadata.keyType -> metadata.annotationType
}
}
class IndexReader(fs: FS,
path: String,
cacheCapacity: Int = 8,
leafDecoderBuilder: (InputStream) => Decoder,
internalDecoderBuilder: (InputStream) => Decoder,
val keyType: Type,
val annotationType: Type,
val leafPType: PStruct,
val internalPType: PStruct
) extends AutoCloseable {
private[io] val metadata = IndexReader.readMetadata(fs, path, keyType, annotationType)
val branchingFactor = metadata.branchingFactor
val height = metadata.height
val nKeys = metadata.nKeys
val attributes = metadata.attributes
val indexRelativePath = metadata.indexPath
val ordering = keyType match {
case ts: TStruct => PartitionBoundOrdering(ts)
case t => t.ordering
}
private val is = fs.openNoCompression(path + "/" + indexRelativePath)
private val leafDecoder = leafDecoderBuilder(is)
private val internalDecoder = internalDecoderBuilder(is)
private val region = Region()
private val rv = RegionValue(region)
private var cacheHits = 0L
private var cacheMisses = 0L
@transient private[this] lazy val cache = new util.LinkedHashMap[Long, IndexNode](cacheCapacity, 0.75f, true) {
override def removeEldestEntry(eldest: Entry[Long, IndexNode]): Boolean = size() > cacheCapacity
}
private[io] def readInternalNode(offset: Long): InternalNode = {
if (cache.containsKey(offset)) {
cacheHits += 1
cache.get(offset).asInstanceOf[InternalNode]
} else {
cacheMisses += 1
is.seek(offset)
assert(internalDecoder.readByte() == 1)
rv.setOffset(internalDecoder.readRegionValue(region))
val node = InternalNode(SafeRow(internalPType, rv))
cache.put(offset, node)
region.clear()
node
}
}
private[io] def readLeafNode(offset: Long): LeafNode = {
if (cache.containsKey(offset)) {
cacheHits += 1
cache.get(offset).asInstanceOf[LeafNode]
} else {
cacheMisses += 1
is.seek(offset)
assert(leafDecoder.readByte() == 0)
rv.setOffset(leafDecoder.readRegionValue(region))
val node = LeafNode(SafeRow(leafPType, rv))
cache.put(offset, node)
region.clear()
node
}
}
private def lowerBound(key: Annotation, level: Int, offset: Long): Long = {
if (level == 0) {
val node = readLeafNode(offset)
val idx = node.children.lowerBound(key, ordering.lt, _.key)
node.firstIndex + idx
} else {
val node = readInternalNode(offset)
val children = node.children
val idx = children.lowerBound(key, ordering.lt, _.firstKey)
lowerBound(key, level - 1, children(idx - 1).indexFileOffset)
}
}
private[io] def lowerBound(key: Annotation): Long = {
if (nKeys == 0 || ordering.lteq(key, readInternalNode(metadata.rootOffset).children.head.firstKey))
0
else
lowerBound(key, height - 1, metadata.rootOffset)
}
private def upperBound(key: Annotation, level: Int, offset: Long): Long = {
if (level == 0) {
val node = readLeafNode(offset)
val idx = node.children.upperBound(key, ordering.lt, _.key)
node.firstIndex + idx
} else {
val node = readInternalNode(offset)
val children = node.children
val n = children.length
val idx = children.upperBound(key, ordering.lt, _.firstKey)
upperBound(key, level - 1, children(idx - 1).indexFileOffset)
}
}
private[io] def upperBound(key: Annotation): Long = {
if (nKeys == 0 || ordering.lt(key, readInternalNode(metadata.rootOffset).children.head.firstKey))
0
else
upperBound(key, height - 1, metadata.rootOffset)
}
private def getLeafNode(index: Long, level: Int, offset: Long): LeafNode = {
if (level == 0) {
readLeafNode(offset)
} else {
val node = readInternalNode(offset)
val firstIndex = node.firstIndex
val nKeysPerChild = math.pow(branchingFactor, level).toLong
val localIndex = (index - firstIndex) / nKeysPerChild
getLeafNode(index, level - 1, node.children(localIndex.toInt).indexFileOffset)
}
}
private def getLeafNode(index: Long): LeafNode =
getLeafNode(index, height - 1, metadata.rootOffset)
def queryByKey(key: Annotation): Array[LeafChild] = {
val ab = new ArrayBuilder[LeafChild]()
keyIterator(key).foreach(ab += _)
ab.result()
}
def keyIterator(key: Annotation): Iterator[LeafChild] =
iterateFrom(key).takeWhile(lc => ordering.equiv(lc.key, key))
def queryByIndex(index: Long): LeafChild = {
require(index >= 0 && index < nKeys)
val node = getLeafNode(index)
val localIdx = index - node.firstIndex
node.children(localIdx.toInt)
}
def queryByInterval(interval: Interval): Iterator[LeafChild] =
queryByInterval(interval.start, interval.end, interval.includesStart, interval.includesEnd)
def queryByInterval(start: Annotation, end: Annotation, includesStart: Boolean, includesEnd: Boolean): Iterator[LeafChild] = {
require(Interval.isValid(ordering, start, end, includesStart, includesEnd))
val startIdx = if (includesStart) lowerBound(start) else upperBound(start)
val endIdx = if (includesEnd) upperBound(end) else lowerBound(end)
iterator(startIdx, endIdx)
}
def iterator: Iterator[LeafChild] = iterator(0, nKeys)
def iterator(start: Long, end: Long) = new Iterator[LeafChild] {
assert(start >= 0 && end <= nKeys && start <= end)
var pos = start
var localPos = 0
var leafNode: LeafNode = _
def next(): LeafChild = {
assert(hasNext)
if (leafNode == null || localPos >= leafNode.children.length) {
leafNode = getLeafNode(pos)
assert(leafNode.firstIndex <= pos && pos < leafNode.firstIndex + branchingFactor)
localPos = (pos - leafNode.firstIndex).toInt
}
val child = leafNode.children(localPos)
pos += 1
localPos += 1
child
}
def hasNext: Boolean = pos < end
def seek(key: Annotation) {
val newPos = lowerBound(key)
assert(newPos >= pos)
localPos += (newPos - pos).toInt
pos = newPos
}
}
def iterateFrom(key: Annotation): Iterator[LeafChild] =
iterator(lowerBound(key), nKeys)
def iterateUntil(key: Annotation): Iterator[LeafChild] =
iterator(0, lowerBound(key))
def close() {
leafDecoder.close()
internalDecoder.close()
log.info(s"Index reader cache queries: ${ cacheHits + cacheMisses }")
log.info(s"Index reader cache hit rate: ${ cacheHits.toDouble / (cacheHits + cacheMisses) }")
}
}
final case class InternalChild(
indexFileOffset: Long,
firstIndex: Long,
firstKey: Annotation,
firstRecordOffset: Long,
firstAnnotation: Annotation)
object InternalNode {
def apply(r: Row): InternalNode = {
val children = r.get(0).asInstanceOf[IndexedSeq[Row]].map(r => InternalChild(r.getLong(0), r.getLong(1), r.get(2), r.getLong(3), r.get(4)))
InternalNode(children)
}
}
final case class InternalNode(children: IndexedSeq[InternalChild]) extends IndexNode {
def firstIndex: Long = {
assert(children.nonEmpty)
children.head.firstIndex
}
}
final case class LeafChild(
key: Annotation,
recordOffset: Long,
annotation: Annotation)
object LeafNode {
def apply(r: Row): LeafNode = {
val firstKeyIndex = r.getLong(0)
val keys = r.get(1).asInstanceOf[IndexedSeq[Row]].map(r => LeafChild(r.get(0), r.getLong(1), r.get(2)))
LeafNode(firstKeyIndex, keys)
}
}
final case class LeafNode(
firstIndex: Long,
children: IndexedSeq[LeafChild]) extends IndexNode
sealed trait IndexNode
| mit |
WantedTechnologies/xpresso | src/main/java/com/wantedtech/common/xpresso/functional/lambda/LambdaListener.java | 3716 | // Generated from Lambda.g by ANTLR 4.5
package com.wantedtech.common.xpresso.functional.lambda;
import java.util.*;
import com.wantedtech.common.xpresso.functional.Function;
import com.wantedtech.common.xpresso.x;
import org.antlr.v4.runtime.misc.NotNull;
import org.antlr.v4.runtime.tree.ParseTreeListener;
/**
* This interface defines a complete listener for a parse tree produced by
* {@link LambdaParser}.
*/
public interface LambdaListener extends ParseTreeListener {
/**
* Enter a parse tree produced by {@link LambdaParser#eval}.
* @param ctx the parse tree
*/
void enterEval(LambdaParser.EvalContext ctx);
/**
* Exit a parse tree produced by {@link LambdaParser#eval}.
* @param ctx the parse tree
*/
void exitEval(LambdaParser.EvalContext ctx);
/**
* Enter a parse tree produced by {@link LambdaParser#lambdaExpression}.
* @param ctx the parse tree
*/
void enterLambdaExpression(LambdaParser.LambdaExpressionContext ctx);
/**
* Exit a parse tree produced by {@link LambdaParser#lambdaExpression}.
* @param ctx the parse tree
*/
void exitLambdaExpression(LambdaParser.LambdaExpressionContext ctx);
/**
* Enter a parse tree produced by {@link LambdaParser#anyExpression}.
* @param ctx the parse tree
*/
void enterAnyExpression(LambdaParser.AnyExpressionContext ctx);
/**
* Exit a parse tree produced by {@link LambdaParser#anyExpression}.
* @param ctx the parse tree
*/
void exitAnyExpression(LambdaParser.AnyExpressionContext ctx);
/**
* Enter a parse tree produced by {@link LambdaParser#arithmeticExpressionE}.
* @param ctx the parse tree
*/
void enterArithmeticExpressionE(LambdaParser.ArithmeticExpressionEContext ctx);
/**
* Exit a parse tree produced by {@link LambdaParser#arithmeticExpressionE}.
* @param ctx the parse tree
*/
void exitArithmeticExpressionE(LambdaParser.ArithmeticExpressionEContext ctx);
/**
* Enter a parse tree produced by {@link LambdaParser#booleanExpressionB}.
* @param ctx the parse tree
*/
void enterBooleanExpressionB(LambdaParser.BooleanExpressionBContext ctx);
/**
* Exit a parse tree produced by {@link LambdaParser#booleanExpressionB}.
* @param ctx the parse tree
*/
void exitBooleanExpressionB(LambdaParser.BooleanExpressionBContext ctx);
/**
* Enter a parse tree produced by {@link LambdaParser#productExpressionT}.
* @param ctx the parse tree
*/
void enterProductExpressionT(LambdaParser.ProductExpressionTContext ctx);
/**
* Exit a parse tree produced by {@link LambdaParser#productExpressionT}.
* @param ctx the parse tree
*/
void exitProductExpressionT(LambdaParser.ProductExpressionTContext ctx);
/**
* Enter a parse tree produced by {@link LambdaParser#basicExpressionF}.
* @param ctx the parse tree
*/
void enterBasicExpressionF(LambdaParser.BasicExpressionFContext ctx);
/**
* Exit a parse tree produced by {@link LambdaParser#basicExpressionF}.
* @param ctx the parse tree
*/
void exitBasicExpressionF(LambdaParser.BasicExpressionFContext ctx);
/**
* Enter a parse tree produced by {@link LambdaParser#complexIdentifier}.
* @param ctx the parse tree
*/
void enterComplexIdentifier(LambdaParser.ComplexIdentifierContext ctx);
/**
* Exit a parse tree produced by {@link LambdaParser#complexIdentifier}.
* @param ctx the parse tree
*/
void exitComplexIdentifier(LambdaParser.ComplexIdentifierContext ctx);
/**
* Enter a parse tree produced by {@link LambdaParser#function}.
* @param ctx the parse tree
*/
void enterFunction(LambdaParser.FunctionContext ctx);
/**
* Exit a parse tree produced by {@link LambdaParser#function}.
* @param ctx the parse tree
*/
void exitFunction(LambdaParser.FunctionContext ctx);
} | mit |
pdanpdan/quasar | extras/build/themify.js | 1205 | const packageName = 'themify-icons'
const iconSetName = 'Themify'
const version = '1.0.1'
// ------------
const glob = require('glob')
const { copySync } = require('fs-extra')
const { resolve } = require('path')
const skipped = []
const distFolder = resolve(__dirname, `../themify`)
const { defaultNameMapper, extract, writeExports } = require('./utils')
const svgFolder = resolve(__dirname, `../node_modules/${packageName}/SVG/`)
const svgFiles = glob.sync(svgFolder + '/*.svg')
const iconNames = new Set()
const svgExports = []
const typeExports = []
svgFiles.forEach(file => {
const name = defaultNameMapper(file, 'ti')
if (iconNames.has(name)) {
return
}
try {
const { svgDef, typeDef } = extract(file, name)
svgExports.push(svgDef)
typeExports.push(typeDef)
iconNames.add(name)
}
catch(err) {
console.error(err)
skipped.push(name)
}
})
writeExports(iconSetName, version, distFolder, svgExports, typeExports, skipped)
// then update webfont files
const webfont = [
'themify.woff'
]
webfont.forEach(file => {
copySync(
resolve(__dirname, `../node_modules/${packageName}/fonts/${file}`),
resolve(__dirname, `../themify/${file}`)
)
})
| mit |
AxelSparkster/axelsparkster.github.io | node_modules/caniuse-lite/data/features/prefers-color-scheme.js | 897 | module.exports={A:{A:{"2":"K D G E A B hB"},B:{"2":"2 C d J M H I"},C:{"1":"4 FB","2":"0 1 2 3 6 7 8 9 eB DB F N K D G E A B C d J M H I O P Q R S T U V W X Y Z a b c e f g h i j k l m n o L q r s t u v w x y z HB GB BB CB YB XB"},D:{"2":"0 1 2 3 4 6 7 8 9 F N K D G E A B C d J M H I O P Q R S T U V W X Y Z a b c e f g h i j k l m n o L q r s t u v w x y z HB GB BB CB FB RB MB LB kB JB NB OB PB"},E:{"1":"5 ZB","2":"F N K D G E A B C QB IB SB TB UB VB WB p"},F:{"2":"0 1 5 6 E B C J M H I O P Q R S T U V W X Y Z a b c e f g h i j k l m n o L q r s t u v w x y z aB bB cB dB p AB fB"},G:{"2":"G IB gB EB iB jB KB lB mB nB oB pB qB rB sB tB"},H:{"2":"uB"},I:{"2":"4 DB F vB wB xB yB EB zB 0B"},J:{"2":"D A"},K:{"2":"5 A B C L p AB"},L:{"2":"JB"},M:{"2":"3"},N:{"2":"A B"},O:{"2":"1B"},P:{"2":"F 2B 3B 4B 5B 6B"},Q:{"2":"7B"},R:{"2":"8B"},S:{"2":"9B"}},B:7,C:"prefers-color-scheme media query"};
| mit |
mhowlett/NNanomsg | NNanomsg/Protocols/PublishSocket.cs | 1003 | namespace NNanomsg.Protocols
{
public class PublishSocket : NanomsgSocketBase, IBindSocket, ISendSocket
{
public PublishSocket() : base(Domain.SP, Protocol.PUB) { }
#region Bind
public NanomsgEndpoint Bind(string address)
{
return BindImpl(address);
}
#endregion
#region Send
public void Send(byte[] buffer)
{
SendImpl(buffer);
}
public bool SendImmediate(byte[] buffer)
{
return SendImmediateImpl(buffer);
}
public NanomsgWriteStream CreateSendStream()
{
return CreateSendStreamImpl();
}
public void SendStream(NanomsgWriteStream stream)
{
SendStreamImpl(stream);
}
public bool SendStreamImmediate(NanomsgWriteStream stream)
{
return SendStreamImmediateImpl(stream);
}
#endregion
}
}
| mit |
lookstechnical/givemesoul | blocks/flex_slider_close/edit.php | 384 | <?php defined('C5_EXECUTE') or die("Access Denied.");
?>
<style type="text/css" media="screen">
.ccm-block-field-group h2 { margin-bottom: 5px; }
.ccm-block-field-group td { vertical-align: middle; }
</style>
<div class="ccm-block-field-group">
<h2>close</h2>
<?php echo $form->text('field_1_textbox_text', $field_1_textbox_text, array('style' => 'width: 95%;')); ?>
</div>
| mit |
kevinrodbe/minigrid | index.js | 2962 | /* @license minigrid v1.6.5 - minimal cascading grid layout http://alves.im/minigrid */
(function (exports) {
'use strict';
var transformProp;
(function () {
var style = document.createElement('a').style;
var prop;
if (style[prop = 'webkitTransform'] !== undefined) {
transformProp = prop;
}
if (style[prop = 'msTransform'] !== undefined) {
transformProp = prop;
}
if (style[prop = 'transform'] !== undefined) {
transformProp = prop;
}
}());
function forEach (arr, cb) {
if (arr) {
for (var i = 0, len = arr.length; i < len; i++) {
if (arr[i]) {
cb(arr[i], i, arr);
}
}
}
}
function minigrid (gridContainer, itemSelector, gutter, animate, done) {
var containerEle = gridContainer instanceof Node ? gridContainer : document.querySelector(gridContainer);
if (!containerEle) { return false; }
var itemsNodeList = containerEle.querySelectorAll(itemSelector);
if (itemsNodeList.length === 0) { return false; }
gutter = (typeof gutter === 'number' && isFinite(gutter) && Math.floor(gutter) === gutter) ? gutter : 6;
containerEle.style.width = '';
var containerWidth = containerEle.getBoundingClientRect().width;
var firstChildWidth = itemsNodeList[0].getBoundingClientRect().width + gutter;
var cols = Math.max(Math.floor((containerWidth - gutter) / firstChildWidth), 1);
var count = 0;
containerWidth = (firstChildWidth * cols + gutter) + 'px';
containerEle.style.width = containerWidth;
containerEle.style.position = 'relative';
var itemsGutter = [];
var itemsPosX = [];
for ( var g = 0 ; g < cols ; ++g ) {
itemsPosX.push(g * firstChildWidth + gutter);
itemsGutter.push(gutter);
}
forEach(itemsNodeList, function (item) {
var itemIndex = itemsGutter
.slice(0)
.sort(function (a, b) {
return a - b;
})
.shift();
itemIndex = itemsGutter.indexOf(itemIndex);
var posX = itemsPosX[itemIndex];
var posY = itemsGutter[itemIndex];
item.style.position = 'absolute';
if (!animate && transformProp) {
item.style[transformProp] = 'translate3D(' + posX + 'px,' + posY + 'px, 0)';
}
itemsGutter[itemIndex] += item.getBoundingClientRect().height + gutter;
count = count + 1;
if (animate) {
return animate(item, posX, posY, count);
}
});
var containerHeight = itemsGutter
.slice(0)
.sort(function (a, b) {
return a - b;
})
.pop();
containerEle.style.height = containerHeight + 'px';
if (typeof done === 'function') {
done(itemsNodeList);
}
}
if (typeof define === 'function' && define.amd) {
define(function() { return minigrid; });
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = minigrid;
} else {
exports.minigrid = minigrid;
}
})(this);
| mit |
iamsaint/yii2-user-mongo | models/UserQuery.php | 807 | <?php
/*
* This file is part of the Dektrium project.
*
* (c) Dektrium project <http://github.com/dektrium/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace hipstercreative\user\models;
use yii\mongodb\ActiveQuery;
/**
* UserQuery
*
* @author Dmitry Erofeev <dmeroff@gmail.com
*/
class UserQuery extends ActiveQuery
{
/**
* Only confirmed users.
*
* @return $this
*/
public function confirmed()
{
$this->andWhere('confirmed_at IS NOT NULL');
return $this;
}
/**
* Only unconfirmed users.
*
* @return $this
*/
public function unconfirmed()
{
$this->andWhere('confirmed_at IS NULL');
return $this;
}
}
| mit |
dbagaev/mesh | mesh/data/Tests/Test_Stl.cpp | 1929 | #include <Data/TriangleSurface.h>
#include <Math/Vector3d.h>
#include "gtest/gtest.h"
using namespace mesh;
TEST(Test_surface, Basic_Test)
{
Data::TriangleSurface surface;
EXPECT_EQ(0, surface.getNumberPoints());
EXPECT_EQ(0, surface.getNumberTriangles());
Data::Point * p_points[3];
Data::Point * p_point;
p_point = surface.addPoint(0, 0, 0);
EXPECT_EQ(1, surface.getNumberPoints());
EXPECT_FALSE(p_point == nullptr);
p_points[0] = p_point;
p_point = surface.addPoint(0, 0, 0);
EXPECT_EQ(1, surface.getNumberPoints());
EXPECT_EQ(p_points[0], p_point);
p_point = surface.addPoint(100, 0, 0);
EXPECT_EQ(2, surface.getNumberPoints());
EXPECT_FALSE(p_point == nullptr);
p_points[1] = p_point;
p_point = surface.addPoint(100, 0, 0);
EXPECT_EQ(2, surface.getNumberPoints());
EXPECT_EQ(p_points[1], p_point);
p_point = surface.addPoint(0, 100, 0);
EXPECT_EQ(3, surface.getNumberPoints());
EXPECT_FALSE(p_point == nullptr);
p_points[2] = p_point;
p_point = surface.addPoint(0, 100, 0);
EXPECT_EQ(3, surface.getNumberPoints());
EXPECT_EQ(p_points[2], p_point);
auto p_triangle = surface.addTriangle(p_points[0], p_points[1], p_points[2]);
EXPECT_FALSE(p_triangle == nullptr);
EXPECT_EQ(3, surface.getNumberPoints());
EXPECT_EQ(1, surface.getNumberTriangles());
p_triangle = surface.addTriangle(Math::Vector3dDouble{0, 0, 0}, Math::Vector3dDouble{100, 0, 0}, Math::Vector3dDouble{0, 0, 100});
EXPECT_FALSE(p_triangle == nullptr);
EXPECT_EQ(4, surface.getNumberPoints());
EXPECT_EQ(2, surface.getNumberTriangles());
p_triangle = surface.addTriangle(Math::Vector3dDouble{0, 0, 0}, Math::Vector3dDouble{100, 0, 0}, Math::Vector3dDouble{0, 0, 100});
EXPECT_FALSE(p_triangle == nullptr);
EXPECT_EQ(4, surface.getNumberPoints());
EXPECT_EQ(3, surface.getNumberTriangles());
}
| mit |
HackerSir/CheckIn2017 | database/migrations/2021_07_25_195754_create_roles.php | 964 | <?php
use Illuminate\Database\Migrations\Migration;
class CreateRoles extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
DB::table('roles')->insert([
[
'name' => 'Admin',
'display_name' => '管理員',
'description' => '擁有最高權限的網站管理者',
],
[
'name' => 'EAS',
'display_name' => '課外活動組',
'description' => '擁有活動權限的管理者',
],
[
'name' => 'staff',
'display_name' => '服務台',
'description' => '服務台工作人員',
],
]);
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
DB::table('roles')->delete();
}
}
| mit |
gheine/apidoc | avro/src/test/scala/me/apidoc/avro/AvroIdlServiceValidatorSpec.scala | 700 | package me.apidoc.avro
import lib.ServiceConfiguration
import org.scalatest.{FunSpec, Matchers}
class AvroIdlServiceValidatorSpec extends FunSpec with Matchers {
private def readFile(path: String): String = {
scala.io.Source.fromFile(path).getLines.mkString("\n")
}
val config = ServiceConfiguration(
orgKey = "gilt",
orgNamespace = "io.apibuilder",
version = "0.0.1-dev"
)
it("parses") {
AvroIdlServiceValidator(config, readFile("avro/example.avdl")).validate match {
case Left(errors) => {
println("ERRORS: " + errors.mkString(", "))
}
case Right(service) => {
println("No errors. Service: " + service.name)
}
}
}
}
| mit |
ankitkayastha/VOOGASalad | src/authoring_environment/object_editor/ObjectEditorController.java | 7555 | package authoring_environment.object_editor;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.ResourceBundle;
import authoring_environment.PopUpError;
import authoring_environment.Event.EventController;
import authoring_environment.ParamPopups.ParamController;
import authoring_environment.main.IUpdateHandle;
import javafx.collections.MapChangeListener;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TextInputDialog;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;
import javafx.util.Callback;
import structures.data.DataGame;
import structures.data.DataObject;
import structures.data.DataSprite;
import structures.data.access_restricters.IObjectInterface;
import structures.data.actions.logic.Close;
import structures.data.actions.logic.Else;
import structures.data.actions.logic.Open;
import structures.data.actions.params.IParameter;
import structures.data.interfaces.IAction;
import structures.data.interfaces.IDataEvent;
public class ObjectEditorController {
ObjectEditorView view;
ObjectEditorModel model;
IUpdateHandle updater;
private ResourceBundle r = ResourceBundle.getBundle("authoring_environment/object_editor/ObjectControllerResources");
public ObjectEditorController(IObjectInterface dataGame, DataObject o) {
view = new ObjectEditorView(dataGame.getName());
model = new ObjectEditorModel(dataGame, o);
initAll();
}
public ObjectEditorController(IObjectInterface dataGame) {
TextInputDialog dialog = new TextInputDialog(r.getString("name"));
dialog.setTitle(r.getString("create"));
dialog.setHeaderText(r.getString("enter"));
Optional<String> result = dialog.showAndWait();
String name = "";
List<DataObject> list =dataGame.getObjects();
List<String> strlist = new ArrayList<String>();
for(DataObject d :list){
strlist.add(d.getName());
}
if (result.isPresent()) {
boolean dup =false;
for(String str:strlist){
if(str.equals(result.get())){
dup = true;
}
}
if(!dup){
name = result.get();
model = new ObjectEditorModel((IObjectInterface) dataGame, name);
view = new ObjectEditorView(dataGame.getName());
initAll();
}
else{
PopUpError er = new PopUpError(r.getString("duplicate"));
ObjectEditorController control = new ObjectEditorController(dataGame);
}
}
}
public void initAll() {
view.getBottomPane().getCloseButton().setOnAction(e -> {
model.changeObjectName(view.getBottomPane().getNameBoxText());
model.setSolid(view.getBottomPane().getCheckBox().isSelected());
close(e);
});
// view.getCenterPane().getSpriteUpdateButton().setOnAction(e -> {
// refreshSprite();
// });
view.getBottomPane().getCheckBox().setSelected(model.isSolid());
view.getBottomPane().getNameBox().setText(model.getObject().getName());
view.getRightPane().getListView().setItems(model.getEvents());
view.getRightPane().getListView().setCellFactory(new Callback<ListView<IDataEvent>, ListCell<IDataEvent>>() {
@Override
public ListCell<IDataEvent> call(ListView<IDataEvent> arg0) {
final ListCell<IDataEvent> cell = new ListCell<IDataEvent>() {
@Override
public void updateItem(IDataEvent item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
} else {
String description =item.getName()+ ":";
int indents =0 ;
for(IAction action: model.getMap().get(item)){
description += "\n ";
if(action instanceof Close || action instanceof Else){
indents -=1;
}
for(int i=0; i<indents;i++){
description += " ";
}
description +=action.getDescription();
if(action instanceof Open || action instanceof Else){
indents +=1;
}
}
setText(description);
}
}
};
cell.requestFocus();
cell.setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent key) {
if (key.getCode().equals(KeyCode.ENTER)) {
eventPopup(cell.getItem());
}
}
});
cell.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent click) {
if (click.getClickCount() == 2) {
//Use ListView's getSelected Item
IDataEvent selected = cell.getItem();
eventPopup(selected);
}
}
});
return cell;
}
});
view.getRightPane().getListView().setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
if (event.getCode().equals(KeyCode.ENTER)) {
eventPopup(view.getRightPane().getListView().getSelectionModel().getSelectedItem());
}
if (event.getCode().equals(KeyCode.DELETE)) {
model.deleteEvent(view.getRightPane().getListView().getSelectionModel().getSelectedItem());
}
}
});
view.getRightPane().getDeleteButton().setOnAction(e -> {
model.deleteEvent(view.getRightPane().getListView().getSelectionModel().getSelectedItem());
});
view.getRightPane().getEditButton().setOnAction(e -> {
eventPopup(view.getRightPane().getListView().getSelectionModel().getSelectedItem());
});
view.getLeftPane().getListView().setItems(model.createLeftPaneList());
view.getLeftPane().getListView().setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent key) {
if (key.getCode().equals(KeyCode.ENTER)) {
popUpFactory();
}
}
});
view.getLeftPane().getListView().setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent click) {
if (click.getClickCount() == 2) {
popUpFactory();
}
}
});
view.getLeftPane().getAddButton().setOnAction(e -> {
popUpFactory();
}
);
for (DataSprite s : model.getSprites()) {
view.getTopPane().addToMenu(view.getTopPane().createMenuItem(s.getName(), e -> {
model.setSprite(s);
refreshSprite();
}));
};
model.getMap().addListener(new MapChangeListener<Object, Object>() {
@Override
public void onChanged(Change<?, ?> arg0) {
model.getEvents();
}
});
refreshSprite();
}
private void popUpFactory() {
String selected = view.getLeftPane().getListView().getSelectionModel().getSelectedItem();
if(selected!=null){
model.getPopUpFactory().create(selected,model.getObject(), model.getGame());
}
}
private void eventPopup(IDataEvent e) {
if(e !=null){
EventController control = new EventController(e, model.getObject(),model.getGame());
control.showAndWait();
List<IDataEvent> itemscopy = new ArrayList<IDataEvent>(view.getRightPane().getListView().getItems());
view.getRightPane().getListView().getItems().setAll(itemscopy);
}
}
private void refreshSprite() {
String n = model.getSpriteName();
view.getCenterPane().update(n);
}
private void close(ActionEvent e) {
Node source = (Node) e.getSource();
Stage stage = (Stage) source.getScene().getWindow();
stage.close();
updater.update();
}
private void addSpriteToMenu(DataSprite s, Menu menu) {
MenuItem m = new MenuItem(s.getName());
m.setOnAction(e -> model.setSprite(s));
menu.getItems().add(m);
}
public void setOnClose(IUpdateHandle updateHandle) {
updater = updateHandle;
}
}
| mit |
gigya/orleans | src/OrleansRuntime/Streams/PubSub/PubSubRendezvousGrain.cs | 16321 | using System;
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
using Orleans.CodeGeneration;
using Orleans.Runtime;
namespace Orleans.Streams
{
[Serializable]
internal class PubSubGrainState
{
public HashSet<PubSubPublisherState> Producers { get; set; }
public HashSet<PubSubSubscriptionState> Consumers { get; set; }
}
[Orleans.Providers.StorageProvider(ProviderName = "PubSubStore")]
internal class PubSubRendezvousGrain : Grain<PubSubGrainState>, IPubSubRendezvousGrain
{
private Logger logger;
private const bool DEBUG_PUB_SUB = false;
private static readonly CounterStatistic counterProducersAdded;
private static readonly CounterStatistic counterProducersRemoved;
private static readonly CounterStatistic counterProducersTotal;
private static readonly CounterStatistic counterConsumersAdded;
private static readonly CounterStatistic counterConsumersRemoved;
private static readonly CounterStatistic counterConsumersTotal;
static PubSubRendezvousGrain()
{
counterProducersAdded = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_PRODUCERS_ADDED);
counterProducersRemoved = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_PRODUCERS_REMOVED);
counterProducersTotal = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_PRODUCERS_TOTAL);
counterConsumersAdded = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_CONSUMERS_ADDED);
counterConsumersRemoved = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_CONSUMERS_REMOVED);
counterConsumersTotal = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_CONSUMERS_TOTAL);
}
public override async Task OnActivateAsync()
{
logger = GetLogger(this.GetType().Name + "-" + RuntimeIdentity + "-" + IdentityString);
LogPubSubCounts("OnActivateAsync");
if (State.Consumers == null)
State.Consumers = new HashSet<PubSubSubscriptionState>();
if (State.Producers == null)
State.Producers = new HashSet<PubSubPublisherState>();
int numRemoved = RemoveDeadProducers();
if (numRemoved > 0)
{
if (State.Producers.Count > 0 || State.Consumers.Count > 0)
await WriteStateAsync();
else
await ClearStateAsync(); //State contains no producers or consumers, remove it from storage
}
if (logger.IsVerbose)
logger.Info("OnActivateAsync-Done");
}
public override Task OnDeactivateAsync()
{
LogPubSubCounts("OnDeactivateAsync");
return TaskDone.Done;
}
private int RemoveDeadProducers()
{
// Remove only those we know for sure are Dead.
int numRemoved = 0;
if (State.Producers != null && State.Producers.Count > 0)
numRemoved = State.Producers.RemoveWhere(producerState => IsDeadProducer(producerState.Producer));
if (numRemoved > 0)
{
LogPubSubCounts("RemoveDeadProducers: removed {0} outdated producers", numRemoved);
counterProducersRemoved.Increment();
counterProducersTotal.DecrementBy(numRemoved);
}
return numRemoved;
}
/// accept and notify only Active producers.
private static bool IsActiveProducer(IStreamProducerExtension producer)
{
var grainRef = producer as GrainReference;
if (grainRef !=null && grainRef.GrainId.IsSystemTarget && grainRef.IsInitializedSystemTarget)
return RuntimeClient.Current.GetSiloStatus(grainRef.SystemTargetSilo).Equals(SiloStatus.Active);
return true;
}
private static bool IsDeadProducer(IStreamProducerExtension producer)
{
var grainRef = producer as GrainReference;
if (grainRef != null && grainRef.GrainId.IsSystemTarget && grainRef.IsInitializedSystemTarget)
return RuntimeClient.Current.GetSiloStatus(grainRef.SystemTargetSilo).Equals(SiloStatus.Dead);
return false;
}
public async Task<ISet<PubSubSubscriptionState>> RegisterProducer(StreamId streamId, IStreamProducerExtension streamProducer)
{
if (!IsActiveProducer(streamProducer))
throw new ArgumentException(String.Format("Trying to register non active IStreamProducerExtension: {0}", streamProducer.ToString()), "streamProducer");
RemoveDeadProducers();
var publisherState = new PubSubPublisherState(streamId, streamProducer);
State.Producers.Add(publisherState);
counterProducersAdded.Increment();
counterProducersTotal.Increment();
LogPubSubCounts("RegisterProducer {0}", streamProducer);
await WriteStateAsync();
return State.Consumers.Where(c => !c.IsFaulted).ToSet();
}
public async Task UnregisterProducer(StreamId streamId, IStreamProducerExtension streamProducer)
{
int numRemoved = State.Producers.RemoveWhere(s => s.Equals(streamId, streamProducer));
counterProducersRemoved.Increment();
counterProducersTotal.DecrementBy(numRemoved);
LogPubSubCounts("UnregisterProducer {0} NumRemoved={1}", streamProducer, numRemoved);
if (numRemoved > 0)
await WriteStateAsync();
if (State.Producers.Count == 0 && State.Consumers.Count == 0)
{
await ClearStateAsync(); //State contains no producers or consumers, remove it from storage
DeactivateOnIdle(); // No producers or consumers left now, so flag ourselves to expedite Deactivation
}
}
public async Task RegisterConsumer(
GuidId subscriptionId,
StreamId streamId,
IStreamConsumerExtension streamConsumer,
IStreamFilterPredicateWrapper filter)
{
PubSubSubscriptionState pubSubState = State.Consumers.FirstOrDefault(s => s.Equals(subscriptionId));
if (pubSubState == null)
{
pubSubState = new PubSubSubscriptionState(subscriptionId, streamId, streamConsumer);
State.Consumers.Add(pubSubState);
}
if (pubSubState.IsFaulted)
throw new FaultedSubscriptionException(subscriptionId, streamId);
if (filter != null)
pubSubState.AddFilter(filter);
counterConsumersAdded.Increment();
counterConsumersTotal.Increment();
LogPubSubCounts("RegisterConsumer {0}", streamConsumer);
await WriteStateAsync();
int numProducers = State.Producers.Count;
if (numProducers <= 0)
return;
if (logger.IsVerbose)
logger.Info("Notifying {0} existing producer(s) about new consumer {1}. Producers={2}",
numProducers, streamConsumer, Utils.EnumerableToString(State.Producers));
// Notify producers about a new streamConsumer.
var tasks = new List<Task>();
var producers = State.Producers.ToList();
int initialProducerCount = producers.Count;
foreach (var producerState in producers)
{
PubSubPublisherState producer = producerState; // Capture loop variable
if (!IsActiveProducer(producer.Producer))
{
// Producer is not active (could be stopping / shutting down) so skip
if (logger.IsVerbose) logger.Verbose("Producer {0} on stream {1} is not active - skipping.", producer, streamId);
continue;
}
tasks.Add(NotifyProducer(producer, subscriptionId, streamId, streamConsumer, filter));
}
Exception exception = null;
try
{
await Task.WhenAll(tasks);
}
catch (Exception exc)
{
exception = exc;
}
// if the number of producers has been changed, resave state.
if (State.Producers.Count != initialProducerCount)
await WriteStateAsync();
if (exception != null)
throw exception;
}
private async Task NotifyProducer(PubSubPublisherState producer, GuidId subscriptionId, StreamId streamId,
IStreamConsumerExtension streamConsumer, IStreamFilterPredicateWrapper filter)
{
try
{
await producer.Producer.AddSubscriber(subscriptionId, streamId, streamConsumer, filter);
}
catch (GrainExtensionNotInstalledException)
{
RemoveProducer(producer);
}
catch (ClientNotAvailableException)
{
RemoveProducer(producer);
}
}
private void RemoveProducer(PubSubPublisherState producer)
{
logger.Warn((int)ErrorCode.Stream_ProducerIsDead,
"Producer {0} on stream {1} is no longer active - permanently removing producer.",
producer, producer.Stream);
if (!State.Producers.Remove(producer)) return;
counterProducersRemoved.Increment();
counterProducersTotal.DecrementBy(1);
}
public async Task UnregisterConsumer(GuidId subscriptionId, StreamId streamId)
{
if(State.Consumers.Any(c => c.IsFaulted && c.Equals(subscriptionId)))
throw new FaultedSubscriptionException(subscriptionId, streamId);
int numRemoved = State.Consumers.RemoveWhere(c => c.Equals(subscriptionId));
counterConsumersRemoved.Increment();
counterConsumersTotal.DecrementBy(numRemoved);
LogPubSubCounts("UnregisterSubscription {0} NumRemoved={1}", subscriptionId, numRemoved);
await WriteStateAsync();
await NotifyProducersOfRemovedSubscription(subscriptionId, streamId);
await ClearStateWhenEmpty();
}
public Task<int> ProducerCount(StreamId streamId)
{
return Task.FromResult(State.Producers.Count);
}
public Task<int> ConsumerCount(StreamId streamId)
{
return Task.FromResult(GetConsumersForStream(streamId).Length);
}
public Task<PubSubSubscriptionState[]> DiagGetConsumers(StreamId streamId)
{
return Task.FromResult(GetConsumersForStream(streamId));
}
private PubSubSubscriptionState[] GetConsumersForStream(StreamId streamId)
{
return State.Consumers.Where(c => !c.IsFaulted && c.Stream.Equals(streamId)).ToArray();
}
private void LogPubSubCounts(string fmt, params object[] args)
{
if (logger.IsVerbose || DEBUG_PUB_SUB)
{
int numProducers = 0;
int numConsumers = 0;
if (State != null && State.Producers != null)
numProducers = State.Producers.Count;
if (State != null && State.Consumers != null)
numConsumers = State.Consumers.Count;
string when = args != null && args.Length != 0 ? String.Format(fmt, args) : fmt;
logger.Info("{0}. Now have total of {1} producers and {2} consumers. All Consumers = {3}, All Producers = {4}",
when, numProducers, numConsumers, Utils.EnumerableToString(State.Consumers), Utils.EnumerableToString(State.Producers));
}
}
// Check that what we have cached locally matches what is in the persistent table.
public async Task Validate()
{
var captureProducers = State.Producers;
var captureConsumers = State.Consumers;
await ReadStateAsync();
if (captureProducers.Count != State.Producers.Count)
{
throw new Exception(String.Format("State mismatch between PubSubRendezvousGrain and its persistent state. captureProducers.Count={0}, State.Producers.Count={1}",
captureProducers.Count, State.Producers.Count));
}
foreach (var producer in captureProducers)
if (!State.Producers.Contains(producer))
throw new Exception(String.Format("State mismatch between PubSubRendezvousGrain and its persistent state. captureProducers={0}, State.Producers={1}",
Utils.EnumerableToString(captureProducers), Utils.EnumerableToString(State.Producers)));
if (captureConsumers.Count != State.Consumers.Count)
{
LogPubSubCounts("Validate: Consumer count mismatch");
throw new Exception(String.Format("State mismatch between PubSubRendezvousGrain and its persistent state. captureConsumers.Count={0}, State.Consumers.Count={1}",
captureConsumers.Count, State.Consumers.Count));
}
foreach (PubSubSubscriptionState consumer in captureConsumers)
if (!State.Consumers.Contains(consumer))
throw new Exception(String.Format("State mismatch between PubSubRendezvousGrain and its persistent state. captureConsumers={0}, State.Consumers={1}",
Utils.EnumerableToString(captureConsumers), Utils.EnumerableToString(State.Consumers)));
}
public Task<List<GuidId>> GetAllSubscriptions(StreamId streamId, IStreamConsumerExtension streamConsumer)
{
List<GuidId> subscriptionIds = State.Consumers.Where(c => !c.IsFaulted && c.Consumer.Equals(streamConsumer))
.Select(c => c.SubscriptionId)
.ToList();
return Task.FromResult(subscriptionIds);
}
public async Task FaultSubscription(GuidId subscriptionId)
{
PubSubSubscriptionState pubSubState = State.Consumers.FirstOrDefault(s => s.Equals(subscriptionId));
if (pubSubState == null)
{
return;
}
pubSubState.Fault();
if (logger.IsVerbose) logger.Verbose("Setting subscription {0} to a faulted state.", subscriptionId.Guid);
await WriteStateAsync();
await NotifyProducersOfRemovedSubscription(pubSubState.SubscriptionId, pubSubState.Stream);
await ClearStateWhenEmpty();
}
private async Task NotifyProducersOfRemovedSubscription(GuidId subscriptionId, StreamId streamId)
{
int numProducers = State.Producers.Count;
if (numProducers > 0)
{
if (logger.IsVerbose) logger.Verbose("Notifying {0} existing producers about unregistered consumer.", numProducers);
// Notify producers about unregistered consumer.
var tasks = new List<Task>();
foreach (var producerState in State.Producers.Where(producerState => IsActiveProducer(producerState.Producer)))
tasks.Add(producerState.Producer.RemoveSubscriber(subscriptionId, streamId));
await Task.WhenAll(tasks);
}
}
private async Task ClearStateWhenEmpty()
{
if (State.Producers.Count == 0 && State.Consumers.Count == 0) // + we already know that numProducers == 0 from previous if-clause
{
await ClearStateAsync(); //State contains no producers or consumers, remove it from storage
// No producers or consumers left now, so flag ourselves to expedite Deactivation
DeactivateOnIdle();
}
}
}
}
| mit |
voxeolabs/prism-samples | samples/registrar/registrar/WEB-INF/classes/com/voxeo/sipmethod/sample/registrar/AddressManagerService.java | 2192 |
package com.voxeo.sipmethod.sample.registrar;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceFeature;
/**
* This class was generated by the JAX-WS RI.
* JAX-WS RI 2.1.1-b03-
* Generated source version: 2.1
*
*/
@WebServiceClient(name = "AddressManagerService", targetNamespace = "http://registrar.sample.sipmethod.voxeo.com/", wsdlLocation = "http://localhost:8080/registrar/services/manager?wsdl")
public class AddressManagerService
extends Service
{
private final static URL ADDRESSMANAGERSERVICE_WSDL_LOCATION;
static {
URL url = null;
try {
url = new URL("http://localhost:8080/registrar/services/manager?wsdl");
} catch (MalformedURLException e) {
e.printStackTrace();
}
ADDRESSMANAGERSERVICE_WSDL_LOCATION = url;
}
public AddressManagerService(URL wsdlLocation, QName serviceName) {
super(wsdlLocation, serviceName);
}
public AddressManagerService() {
super(ADDRESSMANAGERSERVICE_WSDL_LOCATION, new QName("http://registrar.sample.sipmethod.voxeo.com/", "AddressManagerService"));
}
/**
*
* @return
* returns AddressManager
*/
@WebEndpoint(name = "AddressManagerPort")
public AddressManager getAddressManagerPort() {
return (AddressManager)super.getPort(new QName("http://registrar.sample.sipmethod.voxeo.com/", "AddressManagerPort"), AddressManager.class);
}
/**
*
* @param features
* A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* @return
* returns AddressManager
*/
@WebEndpoint(name = "AddressManagerPort")
public AddressManager getAddressManagerPort(WebServiceFeature... features) {
return (AddressManager)super.getPort(new QName("http://registrar.sample.sipmethod.voxeo.com/", "AddressManagerPort"), AddressManager.class, features);
}
}
| mit |
codingbat/android-sitar-music-player | app/src/main/java/com/nazmulalam/sitarplayer/SitarPlayerApplication.java | 454 | package com.nazmulalam.sitarplayer;
import android.app.Application;
import com.crashlytics.android.Crashlytics;
import com.crashlytics.android.answers.Answers;
import io.fabric.sdk.android.Fabric;
public class SitarPlayerApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
if (BuildConfig.USE_CRASHLYTICS) {
Fabric.with(this, new Crashlytics());
Fabric.with(this, new Answers());
}
}
}
| mit |
saas-plat/cqrs-fx | src/snapshot/mysql_snapshot_storage.js | 3270 | import config from '../config';
import {expr} from '../utils';
import mysql from 'mysql';
import SnapshotStorage from './snapshot_storage';
import assert from 'assert';
export default class MySqlSnapshotStorage extends SnapshotStorage {
constructor() {
super();
this._tableName = config.get('snapshot').table;
this.db = mysql.createPool({
...config.get('mysql'),
...config.get('event').mysql
});
}
count(spec) {
return new Promise(function(resolve, reject) {
this.db.query('select count(*) from ?? where ??', [
this._tableName, expr(spec)
], function(err, result) {
if (err)
reject(err);
resolve(result[0][0]);
});
});
}
first(spec) {
return new Promise(function(resolve, reject) {
this.db.query('select id,aggregate_root_type,aggregate_root_id,data,version,branch,timestamp from ?? where ?? order by version asc ', [
this._tableName, expr(spec)
], function(err, ...result) {
if (err)
reject(err);
resolve(result);
});
});
}
commit() {
let list = this._actionList.slice(0);
let count = list.length;
let checkCommit = (connection, resolve, reject) => {
if (err) {
return connection.rollback(function() {
connection.release();
reject(err);
});
}
count--;
if (count === 0) {
connection.commit(function(err) {
connection.release();
if (err)
reject(err);
log('保存快照完成');
let s = 0;
for (let i = 0, l = this._actionList.length; i < l; i++) {
if (this._actionList[i] == list[0]) {
s = i;
break;
}
}
this._actionList.splice(i, list.length);
resolve();
});
}
};
return new Promise(function(resolve, reject) {
if (count <= 0) {
resolve();
return;
}
this.db.getConnection(function(err, connection) {
connection.beginTransaction(function(err) {
if (err)
reject(err);
list.forEach(function(item) {
if (item.action == 1) {
connection.query('update ?? data,version,branch,timestamp values (?,?,?,?) where ??', [
this._tableName,
spec.data,
spec.version,
spec.branch,
spec.timestamp,
expr(item.spec)
], function(err) {
checkCommit(connection, resolve, reject);
});
}
if (item.action === 0) {
connection.query('inert into ?? (id,aggregate_root_type,aggregate_root_id,data,version,branch,timestamp) values (?,?,?,?,?,?,?)', [
this._tableName,
spec.id,
spec.aggregateRootType,
spec.aggregateRootID,
spec.data,
spec.version,
spec.branch,
spec.timestamp
], function(err) {
checkCommit(connection, resolve, reject);
});
}
});
});
});
});
}
async drop() {
// todo
}
}
| mit |
miamiruby/consul | spec/shared/app_root/app/models/deal.rb | 15 | class Deal
end | mit |
P0ke55/specbot | src/main/java/com/github/steveice10/mc/auth/exception/request/UserMigratedException.java | 599 | package com.github.steveice10.mc.auth.exception.request;
/**
* Thrown when using the username of an account that has been migrated to an email address.
*/
public class UserMigratedException extends InvalidCredentialsException {
private static final long serialVersionUID = 1L;
public UserMigratedException() {
}
public UserMigratedException(String message) {
super(message);
}
public UserMigratedException(String message, Throwable cause) {
super(message, cause);
}
public UserMigratedException(Throwable cause) {
super(cause);
}
}
| mit |
hcrlab/access_teleop | rosbridge_suite/rosbridge_library/test/capabilities/test_call_service.py | 3268 | #!/usr/bin/env python
import sys
import rospy
import rostest
import unittest
import time
from roscpp.srv import GetLoggers
from json import loads, dumps
from std_msgs.msg import String
from std_srvs.srv import SetBool
from rosbridge_library.capabilities.call_service import CallService
from rosbridge_library.protocol import Protocol
from rosbridge_library.protocol import InvalidArgumentException, MissingArgumentException
class TestCallService(unittest.TestCase):
def setUp(self):
rospy.init_node("test_call_service")
def test_missing_arguments(self):
proto = Protocol("test_missing_arguments")
s = CallService(proto)
msg = loads(dumps({"op": "call_service"}))
self.assertRaises(MissingArgumentException, s.call_service, msg)
def test_invalid_arguments(self):
proto = Protocol("test_invalid_arguments")
s = CallService(proto)
msg = loads(dumps({"op": "call_service", "service": 3}))
self.assertRaises(InvalidArgumentException, s.call_service, msg)
def test_call_service_works(self):
# Prepare to call the service the 'proper' way
p = rospy.ServiceProxy(rospy.get_name() + "/get_loggers", GetLoggers)
p.wait_for_service()
time.sleep(1.0)
proto = Protocol("test_call_service_works")
s = CallService(proto)
msg = loads(dumps({"op": "call_service", "service": rospy.get_name() + "/get_loggers"}))
received = {"msg": None, "arrived": False}
def cb(msg, cid=None):
received["msg"] = msg
received["arrived"] = True
proto.send = cb
s.call_service(msg)
timeout = 5.0
start = rospy.Time.now()
while rospy.Time.now() - start < rospy.Duration(timeout):
if received["arrived"]:
break
time.sleep(0.1)
# The rosbridge service call actually causes another logger to appear,
# so do the "regular" service call after that.
ret = p()
self.assertTrue(received["msg"]["result"])
for x, y in zip(ret.loggers, received["msg"]["values"]["loggers"]):
self.assertEqual(x.name, y["name"])
self.assertEqual(x.level, y["level"])
def test_call_service_fail(self):
# Dummy service that instantly fails
service_server = rospy.Service("set_bool_fail", SetBool,
lambda req: None)
proto = Protocol("test_call_service_fail")
s = CallService(proto)
send_msg = loads(dumps({"op": "call_service", "service": rospy.get_name() + "/set_bool_fail", "args": '[ true ]'}))
received = {"msg": None, "arrived": False}
def cb(msg, cid=None):
received["msg"] = msg
received["arrived"] = True
proto.send = cb
s.call_service(send_msg)
timeout = 5.0
start = rospy.Time.now()
while rospy.Time.now() - start < rospy.Duration(timeout):
if received["arrived"]:
break
time.sleep(0.1)
self.assertFalse(received["msg"]["result"])
PKG = 'rosbridge_library'
NAME = 'test_call_service'
if __name__ == '__main__':
rostest.unitrun(PKG, NAME, TestCallService)
| mit |
lionfire/Core | src/LionFire.ObjectBus/Referencing/Resolution/ReferenceResolutionService.cs | 994 | using LionFire.Referencing;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace LionFire.Persistence.Resolution
{
public class ReferenceResolutionService : IReferenceResolutionService
{
public IEnumerable<IReferenceResolutionStrategy> Strategies { get; }
//PreferredStrategies
//AllowedStrategies
//AutomigrateStrategies
//MigrateStrategies
//NotFoundStrategies
public ReferenceResolutionService(IEnumerable<IReferenceResolutionStrategy> strategies)
{
this.Strategies = strategies;
}
public Task<IEnumerable<ReadResolutionResult<T>>> ResolveAll<T>(IReference reference, ResolveOptions options = null) => throw new NotImplementedException();
public Task<IEnumerable<WriteResolutionResult<T>>> ResolveAllForWrite<T>(IReference reference, ResolveOptions options = null) => throw new NotImplementedException();
}
}
| mit |
TheFehr/Orsum-consilii-scholai | platforms/windows/www/plugins/cordova-plugin-camera/src/windows/CameraProxy.js | 37460 | cordova.define("cordova-plugin-camera.CameraProxy", function(require, exports, module) {
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
/*jshint unused:true, undef:true, browser:true */
/*global Windows:true, URL:true, module:true, require:true, WinJS:true */
var Camera = require('./Camera');
var getAppData = function () {
return Windows.Storage.ApplicationData.current;
};
var encodeToBase64String = function (buffer) {
return Windows.Security.Cryptography.CryptographicBuffer.encodeToBase64String(buffer);
};
var OptUnique = Windows.Storage.CreationCollisionOption.generateUniqueName;
var CapMSType = Windows.Media.Capture.MediaStreamType;
var webUIApp = Windows.UI.WebUI.WebUIApplication;
var fileIO = Windows.Storage.FileIO;
var pickerLocId = Windows.Storage.Pickers.PickerLocationId;
module.exports = {
// args will contain :
// ... it is an array, so be careful
// 0 quality:50,
// 1 destinationType:Camera.DestinationType.FILE_URI,
// 2 sourceType:Camera.PictureSourceType.CAMERA,
// 3 targetWidth:-1,
// 4 targetHeight:-1,
// 5 encodingType:Camera.EncodingType.JPEG,
// 6 mediaType:Camera.MediaType.PICTURE,
// 7 allowEdit:false,
// 8 correctOrientation:false,
// 9 saveToPhotoAlbum:false,
// 10 popoverOptions:null
// 11 cameraDirection:0
takePicture: function (successCallback, errorCallback, args) {
var sourceType = args[2];
if (sourceType != Camera.PictureSourceType.CAMERA) {
takePictureFromFile(successCallback, errorCallback, args);
} else {
takePictureFromCamera(successCallback, errorCallback, args);
}
}
};
// https://msdn.microsoft.com/en-us/library/windows/apps/ff462087(v=vs.105).aspx
var windowsVideoContainers = [".avi", ".flv", ".asx", ".asf", ".mov", ".mp4", ".mpg", ".rm", ".srt", ".swf", ".wmv", ".vob"];
var windowsPhoneVideoContainers = [".avi", ".3gp", ".3g2", ".wmv", ".3gp", ".3g2", ".mp4", ".m4v"];
// Default aspect ratio 1.78 (16:9 hd video standard)
var DEFAULT_ASPECT_RATIO = '1.8';
// Highest possible z-index supported across browsers. Anything used above is converted to this value.
var HIGHEST_POSSIBLE_Z_INDEX = 2147483647;
// Resize method
function resizeImage(successCallback, errorCallback, file, targetWidth, targetHeight, encodingType) {
var tempPhotoFileName = "";
if (encodingType == Camera.EncodingType.PNG) {
tempPhotoFileName = "camera_cordova_temp_return.png";
} else {
tempPhotoFileName = "camera_cordova_temp_return.jpg";
}
var storageFolder = getAppData().localFolder;
file.copyAsync(storageFolder, file.name, Windows.Storage.NameCollisionOption.replaceExisting)
.then(function (storageFile) {
return fileIO.readBufferAsync(storageFile);
})
.then(function(buffer) {
var strBase64 = encodeToBase64String(buffer);
var imageData = "data:" + file.contentType + ";base64," + strBase64;
var image = new Image();
image.src = imageData;
image.onload = function() {
var ratio = Math.min(targetWidth / this.width, targetHeight / this.height);
var imageWidth = ratio * this.width;
var imageHeight = ratio * this.height;
var canvas = document.createElement('canvas');
var storageFileName;
canvas.width = imageWidth;
canvas.height = imageHeight;
canvas.getContext("2d").drawImage(this, 0, 0, imageWidth, imageHeight);
var fileContent = canvas.toDataURL(file.contentType).split(',')[1];
var storageFolder = getAppData().localFolder;
storageFolder.createFileAsync(tempPhotoFileName, OptUnique)
.then(function (storagefile) {
var content = Windows.Security.Cryptography.CryptographicBuffer.decodeFromBase64String(fileContent);
storageFileName = storagefile.name;
return fileIO.writeBufferAsync(storagefile, content);
})
.done(function () {
successCallback("ms-appdata:///local/" + storageFileName);
}, errorCallback);
};
})
.done(null, function(err) {
errorCallback(err);
}
);
}
// Because of asynchronous method, so let the successCallback be called in it.
function resizeImageBase64(successCallback, errorCallback, file, targetWidth, targetHeight) {
fileIO.readBufferAsync(file).done( function(buffer) {
var strBase64 = encodeToBase64String(buffer);
var imageData = "data:" + file.contentType + ";base64," + strBase64;
var image = new Image();
image.src = imageData;
image.onload = function() {
var ratio = Math.min(targetWidth / this.width, targetHeight / this.height);
var imageWidth = ratio * this.width;
var imageHeight = ratio * this.height;
var canvas = document.createElement('canvas');
canvas.width = imageWidth;
canvas.height = imageHeight;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0, imageWidth, imageHeight);
// The resized file ready for upload
var finalFile = canvas.toDataURL(file.contentType);
// Remove the prefix such as "data:" + contentType + ";base64," , in order to meet the Cordova API.
var arr = finalFile.split(",");
var newStr = finalFile.substr(arr[0].length + 1);
successCallback(newStr);
};
}, function(err) { errorCallback(err); });
}
function takePictureFromFile(successCallback, errorCallback, args) {
// Detect Windows Phone
if (navigator.appVersion.indexOf('Windows Phone 8.1') >= 0) {
takePictureFromFileWP(successCallback, errorCallback, args);
} else {
takePictureFromFileWindows(successCallback, errorCallback, args);
}
}
function takePictureFromFileWP(successCallback, errorCallback, args) {
var mediaType = args[6],
destinationType = args[1],
targetWidth = args[3],
targetHeight = args[4],
encodingType = args[5];
/*
Need to add and remove an event listener to catch activation state
Using FileOpenPicker will suspend the app and it's required to catch the PickSingleFileAndContinue
https://msdn.microsoft.com/en-us/library/windows/apps/xaml/dn631755.aspx
*/
var filePickerActivationHandler = function(eventArgs) {
if (eventArgs.kind === Windows.ApplicationModel.Activation.ActivationKind.pickFileContinuation) {
var file = eventArgs.files[0];
if (!file) {
errorCallback("User didn't choose a file.");
webUIApp.removeEventListener("activated", filePickerActivationHandler);
return;
}
if (destinationType == Camera.DestinationType.FILE_URI || destinationType == Camera.DestinationType.NATIVE_URI) {
if (targetHeight > 0 && targetWidth > 0) {
resizeImage(successCallback, errorCallback, file, targetWidth, targetHeight, encodingType);
}
else {
var storageFolder = getAppData().localFolder;
file.copyAsync(storageFolder, file.name, Windows.Storage.NameCollisionOption.replaceExisting).done(function (storageFile) {
if(destinationType == Camera.DestinationType.NATIVE_URI) {
successCallback("ms-appdata:///local/" + storageFile.name);
}
else {
successCallback(URL.createObjectURL(storageFile));
}
}, function () {
errorCallback("Can't access localStorage folder.");
});
}
}
else {
if (targetHeight > 0 && targetWidth > 0) {
resizeImageBase64(successCallback, errorCallback, file, targetWidth, targetHeight);
} else {
fileIO.readBufferAsync(file).done(function (buffer) {
var strBase64 =encodeToBase64String(buffer);
successCallback(strBase64);
}, errorCallback);
}
}
webUIApp.removeEventListener("activated", filePickerActivationHandler);
}
};
var fileOpenPicker = new Windows.Storage.Pickers.FileOpenPicker();
if (mediaType == Camera.MediaType.PICTURE) {
fileOpenPicker.fileTypeFilter.replaceAll([".png", ".jpg", ".jpeg"]);
fileOpenPicker.suggestedStartLocation = pickerLocId.picturesLibrary;
}
else if (mediaType == Camera.MediaType.VIDEO) {
fileOpenPicker.fileTypeFilter.replaceAll(windowsPhoneVideoContainers);
fileOpenPicker.suggestedStartLocation = pickerLocId.videosLibrary;
}
else {
fileOpenPicker.fileTypeFilter.replaceAll(["*"]);
fileOpenPicker.suggestedStartLocation = pickerLocId.documentsLibrary;
}
webUIApp.addEventListener("activated", filePickerActivationHandler);
fileOpenPicker.pickSingleFileAndContinue();
}
function takePictureFromFileWindows(successCallback, errorCallback, args) {
var mediaType = args[6],
destinationType = args[1],
targetWidth = args[3],
targetHeight = args[4],
encodingType = args[5];
var fileOpenPicker = new Windows.Storage.Pickers.FileOpenPicker();
if (mediaType == Camera.MediaType.PICTURE) {
fileOpenPicker.fileTypeFilter.replaceAll([".png", ".jpg", ".jpeg"]);
fileOpenPicker.suggestedStartLocation = pickerLocId.picturesLibrary;
}
else if (mediaType == Camera.MediaType.VIDEO) {
fileOpenPicker.fileTypeFilter.replaceAll(windowsVideoContainers);
fileOpenPicker.suggestedStartLocation = pickerLocId.videosLibrary;
}
else {
fileOpenPicker.fileTypeFilter.replaceAll(["*"]);
fileOpenPicker.suggestedStartLocation = pickerLocId.documentsLibrary;
}
fileOpenPicker.pickSingleFileAsync().done(function (file) {
if (!file) {
errorCallback("User didn't choose a file.");
return;
}
if (destinationType == Camera.DestinationType.FILE_URI || destinationType == Camera.DestinationType.NATIVE_URI) {
if (targetHeight > 0 && targetWidth > 0) {
resizeImage(successCallback, errorCallback, file, targetWidth, targetHeight, encodingType);
}
else {
var storageFolder = getAppData().localFolder;
file.copyAsync(storageFolder, file.name, Windows.Storage.NameCollisionOption.replaceExisting).done(function (storageFile) {
if(destinationType == Camera.DestinationType.NATIVE_URI) {
successCallback("ms-appdata:///local/" + storageFile.name);
}
else {
successCallback(URL.createObjectURL(storageFile));
}
}, function () {
errorCallback("Can't access localStorage folder.");
});
}
}
else {
if (targetHeight > 0 && targetWidth > 0) {
resizeImageBase64(successCallback, errorCallback, file, targetWidth, targetHeight);
} else {
fileIO.readBufferAsync(file).done(function (buffer) {
var strBase64 =encodeToBase64String(buffer);
successCallback(strBase64);
}, errorCallback);
}
}
}, function () {
errorCallback("User didn't choose a file.");
});
}
function takePictureFromCamera(successCallback, errorCallback, args) {
// Check if necessary API available
if (!Windows.Media.Capture.CameraCaptureUI) {
takePictureFromCameraWP(successCallback, errorCallback, args);
} else {
takePictureFromCameraWindows(successCallback, errorCallback, args);
}
}
function takePictureFromCameraWP(successCallback, errorCallback, args) {
// We are running on WP8.1 which lacks CameraCaptureUI class
// so we need to use MediaCapture class instead and implement custom UI for camera
var destinationType = args[1],
targetWidth = args[3],
targetHeight = args[4],
encodingType = args[5],
saveToPhotoAlbum = args[9],
cameraDirection = args[11],
capturePreview = null,
cameraCaptureButton = null,
cameraCancelButton = null,
capture = null,
captureSettings = null,
CaptureNS = Windows.Media.Capture,
sensor = null;
function createCameraUI() {
// create style for take and cancel buttons
var buttonStyle = "width:45%;padding: 10px 16px;font-size: 18px;line-height: 1.3333333;color: #333;background-color: #fff;border-color: #ccc; border: 1px solid transparent;border-radius: 6px; display: block; margin: 20px; z-index: 1000;border-color: #adadad;";
// Create fullscreen preview
// z-order style element for capturePreview and cameraCancelButton elts
// is necessary to avoid overriding by another page elements, -1 sometimes is not enough
capturePreview = document.createElement("video");
capturePreview.style.cssText = "position: fixed; left: 0; top: 0; width: 100%; height: 100%; z-index: " + (HIGHEST_POSSIBLE_Z_INDEX - 1) + ";";
// Create capture button
cameraCaptureButton = document.createElement("button");
cameraCaptureButton.innerText = "Take";
cameraCaptureButton.style.cssText = buttonStyle + "position: fixed; left: 0; bottom: 0; margin: 20px; z-index: " + HIGHEST_POSSIBLE_Z_INDEX + ";";
// Create cancel button
cameraCancelButton = document.createElement("button");
cameraCancelButton.innerText = "Cancel";
cameraCancelButton.style.cssText = buttonStyle + "position: fixed; right: 0; bottom: 0; margin: 20px; z-index: " + HIGHEST_POSSIBLE_Z_INDEX + ";";
capture = new CaptureNS.MediaCapture();
captureSettings = new CaptureNS.MediaCaptureInitializationSettings();
captureSettings.streamingCaptureMode = CaptureNS.StreamingCaptureMode.video;
}
function continueVideoOnFocus() {
// if preview is defined it would be stuck, play it
if (capturePreview) {
capturePreview.play();
}
}
function startCameraPreview() {
// Search for available camera devices
// This is necessary to detect which camera (front or back) we should use
var DeviceEnum = Windows.Devices.Enumeration;
var expectedPanel = cameraDirection === 1 ? DeviceEnum.Panel.front : DeviceEnum.Panel.back;
// Add focus event handler to capture the event when user suspends the app and comes back while the preview is on
window.addEventListener("focus", continueVideoOnFocus);
DeviceEnum.DeviceInformation.findAllAsync(DeviceEnum.DeviceClass.videoCapture).then(function (devices) {
if (devices.length <= 0) {
destroyCameraPreview();
errorCallback('Camera not found');
return;
}
devices.forEach(function(currDev) {
if (currDev.enclosureLocation.panel && currDev.enclosureLocation.panel == expectedPanel) {
captureSettings.videoDeviceId = currDev.id;
}
});
captureSettings.photoCaptureSource = Windows.Media.Capture.PhotoCaptureSource.photo;
return capture.initializeAsync(captureSettings);
}).then(function () {
// create focus control if available
var VideoDeviceController = capture.videoDeviceController;
var FocusControl = VideoDeviceController.focusControl;
if (FocusControl.supported === true) {
capturePreview.addEventListener('click', function () {
// Make sure function isn't called again before previous focus is completed
if (this.getAttribute('clicked') === '1') {
return false;
} else {
this.setAttribute('clicked', '1');
}
var preset = Windows.Media.Devices.FocusPreset.autoNormal;
var parent = this;
FocusControl.setPresetAsync(preset).done(function () {
// set the clicked attribute back to '0' to allow focus again
parent.setAttribute('clicked', '0');
});
});
}
// msdn.microsoft.com/en-us/library/windows/apps/hh452807.aspx
capturePreview.msZoom = true;
capturePreview.src = URL.createObjectURL(capture);
capturePreview.play();
// Bind events to controls
sensor = Windows.Devices.Sensors.SimpleOrientationSensor.getDefault();
if (sensor !== null) {
sensor.addEventListener("orientationchanged", onOrientationChange);
}
// add click events to capture and cancel buttons
cameraCaptureButton.addEventListener('click', onCameraCaptureButtonClick);
cameraCancelButton.addEventListener('click', onCameraCancelButtonClick);
// Change default orientation
if (sensor) {
setPreviewRotation(sensor.getCurrentOrientation());
} else {
setPreviewRotation(Windows.Graphics.Display.DisplayInformation.getForCurrentView().currentOrientation);
}
// Get available aspect ratios
var aspectRatios = getAspectRatios(capture);
// Couldn't find a good ratio
if (aspectRatios.length === 0) {
destroyCameraPreview();
errorCallback('There\'s not a good aspect ratio available');
return;
}
// add elements to body
document.body.appendChild(capturePreview);
document.body.appendChild(cameraCaptureButton);
document.body.appendChild(cameraCancelButton);
if (aspectRatios.indexOf(DEFAULT_ASPECT_RATIO) > -1) {
return setAspectRatio(capture, DEFAULT_ASPECT_RATIO);
} else {
// Doesn't support 16:9 - pick next best
return setAspectRatio(capture, aspectRatios[0]);
}
}).done(null, function (err) {
destroyCameraPreview();
errorCallback('Camera intitialization error ' + err);
});
}
function destroyCameraPreview() {
// If sensor is available, remove event listener
if (sensor !== null) {
sensor.removeEventListener('orientationchanged', onOrientationChange);
}
// Pause and dispose preview element
capturePreview.pause();
capturePreview.src = null;
// Remove event listeners from buttons
cameraCaptureButton.removeEventListener('click', onCameraCaptureButtonClick);
cameraCancelButton.removeEventListener('click', onCameraCancelButtonClick);
// Remove the focus event handler
window.removeEventListener("focus", continueVideoOnFocus);
// Remove elements
[capturePreview, cameraCaptureButton, cameraCancelButton].forEach(function (elem) {
if (elem /* && elem in document.body.childNodes */) {
document.body.removeChild(elem);
}
});
// Stop and dispose media capture manager
if (capture) {
capture.stopRecordAsync();
capture = null;
}
}
function captureAction() {
var encodingProperties,
fileName,
tempFolder = getAppData().temporaryFolder;
if (encodingType == Camera.EncodingType.PNG) {
fileName = 'photo.png';
encodingProperties = Windows.Media.MediaProperties.ImageEncodingProperties.createPng();
} else {
fileName = 'photo.jpg';
encodingProperties = Windows.Media.MediaProperties.ImageEncodingProperties.createJpeg();
}
tempFolder.createFileAsync(fileName, OptUnique)
.then(function(tempCapturedFile) {
return new WinJS.Promise(function (complete) {
var photoStream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
var finalStream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
capture.capturePhotoToStreamAsync(encodingProperties, photoStream)
.then(function() {
return Windows.Graphics.Imaging.BitmapDecoder.createAsync(photoStream);
})
.then(function(dec) {
finalStream.size = 0; // BitmapEncoder requires the output stream to be empty
return Windows.Graphics.Imaging.BitmapEncoder.createForTranscodingAsync(finalStream, dec);
})
.then(function(enc) {
// We need to rotate the photo wrt sensor orientation
enc.bitmapTransform.rotation = orientationToRotation(sensor.getCurrentOrientation());
return enc.flushAsync();
})
.then(function() {
return tempCapturedFile.openAsync(Windows.Storage.FileAccessMode.readWrite);
})
.then(function(fileStream) {
return Windows.Storage.Streams.RandomAccessStream.copyAndCloseAsync(finalStream, fileStream);
})
.done(function() {
photoStream.close();
finalStream.close();
complete(tempCapturedFile);
}, function() {
photoStream.close();
finalStream.close();
throw new Error("An error has occured while capturing the photo.");
});
});
})
.done(function(capturedFile) {
destroyCameraPreview();
savePhoto(capturedFile, {
destinationType: destinationType,
targetHeight: targetHeight,
targetWidth: targetWidth,
encodingType: encodingType,
saveToPhotoAlbum: saveToPhotoAlbum
}, successCallback, errorCallback);
}, function(err) {
destroyCameraPreview();
errorCallback(err);
});
}
function getAspectRatios(capture) {
var videoDeviceController = capture.videoDeviceController;
var photoAspectRatios = videoDeviceController.getAvailableMediaStreamProperties(CapMSType.photo).map(function (element) {
return (element.width / element.height).toFixed(1);
}).filter(function (element, index, array) { return (index === array.indexOf(element)); });
var videoAspectRatios = videoDeviceController.getAvailableMediaStreamProperties(CapMSType.videoRecord).map(function (element) {
return (element.width / element.height).toFixed(1);
}).filter(function (element, index, array) { return (index === array.indexOf(element)); });
var videoPreviewAspectRatios = videoDeviceController.getAvailableMediaStreamProperties(CapMSType.videoPreview).map(function (element) {
return (element.width / element.height).toFixed(1);
}).filter(function (element, index, array) { return (index === array.indexOf(element)); });
var allAspectRatios = [].concat(photoAspectRatios, videoAspectRatios, videoPreviewAspectRatios);
var aspectObj = allAspectRatios.reduce(function (map, item) {
if (!map[item]) {
map[item] = 0;
}
map[item]++;
return map;
}, {});
return Object.keys(aspectObj).filter(function (k) {
return aspectObj[k] === 3;
});
}
function setAspectRatio(capture, aspect) {
// Max photo resolution with desired aspect ratio
var videoDeviceController = capture.videoDeviceController;
var photoResolution = videoDeviceController.getAvailableMediaStreamProperties(CapMSType.photo)
.filter(function (elem) {
return ((elem.width / elem.height).toFixed(1) === aspect);
})
.reduce(function (prop1, prop2) {
return (prop1.width * prop1.height) > (prop2.width * prop2.height) ? prop1 : prop2;
});
// Max video resolution with desired aspect ratio
var videoRecordResolution = videoDeviceController.getAvailableMediaStreamProperties(CapMSType.videoRecord)
.filter(function (elem) {
return ((elem.width / elem.height).toFixed(1) === aspect);
})
.reduce(function (prop1, prop2) {
return (prop1.width * prop1.height) > (prop2.width * prop2.height) ? prop1 : prop2;
});
// Max video preview resolution with desired aspect ratio
var videoPreviewResolution = videoDeviceController.getAvailableMediaStreamProperties(CapMSType.videoPreview)
.filter(function (elem) {
return ((elem.width / elem.height).toFixed(1) === aspect);
})
.reduce(function (prop1, prop2) {
return (prop1.width * prop1.height) > (prop2.width * prop2.height) ? prop1 : prop2;
});
return videoDeviceController.setMediaStreamPropertiesAsync(CapMSType.photo, photoResolution)
.then(function () {
return videoDeviceController.setMediaStreamPropertiesAsync(CapMSType.videoPreview, videoPreviewResolution);
})
.then(function () {
return videoDeviceController.setMediaStreamPropertiesAsync(CapMSType.videoRecord, videoRecordResolution);
});
}
/**
* When Capture button is clicked, try to capture a picture and return
*/
function onCameraCaptureButtonClick() {
// Make sure user can't click more than once
if (this.getAttribute('clicked') === '1') {
return false;
} else {
this.setAttribute('clicked', '1');
}
captureAction();
}
/**
* When Cancel button is clicked, destroy camera preview and return with error callback
*/
function onCameraCancelButtonClick() {
// Make sure user can't click more than once
if (this.getAttribute('clicked') === '1') {
return false;
} else {
this.setAttribute('clicked', '1');
}
destroyCameraPreview();
errorCallback('no image selected');
}
/**
* When the phone orientation change, get the event and change camera preview rotation
* @param {Object} e - SimpleOrientationSensorOrientationChangedEventArgs
*/
function onOrientationChange(e) {
setPreviewRotation(e.orientation);
}
/**
* Converts SimpleOrientation to a VideoRotation to remove difference between camera sensor orientation
* and video orientation
* @param {number} orientation - Windows.Devices.Sensors.SimpleOrientation
* @return {number} - Windows.Media.Capture.VideoRotation
*/
function orientationToRotation(orientation) {
// VideoRotation enumerable and BitmapRotation enumerable have the same values
// https://msdn.microsoft.com/en-us/library/windows/apps/windows.media.capture.videorotation.aspx
// https://msdn.microsoft.com/en-us/library/windows/apps/windows.graphics.imaging.bitmaprotation.aspx
switch (orientation) {
// portrait
case Windows.Devices.Sensors.SimpleOrientation.notRotated:
return Windows.Media.Capture.VideoRotation.clockwise90Degrees;
// landscape
case Windows.Devices.Sensors.SimpleOrientation.rotated90DegreesCounterclockwise:
return Windows.Media.Capture.VideoRotation.none;
// portrait-flipped (not supported by WinPhone Apps)
case Windows.Devices.Sensors.SimpleOrientation.rotated180DegreesCounterclockwise:
// Falling back to portrait default
return Windows.Media.Capture.VideoRotation.clockwise90Degrees;
// landscape-flipped
case Windows.Devices.Sensors.SimpleOrientation.rotated270DegreesCounterclockwise:
return Windows.Media.Capture.VideoRotation.clockwise180Degrees;
// faceup & facedown
default:
// Falling back to portrait default
return Windows.Media.Capture.VideoRotation.clockwise90Degrees;
}
}
/**
* Rotates the current MediaCapture's video
* @param {number} orientation - Windows.Devices.Sensors.SimpleOrientation
*/
function setPreviewRotation(orientation) {
capture.setPreviewRotation(orientationToRotation(orientation));
}
try {
createCameraUI();
startCameraPreview();
} catch (ex) {
errorCallback(ex);
}
}
function takePictureFromCameraWindows(successCallback, errorCallback, args) {
var destinationType = args[1],
targetWidth = args[3],
targetHeight = args[4],
encodingType = args[5],
allowCrop = !!args[7],
saveToPhotoAlbum = args[9],
WMCapture = Windows.Media.Capture,
cameraCaptureUI = new WMCapture.CameraCaptureUI();
cameraCaptureUI.photoSettings.allowCropping = allowCrop;
if (encodingType == Camera.EncodingType.PNG) {
cameraCaptureUI.photoSettings.format = WMCapture.CameraCaptureUIPhotoFormat.png;
} else {
cameraCaptureUI.photoSettings.format = WMCapture.CameraCaptureUIPhotoFormat.jpeg;
}
// decide which max pixels should be supported by targetWidth or targetHeight.
var maxRes = null;
var UIMaxRes = WMCapture.CameraCaptureUIMaxPhotoResolution;
var totalPixels = targetWidth * targetHeight;
if (targetWidth == -1 && targetHeight == -1) {
maxRes = UIMaxRes.highestAvailable;
}
// Temp fix for CB-10539
/*else if (totalPixels <= 320 * 240) {
maxRes = UIMaxRes.verySmallQvga;
}*/
else if (totalPixels <= 640 * 480) {
maxRes = UIMaxRes.smallVga;
} else if (totalPixels <= 1024 * 768) {
maxRes = UIMaxRes.mediumXga;
} else if (totalPixels <= 3 * 1000 * 1000) {
maxRes = UIMaxRes.large3M;
} else if (totalPixels <= 5 * 1000 * 1000) {
maxRes = UIMaxRes.veryLarge5M;
} else {
maxRes = UIMaxRes.highestAvailable;
}
cameraCaptureUI.photoSettings.maxResolution = maxRes;
var cameraPicture;
var savePhotoOnFocus = function() {
window.removeEventListener("focus", savePhotoOnFocus);
// call only when the app is in focus again
savePhoto(cameraPicture, {
destinationType: destinationType,
targetHeight: targetHeight,
targetWidth: targetWidth,
encodingType: encodingType,
saveToPhotoAlbum: saveToPhotoAlbum
}, successCallback, errorCallback);
};
// add and delete focus eventHandler to capture the focus back from cameraUI to app
window.addEventListener("focus", savePhotoOnFocus);
cameraCaptureUI.captureFileAsync(WMCapture.CameraCaptureUIMode.photo).done(function(picture) {
if (!picture) {
errorCallback("User didn't capture a photo.");
window.removeEventListener("focus", savePhotoOnFocus);
return;
}
cameraPicture = picture;
}, function() {
errorCallback("Fail to capture a photo.");
window.removeEventListener("focus", savePhotoOnFocus);
});
}
function savePhoto(picture, options, successCallback, errorCallback) {
// success callback for capture operation
var success = function(picture) {
if (options.destinationType == Camera.DestinationType.FILE_URI || options.destinationType == Camera.DestinationType.NATIVE_URI) {
if (options.targetHeight > 0 && options.targetWidth > 0) {
resizeImage(successCallback, errorCallback, picture, options.targetWidth, options.targetHeight, options.encodingType);
} else {
picture.copyAsync(getAppData().localFolder, picture.name, OptUnique).done(function (copiedFile) {
successCallback("ms-appdata:///local/" + copiedFile.name);
},errorCallback);
}
} else {
if (options.targetHeight > 0 && options.targetWidth > 0) {
resizeImageBase64(successCallback, errorCallback, picture, options.targetWidth, options.targetHeight);
} else {
fileIO.readBufferAsync(picture).done(function(buffer) {
var strBase64 = encodeToBase64String(buffer);
picture.deleteAsync().done(function() {
successCallback(strBase64);
}, function(err) {
errorCallback(err);
});
}, errorCallback);
}
}
};
if (!options.saveToPhotoAlbum) {
success(picture);
return;
} else {
var savePicker = new Windows.Storage.Pickers.FileSavePicker();
var saveFile = function(file) {
if (file) {
// Prevent updates to the remote version of the file until we're done
Windows.Storage.CachedFileManager.deferUpdates(file);
picture.moveAndReplaceAsync(file)
.then(function() {
// Let Windows know that we're finished changing the file so
// the other app can update the remote version of the file.
return Windows.Storage.CachedFileManager.completeUpdatesAsync(file);
})
.done(function(updateStatus) {
if (updateStatus === Windows.Storage.Provider.FileUpdateStatus.complete) {
success(picture);
} else {
errorCallback("File update status is not complete.");
}
}, errorCallback);
} else {
errorCallback("Failed to select a file.");
}
};
savePicker.suggestedStartLocation = pickerLocId.picturesLibrary;
if (options.encodingType === Camera.EncodingType.PNG) {
savePicker.fileTypeChoices.insert("PNG", [".png"]);
savePicker.suggestedFileName = "photo.png";
} else {
savePicker.fileTypeChoices.insert("JPEG", [".jpg"]);
savePicker.suggestedFileName = "photo.jpg";
}
// If Windows Phone 8.1 use pickSaveFileAndContinue()
if (navigator.appVersion.indexOf('Windows Phone 8.1') >= 0) {
/*
Need to add and remove an event listener to catch activation state
Using FileSavePicker will suspend the app and it's required to catch the pickSaveFileContinuation
https://msdn.microsoft.com/en-us/library/windows/apps/xaml/dn631755.aspx
*/
var fileSaveHandler = function(eventArgs) {
if (eventArgs.kind === Windows.ApplicationModel.Activation.ActivationKind.pickSaveFileContinuation) {
var file = eventArgs.file;
saveFile(file);
webUIApp.removeEventListener("activated", fileSaveHandler);
}
};
webUIApp.addEventListener("activated", fileSaveHandler);
savePicker.pickSaveFileAndContinue();
} else {
savePicker.pickSaveFileAsync()
.done(saveFile, errorCallback);
}
}
}
require("cordova/exec/proxy").add("Camera",module.exports);
});
| mit |
rodolphopicolo/e-BR | e-BR/src/io/echosystem/ebr/nfe/bind/v4/sv130/TProcEvento.java | 3292 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2017.10.04 at 07:58:11 AM BRT
//
package io.echosystem.ebr.nfe.bind.v4.sv130;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* Tipo procEvento
*
* <p>Java class for TProcEvento complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="TProcEvento">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="evento" type="{http://www.portalfiscal.inf.br/nfe}TEvento"/>
* <element name="retEvento" type="{http://www.portalfiscal.inf.br/nfe}TRetEvento"/>
* </sequence>
* <attribute name="versao" use="required" type="{http://www.portalfiscal.inf.br/nfe}TVerEvento" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "TProcEvento", namespace = "http://www.portalfiscal.inf.br/nfe", propOrder = {
"evento",
"retEvento"
})
public class TProcEvento {
@XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true)
protected TEvento evento;
@XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true)
protected TRetEvento retEvento;
@XmlAttribute(name = "versao", required = true)
protected String versao;
/**
* Gets the value of the evento property.
*
* @return
* possible object is
* {@link TEvento }
*
*/
public TEvento getEvento() {
return evento;
}
/**
* Sets the value of the evento property.
*
* @param value
* allowed object is
* {@link TEvento }
*
*/
public void setEvento(TEvento value) {
this.evento = value;
}
/**
* Gets the value of the retEvento property.
*
* @return
* possible object is
* {@link TRetEvento }
*
*/
public TRetEvento getRetEvento() {
return retEvento;
}
/**
* Sets the value of the retEvento property.
*
* @param value
* allowed object is
* {@link TRetEvento }
*
*/
public void setRetEvento(TRetEvento value) {
this.retEvento = value;
}
/**
* Gets the value of the versao property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getVersao() {
return versao;
}
/**
* Sets the value of the versao property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setVersao(String value) {
this.versao = value;
}
}
| mit |
Microsoft/clrmd | src/Microsoft.Diagnostics.Runtime.Utilities/Debugger/Structs/ExceptionRecord64.cs | 704 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.InteropServices;
namespace Microsoft.Diagnostics.Runtime.Interop
{
[StructLayout(LayoutKind.Sequential)]
public unsafe struct EXCEPTION_RECORD64
{
public uint ExceptionCode;
public uint ExceptionFlags;
public ulong ExceptionRecord;
public ulong ExceptionAddress;
public uint NumberParameters;
public uint __unusedAlignment;
public fixed ulong ExceptionInformation[15]; //EXCEPTION_MAXIMUM_PARAMETERS
}
} | mit |
MTASZTAKI/ApertusVR | plugins/languageAPI/jsAPI/3rdParty/nodejs/10.1.0/source/deps/v8/tools/testrunner/testproc/variant.py | 2352 | # Copyright 2018 the V8 project authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from . import base
from ..local.variants import ALL_VARIANTS, ALL_VARIANT_FLAGS
from .result import GroupedResult
STANDARD_VARIANT = set(["default"])
class VariantProc(base.TestProcProducer):
"""Processor creating variants.
For each test it keeps generator that returns variant, flags and id suffix.
It produces variants one at a time, so it's waiting for the result of one
variant to create another variant of the same test.
It maintains the order of the variants passed to the init.
There are some cases when particular variant of the test is not valid. To
ignore subtests like that, StatusFileFilterProc should be placed somewhere
after the VariantProc.
"""
def __init__(self, variants):
super(VariantProc, self).__init__('VariantProc')
self._next_variant = {}
self._variant_gens = {}
self._variants = variants
def setup(self, requirement=base.DROP_RESULT):
super(VariantProc, self).setup(requirement)
# VariantProc is optimized for dropping the result and it should be placed
# in the chain where it's possible.
assert requirement == base.DROP_RESULT
def _next_test(self, test):
gen = self._variants_gen(test)
self._next_variant[test.procid] = gen
self._try_send_new_subtest(test, gen)
def _result_for(self, test, subtest, result):
gen = self._next_variant[test.procid]
self._try_send_new_subtest(test, gen)
def _try_send_new_subtest(self, test, variants_gen):
for variant, flags, suffix in variants_gen:
subtest = self._create_subtest(test, '%s-%s' % (variant, suffix),
variant=variant, flags=flags)
self._send_test(subtest)
return
del self._next_variant[test.procid]
self._send_result(test, None)
def _variants_gen(self, test):
"""Generator producing (variant, flags, procid suffix) tuples."""
return self._get_variants_gen(test).gen(test)
def _get_variants_gen(self, test):
key = test.suite.name
variants_gen = self._variant_gens.get(key)
if not variants_gen:
variants_gen = test.suite.get_variants_gen(self._variants)
self._variant_gens[key] = variants_gen
return variants_gen
| mit |
Nafta7/gulp-tasks | src/gutaska.js | 744 | const modula = require('modula-loader')
const loadPlugins = require('./load-plugins')
let plugins = loadPlugins()
function taskify(config) {
var opts = config.opts || {}
var args = config.args || {}
opts.exclude = opts.exclude || []
args.plugins = Object.assign(plugins, args.plugins)
var modules = modula('tasks', {
args: args,
opts: {
include: opts.include,
exclude: opts.exclude,
flat: opts.flat
}
})
Object.keys(modules).forEach(key => {
if (modules[key] instanceof Function) {
createTask(args.gulp, modules[key], key)
}
})
return modules
}
function createTask(gulp, func, name) {
gulp.task(name, function(done) {
func()
done()
})
}
module.exports = taskify
| mit |
Ben-Mathews/WpfDockingWindowsApplicationTemplate | wpftoolkit-110921/Main/Source/ExtendedWPFToolkitSolution/Src/Xceed.Wpf.AvalonDock/Win32Helper.cs | 21203 | /*************************************************************************************
Extended WPF Toolkit
Copyright (C) 2007-2013 Xceed Software Inc.
This program is provided to you under the terms of the Microsoft Public
License (Ms-PL) as published at http://wpftoolkit.codeplex.com/license
For more features, controls, and fast professional support,
pick up the Plus Edition at http://xceed.com/wpf_toolkit
Stay informed: follow @datagrid on Twitter or Like http://facebook.com/datagrids
***********************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows;
namespace Xceed.Wpf.AvalonDock
{
internal static class Win32Helper
{
[DllImport("user32.dll", EntryPoint = "CreateWindowEx", CharSet = CharSet.Unicode)]
internal static extern IntPtr CreateWindowEx(int dwExStyle,
string lpszClassName,
string lpszWindowName,
int style,
int x, int y,
int width, int height,
IntPtr hwndParent,
IntPtr hMenu,
IntPtr hInst,
[MarshalAs(UnmanagedType.AsAny)] object pvParam);
internal const int
WS_CHILD = 0x40000000,
WS_VISIBLE = 0x10000000,
WS_VSCROLL = 0x00200000,
WS_BORDER = 0x00800000,
WS_CLIPSIBLINGS = 0x04000000,
WS_CLIPCHILDREN = 0x02000000,
WS_TABSTOP = 0x00010000,
WS_GROUP = 0x00020000;
/// <summary>
/// SetWindowPos Flags
/// </summary>
[Flags()]
internal enum SetWindowPosFlags : uint
{
/// <summary>If the calling thread and the thread that owns the window are attached to different input queues,
/// the system posts the request to the thread that owns the window. This prevents the calling thread from
/// blocking its execution while other threads process the request.</summary>
/// <remarks>SWP_ASYNCWINDOWPOS</remarks>
SynchronousWindowPosition = 0x4000,
/// <summary>Prevents generation of the WM_SYNCPAINT message.</summary>
/// <remarks>SWP_DEFERERASE</remarks>
DeferErase = 0x2000,
/// <summary>Draws a frame (defined in the window's class description) around the window.</summary>
/// <remarks>SWP_DRAWFRAME</remarks>
DrawFrame = 0x0020,
/// <summary>Applies new frame styles set using the SetWindowLong function. Sends a WM_NCCALCSIZE message to
/// the window, even if the window's size is not being changed. If this flag is not specified, WM_NCCALCSIZE
/// is sent only when the window's size is being changed.</summary>
/// <remarks>SWP_FRAMECHANGED</remarks>
FrameChanged = 0x0020,
/// <summary>Hides the window.</summary>
/// <remarks>SWP_HIDEWINDOW</remarks>
HideWindow = 0x0080,
/// <summary>Does not activate the window. If this flag is not set, the window is activated and moved to the
/// top of either the topmost or non-topmost group (depending on the setting of the hWndInsertAfter
/// parameter).</summary>
/// <remarks>SWP_NOACTIVATE</remarks>
DoNotActivate = 0x0010,
/// <summary>Discards the entire contents of the client area. If this flag is not specified, the valid
/// contents of the client area are saved and copied back into the client area after the window is sized or
/// repositioned.</summary>
/// <remarks>SWP_NOCOPYBITS</remarks>
DoNotCopyBits = 0x0100,
/// <summary>Retains the current position (ignores X and Y parameters).</summary>
/// <remarks>SWP_NOMOVE</remarks>
IgnoreMove = 0x0002,
/// <summary>Does not change the owner window's position in the Z order.</summary>
/// <remarks>SWP_NOOWNERZORDER</remarks>
DoNotChangeOwnerZOrder = 0x0200,
/// <summary>Does not redraw changes. If this flag is set, no repainting of any kind occurs. This applies to
/// the client area, the nonclient area (including the title bar and scroll bars), and any part of the parent
/// window uncovered as a result of the window being moved. When this flag is set, the application must
/// explicitly invalidate or redraw any parts of the window and parent window that need redrawing.</summary>
/// <remarks>SWP_NOREDRAW</remarks>
DoNotRedraw = 0x0008,
/// <summary>Same as the SWP_NOOWNERZORDER flag.</summary>
/// <remarks>SWP_NOREPOSITION</remarks>
DoNotReposition = 0x0200,
/// <summary>Prevents the window from receiving the WM_WINDOWPOSCHANGING message.</summary>
/// <remarks>SWP_NOSENDCHANGING</remarks>
DoNotSendChangingEvent = 0x0400,
/// <summary>Retains the current size (ignores the cx and cy parameters).</summary>
/// <remarks>SWP_NOSIZE</remarks>
IgnoreResize = 0x0001,
/// <summary>Retains the current Z order (ignores the hWndInsertAfter parameter).</summary>
/// <remarks>SWP_NOZORDER</remarks>
IgnoreZOrder = 0x0004,
/// <summary>Displays the window.</summary>
/// <remarks>SWP_SHOWWINDOW</remarks>
ShowWindow = 0x0040,
}
/// <summary>
/// Special window handles
/// </summary>
internal static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
internal static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2);
internal static readonly IntPtr HWND_TOP = new IntPtr(0);
internal static readonly IntPtr HWND_BOTTOM = new IntPtr(1);
[StructLayout(LayoutKind.Sequential)]
internal class WINDOWPOS
{
public IntPtr hwnd;
public IntPtr hwndInsertAfter;
public int x;
public int y;
public int cx;
public int cy;
public int flags;
};
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, SetWindowPosFlags uFlags);
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
internal static extern bool IsChild(IntPtr hWndParent, IntPtr hwnd);
[DllImport("user32.dll")]
internal static extern IntPtr SetFocus(IntPtr hWnd);
internal const int WM_WINDOWPOSCHANGED = 0x0047;
internal const int WM_WINDOWPOSCHANGING = 0x0046;
internal const int WM_NCMOUSEMOVE = 0xa0;
internal const int WM_NCLBUTTONDOWN = 0xA1;
internal const int WM_NCLBUTTONUP = 0xA2;
internal const int WM_NCLBUTTONDBLCLK = 0xA3;
internal const int WM_NCRBUTTONDOWN = 0xA4;
internal const int WM_NCRBUTTONUP = 0xA5;
internal const int WM_CAPTURECHANGED = 0x0215;
internal const int WM_EXITSIZEMOVE = 0x0232;
internal const int WM_ENTERSIZEMOVE = 0x0231;
internal const int WM_MOVE = 0x0003;
internal const int WM_MOVING = 0x0216;
internal const int WM_KILLFOCUS = 0x0008;
internal const int WM_SETFOCUS = 0x0007;
internal const int WM_ACTIVATE = 0x0006;
internal const int WM_NCHITTEST = 0x0084;
internal const int WM_INITMENUPOPUP = 0x0117;
internal const int WM_KEYDOWN = 0x0100;
internal const int WM_KEYUP = 0x0101;
internal const int WA_INACTIVE = 0x0000;
internal const int WM_SYSCOMMAND = 0x0112;
// These are the wParam of WM_SYSCOMMAND
internal const int SC_MAXIMIZE = 0xF030;
internal const int SC_RESTORE = 0xF120;
internal const int
WM_CREATE = 0x0001;
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr SetActiveWindow(IntPtr hWnd);
[DllImport("user32.dll", EntryPoint = "DestroyWindow", CharSet = CharSet.Unicode)]
internal static extern bool DestroyWindow(IntPtr hwnd);
internal const int HT_CAPTION = 0x2;
[DllImportAttribute("user32.dll")]
internal static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
[DllImportAttribute("user32.dll")]
internal static extern int PostMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
static extern bool GetClientRect(IntPtr hWnd, out RECT lpRect);
[DllImport("user32.dll")]
internal static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
// Hook Types
public enum HookType : int
{
WH_JOURNALRECORD = 0,
WH_JOURNALPLAYBACK = 1,
WH_KEYBOARD = 2,
WH_GETMESSAGE = 3,
WH_CALLWNDPROC = 4,
WH_CBT = 5,
WH_SYSMSGFILTER = 6,
WH_MOUSE = 7,
WH_HARDWARE = 8,
WH_DEBUG = 9,
WH_SHELL = 10,
WH_FOREGROUNDIDLE = 11,
WH_CALLWNDPROCRET = 12,
WH_KEYBOARD_LL = 13,
WH_MOUSE_LL = 14
}
public const int HCBT_SETFOCUS = 9;
public const int HCBT_ACTIVATE = 5;
[DllImport("kernel32.dll")]
public static extern uint GetCurrentThreadId();
public delegate int HookProc(int code, IntPtr wParam,
IntPtr lParam);
[DllImport("user32.dll")]
public static extern IntPtr SetWindowsHookEx(HookType code,
HookProc func,
IntPtr hInstance,
int threadID);
[DllImport("user32.dll")]
public static extern int UnhookWindowsHookEx(IntPtr hhook);
[DllImport("user32.dll")]
public static extern int CallNextHookEx(IntPtr hhook,
int code, IntPtr wParam, IntPtr lParam);
[Serializable, StructLayout(LayoutKind.Sequential)]
internal struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
public RECT(int left_, int top_, int right_, int bottom_)
{
Left = left_; Top = top_; Right = right_; Bottom = bottom_;
}
public int Height
{
get { return Bottom - Top; }
}
public int Width
{
get { return Right - Left; }
}
public Size Size { get { return new Size(Width, Height); } }
public Point Location { get { return new Point(Left, Top); } }
// Handy method for converting to a System.Drawing.Rectangle
public Rect ToRectangle() { return new Rect(Left, Top, Right, Bottom); }
public static RECT FromRectangle(Rect rectangle)
{ return new Rect(rectangle.Left, rectangle.Top, rectangle.Right, rectangle.Bottom); }
public override int GetHashCode()
{ return Left ^ ((Top << 13) | (Top >> 0x13)) ^ ((Width << 0x1a) | (Width >> 6)) ^ ((Height << 7) | (Height >> 0x19)); }
#region Operator overloads
public static implicit operator Rect(RECT rect) { return rect.ToRectangle(); } public static implicit operator RECT(Rect rect) { return FromRectangle(rect); }
#endregion
}
internal static RECT GetClientRect(IntPtr hWnd)
{
RECT result = new RECT();
GetClientRect(hWnd, out result);
return result;
}
internal static RECT GetWindowRect(IntPtr hWnd)
{
RECT result = new RECT();
GetWindowRect(hWnd, out result);
return result;
}
[DllImport("user32.dll")]
internal static extern IntPtr GetTopWindow(IntPtr hWnd);
internal const uint GW_HWNDNEXT = 2;
internal const uint GW_HWNDPREV = 3;
[DllImport("user32.dll", SetLastError = true)]
internal static extern IntPtr GetWindow(IntPtr hWnd, uint uCmd);
internal enum GetWindow_Cmd : uint
{
GW_HWNDFIRST = 0,
GW_HWNDLAST = 1,
GW_HWNDNEXT = 2,
GW_HWNDPREV = 3,
GW_OWNER = 4,
GW_CHILD = 5,
GW_ENABLEDPOPUP = 6
}
internal static int MakeLParam(int LoWord, int HiWord)
{
return (int) ((HiWord << 16) | (LoWord & 0xffff));
}
internal const int WM_MOUSEMOVE = 0x200;
internal const int WM_LBUTTONDOWN = 0x201;
internal const int WM_LBUTTONUP = 0x202;
internal const int WM_LBUTTONDBLCLK = 0x203;
internal const int WM_RBUTTONDOWN = 0x204;
internal const int WM_RBUTTONUP = 0x205;
internal const int WM_RBUTTONDBLCLK = 0x206;
internal const int WM_MBUTTONDOWN = 0x207;
internal const int WM_MBUTTONUP = 0x208;
internal const int WM_MBUTTONDBLCLK = 0x209;
internal const int WM_MOUSEWHEEL = 0x20A;
internal const int WM_MOUSEHWHEEL = 0x20E;
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetCursorPos(ref Win32Point pt);
[StructLayout(LayoutKind.Sequential)]
internal struct Win32Point
{
public Int32 X;
public Int32 Y;
};
internal static Point GetMousePosition()
{
Win32Point w32Mouse = new Win32Point();
GetCursorPos(ref w32Mouse);
return new Point(w32Mouse.X, w32Mouse.Y);
}
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool IsWindowVisible(IntPtr hWnd);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool IsWindowEnabled(IntPtr hWnd);
[DllImport("user32.dll")]
internal static extern IntPtr GetFocus();
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool BringWindowToTop(IntPtr hWnd);
[DllImport("user32.dll", SetLastError = true)]
internal static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
[DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Auto)]
internal static extern IntPtr GetParent(IntPtr hWnd);
/// <summary>
/// Changes an attribute of the specified window. The function also sets the 32-bit (long) value at the specified offset into the extra window memory.
/// </summary>
/// <param name="hWnd">A handle to the window and, indirectly, the class to which the window belongs..</param>
/// <param name="nIndex">The zero-based offset to the value to be set. Valid values are in the range zero through the number of bytes of extra window memory, minus the size of an integer. To set any other value, specify one of the following values: GWL_EXSTYLE, GWL_HINSTANCE, GWL_ID, GWL_STYLE, GWL_USERDATA, GWL_WNDPROC </param>
/// <param name="dwNewLong">The replacement value.</param>
/// <returns>If the function succeeds, the return value is the previous value of the specified 32-bit integer.
/// If the function fails, the return value is zero. To get extended error information, call GetLastError. </returns>
[DllImport("user32.dll")]
static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
[DllImport("user32.dll", SetLastError = true)]
static extern int GetWindowLong(IntPtr hWnd, int nIndex);
public static void SetOwner(IntPtr childHandle, IntPtr ownerHandle)
{
SetWindowLong(
childHandle,
-8, // GWL_HWNDPARENT
ownerHandle.ToInt32());
}
public static IntPtr GetOwner(IntPtr childHandle)
{
return new IntPtr(GetWindowLong(childHandle, -8));
}
//Monitor Patch #13440
/// <summary>
/// The MonitorFromRect function retrieves a handle to the display monitor that
/// has the largest area of intersection with a specified rectangle.
/// </summary>
/// <param name="lprc">Pointer to a RECT structure that specifies the rectangle of interest in
/// virtual-screen coordinates</param>
/// <param name="dwFlags">Determines the function's return value if the rectangle does not intersect
/// any display monitor</param>
/// <returns>
/// If the rectangle intersects one or more display monitor rectangles, the return value
/// is an HMONITOR handle to the display monitor that has the largest area of intersection with the rectangle.
/// If the rectangle does not intersect a display monitor, the return value depends on the value of dwFlags.
/// </returns>
[DllImport("user32.dll")]
public static extern IntPtr MonitorFromRect([In] ref RECT lprc, uint dwFlags);
/// <summary>
/// The MonitorFromWindow function retrieves a handle to the display monitor that has the largest area of intersection with the bounding rectangle of a specified window.
/// </summary>
/// <param name="hwnd">A handle to the window of interest.</param>
/// <param name="dwFlags">Determines the function's return value if the window does not intersect any display monitor.</param>
/// <returns>If the window intersects one or more display monitor rectangles, the return value is an HMONITOR handle to the display monitor that has the largest area of intersection with the window.
/// If the window does not intersect a display monitor, the return value depends on the value of dwFlags.
/// </returns>
[DllImport("user32.dll")]
public static extern IntPtr MonitorFromWindow(IntPtr hwnd, uint dwFlags);
/// <summary>
/// The MONITORINFO structure contains information about a display monitor.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public class MonitorInfo
{
/// <summary>
/// The size of the structure, in bytes.
/// </summary>
public int Size = Marshal.SizeOf(typeof(MonitorInfo));
/// <summary>
/// A RECT structure that specifies the display monitor rectangle, expressed
/// in virtual-screen coordinates.
/// Note that if the monitor is not the primary display monitor,
/// some of the rectangle's coordinates may be negative values.
/// </summary>
public RECT Monitor;
/// <summary>
/// A RECT structure that specifies the work area rectangle of the display monitor,
/// expressed in virtual-screen coordinates. Note that if the monitor is not the primary
/// display monitor, some of the rectangle's coordinates may be negative values.
/// </summary>
public RECT Work;
/// <summary>
/// A set of flags that represent attributes of the display monitor.
/// </summary>
public uint Flags;
}
/// <summary>
/// The GetMonitorInfo function retrieves information about a display monitor.
/// </summary>
/// <param name="hMonitor">Handle to the display monitor of interest.</param>
/// <param name="lpmi">Pointer to a MONITORINFO or MONITORINFOEX structure that receives
/// information about the specified display monitor</param>
/// <returns>If the function succeeds, the return value is nonzero.
/// If the function fails, the return value is zero.</returns>
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetMonitorInfo(IntPtr hMonitor, [In, Out] MonitorInfo lpmi);
}
}
| mit |
brandonroberts/platform | projects/example-app/src/app/core/effects/router.effects.spec.ts | 1274 | import { Title } from '@angular/platform-browser';
import { TestBed } from '@angular/core/testing';
import { of } from 'rxjs';
import { Actions } from '@ngrx/effects';
import { routerNavigatedAction } from '@ngrx/router-store';
import { provideMockStore } from '@ngrx/store/testing';
import { RouterEffects } from '@example-app/core/effects';
import * as fromRoot from '@example-app/reducers';
describe('RouterEffects', () => {
let effects: RouterEffects;
let titleService: Title;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
RouterEffects,
{
provide: Actions,
useValue: of(routerNavigatedAction),
},
provideMockStore({
selectors: [
{ selector: fromRoot.selectRouteData, value: { title: 'Search' } },
],
}),
{ provide: Title, useValue: { setTitle: jest.fn() } },
],
});
effects = TestBed.inject(RouterEffects);
titleService = TestBed.inject(Title);
});
describe('updateTitle$', () => {
it('should update the title on router navigation', () => {
effects.updateTitle$.subscribe();
expect(titleService.setTitle).toHaveBeenCalledWith(
'Book Collection - Search'
);
});
});
});
| mit |
CLARIAH/qber | src/js/stores/CSVStore.js | 1745 | var QBerDispatcher = require('../dispatcher/QBerDispatcher');
var EventEmitter = require('events').EventEmitter;
var CSVConstants = require('../constants/CSVConstants');
var DatasetStore = require('./DatasetStore');
var assign = require('object-assign');
var CHANGE_EVENT = 'change';
var _files;
var _study;
var _modal_visible = true;
var CSVStore = assign({}, EventEmitter.prototype, {
getModalVisible: function(){
return _modal_visible;
},
setModalVisible: function(visible_or_not){
_modal_visible = visible_or_not;
},
getFiles: function() {
return _files;
},
setFiles: function(files) {
_files = files;
},
getStudy: function() {
return _study;
},
setStudy: function(study) {
_study = study;
},
emitChange: function() {
this.emit(CHANGE_EVENT);
},
/**
* @param {function} callback
*/
addChangeListener: function(callback) {
this.on(CHANGE_EVENT, callback);
},
/**
* @param {function} callback
*/
removeChangeListener: function(callback) {
this.removeListener(CHANGE_EVENT, callback);
}
});
// Register callback to handle all updates
QBerDispatcher.register(function(action) {
switch(action.actionType) {
case CSVConstants.CSV_UPDATE_FILES:
CSVStore.setFiles(action.file_list.files);
CSVStore.setStudy(action.file_list.study);
CSVStore.emitChange();
break;
case CSVConstants.CSV_CLOSE_DROPZONE:
CSVStore.setModalVisible(false);
CSVStore.emitChange();
break;
case CSVConstants.CSV_SHOW_DROPZONE:
console.log('Showing modal for CSV');
CSVStore.setModalVisible(true);
CSVStore.emitChange();
break;
default:
// no op
}
});
module.exports = CSVStore;
| mit |
navalev/azure-sdk-for-java | sdk/storage/azure-storage-file-datalake/src/main/java/com/azure/storage/file/datalake/implementation/models/PathsSetAccessControlResponse.java | 1186 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.storage.file.datalake.implementation.models;
import com.azure.core.http.HttpHeaders;
import com.azure.core.http.HttpRequest;
import com.azure.core.http.rest.ResponseBase;
/**
* Contains all response data for the setAccessControl operation.
*/
public final class PathsSetAccessControlResponse extends ResponseBase<PathSetAccessControlHeaders, Void> {
/**
* Creates an instance of PathsSetAccessControlResponse.
*
* @param request the request which resulted in this PathsSetAccessControlResponse.
* @param statusCode the status code of the HTTP response.
* @param rawHeaders the raw headers of the HTTP response.
* @param value the deserialized value of the HTTP response.
* @param headers the deserialized headers of the HTTP response.
*/
public PathsSetAccessControlResponse(HttpRequest request, int statusCode, HttpHeaders rawHeaders, Void value, PathSetAccessControlHeaders headers) {
super(request, statusCode, rawHeaders, value, headers);
}
}
| mit |
siggame/Joueur.cpp | games/stumped/tile.hpp | 4902 | #ifndef GAMES_STUMPED_TILE_H
#define GAMES_STUMPED_TILE_H
// Tile
// A Tile in the game that makes up the 2D map grid.
// DO NOT MODIFY THIS FILE
// Never try to directly create an instance of this class, or modify its member variables.
// Instead, you should only be reading its variables and calling its functions.
#include <vector>
#include <queue>
#include <deque>
#include <unordered_map>
#include <string>
#include <initializer_list>
#include "../../joueur/src/any.hpp"
#include "game_object.hpp"
#include "impl/stumped_fwd.hpp"
// <<-- Creer-Merge: includes -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
// you can add additional #includes here
// <<-- /Creer-Merge: includes -->>
namespace cpp_client
{
namespace stumped
{
/// <summary>
/// A Tile in the game that makes up the 2D map grid.
/// </summary>
class Tile_ : public Game_object_
{
public:
/// <summary>
/// The Beaver on this Tile if present, otherwise null.
/// </summary>
const Beaver& beaver;
/// <summary>
/// The number of branches dropped on this Tile.
/// </summary>
const int& branches;
/// <summary>
/// The cardinal direction water is flowing on this Tile ('North', 'East', 'South', 'West').
/// </summary>
const std::string& flow_direction;
/// <summary>
/// The number of food dropped on this Tile.
/// </summary>
const int& food;
/// <summary>
/// The owner of the Beaver lodge on this Tile, if present, otherwise null.
/// </summary>
const Player& lodge_owner;
/// <summary>
/// The resource Spawner on this Tile if present, otherwise null.
/// </summary>
const Spawner& spawner;
/// <summary>
/// The Tile to the 'East' of this one (x+1, y). Null if out of bounds of the map.
/// </summary>
const Tile& tile_east;
/// <summary>
/// The Tile to the 'North' of this one (x, y-1). Null if out of bounds of the map.
/// </summary>
const Tile& tile_north;
/// <summary>
/// The Tile to the 'South' of this one (x, y+1). Null if out of bounds of the map.
/// </summary>
const Tile& tile_south;
/// <summary>
/// The Tile to the 'West' of this one (x-1, y). Null if out of bounds of the map.
/// </summary>
const Tile& tile_west;
/// <summary>
/// What type of Tile this is, either 'water' or 'land'.
/// </summary>
const std::string& type;
/// <summary>
/// The x (horizontal) position of this Tile.
/// </summary>
const int& x;
/// <summary>
/// The y (vertical) position of this Tile.
/// </summary>
const int& y;
// <<-- Creer-Merge: member variables -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
// You can add additional member variables here. None of them will be tracked or updated by the server.
// <<-- /Creer-Merge: member variables -->>
/// <summary>
/// The list of all valid directions Tiles can be in
/// </summary>
static const std::vector<std::string> directions;
/// <summary>
/// Gets the neighbors of this Tile
/// </summary>
/// <returns>The neighboring (adjacent) Tiles to this tile</returns>
std::vector<Tile> get_neighbors();
/// <summary>
/// Checks if a Tile is pathable to units
/// </summary>
/// <returns>true if pathable, false otherwise</returns>
bool is_pathable();
/// <summary>
/// Checks if this Tile has a specific neighboring Tile
/// </summary>
/// <param name="tile">Tile to check against</param>
/// <returns>if the tile is a neighbor of this Tile, false otherwise</returns>
bool has_neighbor(const Tile& tile);
// <<-- Creer-Merge: methods -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
// You can add additional methods here.
// <<-- /Creer-Merge: methods -->>
~Tile_();
// ####################
// Don't edit these!
// ####################
/// \cond FALSE
Tile_(std::initializer_list<std::pair<std::string, Any&&>> init);
Tile_() : Tile_({}){}
virtual void resize(const std::string& name, std::size_t size) override;
virtual void change_vec_values(const std::string& name, std::vector<std::pair<std::size_t, Any>>& values) override;
virtual void remove_key(const std::string& name, Any& key) override;
virtual std::unique_ptr<Any> add_key_value(const std::string& name, Any& key, Any& value) override;
virtual bool is_map(const std::string& name) override;
virtual void rebind_by_name(Any* to_change, const std::string& member, std::shared_ptr<Base_object> ref) override;
/// \endcond
// ####################
// Don't edit these!
// ####################
};
} // stumped
} // cpp_client
#endif // GAMES_STUMPED_TILE_H
| mit |
ktschap/masala-dosa | pep/pepparkmead/src/pepparkmead/controller/AdminController.java | 483 | package pepparkmead.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping("/admin/Admin.do")
public class AdminController {
@RequestMapping(method = RequestMethod.GET)
public String getAdminPage(ModelMap model) throws Exception {
return "Admin";
}
}
| mit |
aspose-email/Aspose.Email-for-.NET | Examples/CSharp/IMAP/ImapBackupOperationWithMultiConnection.cs | 1346 | using System;
using Aspose.Email.Clients.Imap;
using Aspose.Email.Clients;
using Aspose.Email.Storage.Pst;
namespace Aspose.Email.Examples.CSharp.Email.IMAP
{
class ImapBackupOperationWithMultiConnection
{
public static void Run()
{
//ExStart:1
// The path to the File directory.
string dataDir = RunExamples.GetDataDir_IMAP();
// Create an instance of the ImapClient class
ImapClient imapClient = new ImapClient();
// Specify host, username and password, and set port for your client
imapClient.Host = "imap.gmail.com";
imapClient.Username = "your.username@gmail.com";
imapClient.Password = "your.password";
imapClient.Port = 993;
imapClient.SecurityOptions = SecurityOptions.Auto;
imapClient.UseMultiConnection = MultiConnectionMode.Enable;
ImapMailboxInfo mailboxInfo = imapClient.MailboxInfo;
ImapFolderInfo info = imapClient.GetFolderInfo(mailboxInfo.Inbox.Name);
ImapFolderInfoCollection infos = new ImapFolderInfoCollection();
infos.Add(info);
imapClient.Backup(infos, dataDir + @"\ImapBackup.pst", BackupOptions.Recursive);
//ExEnd:1
}
}
}
| mit |
bryson/vagrant | plugins/guests/debian/cap/change_host_name.rb | 3858 | require "log4r"
require_relative "../../linux/cap/network_interfaces"
module VagrantPlugins
module GuestDebian
module Cap
class ChangeHostName
extend Vagrant::Util::GuestInspection::Linux
def self.change_host_name(machine, name)
@logger = Log4r::Logger.new("vagrant::guest::debian::changehostname")
comm = machine.communicate
if !comm.test("hostname -f | grep '^#{name}$'", sudo: false)
basename = name.split(".", 2)[0]
comm.sudo <<-EOH.gsub(/^ {14}/, '')
# Set the hostname
echo '#{basename}' > /etc/hostname
# Prepend ourselves to /etc/hosts
grep -w '#{name}' /etc/hosts || {
if grep -w '^127\\.0\\.1\\.1' /etc/hosts ; then
sed -i'' 's/^127\\.0\\.1\\.1\\s.*$/127.0.1.1\\t#{name}\\t#{basename}/' /etc/hosts
else
sed -i'' '1i 127.0.1.1\\t#{name}\\t#{basename}' /etc/hosts
fi
}
# Update mailname
echo '#{name}' > /etc/mailname
EOH
if hostnamectl?(comm)
comm.sudo("hostnamectl set-hostname '#{basename}'")
else
comm.sudo <<-EOH.gsub(/^ {14}/, '')
hostname -F /etc/hostname
# Restart hostname services
if test -f /etc/init.d/hostname; then
/etc/init.d/hostname start || true
fi
if test -f /etc/init.d/hostname.sh; then
/etc/init.d/hostname.sh start || true
fi
EOH
end
restart_command = nil
if systemd?(comm)
if systemd_networkd?(comm)
@logger.debug("Attempting to restart networking with systemd-networkd")
restart_command = "systemctl restart systemd-networkd.service"
elsif systemd_controlled?(comm, "NetworkManager.service")
@logger.debug("Attempting to restart networking with NetworkManager")
restart_command = "systemctl restart NetworkManager.service"
end
end
if restart_command
comm.sudo(restart_command)
else
restart_each_interface(machine, @logger)
end
end
end
protected
# Due to how most Debian systems and older Ubuntu systems handle restarting
# networking, we cannot simply run the networking init script or use the ifup/down
# tools to restart all interfaces to renew the machines DHCP lease when setting
# its hostname. This method is a workaround for those older systems that
# cannoy reliably restart networking. It restarts each individual interface
# on its own instead.
#
# @param [Vagrant::Machine] machine
# @param [Log4r::Logger] logger
def self.restart_each_interface(machine, logger)
comm = machine.communicate
interfaces = VagrantPlugins::GuestLinux::Cap::NetworkInterfaces.network_interfaces(machine)
nettools = true
if systemd?(comm)
@logger.debug("Attempting to restart networking with systemctl")
nettools = false
else
@logger.debug("Attempting to restart networking with ifup/down nettools")
end
interfaces.each do |iface|
logger.debug("Restarting interface #{iface} on guest #{machine.name}")
if nettools
restart_command = "ifdown #{iface};ifup #{iface}"
else
restart_command = "systemctl stop ifup@#{iface}.service;systemctl start ifup@#{iface}.service"
end
comm.sudo(restart_command)
end
end
end
end
end
end
| mit |
Webiny/Crypt | Bridge/Sodium/Crypt.php | 5963 | <?php
/**
* Webiny Framework (http://www.webiny.com/framework)
*
* @copyright Copyright Webiny LTD
*/
namespace Webiny\Component\Crypt\Bridge\Sodium;
use ParagonIE\Halite\HiddenString;
use ParagonIE\Halite\KeyFactory;
use ParagonIE\Halite\Symmetric\Crypto;
use Webiny\Component\Crypt\Bridge\CryptInterface;
use Webiny\Component\Security\Token\CryptDrivers\Crypt\CryptException;
/**
* Class Crypt.
*
* This is a simple class providing the basic cryptographic methods.
*
* It's using libsodium instead of old mcrypt, via paragonie/halite PHP package.
* @package Webiny\Component\Crypt\Bridge\Webiny
*/
class Crypt implements CryptInterface
{
const CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
const NUMBERS = '0123456789';
const SYMBOLS = '!"#$%&\'()* +,-./:;<=>?@[\]^_`{|}~';
const HASH = 'sha512';
/**
* Encrypt the given $string using a cypher and the secret $key
*
* @param string $string The string you want to encrypt.
* @param string $key The secret key that will be used to encrypt the string.
*
* @return string|bool Encrypted string. False if encryption fails.
*/
public function encrypt($string, $key)
{
try{
$salt = $this->generateRandomString(16);
$key = KeyFactory::deriveEncryptionKey(new HiddenString($key), $salt);
$msg = Crypto::encrypt(new HiddenString($string), $key);
return base64_encode($salt . $msg);
}catch (\Exception $e){
return false;
}
}
/**
* Decrypt a string that has been encrypted with the 'encrypt' method.
* In order to decrypt the string correctly, you must provide the same secret key that was used for the encryption
* process.
*
* @param string $string The string you want to decrypt.
* @param string $key The secret key that was used to encrypt the $string.
*
* @return string Decrypted string.
* @throws CryptException
*/
public function decrypt($string, $key)
{
try{
$string = base64_decode($string);
if (!$string) {
return false;
}
$salt = $this->subStr($string, 0, 16);
$cipherText = $this->subStr($string, 16);
$key = KeyFactory::deriveEncryptionKey(new HiddenString($key), $salt);
$msg = Crypto::decrypt($cipherText, $key);
return $msg->getString();
}catch (\Exception $e){
return false;
}
}
/**
* Creates a hash from the given $password string.
* The hashing algorithm used depends on your config.
*
* @param string $password String you wish to hash.
*
* @return string Hash of the given string.
*/
public function createPasswordHash($password)
{
return \Sodium\crypto_pwhash_str($password, \Sodium\CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE, \Sodium\CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE);
}
/**
* Verify if the given $hash matches the given $password.
*
* @param string $password Original, un-hashed, password.
* @param string $hash Hash string to which the check should be made
*
* @return bool True if $password matches the $hash, otherwise false is returned.
*/
public function verifyPasswordHash($password, $hash)
{
return \Sodium\crypto_pwhash_str_verify($hash, $password);
}
/**
* Generates a random integer between the given $min and $max values.
*
* @param int $min Lower limit.
* @param int $max Upper limit
*
* @return int Random number between $min and $max.
*/
public function generateRandomInt($min = 1, $max = PHP_INT_MAX)
{
return random_int($min, $max);
}
/**
* Generates a random string using the defined character set.
* If $chars param is empty, the string will be generated using numbers, letters and special characters.
*
* @param int $length Length of the generated string.
* @param string $chars A string containing a list of chars that will be uses for generating the random string.
*
* @return string Random string with the given $length containing only the provided set of $chars.
*/
public function generateRandomString($length, $chars = '')
{
// define the character map
if (empty($chars)) {
$chars = self::CHARS . self::NUMBERS . self::SYMBOLS;
}
$mapSize = strlen($chars);
$string = '';
for ($i = 0; $i < $length; ++$i) {
$string .= $chars[($this->generateRandomInt(1, $mapSize)-1)];
}
return $string;
}
/**
* Generates a random string, but without using special characters that are hard to read.
* This method is ok to use for generating random user passwords. (which, of course, should be changed after first login).
*
* @param int $length Length of the random string.
*
* @return string Random string with the given $length.
*/
public function generateUserReadableString($length)
{
return $this->generateRandomString($length, self::CHARS . self::NUMBERS);
}
/**
* Generates a random string with a lot of 'noise' (special characters).
* Use this method to generate API keys, salts and similar.
*
* @param int $length Length of the random string.
*
* @return string Random string with the given $length.
*/
public function generateHardReadableString($length)
{
return $this->generateRandomString($length, self::SYMBOLS . self::CHARS . self::NUMBERS . self::SYMBOLS);
}
/**
* Helper function for substr.
*
* @param $str
* @param $start
* @param $len
*
* @return string
*/
private function subStr($str, $start, $len = null)
{
return mb_substr($str, $start, $len, '8bit');
}
}
| mit |
microsoft/LightGBM | include/LightGBM/utils/yamc/yamc_shared_lock.hpp | 5050 | /*
* yamc_shared_lock.hpp
*
* MIT License
*
* Copyright (c) 2017 yohhoy
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef YAMC_SHARED_LOCK_HPP_
#define YAMC_SHARED_LOCK_HPP_
#include <cassert>
#include <chrono>
#include <mutex>
#include <system_error>
#include <utility> // std::swap
/*
* std::shared_lock in C++14 Standard Library
*
* - yamc::shared_lock<Mutex>
*/
namespace yamc {
template <typename Mutex>
class shared_lock {
void locking_precondition(const char* emsg) {
if (pm_ == nullptr) {
throw std::system_error(
std::make_error_code(std::errc::operation_not_permitted), emsg);
}
if (owns_) {
throw std::system_error(
std::make_error_code(std::errc::resource_deadlock_would_occur), emsg);
}
}
public:
using mutex_type = Mutex;
shared_lock() noexcept = default;
explicit shared_lock(mutex_type* m) {
m->lock_shared();
pm_ = m;
owns_ = true;
}
shared_lock(const mutex_type& m, std::defer_lock_t) noexcept {
pm_ = &m;
owns_ = false;
}
shared_lock(const mutex_type& m, std::try_to_lock_t) {
pm_ = &m;
owns_ = m.try_lock_shared();
}
shared_lock(const mutex_type& m, std::adopt_lock_t) {
pm_ = &m;
owns_ = true;
}
template <typename Clock, typename Duration>
shared_lock(const mutex_type& m,
const std::chrono::time_point<Clock, Duration>& abs_time) {
pm_ = &m;
owns_ = m.try_lock_shared_until(abs_time);
}
template <typename Rep, typename Period>
shared_lock(const mutex_type& m,
const std::chrono::duration<Rep, Period>& rel_time) {
pm_ = &m;
owns_ = m.try_lock_shared_for(rel_time);
}
~shared_lock() {
if (owns_) {
assert(pm_ != nullptr);
pm_->unlock_shared();
}
}
shared_lock(const shared_lock&) = delete;
shared_lock& operator=(const shared_lock&) = delete;
shared_lock(shared_lock&& rhs) noexcept {
if (pm_ && owns_) {
pm_->unlock_shared();
}
pm_ = rhs.pm_;
owns_ = rhs.owns_;
rhs.pm_ = nullptr;
rhs.owns_ = false;
}
shared_lock& operator=(shared_lock&& rhs) noexcept {
if (pm_ && owns_) {
pm_->unlock_shared();
}
pm_ = rhs.pm_;
owns_ = rhs.owns_;
rhs.pm_ = nullptr;
rhs.owns_ = false;
return *this;
}
void lock() {
locking_precondition("shared_lock::lock");
pm_->lock_shared();
owns_ = true;
}
bool try_lock() {
locking_precondition("shared_lock::try_lock");
return (owns_ = pm_->try_lock_shared());
}
template <typename Rep, typename Period>
bool try_lock_for(const std::chrono::duration<Rep, Period>& rel_time) {
locking_precondition("shared_lock::try_lock_for");
return (owns_ = pm_->try_lock_shared_for(rel_time));
}
template <typename Clock, typename Duration>
bool try_lock_until(
const std::chrono::time_point<Clock, Duration>& abs_time) {
locking_precondition("shared_lock::try_lock_until");
return (owns_ = pm_->try_lock_shared_until(abs_time));
}
void unlock() {
assert(pm_ != nullptr);
if (!owns_) {
throw std::system_error(
std::make_error_code(std::errc::operation_not_permitted),
"shared_lock::unlock");
}
pm_->unlock_shared();
owns_ = false;
}
void swap(shared_lock& sl) noexcept {
std::swap(pm_, sl.pm_);
std::swap(owns_, sl.owns_);
}
mutex_type* release() noexcept {
mutex_type* result = pm_;
pm_ = nullptr;
owns_ = false;
return result;
}
bool owns_lock() const noexcept { return owns_; }
explicit operator bool() const noexcept { return owns_; }
mutex_type* mutex() const noexcept { return pm_; }
private:
mutex_type* pm_ = nullptr;
bool owns_ = false;
};
} // namespace yamc
namespace std {
/// std::swap() specialization for yamc::shared_lock<Mutex> type
template <typename Mutex>
void swap(yamc::shared_lock<Mutex>& lhs,
yamc::shared_lock<Mutex>& rhs) noexcept {
lhs.swap(rhs);
}
} // namespace std
#endif
| mit |
kay-kim/mongoid | spec/app/models/vertex.rb | 205 | class Vertex
include Mongoid::Document
has_and_belongs_to_many :parents, inverse_of: :children, class_name: 'Vertex'
has_and_belongs_to_many :children, inverse_of: :parents, class_name: 'Vertex'
end | mit |
kmhasan-class/fall2017java | section3/Lab5/src/account/CurrentAccount.java | 600 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package account;
/**
*
* @author kmhasan
*/
public class CurrentAccount extends BankAccount {
public CurrentAccount(int accountId,
String accountName,
String emailAddress,
double balance) {
super(accountId, accountName, emailAddress, balance);
}
@Override
public boolean withdraw(double amount) {
return super.withdraw(amount + 20);
}
}
| mit |
LBenzahia/cltk | cltk/prosody/latin/metrical_validator.py | 12651 | """Utility class for validating scansion patterns: hexameter, hendecasyllables, pentameter.
Allows users to configure the scansion symbols internally via a constructor argument;
a suitable default is provided."""
import logging
from typing import List
from cltk.prosody.latin.scansion_constants import ScansionConstants
from Levenshtein import distance
LOG = logging.getLogger(__name__)
LOG.addHandler(logging.NullHandler())
__author__ = ['Todd Cook <todd.g.cook@gmail.com>']
__license__ = 'MIT License'
class MetricalValidator:
"""Currently supports validation for: hexameter, hendecasyllables, pentameter."""
def is_valid_hexameter(self, scanned_line: str) -> bool:
"""Determine if a scansion pattern is one of the valid hexameter metrical patterns
:param scanned_line: a line containing a sequence of stressed and unstressed syllables
:return bool
>>> print(MetricalValidator().is_valid_hexameter("-UU---UU---UU-U"))
True
"""
line = scanned_line.replace(self.constants.FOOT_SEPARATOR, "")
line = line.replace(" ", "")
if len(line) < 12:
return False
line = line[:-1] + self.constants.OPTIONAL_ENDING
return self.VALID_HEXAMETERS.__contains__(line)
def is_valid_hendecasyllables(self, scanned_line: str) -> bool:
"""Determine if a scansion pattern is one of the valid Hendecasyllables metrical patterns
:param scanned_line: a line containing a sequence of stressed and unstressed syllables
:return bool
>>> print(MetricalValidator().is_valid_hendecasyllables("-U-UU-U-U-U"))
True
"""
line = scanned_line.replace(self.constants.FOOT_SEPARATOR, "")
line = line.replace(" ", "")
if len(line) < 11:
return False
line = line[:-1] + self.constants.OPTIONAL_ENDING
return self.VALID_HENDECASYLLABLES.__contains__(line)
def is_valid_pentameter(self, scanned_line: str) -> bool:
"""Determine if a scansion pattern is one of the valid Pentameter metrical patterns
:param scanned_line: a line containing a sequence of stressed and unstressed syllables
:return bool: whether or not the scansion is a valid pentameter
>>> print(MetricalValidator().is_valid_pentameter('-UU-UU--UU-UUX'))
True
"""
line = scanned_line.replace(self.constants.FOOT_SEPARATOR, "")
line = line.replace(" ", "")
if len(line) < 10:
return False
line = line[:-1] + self.constants.OPTIONAL_ENDING
return self.VALID_PENTAMETERS.__contains__(line)
def __init__(self, constants=ScansionConstants()):
self.constants = constants
self.VALID_HEXAMETERS = [self._build_hexameter_template(bin(x)[3:]) for x in range(32, 64)]
self.VALID_HENDECASYLLABLES = self._build_hendecasyllable_templates()
self.VALID_PENTAMETERS = self._build_pentameter_templates()
def hexameter_feet(self, scansion: str) -> List[str]:
"""
Produces a list of hexameter feet, stressed and unstressed syllables with spaces intact.
If the scansion line is not entirely correct, it will attempt to corral one or more improper
patterns into one or more feet.
:param: scansion: the scanned line
:return list of strings, representing the feet of the hexameter, or if the scansion is
wildly incorrect, the function will return an empty list.
>>> print("|".join(MetricalValidator().hexameter_feet(
... "- U U - - - - - - - U U - U")).strip() )
- U U |- - |- - |- - |- U U |- U
>>> print("|".join(MetricalValidator().hexameter_feet(
... "- U U - - U - - - - U U - U")).strip())
- U U |- - |U - |- - |- U U |- U
"""
backwards_scan = list(scansion.rstrip())
feet = []
candidates = [self.constants.STRESSED + self.constants.OPTIONAL_ENDING,
self.constants.STRESSED + self.constants.STRESSED,
self.constants.STRESSED + self.constants.UNSTRESSED,
self.constants.UNSTRESSED + self.constants.STRESSED]
incomplete_foot = self.constants.UNSTRESSED + self.constants.UNSTRESSED
try:
while len(backwards_scan) > 0:
spaces = []
chunk1 = backwards_scan.pop()
while len("".join(chunk1).replace(" ", "")) == 0:
if len(backwards_scan) == 0:
feet.append(chunk1)
return feet[::-1]
chunk1 = backwards_scan.pop() + "".join(chunk1)
chunk2 = backwards_scan.pop()
while chunk2 == " ":
spaces.append(chunk2)
if len(backwards_scan) == 0:
feet.append(chunk2)
return feet[::-1]
chunk2 = backwards_scan.pop()
new_candidate = "".join(chunk2) + "".join(spaces) + "".join(chunk1)
if new_candidate.replace(" ", "") in candidates:
feet.append(new_candidate)
else:
if new_candidate.replace(" ", "") == incomplete_foot:
spaces2 = []
previous_mark = backwards_scan.pop()
while previous_mark == " ":
spaces2.append(previous_mark)
previous_mark = backwards_scan.pop()
if previous_mark == self.constants.STRESSED:
new_candidate = "".join(previous_mark) + "".join(
spaces2) + new_candidate
feet.append(new_candidate)
else:
feet.append(new_candidate) # invalid foot
spaces3 = []
next_mark = backwards_scan.pop()
while next_mark == " ":
spaces3.append(previous_mark)
next_mark = backwards_scan.pop()
feet.append("".join(next_mark) + "".join(spaces3) + previous_mark)
except Exception as ex:
LOG.error("err at: {}, {}".format(scansion, ex))
return list()
return feet[::-1]
@staticmethod
def hexameter_known_stresses() -> List[int]:
"""Provide a list of known stress positions for a hexameter.
:return: a zero based list enumerating which syllables are known to be stressed.
"""
return list(range(17)[::3])
@staticmethod
def hexameter_possible_unstresses() -> List[int]:
"""
Provide a list of possible positions which may be unstressed syllables in a hexameter.
:return: a zero based list enumerating which syllables are known to be unstressed.
"""
return list(set(range(17)) - set(range(17)[::3]))
def closest_hexameter_patterns(self, scansion: str) -> List[str]:
"""
Find the closest group of matching valid hexameter patterns.
:return: list of the closest valid hexameter patterns; only candidates with a matching
length/number of syllables are considered.
>>> print(MetricalValidator().closest_hexameter_patterns('-UUUUU-----UU--'))
['-UU-UU-----UU--']
"""
return self._closest_patterns(self.VALID_HEXAMETERS, scansion)
@staticmethod
def pentameter_possible_stresses() -> List[int]:
"""
Provide a list of possible stress positions for a hexameter.
:return: a zero based list enumerating which syllables are known to be stressed.
"""
return list(range(0, 6)) + [8]
def closest_pentameter_patterns(self, scansion: str) -> List[str]:
"""
Find the closest group of matching valid pentameter patterns.
:return: list of the closest valid pentameter patterns; only candidates with a matching
length/number of syllables are considered.
>>> print(MetricalValidator().closest_pentameter_patterns('--UUU--UU-UUX'))
['---UU--UU-UUX']
"""
return self._closest_patterns(self.VALID_PENTAMETERS, scansion)
def closest_hendecasyllable_patterns(self, scansion: str) -> List[str]:
"""
Find the closest group of matching valid hendecasyllable patterns.
:return: list of the closest valid hendecasyllable patterns; only candidates with a matching
length/number of syllables are considered.
>>> print(MetricalValidator().closest_hendecasyllable_patterns('UU-UU-U-U-X'))
['-U-UU-U-U-X', 'U--UU-U-U-X']
"""
return self._closest_patterns(self.VALID_HENDECASYLLABLES, scansion)
def _closest_patterns(self, patterns: List[str], scansion: str) -> List[str]:
"""
Find the closest group of matching valid patterns.
:patterns: a list of patterns
:scansion: the scansion pattern thus far
:return: list of the closest valid patterns; only candidates with a matching
length/number of syllables are considered.
"""
pattern = scansion.replace(" ", "")
pattern = pattern.replace(self.constants.FOOT_SEPARATOR, "")
ending = pattern[-1]
candidate = pattern[:len(pattern) - 1] + self.constants.OPTIONAL_ENDING
cans = [(distance(candidate, x), x) for x in patterns
if len(x) == len(candidate)]
if cans:
cans = sorted(cans, key=lambda tup: tup[0])
top = cans[0][0]
return [can[1][:-1] + ending for can in cans if can[0] == top]
return []
def _build_hexameter_template(self, stress_positions: str) -> str:
"""
Build a hexameter scansion template from string of 5 binary numbers;
NOTE: Traditionally the fifth foot is dactyl and spondee substitution is rare,
however since it *is* a possible combination, we include it here.
:param stress_positions: 5 binary integers, indicating whether foot is dactyl or spondee
:return: a valid hexameter scansion template, a string representing stressed and
unstresssed syllables with the optional terminal ending.
>>> print(MetricalValidator()._build_hexameter_template("01010"))
-UU---UU---UU-X
"""
hexameter = []
for binary in stress_positions:
if binary == "1":
hexameter.append(self.constants.SPONDEE)
if binary == "0":
hexameter.append(self.constants.DACTYL)
hexameter.append(self.constants.HEXAMETER_ENDING)
return "".join(hexameter)
def _build_hendecasyllable_templates(self) -> List[str]:
return [
# -U - U U - U - U - X
self.constants.TROCHEE + self.constants.TROCHEE +
self.constants.IAMB + self.constants.IAMB + self.constants.IAMB
+ self.constants.OPTIONAL_ENDING,
# -- - U U - U - U - X
self.constants.SPONDEE + self.constants.TROCHEE +
self.constants.IAMB + self.constants.IAMB + self.constants.IAMB
+ self.constants.OPTIONAL_ENDING,
# U- - U U - U - U - X
self.constants.IAMB + self.constants.TROCHEE +
self.constants.IAMB + self.constants.IAMB + self.constants.IAMB
+ self.constants.OPTIONAL_ENDING]
def _build_pentameter_templates(self) -> List[str]:
"""Create pentameter templates."""
return [ # '-UU|-UU|-|-UU|-UU|X'
self.constants.DACTYL + self.constants.DACTYL +
self.constants.STRESSED + self.constants.DACTYL + self.constants.DACTYL
+ self.constants.OPTIONAL_ENDING,
# '-UU|--|-|-UU|-UU|X'
self.constants.DACTYL + self.constants.SPONDEE +
self.constants.STRESSED + self.constants.DACTYL + self.constants.DACTYL
+ self.constants.OPTIONAL_ENDING,
# '--|-UU|-|-UU|-UU|X'
self.constants.SPONDEE + self.constants.DACTYL +
self.constants.STRESSED + self.constants.DACTYL + self.constants.DACTYL
+ self.constants.OPTIONAL_ENDING,
# '--|--|-|-UU|-UU|X'
self.constants.SPONDEE + self.constants.SPONDEE +
self.constants.STRESSED + self.constants.DACTYL + self.constants.DACTYL
+ self.constants.OPTIONAL_ENDING]
| mit |
elmasse/Ext.i18n.Bundle | examples/bundleApp/app.js | 725 | /*
* This file is generated and updated by Sencha Cmd. You can edit this file as
* needed for your application, but these edits will have to be merged by
* Sencha Cmd when upgrading.
*/
Ext.application({
name: 'bundleApp',
extend: 'bundleApp.Application',
autoCreateViewport: 'bundleApp.view.main.Main'
//-------------------------------------------------------------------------
// Most customizations should be made to bundleApp.Application. If you need to
// customize this file, doing so below this section reduces the likelihood
// of merge conflicts when upgrading to new versions of Sencha Cmd.
//-------------------------------------------------------------------------
});
| mit |