code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2d357d86-395a-43e1-9c1b-da7a228f2e0a")]
| danice/Nancy.Hal | src/Nancy.Hal/Properties/AssemblyInfo.cs | C# | mit | 491 |
<?php
/**
* This file is part of the Zephir.
*
* (c) Phalcon Team <team@zephir-lang.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Zephir\Detectors;
/**
* ForValueUseDetector.
*
* Detects whether the traversed variable is modified within the 'for's block
*/
class ForValueUseDetector extends WriteDetector
{
/**
* ForValueUseDetector constructor.
*
* Initialize detector with safe defaults
*/
public function __construct()
{
$this->setDetectionFlags(self::DETECT_NONE);
}
}
| phalcon/zephir | Library/Detectors/ForValueUseDetector.php | PHP | mit | 630 |
<?php
namespace Platformsh\Cli\Command\Integration;
use Platformsh\Cli\Command\PlatformCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class IntegrationDeleteCommand extends PlatformCommand
{
/**
* {@inheritdoc}
*/
protected function configure()
{
$this
->setName('integration:delete')
->addArgument('id', InputArgument::REQUIRED, 'The integration ID')
->setDescription('Delete an integration from a project');
$this->addProjectOption();
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->validateInput($input);
$id = $input->getArgument('id');
$integration = $this->getSelectedProject()
->getIntegration($id);
if (!$integration) {
$this->stdErr->writeln("Integration not found: <error>$id</error>");
return 1;
}
if (!$integration->operationAvailable('delete')) {
$this->stdErr->writeln("The integration <error>$id</error> cannot be deleted");
return 1;
}
$type = $integration->getProperty('type');
$confirmText = "Delete the integration <info>$id</info> (type: $type)?";
if (!$this->getHelper('question')
->confirm($confirmText, $input, $this->stdErr)
) {
return 1;
}
$integration->delete();
$this->stdErr->writeln("Deleted integration <info>$id</info>");
return 0;
}
}
| Fredplais/platformsh-cli | src/Command/Integration/IntegrationDeleteCommand.php | PHP | mit | 1,647 |
__author__ = 'Nishanth'
from juliabox.cloud import JBPluginCloud
from juliabox.jbox_util import JBoxCfg, retry_on_errors
from googleapiclient.discovery import build
from oauth2client.client import GoogleCredentials
import threading
class JBoxGCD(JBPluginCloud):
provides = [JBPluginCloud.JBP_DNS, JBPluginCloud.JBP_DNS_GCD]
threadlocal = threading.local()
INSTALLID = None
REGION = None
DOMAIN = None
@staticmethod
def configure():
cloud_host = JBoxCfg.get('cloud_host')
JBoxGCD.INSTALLID = cloud_host['install_id']
JBoxGCD.REGION = cloud_host['region']
JBoxGCD.DOMAIN = cloud_host['domain']
@staticmethod
def domain():
if JBoxGCD.DOMAIN is None:
JBoxGCD.configure()
return JBoxGCD.DOMAIN
@staticmethod
def connect():
c = getattr(JBoxGCD.threadlocal, 'conn', None)
if c is None:
JBoxGCD.configure()
creds = GoogleCredentials.get_application_default()
JBoxGCD.threadlocal.conn = c = build("dns", "v1", credentials=creds)
return c
@staticmethod
@retry_on_errors(retries=2)
def add_cname(name, value):
JBoxGCD.connect().changes().create(
project=JBoxGCD.INSTALLID, managedZone=JBoxGCD.REGION,
body={'kind': 'dns#change',
'additions': [
{'rrdatas': [value],
'kind': 'dns#resourceRecordSet',
'type': 'A',
'name': name,
'ttl': 300} ] }).execute()
@staticmethod
@retry_on_errors(retries=2)
def delete_cname(name):
resp = JBoxGCD.connect().resourceRecordSets().list(
project=JBoxGCD.INSTALLID, managedZone=JBoxGCD.REGION,
name=name, type='A').execute()
if len(resp['rrsets']) == 0:
JBoxGCD.log_debug('No prior dns registration found for %s', name)
else:
cname = resp['rrsets'][0]['rrdatas'][0]
ttl = resp['rrsets'][0]['ttl']
JBoxGCD.connect().changes().create(
project=JBoxGCD.INSTALLID, managedZone=JBoxGCD.REGION,
body={'kind': 'dns#change',
'deletions': [
{'rrdatas': [str(cname)],
'kind': 'dns#resourceRecordSet',
'type': 'A',
'name': name,
'ttl': ttl} ] }).execute()
JBoxGCD.log_warn('Prior dns registration was found for %s', name)
| JuliaLang/JuliaBox | engine/src/juliabox/plugins/dns_gcd/impl_gcd.py | Python | mit | 2,592 |
require 'rails'
module StripeI18n
class Railtie < ::Rails::Railtie
initializer 'stripe-i18n' do |app|
StripeI18n::Railtie.instance_eval do
pattern = pattern_from app.config.i18n.available_locales
add("rails/locale/#{pattern}.yml")
end
end
protected
def self.add(pattern)
files = Dir[File.join(File.dirname(__FILE__), '../..', pattern)]
I18n.load_path.concat(files)
end
def self.pattern_from(args)
array = Array(args || [])
array.blank? ? '*' : "{#{array.join ','}}"
end
end
end
| ekosz/stripe-i18n | lib/stripe_i18n/railtie.rb | Ruby | mit | 567 |
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi
*
* 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 hudson.node_monitors;
import hudson.Extension;
import hudson.FilePath;
import hudson.Functions;
import hudson.model.Computer;
import hudson.remoting.Callable;
import jenkins.model.Jenkins;
import hudson.node_monitors.DiskSpaceMonitorDescriptor.DiskSpace;
import org.kohsuke.stapler.DataBoundConstructor;
import java.io.IOException;
import java.text.ParseException;
/**
* Checks available disk space of the remote FS root.
* Requires Mustang.
*
* @author Kohsuke Kawaguchi
* @since 1.123
*/
public class DiskSpaceMonitor extends AbstractDiskSpaceMonitor {
@DataBoundConstructor
public DiskSpaceMonitor(String freeSpaceThreshold) throws ParseException {
super(freeSpaceThreshold);
}
public DiskSpaceMonitor() {}
public DiskSpace getFreeSpace(Computer c) {
return DESCRIPTOR.get(c);
}
@Override
public String getColumnCaption() {
// Hide this column from non-admins
return Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER) ? super.getColumnCaption() : null;
}
public static final DiskSpaceMonitorDescriptor DESCRIPTOR = new DiskSpaceMonitorDescriptor() {
public String getDisplayName() {
return Messages.DiskSpaceMonitor_DisplayName();
}
@Override
protected Callable<DiskSpace, IOException> createCallable(Computer c) {
FilePath p = c.getNode().getRootPath();
if(p==null) return null;
return p.asCallableWith(new GetUsableSpace());
}
};
@Extension
public static DiskSpaceMonitorDescriptor install() {
if(Functions.isMustangOrAbove()) return DESCRIPTOR;
return null;
}
}
| chenDoInG/jenkins | core/src/main/java/hudson/node_monitors/DiskSpaceMonitor.java | Java | mit | 2,868 |
class PersonalFileUploader < FileUploader
def self.dynamic_path_segment(model)
File.join(CarrierWave.root, model_path(model))
end
def self.base_dir
File.join(root_dir, '-', 'system')
end
private
def secure_url
File.join(self.class.model_path(model), secret, file.filename)
end
def self.model_path(model)
if model
File.join("/#{base_dir}", model.class.to_s.underscore, model.id.to_s)
else
File.join("/#{base_dir}", 'temp')
end
end
end
| t-zuehlsdorff/gitlabhq | app/uploaders/personal_file_uploader.rb | Ruby | mit | 492 |
<?php
/*
* $Id: MssqlPlatform.php 3752 2007-04-11 09:11:18Z fabien $
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information please see
* <http://propel.phpdb.org>.
*/
require_once 'propel/engine/platform/DefaultPlatform.php';
include_once 'propel/engine/database/model/Domain.php';
/**
* MS SQL Platform implementation.
*
* @author Hans Lellelid <hans@xmpl.org> (Propel)
* @author Martin Poeschl <mpoeschl@marmot.at> (Torque)
* @version $Revision: 536 $
* @package propel.engine.platform
*/
class MssqlPlatform extends DefaultPlatform {
/**
* Initializes db specific domain mapping.
*/
protected function initialize()
{
parent::initialize();
$this->setSchemaDomainMapping(new Domain(PropelTypes::INTEGER, "INT"));
$this->setSchemaDomainMapping(new Domain(PropelTypes::BOOLEAN, "INT"));
$this->setSchemaDomainMapping(new Domain(PropelTypes::DOUBLE, "FLOAT"));
$this->setSchemaDomainMapping(new Domain(PropelTypes::LONGVARCHAR, "TEXT"));
$this->setSchemaDomainMapping(new Domain(PropelTypes::CLOB, "TEXT"));
$this->setSchemaDomainMapping(new Domain(PropelTypes::DATE, "DATETIME"));
$this->setSchemaDomainMapping(new Domain(PropelTypes::BU_DATE, "DATETIME"));
$this->setSchemaDomainMapping(new Domain(PropelTypes::TIME, "DATETIME"));
$this->setSchemaDomainMapping(new Domain(PropelTypes::TIMESTAMP, "DATETIME"));
$this->setSchemaDomainMapping(new Domain(PropelTypes::BU_TIMESTAMP, "DATETIME"));
$this->setSchemaDomainMapping(new Domain(PropelTypes::BINARY, "BINARY(7132)"));
$this->setSchemaDomainMapping(new Domain(PropelTypes::VARBINARY, "IMAGE"));
$this->setSchemaDomainMapping(new Domain(PropelTypes::LONGVARBINARY, "IMAGE"));
$this->setSchemaDomainMapping(new Domain(PropelTypes::BLOB, "IMAGE"));
}
/**
* @see Platform#getMaxColumnNameLength()
*/
public function getMaxColumnNameLength()
{
return 128;
}
/**
* @return Explicitly returns <code>NULL</code> if null values are
* allowed (as recomended by Microsoft).
* @see Platform#getNullString(boolean)
*/
public function getNullString($notNull)
{
return ($notNull ? "NOT NULL" : "NULL");
}
/**
* @see Platform::supportsNativeDeleteTrigger()
*/
public function supportsNativeDeleteTrigger()
{
return true;
}
/**
* @see Platform::hasSize(String)
*/
public function hasSize($sqlType)
{
return !("INT" == $sqlType || "TEXT" == $sqlType);
}
/**
* @see Platform::quoteIdentifier()
*/
public function quoteIdentifier($text)
{
return '[' . $text . ']';
}
}
| vincent03460/fxcmiscc-partner | lib/symfony/vendor/propel-generator/classes/propel/engine/platform/MssqlPlatform.php | PHP | mit | 3,539 |
/*
* 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.
*/
'use strict';
const models = require('./index');
/**
* Properties of an artifact source.
*
* @extends models['Resource']
*/
class ArtifactSource extends models['Resource'] {
/**
* Create a ArtifactSource.
* @member {string} [displayName] The artifact source's display name.
* @member {string} [uri] The artifact source's URI.
* @member {string} [sourceType] The artifact source's type. Possible values
* include: 'VsoGit', 'GitHub'
* @member {string} [folderPath] The folder containing artifacts.
* @member {string} [armTemplateFolderPath] The folder containing Azure
* Resource Manager templates.
* @member {string} [branchRef] The artifact source's branch reference.
* @member {string} [securityToken] The security token to authenticate to the
* artifact source.
* @member {string} [status] Indicates if the artifact source is enabled
* (values: Enabled, Disabled). Possible values include: 'Enabled',
* 'Disabled'
* @member {date} [createdDate] The artifact source's creation date.
* @member {string} [provisioningState] The provisioning status of the
* resource.
* @member {string} [uniqueIdentifier] The unique immutable identifier of a
* resource (Guid).
*/
constructor() {
super();
}
/**
* Defines the metadata of ArtifactSource
*
* @returns {object} metadata of ArtifactSource
*
*/
mapper() {
return {
required: false,
serializedName: 'ArtifactSource',
type: {
name: 'Composite',
className: 'ArtifactSource',
modelProperties: {
id: {
required: false,
readOnly: true,
serializedName: 'id',
type: {
name: 'String'
}
},
name: {
required: false,
readOnly: true,
serializedName: 'name',
type: {
name: 'String'
}
},
type: {
required: false,
readOnly: true,
serializedName: 'type',
type: {
name: 'String'
}
},
location: {
required: false,
serializedName: 'location',
type: {
name: 'String'
}
},
tags: {
required: false,
serializedName: 'tags',
type: {
name: 'Dictionary',
value: {
required: false,
serializedName: 'StringElementType',
type: {
name: 'String'
}
}
}
},
displayName: {
required: false,
serializedName: 'properties.displayName',
type: {
name: 'String'
}
},
uri: {
required: false,
serializedName: 'properties.uri',
type: {
name: 'String'
}
},
sourceType: {
required: false,
serializedName: 'properties.sourceType',
type: {
name: 'String'
}
},
folderPath: {
required: false,
serializedName: 'properties.folderPath',
type: {
name: 'String'
}
},
armTemplateFolderPath: {
required: false,
serializedName: 'properties.armTemplateFolderPath',
type: {
name: 'String'
}
},
branchRef: {
required: false,
serializedName: 'properties.branchRef',
type: {
name: 'String'
}
},
securityToken: {
required: false,
serializedName: 'properties.securityToken',
type: {
name: 'String'
}
},
status: {
required: false,
serializedName: 'properties.status',
type: {
name: 'String'
}
},
createdDate: {
required: false,
readOnly: true,
serializedName: 'properties.createdDate',
type: {
name: 'DateTime'
}
},
provisioningState: {
required: false,
serializedName: 'properties.provisioningState',
type: {
name: 'String'
}
},
uniqueIdentifier: {
required: false,
serializedName: 'properties.uniqueIdentifier',
type: {
name: 'String'
}
}
}
}
};
}
}
module.exports = ArtifactSource;
| lmazuel/azure-sdk-for-node | lib/services/devTestLabs/lib/models/artifactSource.js | JavaScript | mit | 5,125 |
// implementation for cube_support.h
#include <utils/multiindex.h>
#include <utils/fixed_array1d.h>
using MathTL::multi_degree;
using MathTL::FixedArray1D;
namespace WaveletTL
{
template <class IBASIS, unsigned int DIM>
inline
void
support(const CubeBasis<IBASIS,DIM>& basis,
const typename CubeBasis<IBASIS,DIM>::Index& lambda,
typename CubeBasis<IBASIS,DIM>::Support& supp)
{
basis.support(lambda, supp);
}
template <class IBASIS, unsigned int DIM>
bool
intersect_supports(const CubeBasis<IBASIS,DIM>& basis,
const typename CubeBasis<IBASIS,DIM>::Index& lambda,
const typename CubeBasis<IBASIS,DIM>::Index& mu,
typename CubeBasis<IBASIS,DIM>::Support& supp)
{
typename CubeBasis<IBASIS,DIM>::Support supp_lambda;
WaveletTL::support<IBASIS,DIM>(basis, lambda, supp_lambda);
typename CubeBasis<IBASIS,DIM>::Support supp_mu;
WaveletTL::support<IBASIS,DIM>(basis, mu, supp_mu);
// determine support intersection granularity,
// adjust single support granularities if necessary
supp.j = std::max(supp_lambda.j, supp_mu.j);
if (supp_lambda.j > supp_mu.j)
{
const int adjust = 1<<(supp_lambda.j-supp_mu.j);
for (unsigned int i = 0; i < DIM; i++)
{
supp_mu.a[i] *= adjust;
supp_mu.b[i] *= adjust;
}
}
else
{
const int adjust = 1<<(supp_mu.j-supp_lambda.j);
for (unsigned int i = 0; i < DIM; i++)
{
supp_lambda.a[i] *= adjust;
supp_lambda.b[i] *= adjust;
}
}
for (unsigned int i = 0; i < DIM; i++)
{
supp.a[i] = std::max(supp_lambda.a[i],supp_mu.a[i]);
supp.b[i] = std::min(supp_lambda.b[i],supp_mu.b[i]);
if (supp.a[i] >= supp.b[i])
{
return false;
}
}
return true;
}
template <class IBASIS, unsigned int DIM>
void intersecting_wavelets(const CubeBasis<IBASIS,DIM>& basis,
const typename CubeBasis<IBASIS,DIM>::Index& lambda,
const int j, const bool generators,
std::list<typename CubeBasis<IBASIS,DIM>::Index>& intersecting)
{
typedef typename CubeBasis<IBASIS,DIM>::Index Index;
intersecting.clear();
#if 1
// the set of intersecting wavelets is a cartesian product from d sets from the 1D case,
// so we only have to compute the relevant 1D indices
typedef typename IBASIS::Index Index1D;
FixedArray1D<std::list<Index1D>,DIM>
intersecting_1d_generators, intersecting_1d_wavelets;
// prepare all intersecting wavelets and generators in the i-th coordinate direction
for (unsigned int i = 0; i < DIM; i++)
{
intersecting_wavelets(*basis.bases()[i],
Index1D(lambda.j(),
lambda.e()[i],
lambda.k()[i],
basis.bases()[i]),
j, true, intersecting_1d_generators[i]);
if (!(generators))
{
intersecting_wavelets(*basis.bases()[i],
Index1D(lambda.j(),
lambda.e()[i],
lambda.k()[i],
basis.bases()[i]),
j, false, intersecting_1d_wavelets[i]);
}
}
// generate all relevant tensor product indices with either e=(0,...,0) or e!=(0,...,0)
typedef std::list<FixedArray1D<Index1D,DIM> > list_type;
list_type indices;
FixedArray1D<Index1D,DIM> helpindex;
if (DIM > 1 || (DIM == 1 && generators))
{
for (typename std::list<Index1D>::const_iterator it(intersecting_1d_generators[0].begin()),
itend(intersecting_1d_generators[0].end());
it != itend; ++it)
{
helpindex[0] = *it;
indices.push_back(helpindex);
}
}
if (!(generators))
{
for (typename std::list<Index1D>::const_iterator it(intersecting_1d_wavelets[0].begin()),
itend(intersecting_1d_wavelets[0].end());
it != itend; ++it)
{
helpindex[0] = *it;
indices.push_back(helpindex);
}
}
for (unsigned int i = 1; i < DIM; i++)
{
list_type sofar;
sofar.swap(indices);
for (typename list_type::const_iterator itready(sofar.begin()), itreadyend(sofar.end());
itready != itreadyend; ++itready)
{
helpindex = *itready;
unsigned int esum = 0;
for (unsigned int k = 0; k < i; k++)
{
esum += helpindex[k].e();
}
if (generators || (i < DIM-1 || (i == (DIM-1) && esum > 0)))
{
for (typename std::list<Index1D>::const_iterator it(intersecting_1d_generators[i].begin()),
itend(intersecting_1d_generators[i].end());
it != itend; ++it)
{
helpindex[i] = *it;
indices.push_back(helpindex);
}
}
if (!(generators))
{
for (typename std::list<Index1D>::const_iterator it(intersecting_1d_wavelets[i].begin()),
itend(intersecting_1d_wavelets[i].end());
it != itend; ++it)
{
helpindex[i] = *it;
indices.push_back(helpindex);
}
}
}
}
// compose the results
typename Index::type_type help_e;
typename Index::translation_type help_k;
for (typename list_type::const_iterator it(indices.begin()), itend(indices.end());
it != itend; ++it)
{
for (unsigned int i = 0; i < DIM; i++)
{
help_e[i] = (*it)[i].e();
help_k[i] = (*it)[i].k();
}
intersecting.push_back(Index(j, help_e, help_k, &basis));
}
#else
typedef typename CubeBasis<IBASIS,DIM>::Index Index;
int k = -1;
if ( generators ) {
k=0;
}
else {
k=j-basis.j0()+1;
}
//std::list<typename Frame::Index> intersect_diff;
//! generators
if (true) {
FixedArray1D<int,DIM>
minkwavelet, maxkwavelet, minkgen, maxkgen;
typedef typename IBASIS::Index Index1D;
int minkkkk;
int maxkkkk;
// prepare all intersecting wavelets and generators in the i-th coordinate direction
for (unsigned int i = 0; i < DIM; i++) {
get_intersecting_wavelets_on_level(*basis.bases()[i],
Index1D(lambda.j(),
lambda.e()[i],
lambda.k()[i],
basis.bases()[i]),
j, true, minkkkk,maxkkkk);
minkgen[i]=minkkkk;
maxkgen[i] = maxkkkk;
if (!(generators))
get_intersecting_wavelets_on_level(*basis.bases()[i],
Index1D(lambda.j(),
lambda.e()[i],
lambda.k()[i],
basis.bases()[i]),
j, false, minkkkk,maxkkkk);
minkwavelet[i] = minkkkk;
maxkwavelet[i] = maxkkkk;
} // end for
unsigned int result = 0;
int deltaresult = 0;
int genfstlvl = 0;
bool gen = 0;
//const Array1D<Index>* full_collection = &basis.full_collection;
MultiIndex<int,DIM> type;
type[DIM-1] = 1;
unsigned int tmp = 1;
bool exit = 0;
// determine how many wavelets there are on all the levels
// below the level of this index
if (! gen) {
result = 0;
genfstlvl =1;
//generators on level j0
for (unsigned int i = 0; i< DIM; i++)
genfstlvl *= (basis.bases()[i])->Deltasize((basis.bases()[i])->j0());
//additional wavelets on level j
// =(#Gen[1]+#Wav[1])*...*(#Gen[Dim-1]+#Wav[Dim-1])
// -#Gen[1]*...*#Gen[Dim-1]
for (int lvl= 0 ;
lvl < (j -basis.j0());
lvl++){
int genCurLvl = 1;
int addWav = 1;
for (unsigned int i = 0; i< DIM; i++) {
unsigned int curJ = basis.bases()[i]->j0()+lvl;
int genCurDim = (basis.bases()[i])->Deltasize(curJ);
genCurLvl *= genCurDim;
addWav *= genCurDim+ (basis.bases()[i])->Nablasize(curJ);
}
result += addWav-genCurLvl;
}
result += genfstlvl;
}
while(!exit){
FixedArray1D<int,DIM> help1, help2;
for(unsigned int i = 0; i<DIM; i++)
help1[i]=0;
// berechnet wie viele indices mit einem zu kleinem translationstyp es gibt, so dass sich die Wavelets nicht schneiden
unsigned int result2 = 0;
for (unsigned int i = 0; i < DIM; i++) { // begin for1
int tmp = 1;
for (unsigned int l = i+1; l < DIM; l++) {
if (type[l] == 0)
tmp *= (basis.bases())[l]->Deltasize(j);
else
tmp *= (basis.bases())[l]->Nablasize(j);
}
help2[i] = tmp;
if (type[i] == 0) {
if (minkgen[i] == (basis.bases())[i]->DeltaLmin())
continue;
}
else
if (minkwavelet[i] == (basis.bases())[i]->Nablamin())
continue;
if (type[i] == 0) {
tmp *= minkgen[i]-(basis.bases())[i]->DeltaLmin();
}
else
tmp *= minkwavelet[i]-(basis.bases())[i]->Nablamin();
result2 += tmp;
} // end for1
int tmp = 0;
if (type[DIM-1] == 0) {
tmp = maxkgen[DIM-1] - minkgen[DIM-1]+1;
}
else{
tmp = maxkwavelet[DIM-1] - minkwavelet[DIM-1]+1;
}
bool exit2 = 0;
while(!exit2){
// fügt die Indizes ein die sich überlappen
for (unsigned int i = result + result2; i < result + result2 + tmp; i++) {
const Index* ind = basis.get_wavelet(i); //&((*full_collection)[i]);
intersecting.push_back(*ind);
}
for (unsigned int i = DIM-2; i >= 0; i--) {
if(type[i]==0){
if ( help1[i] < maxkgen[i]-minkgen[i]) {
help1[i]++;
result2 = result2 + help2[i];
for (unsigned int j = i+1; j<=DIM-2;j++){
if(type[i] == 0){
result2 = result2 - help2[j]*(maxkgen[j] - minkgen[j]+1);
}
else
result2 = result2 - help2[j]*(maxkwavelet[j] - minkwavelet[j]+1);
}
break;
}
else {
help1[i]=0;
exit2 = (i==0);
break;
}
}
else {
if ( help1[i] < maxkwavelet[i] - minkwavelet[i]) {
help1[i]++;
result2 = result2 + help2[i];
for (unsigned int j = i+1; j<=DIM-2;j++){
if(type[i] == 0){
result2 = result2 - help2[j]*(maxkgen[j] - minkgen[j]+1);
}
else
result2 = result2 - help2[j]*(maxkwavelet[j] - minkwavelet[j]+1);
}
break;
}
else {
help1[i]=0;
exit2 = (i==0);
break;
}
}
} //end for
} //end while 2
// berechnet wie viele Indizes von dem jeweiligen Typ in Patches p liegen
tmp = 1;
for (unsigned int i = 0; i < DIM; i++) {
if (type[i] == 0)
tmp *= (basis.bases())[i]->Deltasize(j);
else
tmp *= (basis.bases())[i]->Nablasize(j);
}
result += tmp;
// berechnet den nächsten Typ
for (unsigned int i = DIM-1; i >= 0; i--) {
if ( type[i] == 1 ) {
type[i] = 0;
exit = (i == 0);
if(exit)
break;
}
else {
type[i]++;
break;
}
} //end for
} // end while 1
} // end if
// } // end if
else { // if generators
// a brute force solution
typedef typename CubeBasis<IBASIS,DIM>::Support Support;
Support supp;
if (generators) {
for (Index mu = basis.first_generator (j);; ++mu) {
if (intersect_supports(basis, lambda, mu, supp))
intersecting.push_back(mu);
if (mu == basis.last_generator(j)) break;
}
}
}
//*/
#endif
//#else
#if 0
// a brute force solution
typedef typename CubeBasis<IBASIS,DIM>::Support Support;
Support supp;
if (generators) {
for (Index mu = first_generator<IBASIS,DIM>(&basis, j);; ++mu) {
if (intersect_supports(basis, lambda, mu, supp))
intersecting.push_back(mu);
if (mu == last_generator<IBASIS,DIM>(&basis, j)) break;
}
} else {
for (Index mu = first_wavelet<IBASIS,DIM>(&basis, j);; ++mu) {
if (intersect_supports(basis, lambda, mu, supp))
intersecting.push_back(mu);
if (mu == last_wavelet<IBASIS,DIM>(&basis, j)) break;
}
}
#endif
}
template <class IBASIS, unsigned int DIM>
bool intersect_singular_support(const CubeBasis<IBASIS,DIM>& basis,
const typename CubeBasis<IBASIS,DIM>::Index& lambda,
const typename CubeBasis<IBASIS,DIM>::Index& mu)
{
// we have intersection of the singular supports if and only if
// one of the components have this property in one dimension
typedef typename IBASIS::Index Index1D;
for (unsigned int i = 0; i < DIM; i++) {
if (intersect_singular_support
(*basis.bases()[i],
Index1D(lambda.j(), lambda.e()[i], lambda.k()[i], basis.bases()[i]),
Index1D(mu.j(), mu.e()[i], mu.k()[i], basis.bases()[i])))
return true;
}
return false;
}
}
| agnumerikunimarburg/Marburg_Software_Library | WaveletTL/cube/cube_support.cpp | C++ | mit | 12,820 |
# frozen_string_literal: true
class AddFieldsToCourseMaterialFolders < ActiveRecord::Migration[4.2]
def change
remove_column :course_material_folders, :parent_folder_id, :integer,
foreign_key: { references: :course_material_folders }
add_column :course_material_folders, :parent_id, :integer
add_column :course_material_folders, :course_id, :integer, null: false
add_column :course_material_folders, :can_student_upload, :boolean, null: false, default: false
add_index :course_material_folders, [:parent_id, :name], unique: true, case_sensitive: false
end
end
| cysjonathan/coursemology2 | db/migrate/20150812024950_add_fields_to_course_material_folders.rb | Ruby | mit | 604 |
package bf.io.openshop.entities;
public class Page {
private long id;
private String title;
private String text;
public Page() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Page page = (Page) o;
if (id != page.id) return false;
if (title != null ? !title.equals(page.title) : page.title != null) return false;
return !(text != null ? !text.equals(page.text) : page.text != null);
}
@Override
public int hashCode() {
int result = (int) (id ^ (id >>> 32));
result = 31 * result + (title != null ? title.hashCode() : 0);
result = 31 * result + (text != null ? text.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Page{" +
"id=" + id +
", title='" + title + '\'' +
", text='" + text + '\'' +
'}';
}
}
| openshopio/openshop.io-android | app/src/main/java/bf/io/openshop/entities/Page.java | Java | mit | 1,413 |
/*
* Exchange Web Services Managed API
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
*
* MIT 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.
*/
namespace Microsoft.Exchange.WebServices.Data
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
/// <summary>
/// Represents the response to a folder search operation.
/// </summary>
internal sealed class FindFolderResponse : ServiceResponse
{
private FindFoldersResults results = new FindFoldersResults();
private PropertySet propertySet;
/// <summary>
/// Reads response elements from XML.
/// </summary>
/// <param name="reader">The reader.</param>
internal override void ReadElementsFromXml(EwsServiceXmlReader reader)
{
reader.ReadStartElement(XmlNamespace.Messages, XmlElementNames.RootFolder);
this.results.TotalCount = reader.ReadAttributeValue<int>(XmlAttributeNames.TotalItemsInView);
this.results.MoreAvailable = !reader.ReadAttributeValue<bool>(XmlAttributeNames.IncludesLastItemInRange);
// Ignore IndexedPagingOffset attribute if MoreAvailable is false.
this.results.NextPageOffset = results.MoreAvailable ? reader.ReadNullableAttributeValue<int>(XmlAttributeNames.IndexedPagingOffset) : null;
reader.ReadStartElement(XmlNamespace.Types, XmlElementNames.Folders);
if (!reader.IsEmptyElement)
{
do
{
reader.Read();
if (reader.NodeType == XmlNodeType.Element)
{
Folder folder = EwsUtilities.CreateEwsObjectFromXmlElementName<Folder>(reader.Service, reader.LocalName);
if (folder == null)
{
reader.SkipCurrentElement();
}
else
{
folder.LoadFromXml(
reader,
true, /* clearPropertyBag */
this.propertySet,
true /* summaryPropertiesOnly */);
this.results.Folders.Add(folder);
}
}
}
while (!reader.IsEndElement(XmlNamespace.Types, XmlElementNames.Folders));
}
reader.ReadEndElement(XmlNamespace.Messages, XmlElementNames.RootFolder);
}
/// <summary>
/// Creates a folder instance.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="xmlElementName">Name of the XML element.</param>
/// <returns>Folder</returns>
private Folder CreateFolderInstance(ExchangeService service, string xmlElementName)
{
return EwsUtilities.CreateEwsObjectFromXmlElementName<Folder>(service, xmlElementName);
}
/// <summary>
/// Initializes a new instance of the <see cref="FindFolderResponse"/> class.
/// </summary>
/// <param name="propertySet">The property set from, the request.</param>
internal FindFolderResponse(PropertySet propertySet)
: base()
{
this.propertySet = propertySet;
EwsUtilities.Assert(
this.propertySet != null,
"FindFolderResponse.ctor",
"PropertySet should not be null");
}
/// <summary>
/// Gets the results of the search operation.
/// </summary>
public FindFoldersResults Results
{
get { return this.results; }
}
}
} | axelitus/fork-ews-managed-api | Core/Responses/FindFolderResponse.cs | C# | mit | 5,021 |
require 'spec_helper'
require 'generator_spec/test_case'
require 'generators/refinery/engine/engine_generator'
module Refinery
describe EngineGenerator do
include GeneratorSpec::TestCase
destination File.expand_path("../../../../../../tmp", __FILE__)
before do
prepare_destination
run_generator %w{ rspec_product_test title:string description:text image:image brochure:resource }
end
context "when generating a resource inside existing extensions dir" do
before do
run_generator %w{ rspec_item_test title:string --extension rspec_product_tests --namespace rspec_product_tests --skip }
end
it "creates a new migration with the new resource" do
destination_root.should have_structure {
directory "vendor" do
directory "extensions" do
directory "rspec_product_tests" do
directory "db" do
directory "migrate" do
file "2_create_rspec_product_tests_rspec_item_tests.rb"
end
end
end
end
end
}
end
it "appends routes to the routes file" do
File.open("#{destination_root}/vendor/extensions/rspec_product_tests/config/routes.rb") do |file|
file.grep(%r{rspec_item_tests}).count.should eq(2)
end
end
end
end
end
| resolve/refinerycms | core/spec/lib/generators/refinery/engine/engine_generator_multiple_resources_spec.rb | Ruby | mit | 1,394 |
package inputs
import (
"fmt"
)
// DiskIO is based on telegraf DiskIO.
type DiskIO struct {
baseInput
}
// PluginName is based on telegraf plugin name.
func (d *DiskIO) PluginName() string {
return "diskio"
}
// UnmarshalTOML decodes the parsed data to the object
func (d *DiskIO) UnmarshalTOML(data interface{}) error {
return nil
}
// TOML encodes to toml string.
func (d *DiskIO) TOML() string {
return fmt.Sprintf(`[[inputs.%s]]
## By default, telegraf will gather stats for all devices including
## disk partitions.
## Setting devices will restrict the stats to the specified devices.
# devices = ["sda", "sdb", "vd*"]
## Uncomment the following line if you need disk serial numbers.
# skip_serial_number = false
#
## On systems which support it, device metadata can be added in the form of
## tags.
## Currently only Linux is supported via udev properties. You can view
## available properties for a device by running:
## 'udevadm info -q property -n /dev/sda'
## Note: Most, but not all, udev properties can be accessed this way. Properties
## that are currently inaccessible include DEVTYPE, DEVNAME, and DEVPATH.
# device_tags = ["ID_FS_TYPE", "ID_FS_USAGE"]
#
## Using the same metadata source as device_tags, you can also customize the
## name of the device via templates.
## The 'name_templates' parameter is a list of templates to try and apply to
## the device. The template may contain variables in the form of '$PROPERTY' or
## '${PROPERTY}'. The first template which does not contain any variables not
## present for the device is used as the device name tag.
## The typical use case is for LVM volumes, to get the VG/LV name instead of
## the near-meaningless DM-0 name.
# name_templates = ["$ID_FS_LABEL","$DM_VG_NAME/$DM_LV_NAME"]
`, d.PluginName())
}
| influxdb/influxdb | telegraf/plugins/inputs/diskio.go | GO | mit | 1,832 |
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Task extends Model {
//
}
| voiceBits/bitz-admin | voicebitsapps/app/Task.php | PHP | mit | 98 |
# This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from datetime import timedelta
from flask import flash, redirect, request, session
from indico.core.db import db
from indico.modules.admin import RHAdminBase
from indico.modules.news import logger, news_settings
from indico.modules.news.forms import NewsForm, NewsSettingsForm
from indico.modules.news.models.news import NewsItem
from indico.modules.news.util import get_recent_news
from indico.modules.news.views import WPManageNews, WPNews
from indico.util.date_time import now_utc
from indico.util.i18n import _
from indico.web.flask.util import url_for
from indico.web.forms.base import FormDefaults
from indico.web.rh import RH
from indico.web.util import jsonify_data, jsonify_form
class RHNews(RH):
@staticmethod
def _is_new(item):
days = news_settings.get('new_days')
if not days:
return False
return item.created_dt.date() >= (now_utc() - timedelta(days=days)).date()
def _process(self):
news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all()
return WPNews.render_template('news.html', news=news, _is_new=self._is_new)
class RHNewsItem(RH):
normalize_url_spec = {
'locators': {
lambda self: self.item.locator.slugged
}
}
def _process_args(self):
self.item = NewsItem.get_or_404(request.view_args['news_id'])
def _process(self):
return WPNews.render_template('news_item.html', item=self.item)
class RHManageNewsBase(RHAdminBase):
pass
class RHManageNews(RHManageNewsBase):
def _process(self):
news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all()
return WPManageNews.render_template('admin/news.html', 'news', news=news)
class RHNewsSettings(RHManageNewsBase):
def _process(self):
form = NewsSettingsForm(obj=FormDefaults(**news_settings.get_all()))
if form.validate_on_submit():
news_settings.set_multi(form.data)
get_recent_news.clear_cached()
flash(_('Settings have been saved'), 'success')
return jsonify_data()
return jsonify_form(form)
class RHCreateNews(RHManageNewsBase):
def _process(self):
form = NewsForm()
if form.validate_on_submit():
item = NewsItem()
form.populate_obj(item)
db.session.add(item)
db.session.flush()
get_recent_news.clear_cached()
logger.info('News %r created by %s', item, session.user)
flash(_("News '{title}' has been posted").format(title=item.title), 'success')
return jsonify_data(flash=False)
return jsonify_form(form)
class RHManageNewsItemBase(RHManageNewsBase):
def _process_args(self):
RHManageNewsBase._process_args(self)
self.item = NewsItem.get_or_404(request.view_args['news_id'])
class RHEditNews(RHManageNewsItemBase):
def _process(self):
form = NewsForm(obj=self.item)
if form.validate_on_submit():
old_title = self.item.title
form.populate_obj(self.item)
db.session.flush()
get_recent_news.clear_cached()
logger.info('News %r modified by %s', self.item, session.user)
flash(_("News '{title}' has been updated").format(title=old_title), 'success')
return jsonify_data(flash=False)
return jsonify_form(form)
class RHDeleteNews(RHManageNewsItemBase):
def _process(self):
db.session.delete(self.item)
get_recent_news.clear_cached()
flash(_("News '{title}' has been deleted").format(title=self.item.title), 'success')
logger.info('News %r deleted by %r', self.item, session.user)
return redirect(url_for('news.manage'))
| pferreir/indico | indico/modules/news/controllers.py | Python | mit | 3,954 |
package swarm
import (
"testing"
"time"
ma "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"
context "github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
inet "github.com/ipfs/go-ipfs/p2p/net"
)
func TestNotifications(t *testing.T) {
ctx := context.Background()
swarms := makeSwarms(ctx, t, 5)
defer func() {
for _, s := range swarms {
s.Close()
}
}()
timeout := 5 * time.Second
// signup notifs
notifiees := make([]*netNotifiee, len(swarms))
for i, swarm := range swarms {
n := newNetNotifiee()
swarm.Notify(n)
notifiees[i] = n
}
connectSwarms(t, ctx, swarms)
<-time.After(time.Millisecond)
// should've gotten 5 by now.
// test everyone got the correct connection opened calls
for i, s := range swarms {
n := notifiees[i]
for _, s2 := range swarms {
if s == s2 {
continue
}
var actual []inet.Conn
for len(s.ConnectionsToPeer(s2.LocalPeer())) != len(actual) {
select {
case c := <-n.connected:
actual = append(actual, c)
case <-time.After(timeout):
t.Fatal("timeout")
}
}
expect := s.ConnectionsToPeer(s2.LocalPeer())
for _, c1 := range actual {
found := false
for _, c2 := range expect {
if c1 == c2 {
found = true
break
}
}
if !found {
t.Error("connection not found")
}
}
}
}
complement := func(c inet.Conn) (*Swarm, *netNotifiee, *Conn) {
for i, s := range swarms {
for _, c2 := range s.Connections() {
if c.LocalMultiaddr().Equal(c2.RemoteMultiaddr()) &&
c2.LocalMultiaddr().Equal(c.RemoteMultiaddr()) {
return s, notifiees[i], c2
}
}
}
t.Fatal("complementary conn not found", c)
return nil, nil, nil
}
testOCStream := func(n *netNotifiee, s inet.Stream) {
var s2 inet.Stream
select {
case s2 = <-n.openedStream:
t.Log("got notif for opened stream")
case <-time.After(timeout):
t.Fatal("timeout")
}
if s != s2 {
t.Fatal("got incorrect stream", s.Conn(), s2.Conn())
}
select {
case s2 = <-n.closedStream:
t.Log("got notif for closed stream")
case <-time.After(timeout):
t.Fatal("timeout")
}
if s != s2 {
t.Fatal("got incorrect stream", s.Conn(), s2.Conn())
}
}
streams := make(chan inet.Stream)
for _, s := range swarms {
s.SetStreamHandler(func(s inet.Stream) {
streams <- s
s.Close()
})
}
// open a streams in each conn
for i, s := range swarms {
for _, c := range s.Connections() {
_, n2, _ := complement(c)
st1, err := c.NewStream()
if err != nil {
t.Error(err)
} else {
st1.Write([]byte("hello"))
st1.Close()
testOCStream(notifiees[i], st1)
st2 := <-streams
testOCStream(n2, st2)
}
}
}
// close conns
for i, s := range swarms {
n := notifiees[i]
for _, c := range s.Connections() {
_, n2, c2 := complement(c)
c.Close()
c2.Close()
var c3, c4 inet.Conn
select {
case c3 = <-n.disconnected:
case <-time.After(timeout):
t.Fatal("timeout")
}
if c != c3 {
t.Fatal("got incorrect conn", c, c3)
}
select {
case c4 = <-n2.disconnected:
case <-time.After(timeout):
t.Fatal("timeout")
}
if c2 != c4 {
t.Fatal("got incorrect conn", c, c2)
}
}
}
}
type netNotifiee struct {
listen chan ma.Multiaddr
listenClose chan ma.Multiaddr
connected chan inet.Conn
disconnected chan inet.Conn
openedStream chan inet.Stream
closedStream chan inet.Stream
}
func newNetNotifiee() *netNotifiee {
return &netNotifiee{
listen: make(chan ma.Multiaddr),
listenClose: make(chan ma.Multiaddr),
connected: make(chan inet.Conn),
disconnected: make(chan inet.Conn),
openedStream: make(chan inet.Stream),
closedStream: make(chan inet.Stream),
}
}
func (nn *netNotifiee) Listen(n inet.Network, a ma.Multiaddr) {
nn.listen <- a
}
func (nn *netNotifiee) ListenClose(n inet.Network, a ma.Multiaddr) {
nn.listenClose <- a
}
func (nn *netNotifiee) Connected(n inet.Network, v inet.Conn) {
nn.connected <- v
}
func (nn *netNotifiee) Disconnected(n inet.Network, v inet.Conn) {
nn.disconnected <- v
}
func (nn *netNotifiee) OpenedStream(n inet.Network, v inet.Stream) {
nn.openedStream <- v
}
func (nn *netNotifiee) ClosedStream(n inet.Network, v inet.Stream) {
nn.closedStream <- v
}
| sbruce/go-ipfs | p2p/net/swarm/swarm_notif_test.go | GO | mit | 4,319 |
// --------------------------------------------------------------------------------------------
// <copyright file="TransformVisitor.UnionAll.cs" company="Effort Team">
// Copyright (C) 2011-2014 Effort Team
//
// 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.
// </copyright>
// --------------------------------------------------------------------------------------------
namespace Effort.Internal.DbCommandTreeTransformation
{
using System;
using System.Collections.Generic;
#if !EFOLD
using System.Data.Entity.Core.Common.CommandTrees;
#else
using System.Data.Common.CommandTrees;
#endif
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Effort.Internal.Common;
internal partial class TransformVisitor
{
public override Expression Visit(DbUnionAllExpression expression)
{
Type resultType = edmTypeConverter.Convert(expression.ResultType);
Expression left = this.Visit(expression.Left);
Expression right = this.Visit(expression.Right);
var resultElemType = TypeHelper.GetElementType(resultType);
this.UnifyCollections(resultElemType, ref left, ref right);
return queryMethodExpressionBuilder.Concat(left, right);
}
}
} | wertzui/effort | Main/Source/Effort/Internal/DbCommandTreeTransformation/TransformVisitor.UnionAll.cs | C# | mit | 2,438 |
<?php
namespace Kunstmaan\NodeSearchBundle\Helper\FormWidgets;
use Doctrine\ORM\EntityManager;
use Kunstmaan\AdminBundle\Helper\FormWidgets\FormWidget;
use Kunstmaan\NodeBundle\Entity\Node;
use Kunstmaan\NodeSearchBundle\Entity\NodeSearch;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\HttpFoundation\Request;
class SearchFormWidget extends FormWidget
{
/** @var Node */
private $node;
/** @var NodeSearch */
private $nodeSearch;
/**
* @param Node $node
* @param EntityManager $em
*/
public function __construct(Node $node, EntityManager $em)
{
$this->node = $node;
$this->nodeSearch = $em->getRepository('KunstmaanNodeSearchBundle:NodeSearch')->findOneByNode($this->node);
}
/**
* @param FormBuilderInterface $builder The form builder
*/
public function buildForm(FormBuilderInterface $builder)
{
parent::buildForm($builder);
$data = $builder->getData();
$data['node_search'] = $this->nodeSearch;
$builder->setData($data);
}
/**
* @param Request $request
*/
public function bindRequest(Request $request)
{
$form = $request->request->get('form');
$this->data['node_search'] = $form['node_search']['boost'];
}
/**
* @param EntityManager $em
*/
public function persist(EntityManager $em)
{
$nodeSearch = $em->getRepository('KunstmaanNodeSearchBundle:NodeSearch')->findOneByNode($this->node);
if ($this->data['node_search'] !== null) {
if ($nodeSearch === null) {
$nodeSearch = new NodeSearch();
$nodeSearch->setNode($this->node);
}
$nodeSearch->setBoost($this->data['node_search']);
$em->persist($nodeSearch);
}
}
}
| mwoynarski/KunstmaanBundlesCMS | src/Kunstmaan/NodeSearchBundle/Helper/FormWidgets/SearchFormWidget.php | PHP | mit | 1,850 |
using System.Reflection;
[assembly: AssemblyTitle("Rainbow")]
[assembly: AssemblyDescription("Rainbow serialization library")] | kamsar/Rainbow | src/Rainbow/Properties/AssemblyInfo.cs | C# | mit | 130 |
define(function(require, exports, module) {
var Notify = require('common/bootstrap-notify');
var FileChooser = require('../widget/file/file-chooser3');
exports.run = function() {
var $form = $("#course-material-form");
var materialChooser = new FileChooser({
element: '#material-file-chooser'
});
materialChooser.on('change', function(item) {
$form.find('[name="fileId"]').val(item.id);
});
$form.on('click', '.delete-btn', function(){
var $btn = $(this);
if (!confirm(Translator.trans('真的要删除该资料吗?'))) {
return ;
}
$.post($btn.data('url'), function(){
$btn.parents('.list-group-item').remove();
Notify.success(Translator.trans('资料已删除'));
});
});
$form.on('submit', function(){
if ($form.find('[name="fileId"]').val().length == 0) {
Notify.danger(Translator.trans('请先上传文件或添加资料网络链接!'));
return false;
}
$.post($form.attr('action'), $form.serialize(), function(html){
Notify.success(Translator.trans('资料添加成功!'));
$("#material-list").append(html).show();
$form.find('.text-warning').hide();
$form.find('[name="fileId"]').val('');
$form.find('[name="link"]').val('');
$form.find('[name="description"]').val('');
materialChooser.open();
}).fail(function(){
Notify.success(Translator.trans('资料添加失败,请重试!'));
});
return false;
});
$('.modal').on('hidden.bs.modal', function(){
window.location.reload();
});
};
}); | richtermark/SMEAGOnline | web/bundles/topxiaweb/js/controller/course-manage/material-modal.js | JavaScript | mit | 1,892 |
<?php
/**
* This makes our life easier when dealing with paths. Everything is relative
* to the application root now.
*/
chdir(dirname(__DIR__));
// Decline static file requests back to the PHP built-in webserver
if (php_sapi_name() === 'cli-server' && is_file(__DIR__ . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH))) {
return false;
}
// Setup autoloading
include 'vendor/autoload.php';
if (!defined('APPLICATION_PATH')) {
define('APPLICATION_PATH', realpath(__DIR__ . '/../'));
}
$appConfig = include APPLICATION_PATH . '/config/application.config.php';
if (file_exists(APPLICATION_PATH . '/config/development.config.php')) {
$appConfig = Zend\Stdlib\ArrayUtils::merge($appConfig, include APPLICATION_PATH . '/config/development.config.php');
}
// Run the application!
Zend\Mvc\Application::init($appConfig)->run();
| iansltx/helpwanted | public/index.php | PHP | mit | 843 |
// ---------------------------------------------------------------------------------------------
#region // Copyright (c) 2014, SIL International. All Rights Reserved.
// <copyright from='2008' to='2014' company='SIL International'>
// Copyright (c) 2014, SIL International. All Rights Reserved.
//
// Distributable under the terms of the MIT License (http://sil.mit-license.org/)
// </copyright>
#endregion
//
// This class originated in FieldWorks (under the GNU Lesser General Public License), but we
// have decided to make it avaialble in SIL.ScriptureUtils as part of Palaso so it will be more
// readily available to other projects.
// ---------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
namespace SIL.Scripture
{
/// <summary>
/// Manipulate information for standard chatper/verse schemes
/// </summary>
public class VersificationTable
{
private readonly ScrVers scrVers;
private List<int[]> bookList;
private Dictionary<string, string> toStandard;
private Dictionary<string, string> fromStandard;
private static string baseDir;
private static VersificationTable[] versifications = null;
// Names of the versificaiton files. These are in "\My Paratext Projects"
private static string[] versificationFiles = new string[] { "",
"org.vrs", "lxx.vrs", "vul.vrs", "eng.vrs", "rsc.vrs", "rso.vrs", "oth.vrs",
"oth2.vrs", "oth3.vrs", "oth4.vrs", "oth5.vrs", "oth6.vrs", "oth7.vrs", "oth8.vrs",
"oth9.vrs", "oth10.vrs", "oth11.vrs", "oth12.vrs", "oth13.vrs", "oth14.vrs",
"oth15.vrs", "oth16.vrs", "oth17.vrs", "oth18.vrs", "oth19.vrs", "oth20.vrs",
"oth21.vrs", "oth22.vrs", "oth23.vrs", "oth24.vrs" };
/// ------------------------------------------------------------------------------------
/// <summary>
/// This method should be called once before an application accesses anything that
/// requires versification info.
/// TODO: Paratext needs to call this with ScrTextCollection.SettingsDirectory.
/// </summary>
/// <param name="vrsFolder">Path to the folder containing the .vrs files</param>
/// ------------------------------------------------------------------------------------
public static void Initialize(string vrsFolder)
{
baseDir = vrsFolder;
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Get the versification table for this versification
/// </summary>
/// <param name="vers"></param>
/// <returns></returns>
/// ------------------------------------------------------------------------------------
public static VersificationTable Get(ScrVers vers)
{
Debug.Assert(vers != ScrVers.Unknown);
if (versifications == null)
versifications = new VersificationTable[versificationFiles.GetUpperBound(0)];
// Read versification table if not already read
if (versifications[(int)vers] == null)
{
versifications[(int)vers] = new VersificationTable(vers);
ReadVersificationFile(FileName(vers), versifications[(int)vers]);
}
return versifications[(int)vers];
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Read versification file and "add" its entries.
/// At the moment we only do this once. Eventually we will call this twice.
/// Once for the standard versification, once for custom entries in versification.vrs
/// file for this project.
/// </summary>
/// <param name="fileName"></param>
/// <param name="versification"></param>
/// ------------------------------------------------------------------------------------
private static void ReadVersificationFile(string fileName, VersificationTable versification)
{
using (TextReader reader = new StreamReader(fileName))
{
for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
{
line = line.Trim();
if (line == "" || line[0] == '#')
continue;
if (line.Contains("="))
ParseMappingLine(fileName, versification, line);
else
ParseChapterVerseLine(fileName, versification, line);
}
}
}
// Parse lines mapping from this versification to standard versification
// GEN 1:10 = GEN 2:11
// GEN 1:10-13 = GEN 2:11-14
private static void ParseChapterVerseLine(string fileName, VersificationTable versification, string line)
{
string[] parts = line.Split(' ');
int bookNum = BCVRef.BookToNumber(parts[0]);
if (bookNum == -1)
return; // Deuterocanonical books not supported
if (bookNum == 0)
throw new Exception("Invalid [" + parts[0] + "] " + fileName);
while (versification.bookList.Count < bookNum)
versification.bookList.Add(new int[1] { 1 });
List<int> verses = new List<int>();
for (int i = 1; i <= parts.GetUpperBound(0); ++i)
{
string[] pieces = parts[i].Split(':');
int verseCount;
if (pieces.GetUpperBound(0) != 1 ||
!int.TryParse(pieces[1], out verseCount) || verseCount <= 0)
{
throw new Exception("Invalid [" + line + "] " + fileName);
}
verses.Add(verseCount);
}
versification.bookList[bookNum - 1] = verses.ToArray();
}
// Parse lines giving number of verses for each chapter like
// GEN 1:10 2:23 ...
private static void ParseMappingLine(string fileName, VersificationTable versification, string line)
{
try
{
string[] parts = line.Split('=');
string[] leftPieces = parts[0].Trim().Split('-');
string[] rightPieces = parts[1].Trim().Split('-');
BCVRef left = new BCVRef(leftPieces[0]);
int leftLimit = leftPieces.GetUpperBound(0) == 0 ? 0 : int.Parse(leftPieces[1]);
BCVRef right = new BCVRef(rightPieces[0]);
while (true)
{
versification.toStandard[left.ToString()] = right.ToString();
versification.fromStandard[right.ToString()] = left.ToString();
if (left.Verse >= leftLimit)
break;
left.Verse = left.Verse + 1;
right.Verse = right.Verse + 1;
}
}
catch
{
// ENHANCE: Make it so the TE version of Localizer can have its own resources for stuff
// like this.
throw new Exception("Invalid [" + line + "] " + fileName);
}
}
/// <summary>
/// Gets the name of this requested versification file.
/// </summary>
/// <param name="vers">Versification scheme</param>
public static string GetFileNameForVersification(ScrVers vers)
{
return versificationFiles[(int)vers];
}
// Get path of this versification file.
// Fall back to eng.vrs if not present.
private static string FileName(ScrVers vers)
{
if (baseDir == null)
throw new InvalidOperationException("VersificationTable.Initialize must be called first");
string fileName = Path.Combine(baseDir, GetFileNameForVersification(vers));
if (!File.Exists(fileName))
fileName = Path.Combine(baseDir, GetFileNameForVersification(ScrVers.English));
return fileName;
}
// Create empty versification table
private VersificationTable(ScrVers vers)
{
this.scrVers = vers;
bookList = new List<int[]>();
toStandard = new Dictionary<string, string>();
fromStandard = new Dictionary<string, string>();
}
public int LastBook()
{
return bookList.Count;
}
/// <summary>
/// Last chapter number in this book.
/// </summary>
/// <param name="bookNum"></param>
/// <returns></returns>
public int LastChapter(int bookNum)
{
if (bookNum <= 0)
return 0;
if (bookNum - 1 >= bookList.Count)
return 1;
int[] chapters = bookList[bookNum - 1];
return chapters.GetUpperBound(0) + 1;
}
/// <summary>
/// Last verse number in this book/chapter.
/// </summary>
/// <param name="bookNum"></param>
/// <param name="chapterNum"></param>
/// <returns></returns>
public int LastVerse(int bookNum, int chapterNum)
{
if (bookNum <= 0)
return 0;
if (bookNum - 1 >= bookList.Count)
return 1;
int[] chapters = bookList[bookNum - 1];
// Chapter "0" is the intro material. Pretend that it has 1 verse.
if (chapterNum - 1 > chapters.GetUpperBound(0) || chapterNum < 1)
return 1;
return chapters[chapterNum - 1];
}
/// <summary>
/// Change the passed VerseRef to be this versification.
/// </summary>
/// <param name="vref"></param>
public void ChangeVersification(IVerseReference vref)
{
if (vref.Versification == scrVers)
return;
// Map from existing to standard versification
string verse = vref.ToString();
string verse2;
Get(vref.Versification).toStandard.TryGetValue(verse, out verse2);
if (verse2 == null)
verse2 = verse;
// Map from standard versification to this versification
string verse3;
fromStandard.TryGetValue(verse2, out verse3);
if (verse3 == null)
verse3 = verse2;
// If verse has changed, parse new value
if (verse != verse3)
vref.Parse(verse3);
vref.Versification = scrVers;
}
}
}
| mccarthyrb/libpalaso | SIL.Scripture/VersificationTable.cs | C# | mit | 9,031 |
require 'sprockets/autoload'
require 'sprockets/path_utils'
module Sprockets
class BabelProcessor
VERSION = '1'
def self.instance
@instance ||= new
end
def self.call(input)
instance.call(input)
end
def initialize(options = {})
@options = options.merge({
'blacklist' => (options['blacklist'] || []) + ['useStrict'],
'sourceMap' => false
}).freeze
@cache_key = [
self.class.name,
Autoload::Babel::Transpiler::VERSION,
Autoload::Babel::Source::VERSION,
VERSION,
@options
].freeze
end
def call(input)
data = input[:data]
result = input[:cache].fetch(@cache_key + [data]) do
Autoload::Babel::Transpiler.transform(data, @options.merge(
'sourceRoot' => input[:load_path],
'moduleRoot' => '',
'filename' => input[:filename],
'filenameRelative' => PathUtils.split_subpath(input[:load_path], input[:filename])
))
end
result['code']
end
end
end
| Andreis13/sprockets | lib/sprockets/babel_processor.rb | Ruby | mit | 1,054 |
'use strict';
const EventEmitter = require('events');
const uuid = require('node-uuid');
const ItemType = require('./ItemType');
const { Inventory, InventoryFullError } = require('./Inventory');
const Logger = require('./Logger');
const Player = require('./Player');
/**
* @property {Area} area Area the item belongs to (warning: this is not the area is currently in but the
* area it belongs to on a fresh load)
* @property {object} properties Essentially a blob of whatever attrs the item designer wanted to add
* @property {array|string} behaviors Single or list of behaviors this object uses
* @property {string} description Long description seen when looking at it
* @property {number} id vnum
* @property {boolean} isEquipped Whether or not item is currently equipped
* @property {Map} inventory Current items this item contains
* @property {string} name Name shown in inventory and when equipped
* @property {Room} room Room the item is currently in
* @property {string} roomDesc Description shown when item is seen in a room
* @property {string} script A custom script for this item
* @property {ItemType|string} type
* @property {string} uuid UUID differentiating all instances of this item
*/
class Item extends EventEmitter {
constructor (area, item) {
super();
const validate = ['keywords', 'name', 'id'];
for (const prop of validate) {
if (!(prop in item)) {
throw new ReferenceError(`Item in area [${area.name}] missing required property [${prop}]`);
}
}
this.area = area;
this.properties = item.properties || {};
this.behaviors = item.behaviors || {};
this.defaultItems = item.items || [];
this.description = item.description || 'Nothing special.';
this.entityReference = item.entityReference; // EntityFactory key
this.id = item.id;
this.maxItems = item.maxItems || Infinity;
this.inventory = item.inventory ? new Inventory(item.inventory) : null;
if (this.inventory) {
this.inventory.setMax(this.maxItems);
}
this.isEquipped = item.isEquipped || false;
this.keywords = item.keywords;
this.level = item.level || 1;
this.itemLevel = item.itemLevel || this.level;
this.name = item.name;
this.quality = item.quality || 'common';
this.room = item.room || null;
this.roomDesc = item.roomDesc || '';
this.script = item.script || null;
this.slot = item.slot || null;
this.type = typeof item.type === 'string' ? ItemType[item.type] : (item.type || ItemType.OBJECT);
this.uuid = item.uuid || uuid.v4();
}
hasKeyword(keyword) {
return this.keywords.indexOf(keyword) !== -1;
}
/**
* @param {string} name
* @return {boolean}
*/
hasBehavior(name) {
if (!(this.behaviors instanceof Map)) {
throw new Error("Item has not been hydrated. Cannot access behaviors.");
}
return this.behaviors.has(name);
}
/**
* @param {string} name
* @return {*}
*/
getBehavior(name) {
if (!(this.behaviors instanceof Map)) {
throw new Error("Item has not been hydrated. Cannot access behaviors.");
}
return this.behaviors.get(name);
}
addItem(item) {
this._setupInventory();
this.inventory.addItem(item);
item.belongsTo = this;
}
removeItem(item) {
this.inventory.removeItem(item);
// if we removed the last item unset the inventory
// This ensures that when it's reloaded it won't try to set
// its default inventory. Instead it will persist the fact
// that all the items were removed from it
if (!this.inventory.size) {
this.inventory = null;
}
item.belongsTo = null;
}
isInventoryFull() {
this._setupInventory();
return this.inventory.isFull;
}
_setupInventory() {
if (!this.inventory) {
this.inventory = new Inventory({
items: [],
max: this.maxItems
});
}
}
get qualityColors() {
return ({
poor: ['bold', 'black'],
common: ['bold', 'white'],
uncommon: ['bold', 'green'],
rare: ['bold', 'blue'],
epic: ['bold', 'magenta'],
legendary: ['bold', 'red'],
artifact: ['yellow'],
})[this.quality];
}
/**
* Friendly display colorized by quality
*/
get display() {
return this.qualityColorize(`[${this.name}]`);
}
/**
* Colorize the given string according to this item's quality
* @param {string} string
* @return string
*/
qualityColorize(string) {
const colors = this.qualityColors;
const open = '<' + colors.join('><') + '>';
const close = '</' + colors.reverse().join('></') + '>';
return open + string + close;
}
/**
* For finding the player who has the item in their possession.
* @return {Player|null} owner
*/
findOwner() {
let found = null;
let owner = this.belongsTo;
while (owner) {
if (owner instanceof Player) {
found = owner;
break;
}
owner = owner.belongsTo;
}
return found;
}
hydrate(state, serialized = {}) {
if (typeof this.area === 'string') {
this.area = state.AreaManager.getArea(this.area);
}
// if the item was saved with a custom inventory hydrate it
if (this.inventory) {
this.inventory.hydrate(state);
} else {
// otherwise load its default inv
this.defaultItems.forEach(defaultItemId => {
Logger.verbose(`\tDIST: Adding item [${defaultItemId}] to item [${this.name}]`);
const newItem = state.ItemFactory.create(this.area, defaultItemId);
newItem.hydrate(state);
state.ItemManager.add(newItem);
this.addItem(newItem);
});
}
// perform deep copy if behaviors is set to prevent sharing of the object between
// item instances
const behaviors = JSON.parse(JSON.stringify(serialized.behaviors || this.behaviors));
this.behaviors = new Map(Object.entries(behaviors));
for (let [behaviorName, config] of this.behaviors) {
let behavior = state.ItemBehaviorManager.get(behaviorName);
if (!behavior) {
return;
}
// behavior may be a boolean in which case it will be `behaviorName: true`
config = config === true ? {} : config;
behavior.attach(this, config);
}
}
serialize() {
let behaviors = {};
for (const [key, val] of this.behaviors) {
behaviors[key] = val;
}
return {
entityReference: this.entityReference,
inventory: this.inventory && this.inventory.serialize(),
// behaviors are serialized in case their config was modified during gameplay
// and that state needs to persist (charges of a scroll remaining, etc)
behaviors,
};
}
}
module.exports = Item;
| CodeOtter/tech-career | src/Item.js | JavaScript | mit | 6,892 |
using System;
using System.Collections.Generic;
using Foundation.ObjectHydrator.Interfaces;
namespace Foundation.ObjectHydrator.Generators
{
public class UnitedKingdomCityGenerator : IGenerator<string>
{
private readonly Random _random;
private IList<string> _citynames = new List<string>();
public UnitedKingdomCityGenerator()
{
_random = RandomSingleton.Instance.Random;
LoadCityNames();
}
private void LoadCityNames()
{
_citynames = new List<string>()
{
"Aberaeron",
"Aberdare",
"Aberdeen",
"Aberfeldy",
"Abergavenny",
"Abergele",
"Abertillery",
"Aberystwyth",
"Abingdon",
"Accrington",
"Adlington",
"Airdrie",
"Alcester",
"Aldeburgh",
"Aldershot",
"Aldridge",
"Alford",
"Alfreton",
"Alloa",
"Alnwick",
"Alsager",
"Alston",
"Amesbury",
"Amlwch",
"Ammanford",
"Ampthill",
"Andover",
"Annan",
"Antrim",
"Appleby in Westmorland",
"Arbroath",
"Armagh",
"Arundel",
"Ashbourne",
"Ashburton",
"Ashby de la Zouch",
"Ashford",
"Ashington",
"Ashton in Makerfield",
"Atherstone",
"Auchtermuchty",
"Axminster",
"Aylesbury",
"Aylsham",
"Ayr",
"Bacup",
"Bakewell",
"Bala",
"Ballater",
"Ballycastle",
"Ballyclare",
"Ballymena",
"Ballymoney",
"Ballynahinch",
"Banbridge",
"Banbury",
"Banchory",
"Banff",
"Bangor",
"Barmouth",
"Barnard Castle",
"Barnet",
"Barnoldswick",
"Barnsley",
"Barnstaple",
"Barrhead",
"Barrow in Furness",
"Barry",
"Barton upon Humber",
"Basildon",
"Basingstoke",
"Bath",
"Bathgate",
"Batley",
"Battle",
"Bawtry",
"Beaconsfield",
"Bearsden",
"Beaumaris",
"Bebington",
"Beccles",
"Bedale",
"Bedford",
"Bedlington",
"Bedworth",
"Beeston",
"Bellshill",
"Belper",
"Berkhamsted",
"Berwick upon Tweed",
"Betws y Coed",
"Beverley",
"Bewdley",
"Bexhill on Sea",
"Bicester",
"Biddulph",
"Bideford",
"Biggar",
"Biggleswade",
"Billericay",
"Bilston",
"Bingham",
"Birkenhead",
"Birmingham",
"Bishop Auckland",
"Blackburn",
"Blackheath",
"Blackpool",
"Blaenau Ffestiniog",
"Blandford Forum",
"Bletchley",
"Bloxwich",
"Blyth",
"Bodmin",
"Bognor Regis",
"Bollington",
"Bolsover",
"Bolton",
"Bootle",
"Borehamwood",
"Boston",
"Bourne",
"Bournemouth",
"Brackley",
"Bracknell",
"Bradford",
"Bradford on Avon",
"Brading",
"Bradley Stoke",
"Bradninch",
"Braintree",
"Brechin",
"Brecon",
"Brentwood",
"Bridge of Allan",
"Bridgend",
"Bridgnorth",
"Bridgwater",
"Bridlington",
"Bridport",
"Brigg",
"Brighouse",
"Brightlingsea",
"Brighton",
"Bristol",
"Brixham",
"Broadstairs",
"Bromsgrove",
"Bromyard",
"Brynmawr",
"Buckfastleigh",
"Buckie",
"Buckingham",
"Buckley",
"Bude",
"Budleigh Salterton",
"Builth Wells",
"Bungay",
"Buntingford",
"Burford",
"Burgess Hill",
"Burnham on Crouch",
"Burnham on Sea",
"Burnley",
"Burntisland",
"Burntwood",
"Burry Port",
"Burton Latimer",
"Bury",
"Bushmills",
"Buxton",
"Caernarfon",
"Caerphilly",
"Caistor",
"Caldicot",
"Callander",
"Calne",
"Camberley",
"Camborne",
"Cambridge",
"Camelford",
"Campbeltown",
"Cannock",
"Canterbury",
"Cardiff",
"Cardigan",
"Carlisle",
"Carluke",
"Carmarthen",
"Carnforth",
"Carnoustie",
"Carrickfergus",
"Carterton",
"Castle Douglas",
"Castlederg",
"Castleford",
"Castlewellan",
"Chard",
"Charlbury",
"Chatham",
"Chatteris",
"Chelmsford",
"Cheltenham",
"Chepstow",
"Chesham",
"Cheshunt",
"Chester",
"Chester le Street",
"Chesterfield",
"Chichester",
"Chippenham",
"Chipping Campden",
"Chipping Norton",
"Chipping Sodbury",
"Chorley",
"Christchurch",
"Church Stretton",
"Cinderford",
"Cirencester",
"Clacton on Sea",
"Cleckheaton",
"Cleethorpes",
"Clevedon",
"Clitheroe",
"Clogher",
"Clydebank",
"Coalisland",
"Coalville",
"Coatbridge",
"Cockermouth",
"Coggeshall",
"Colchester",
"Coldstream",
"Coleraine",
"Coleshill",
"Colne",
"Colwyn Bay",
"Comber",
"Congleton",
"Conwy",
"Cookstown",
"Corbridge",
"Corby",
"Coventry",
"Cowbridge",
"Cowdenbeath",
"Cowes",
"Craigavon",
"Cramlington",
"Crawley",
"Crayford",
"Crediton",
"Crewe",
"Crewkerne",
"Criccieth",
"Crickhowell",
"Crieff",
"Cromarty",
"Cromer",
"Crowborough",
"Crowthorne",
"Crumlin",
"Cuckfield",
"Cullen",
"Cullompton",
"Cumbernauld",
"Cupar",
"Cwmbran",
"Dalbeattie",
"Dalkeith",
"Darlington",
"Dartford",
"Dartmouth",
"Darwen",
"Daventry",
"Dawlish",
"Deal",
"Denbigh",
"Denton",
"Derby",
"Dereham",
"Devizes",
"Dewsbury",
"Didcot",
"Dingwall",
"Dinnington",
"Diss",
"Dolgellau",
"Donaghadee",
"Doncaster",
"Dorchester",
"Dorking",
"Dornoch",
"Dover",
"Downham Market",
"Downpatrick",
"Driffield",
"Dronfield",
"Droylsden",
"Dudley",
"Dufftown",
"Dukinfield",
"Dumbarton",
"Dumfries",
"Dunbar",
"Dunblane",
"Dundee",
"Dunfermline",
"Dungannon",
"Dunoon",
"Duns",
"Dunstable",
"Durham",
"Dursley",
"Easingwold",
"East Grinstead",
"East Kilbride",
"Eastbourne",
"Eastleigh",
"Eastwood",
"Ebbw Vale",
"Edenbridge",
"Edinburgh",
"Egham",
"Elgin",
"Ellesmere",
"Ellesmere Port",
"Ely",
"Enniskillen",
"Epping",
"Epsom",
"Erith",
"Esher",
"Evesham",
"Exeter",
"Exmouth",
"Eye",
"Eyemouth",
"Failsworth",
"Fairford",
"Fakenham",
"Falkirk",
"Falkland",
"Falmouth",
"Fareham",
"Faringdon",
"Farnborough",
"Farnham",
"Farnworth",
"Faversham",
"Felixstowe",
"Ferndown",
"Filey",
"Fintona",
"Fishguard",
"Fivemiletown",
"Fleet",
"Fleetwood",
"Flint",
"Flitwick",
"Folkestone",
"Fordingbridge",
"Forfar",
"Forres",
"Fort William",
"Fowey",
"Framlingham",
"Fraserburgh",
"Frodsham",
"Frome",
"Gainsborough",
"Galashiels",
"Gateshead",
"Gillingham",
"Glasgow",
"Glastonbury",
"Glossop",
"Gloucester",
"Godalming",
"Godmanchester",
"Goole",
"Gorseinon",
"Gosport",
"Gourock",
"Grange over Sands",
"Grangemouth",
"Grantham",
"Grantown on Spey",
"Gravesend",
"Grays",
"Great Yarmouth",
"Greenock",
"Grimsby",
"Guildford",
"Haddington",
"Hadleigh",
"Hailsham",
"Halesowen",
"Halesworth",
"Halifax",
"Halstead",
"Haltwhistle",
"Hamilton",
"Harlow",
"Harpenden",
"Harrogate",
"Hartlepool",
"Harwich",
"Haslemere",
"Hastings",
"Hatfield",
"Havant",
"Haverfordwest",
"Haverhill",
"Hawarden",
"Hawick",
"Hay on Wye",
"Hayle",
"Haywards Heath",
"Heanor",
"Heathfield",
"Hebden Bridge",
"Helensburgh",
"Helston",
"Hemel Hempstead",
"Henley on Thames",
"Hereford",
"Herne Bay",
"Hertford",
"Hessle",
"Heswall",
"Hexham",
"High Wycombe",
"Higham Ferrers",
"Highworth",
"Hinckley",
"Hitchin",
"Hoddesdon",
"Holmfirth",
"Holsworthy",
"Holyhead",
"Holywell",
"Honiton",
"Horley",
"Horncastle",
"Hornsea",
"Horsham",
"Horwich",
"Houghton le Spring",
"Hove",
"Howden",
"Hoylake",
"Hucknall",
"Huddersfield",
"Hungerford",
"Hunstanton",
"Huntingdon",
"Huntly",
"Hyde",
"Hythe",
"Ilford",
"Ilfracombe",
"Ilkeston",
"Ilkley",
"Ilminster",
"Innerleithen",
"Inveraray",
"Inverkeithing",
"Inverness",
"Inverurie",
"Ipswich",
"Irthlingborough",
"Irvine",
"Ivybridge",
"Jarrow",
"Jedburgh",
"Johnstone",
"Keighley",
"Keith",
"Kelso",
"Kempston",
"Kendal",
"Kenilworth",
"Kesgrave",
"Keswick",
"Kettering",
"Keynsham",
"Kidderminster",
"Kilbarchan",
"Kilkeel",
"Killyleagh",
"Kilmarnock",
"Kilwinning",
"Kinghorn",
"Kingsbridge",
"Kington",
"Kingussie",
"Kinross",
"Kintore",
"Kirkby",
"Kirkby Lonsdale",
"Kirkcaldy",
"Kirkcudbright",
"Kirkham",
"Kirkwall",
"Kirriemuir",
"Knaresborough",
"Knighton",
"Knutsford",
"Ladybank",
"Lampeter",
"Lanark",
"Lancaster",
"Langholm",
"Largs",
"Larne",
"Laugharne",
"Launceston",
"Laurencekirk",
"Leamington Spa",
"Leatherhead",
"Ledbury",
"Leeds",
"Leek",
"Leicester",
"Leighton Buzzard",
"Leiston",
"Leominster",
"Lerwick",
"Letchworth",
"Leven",
"Lewes",
"Leyland",
"Lichfield",
"Limavady",
"Lincoln",
"Linlithgow",
"Lisburn",
"Liskeard",
"Lisnaskea",
"Littlehampton",
"Liverpool",
"Llandeilo",
"Llandovery",
"Llandrindod Wells",
"Llandudno",
"Llanelli",
"Llanfyllin",
"Llangollen",
"Llanidloes",
"Llanrwst",
"Llantrisant",
"Llantwit Major",
"Llanwrtyd Wells",
"Loanhead",
"Lochgilphead",
"Lockerbie",
"Londonderry",
"Long Eaton",
"Longridge",
"Looe",
"Lossiemouth",
"Lostwithiel",
"Loughborough",
"Loughton",
"Louth",
"Lowestoft",
"Ludlow",
"Lurgan",
"Luton",
"Lutterworth",
"Lydd",
"Lydney",
"Lyme Regis",
"Lymington",
"Lynton",
"Mablethorpe",
"Macclesfield",
"Machynlleth",
"Maesteg",
"Magherafelt",
"Maidenhead",
"Maidstone",
"Maldon",
"Malmesbury",
"Malton",
"Malvern",
"Manchester",
"Manningtree",
"Mansfield",
"March",
"Margate",
"Market Deeping",
"Market Drayton",
"Market Harborough",
"Market Rasen",
"Market Weighton",
"Markethill",
"Markinch",
"Marlborough",
"Marlow",
"Maryport",
"Matlock",
"Maybole",
"Melksham",
"Melrose",
"Melton Mowbray",
"Merthyr Tydfil",
"Mexborough",
"Middleham",
"Middlesbrough",
"Middlewich",
"Midhurst",
"Midsomer Norton",
"Milford Haven",
"Milngavie",
"Milton Keynes",
"Minehead",
"Moffat",
"Mold",
"Monifieth",
"Monmouth",
"Montgomery",
"Montrose",
"Morecambe",
"Moreton in Marsh",
"Moretonhampstead",
"Morley",
"Morpeth",
"Motherwell",
"Musselburgh",
"Nailsea",
"Nailsworth",
"Nairn",
"Nantwich",
"Narberth",
"Neath",
"Needham Market",
"Neston",
"New Mills",
"New Milton",
"Newbury",
"Newcastle",
"Newcastle Emlyn",
"Newcastle upon Tyne",
"Newent",
"Newhaven",
"Newmarket",
"Newport",
"Newport Pagnell",
"Newport on Tay",
"Newquay",
"Newry",
"Newton Abbot",
"Newton Aycliffe",
"Newton Stewart",
"Newton le Willows",
"Newtown",
"Newtownabbey",
"Newtownards",
"Normanton",
"North Berwick",
"North Walsham",
"Northallerton",
"Northampton",
"Northwich",
"Norwich",
"Nottingham",
"Nuneaton",
"Oakham",
"Oban",
"Okehampton",
"Oldbury",
"Oldham",
"Oldmeldrum",
"Olney",
"Omagh",
"Ormskirk",
"Orpington",
"Ossett",
"Oswestry",
"Otley",
"Oundle",
"Oxford",
"Padstow",
"Paignton",
"Painswick",
"Paisley",
"Peebles",
"Pembroke",
"Penarth",
"Penicuik",
"Penistone",
"Penmaenmawr",
"Penrith",
"Penryn",
"Penzance",
"Pershore",
"Perth",
"Peterborough",
"Peterhead",
"Peterlee",
"Petersfield",
"Petworth",
"Pickering",
"Pitlochry",
"Pittenweem",
"Plymouth",
"Pocklington",
"Polegate",
"Pontefract",
"Pontypridd",
"Poole",
"Port Talbot",
"Portadown",
"Portaferry",
"Porth",
"Porthcawl",
"Porthmadog",
"Portishead",
"Portrush",
"Portsmouth",
"Portstewart",
"Potters Bar",
"Potton",
"Poulton le Fylde",
"Prescot",
"Prestatyn",
"Presteigne",
"Preston",
"Prestwick",
"Princes Risborough",
"Prudhoe",
"Pudsey",
"Pwllheli",
"Ramsgate",
"Randalstown",
"Rayleigh",
"Reading",
"Redcar",
"Redditch",
"Redhill",
"Redruth",
"Reigate",
"Retford",
"Rhayader",
"Rhuddlan",
"Rhyl",
"Richmond",
"Rickmansworth",
"Ringwood",
"Ripley",
"Ripon",
"Rochdale",
"Rochester",
"Rochford",
"Romford",
"Romsey",
"Ross on Wye",
"Rostrevor",
"Rothbury",
"Rotherham",
"Rothesay",
"Rowley Regis",
"Royston",
"Rugby",
"Rugeley",
"Runcorn",
"Rushden",
"Rutherglen",
"Ruthin",
"Ryde",
"Rye",
"Saffron Walden",
"Saintfield",
"Salcombe",
"Sale",
"Salford",
"Salisbury",
"Saltash",
"Saltcoats",
"Sandbach",
"Sandhurst",
"Sandown",
"Sandwich",
"Sandy",
"Sawbridgeworth",
"Saxmundham",
"Scarborough",
"Scunthorpe",
"Seaford",
"Seaton",
"Sedgefield",
"Selby",
"Selkirk",
"Selsey",
"Settle",
"Sevenoaks",
"Shaftesbury",
"Shanklin",
"Sheerness",
"Sheffield",
"Shepshed",
"Shepton Mallet",
"Sherborne",
"Sheringham",
"Shildon",
"Shipston on Stour",
"Shoreham by Sea",
"Shrewsbury",
"Sidmouth",
"Sittingbourne",
"Skegness",
"Skelmersdale",
"Skipton",
"Sleaford",
"Slough",
"Smethwick",
"Soham",
"Solihull",
"Somerton",
"South Molton",
"South Shields",
"South Woodham Ferrers",
"Southam",
"Southampton",
"Southborough",
"Southend on Sea",
"Southport",
"Southsea",
"Southwell",
"Southwold",
"Spalding",
"Spennymoor",
"Spilsby",
"Stafford",
"Staines",
"Stamford",
"Stanley",
"Staveley",
"Stevenage",
"Stirling",
"Stockport",
"Stockton on Tees",
"Stoke on Trent",
"Stone",
"Stowmarket",
"Strabane",
"Stranraer",
"Stratford upon Avon",
"Strood",
"Stroud",
"Sudbury",
"Sunderland",
"Sutton Coldfield",
"Sutton in Ashfield",
"Swadlincote",
"Swanage",
"Swanley",
"Swansea",
"Swindon",
"Tadcaster",
"Tadley",
"Tain",
"Talgarth",
"Tamworth",
"Taunton",
"Tavistock",
"Teignmouth",
"Telford",
"Tenby",
"Tenterden",
"Tetbury",
"Tewkesbury",
"Thame",
"Thatcham",
"Thaxted",
"Thetford",
"Thirsk",
"Thornbury",
"Thrapston",
"Thurso",
"Tilbury",
"Tillicoultry",
"Tipton",
"Tiverton",
"Tobermory",
"Todmorden",
"Tonbridge",
"Torpoint",
"Torquay",
"Totnes",
"Totton",
"Towcester",
"Tredegar",
"Tregaron",
"Tring",
"Troon",
"Trowbridge",
"Truro",
"Tunbridge Wells",
"Tywyn",
"Uckfield",
"Ulverston",
"Uppingham",
"Usk",
"Uttoxeter",
"Ventnor",
"Verwood",
"Wadebridge",
"Wadhurst",
"Wakefield",
"Wallasey",
"Wallingford",
"Walsall",
"Waltham Abbey",
"Waltham Cross",
"Walton on Thames",
"Walton on the Naze",
"Wantage",
"Ware",
"Wareham",
"Warminster",
"Warrenpoint",
"Warrington",
"Warwick",
"Washington",
"Watford",
"Wednesbury",
"Wednesfield",
"Wellingborough",
"Wellington",
"Wells",
"Wells next the Sea",
"Welshpool",
"Welwyn Garden City",
"Wem",
"Wendover",
"West Bromwich",
"Westbury",
"Westerham",
"Westhoughton",
"Weston super Mare",
"Wetherby",
"Weybridge",
"Weymouth",
"Whaley Bridge",
"Whitby",
"Whitchurch",
"Whitehaven",
"Whitley Bay",
"Whitnash",
"Whitstable",
"Whitworth",
"Wick",
"Wickford",
"Widnes",
"Wigan",
"Wigston",
"Wigtown",
"Willenhall",
"Wincanton",
"Winchester",
"Windermere",
"Winsford",
"Winslow",
"Wisbech",
"Witham",
"Withernsea",
"Witney",
"Woburn",
"Woking",
"Wokingham",
"Wolverhampton",
"Wombwell",
"Woodbridge",
"Woodstock",
"Wootton Bassett",
"Worcester",
"Workington",
"Worksop",
"Worthing",
"Wotton under Edge",
"Wrexham",
"Wymondham",
"Yarm",
"Yarmouth",
"Yate",
"Yateley",
"Yeadon",
"Yeovil",
"York"
};
}
public string Generate()
{
return _citynames[_random.Next(0, _citynames.Count)];
}
}
} | flightlog/flsserver | src/ObjectHydrator-master/Foundation.ObjectHydrator/Generators/UnitedKingdomCityGenerator.cs | C# | mit | 29,362 |
var JobsList = React.createClass({displayName: "JobsList",
render: function() {
return (
React.createElement(JobItem, {title: "Trabalho Python", desc: "Descricao aqui"})
);
}
});
var JobItem = React.createClass({displayName: "JobItem",
render: function() {
React.createElement("div", {className: "panel panel-default"},
React.createElement("div", {className: "panel-heading"}, this.params.job.title),
React.createElement("div", {className: "panel-body"},
this.params.job.desc
)
)
}
}) | raonyguimaraes/pyjobs | pyjobs/web/static/js/.module-cache/4ae00001aee8e40f0fb90fff1d2d3b85d7f734e2.js | JavaScript | mit | 600 |
/*
* @package jsDAV
* @subpackage CardDAV
* @copyright Copyright(c) 2013 Mike de Boer. <info AT mikedeboer DOT nl>
* @author Mike de Boer <info AT mikedeboer DOT nl>
* @license http://github.com/mikedeboer/jsDAV/blob/master/LICENSE MIT License
*/
"use strict";
var jsDAV_Plugin = require("./../DAV/plugin");
var jsDAV_Property_Href = require("./../DAV/property/href");
var jsDAV_Property_HrefList = require("./../DAV/property/hrefList");
var jsDAV_Property_iHref = require("./../DAV/interfaces/iHref");
var jsCardDAV_iAddressBook = require("./interfaces/iAddressBook");
var jsCardDAV_iCard = require("./interfaces/iCard");
var jsCardDAV_iDirectory = require("./interfaces/iDirectory");
var jsCardDAV_UserAddressBooks = require("./userAddressBooks");
var jsCardDAV_AddressBookQueryParser = require("./addressBookQueryParser");
var jsDAVACL_iPrincipal = require("./../DAVACL/interfaces/iPrincipal");
var jsVObject_Reader = require("./../VObject/reader");
var AsyncEventEmitter = require("./../shared/asyncEvents").EventEmitter;
var Exc = require("./../shared/exceptions");
var Util = require("./../shared/util");
var Xml = require("./../shared/xml");
var Async = require("asyncjs");
/**
* CardDAV plugin
*
* The CardDAV plugin adds CardDAV functionality to the WebDAV server
*/
var jsCardDAV_Plugin = module.exports = jsDAV_Plugin.extend({
/**
* Plugin name
*
* @var String
*/
name: "carddav",
/**
* Url to the addressbooks
*/
ADDRESSBOOK_ROOT: "addressbooks",
/**
* xml namespace for CardDAV elements
*/
NS_CARDDAV: "urn:ietf:params:xml:ns:carddav",
/**
* Add urls to this property to have them automatically exposed as
* 'directories' to the user.
*
* @var array
*/
directories: null,
/**
* Handler class
*
* @var jsDAV_Handler
*/
handler: null,
/**
* Initializes the plugin
*
* @param DAV\Server server
* @return void
*/
initialize: function(handler) {
this.directories = [];
// Events
handler.addEventListener("beforeGetProperties", this.beforeGetProperties.bind(this));
handler.addEventListener("afterGetProperties", this.afterGetProperties.bind(this));
handler.addEventListener("updateProperties", this.updateProperties.bind(this));
handler.addEventListener("report", this.report.bind(this));
handler.addEventListener("onHTMLActionsPanel", this.htmlActionsPanel.bind(this), AsyncEventEmitter.PRIO_HIGH);
handler.addEventListener("onBrowserPostAction", this.browserPostAction.bind(this), AsyncEventEmitter.PRIO_HIGH);
handler.addEventListener("beforeWriteContent", this.beforeWriteContent.bind(this));
handler.addEventListener("beforeCreateFile", this.beforeCreateFile.bind(this));
// Namespaces
Xml.xmlNamespaces[this.NS_CARDDAV] = "card";
// Mapping Interfaces to {DAV:}resourcetype values
handler.resourceTypeMapping["{" + this.NS_CARDDAV + "}addressbook"] = jsCardDAV_iAddressBook;
handler.resourceTypeMapping["{" + this.NS_CARDDAV + "}directory"] = jsCardDAV_iDirectory;
// Adding properties that may never be changed
handler.protectedProperties.push(
"{" + this.NS_CARDDAV + "}supported-address-data",
"{" + this.NS_CARDDAV + "}max-resource-size",
"{" + this.NS_CARDDAV + "}addressbook-home-set",
"{" + this.NS_CARDDAV + "}supported-collation-set"
);
handler.protectedProperties = Util.makeUnique(handler.protectedProperties);
handler.propertyMap["{http://calendarserver.org/ns/}me-card"] = jsDAV_Property_Href;
this.handler = handler;
},
/**
* Returns a list of supported features.
*
* This is used in the DAV: header in the OPTIONS and PROPFIND requests.
*
* @return array
*/
getFeatures: function() {
return ["addressbook"];
},
/**
* Returns a list of reports this plugin supports.
*
* This will be used in the {DAV:}supported-report-set property.
* Note that you still need to subscribe to the 'report' event to actually
* implement them
*
* @param {String} uri
* @return array
*/
getSupportedReportSet: function(uri, callback) {
var self = this;
this.handler.getNodeForPath(uri, function(err, node) {
if (err)
return callback(err);
if (node.hasFeature(jsCardDAV_iAddressBook) || node.hasFeature(jsCardDAV_iCard)) {
return callback(null, [
"{" + self.NS_CARDDAV + "}addressbook-multiget",
"{" + self.NS_CARDDAV + "}addressbook-query"
]);
}
return callback(null, []);
});
},
/**
* Adds all CardDAV-specific properties
*
* @param {String} path
* @param DAV\INode node
* @param {Array} requestedProperties
* @param {Array} returnedProperties
* @return void
*/
beforeGetProperties: function(e, path, node, requestedProperties, returnedProperties) {
var self = this;
if (node.hasFeature(jsDAVACL_iPrincipal)) {
// calendar-home-set property
var addHome = "{" + this.NS_CARDDAV + "}addressbook-home-set";
if (requestedProperties[addHome]) {
var principalId = node.getName();
var addressbookHomePath = this.ADDRESSBOOK_ROOT + "/" + principalId + "/";
delete requestedProperties[addHome];
returnedProperties["200"][addHome] = jsDAV_Property_Href.new(addressbookHomePath);
}
var directories = "{" + this.NS_CARDDAV + "}directory-gateway";
if (this.directories && requestedProperties[directories]) {
delete requestedProperties[directories];
returnedProperties["200"][directories] = jsDAV_Property_HrefList.new(this.directories);
}
}
if (node.hasFeature(jsCardDAV_iCard)) {
// The address-data property is not supposed to be a 'real'
// property, but in large chunks of the spec it does act as such.
// Therefore we simply expose it as a property.
var addressDataProp = "{" + this.NS_CARDDAV + "}address-data";
if (requestedProperties[addressDataProp]) {
delete requestedProperties[addressDataProp];
node.get(function(err, val) {
if (err)
return e.next(err);
returnedProperties["200"][addressDataProp] = val.toString("utf8");
afterICard();
});
}
else
afterICard();
}
else
afterICard();
function afterICard() {
if (node.hasFeature(jsCardDAV_UserAddressBooks)) {
var meCardProp = "{http://calendarserver.org/ns/}me-card";
if (requestedProperties[meCardProp]) {
self.handler.getProperties(node.getOwner(), ["{http://ajax.org/2005/aml}vcard-url"], function(err, props) {
if (err)
return e.next(err);
if (props["{http://ajax.org/2005/aml}vcard-url"]) {
returnedProperties["200"][meCardProp] = jsDAV_Property_Href.new(
props["{http://ajax.org/2005/aml}vcard-url"]
);
delete requestedProperties[meCardProp];
}
e.next();
});
}
else
e.next();
}
else
e.next();
}
},
/**
* This event is triggered when a PROPPATCH method is executed
*
* @param {Array} mutations
* @param {Array} result
* @param DAV\INode node
* @return bool
*/
updateProperties: function(e, mutations, result, node) {
if (!node.hasFeature(jsCardDAV_UserAddressBooks))
return e.next();
var meCard = "{http://calendarserver.org/ns/}me-card";
// The only property we care about
if (!mutations[meCard])
return e.next();
var value = mutations[meCard];
delete mutations[meCard];
if (value.hasFeature(jsDAV_Property_iHref)) {
value = this.handler.calculateUri(value.getHref());
}
else if (!value) {
result["400"][meCard] = null;
return e.stop();
}
this.server.updateProperties(node.getOwner(), {"{http://ajax.org/2005/aml}vcard-url": value}, function(err, innerResult) {
if (err)
return e.next(err);
var closureResult = false;
var props;
for (var status in innerResult) {
props = innerResult[status];
if (props["{http://ajax.org/2005/aml}vcard-url"]) {
result[status][meCard] = null;
status = parseInt(status);
closureResult = (status >= 200 && status < 300);
}
}
if (!closureResult)
return e.stop();
e.next();
});
},
/**
* This functions handles REPORT requests specific to CardDAV
*
* @param {String} reportName
* @param DOMNode dom
* @return bool
*/
report: function(e, reportName, dom) {
switch(reportName) {
case "{" + this.NS_CARDDAV + "}addressbook-multiget" :
this.addressbookMultiGetReport(e, dom);
break;
case "{" + this.NS_CARDDAV + "}addressbook-query" :
this.addressBookQueryReport(e, dom);
break;
default :
return e.next();
}
},
/**
* This function handles the addressbook-multiget REPORT.
*
* This report is used by the client to fetch the content of a series
* of urls. Effectively avoiding a lot of redundant requests.
*
* @param DOMNode dom
* @return void
*/
addressbookMultiGetReport: function(e, dom) {
var properties = Object.keys(Xml.parseProperties(dom));
var hrefElems = dom.getElementsByTagNameNS("urn:DAV", "href");
var propertyList = {};
var self = this;
Async.list(hrefElems)
.each(function(elem, next) {
var uri = self.handler.calculateUri(elem.firstChild.nodeValue);
//propertyList[uri]
self.handler.getPropertiesForPath(uri, properties, 0, function(err, props) {
if (err)
return next(err);
Util.extend(propertyList, props);
next();
});
})
.end(function(err) {
if (err)
return e.next(err);
var prefer = self.handler.getHTTPPrefer();
e.stop();
self.handler.httpResponse.writeHead(207, {
"content-type": "application/xml; charset=utf-8",
"vary": "Brief,Prefer"
});
self.handler.httpResponse.end(self.handler.generateMultiStatus(propertyList, prefer["return-minimal"]));
});
},
/**
* This method is triggered before a file gets updated with new content.
*
* This plugin uses this method to ensure that Card nodes receive valid
* vcard data.
*
* @param {String} path
* @param jsDAV_iFile node
* @param resource data
* @return void
*/
beforeWriteContent: function(e, path, node) {
if (!node.hasFeature(jsCardDAV_iCard))
return e.next();
var self = this;
this.handler.getRequestBody("utf8", null, false, function(err, data) {
if (err)
return e.next(err);
try {
self.validateVCard(data);
}
catch (ex) {
return e.next(ex);
}
e.next();
});
},
/**
* This method is triggered before a new file is created.
*
* This plugin uses this method to ensure that Card nodes receive valid
* vcard data.
*
* @param {String} path
* @param resource data
* @param jsDAV_iCollection parentNode
* @return void
*/
beforeCreateFile: function(e, path, data, enc, parentNode) {
if (!parentNode.hasFeature(jsCardDAV_iAddressBook))
return e.next();
try {
this.validateVCard(data);
}
catch (ex) {
return e.next(ex);
}
e.next();
},
/**
* Checks if the submitted iCalendar data is in fact, valid.
*
* An exception is thrown if it's not.
*
* @param resource|string data
* @return void
*/
validateVCard: function(data) {
// If it's a stream, we convert it to a string first.
if (Buffer.isBuffer(data))
data = data.toString("utf8");
var vobj;
try {
vobj = jsVObject_Reader.read(data);
}
catch (ex) {
throw new Exc.UnsupportedMediaType("This resource only supports valid vcard data. Parse error: " + ex.message);
}
if (vobj.name != "VCARD")
throw new Exc.UnsupportedMediaType("This collection can only support vcard objects.");
if (!vobj.UID)
throw new Exc.BadRequest("Every vcard must have a UID.");
},
/**
* This function handles the addressbook-query REPORT
*
* This report is used by the client to filter an addressbook based on a
* complex query.
*
* @param DOMNode dom
* @return void
*/
addressbookQueryReport: function(e, dom) {
var query = jsCardDAV_AddressBookQueryParser.new(dom);
try {
query.parse();
}
catch(ex) {
return e.next(ex);
}
var depth = this.handler.getHTTPDepth(0);
if (depth === 0) {
this.handler.getNodeForPath(this.handler.getRequestUri(), function(err, node) {
if (err)
return e.next(err);
afterCandidates([node]);
})
}
else {
this.handler.server.tree.getChildren(this.handler.getRequestUri(), function(err, children) {
if (err)
return e.next(err);
afterCandidates(children);
});
}
var self = this;
function afterCandidates(candidateNodes) {
var validNodes = [];
Async.list(candidateNodes)
.each(function(node, next) {
if (!node.hasFeature(jsCardDAV_iCard))
return next();
node.get(function(err, blob) {
if (err)
return next(err);
if (!self.validateFilters(blob.toString("utf8"), query.filters, query.test))
return next();
validNodes.push(node);
if (query.limit && query.limit <= validNodes.length) {
// We hit the maximum number of items, we can stop now.
return next(Async.STOP);
}
next();
});
})
.end(function(err) {
if (err)
return e.next(err);
var result = {};
Async.list(validNodes)
.each(function(validNode, next) {
var href = self.handler.getRequestUri();
if (depth !== 0)
href = href + "/" + validNode.getName();
self.handler.getPropertiesForPath(href, query.requestedProperties, 0, function(err, props) {
if (err)
return next(err);
Util.extend(result, props);
next();
});
})
.end(function(err) {
if (err)
return e.next(err);
e.stop();
var prefer = self.handler.getHTTPPRefer();
self.handler.httpResponse.writeHead(207, {
"content-type": "application/xml; charset=utf-8",
"vary": "Brief,Prefer"
});
self.handler.httpResponse.end(self.handler.generateMultiStatus(result, prefer["return-minimal"]));
});
});
}
},
/**
* Validates if a vcard makes it throught a list of filters.
*
* @param {String} vcardData
* @param {Array} filters
* @param {String} test anyof or allof (which means OR or AND)
* @return bool
*/
validateFilters: function(vcardData, filters, test) {
var vcard;
try {
vcard = jsVObject_Reader.read(vcardData);
}
catch (ex) {
return false;
}
if (!filters)
return true;
var filter, isDefined, success, vProperties, results, texts;
for (var i = 0, l = filters.length; i < l; ++i) {
filter = filters[i];
isDefined = vcard.get(filter.name);
if (filter["is-not-defined"]) {
if (isDefined)
success = false;
else
success = true;
}
else if ((!filter["param-filters"] && !filter["text-matches"]) || !isDefined) {
// We only need to check for existence
success = isDefined;
}
else {
vProperties = vcard.select(filter.name);
results = [];
if (filter["param-filters"])
results.push(this.validateParamFilters(vProperties, filter["param-filters"], filter.test));
if (filter["text-matches"]) {
texts = vProperties.map(function(vProperty) {
return vProperty.value;
});
results.push(this.validateTextMatches(texts, filter["text-matches"], filter.test));
}
if (results.length === 1) {
success = results[0];
}
else {
if (filter.test == "anyof")
success = results[0] || results[1];
else
success = results[0] && results[1];
}
} // else
// There are two conditions where we can already determine whether
// or not this filter succeeds.
if (test == "anyof" && success)
return true;
if (test == "allof" && !success)
return false;
} // foreach
// If we got all the way here, it means we haven't been able to
// determine early if the test failed or not.
//
// This implies for 'anyof' that the test failed, and for 'allof' that
// we succeeded. Sounds weird, but makes sense.
return test === "allof";
},
/**
* Validates if a param-filter can be applied to a specific property.
*
* @todo currently we're only validating the first parameter of the passed
* property. Any subsequence parameters with the same name are
* ignored.
* @param {Array} vProperties
* @param {Array} filters
* @param {String} test
* @return bool
*/
validateParamFilters: function(vProperties, filters, test) {
var filter, isDefined, success, j, l2, vProperty;
for (var i = 0, l = filters.length; i < l; ++i) {
filter = filters[i];
isDefined = false;
for (j = 0, l2 = vProperties.length; j < l2; ++j) {
vProperty = vProperties[j];
isDefined = !!vProperty.get(filter.name);
if (isDefined)
break;
}
if (filter["is-not-defined"]) {
success = !isDefined;
// If there's no text-match, we can just check for existence
}
else if (!filter["text-match"] || !isDefined) {
success = isDefined;
}
else {
success = false;
for (j = 0, l2 = vProperties.length; j < l2; ++j) {
vProperty = vProperties[j];
// If we got all the way here, we'll need to validate the
// text-match filter.
success = Util.textMatch(vProperty.get(filter.name).value, filter["text-match"].value, filter["text-match"]["match-type"]);
if (success)
break;
}
if (filter["text-match"]["negate-condition"])
success = !success;
} // else
// There are two conditions where we can already determine whether
// or not this filter succeeds.
if (test == "anyof" && success)
return true;
if (test == "allof" && !success)
return false;
}
// If we got all the way here, it means we haven't been able to
// determine early if the test failed or not.
//
// This implies for 'anyof' that the test failed, and for 'allof' that
// we succeeded. Sounds weird, but makes sense.
return test == "allof";
},
/**
* Validates if a text-filter can be applied to a specific property.
*
* @param {Array} texts
* @param {Array} filters
* @param {String} test
* @return bool
*/
validateTextMatches: function(texts, filters, test) {
var success, filter, j, l2, haystack;
for (var i = 0, l = filters.length; i < l; ++i) {
filter = filters[i];
success = false;
for (j = 0, l2 = texts.length; j < l2; ++j) {
haystack = texts[j];
success = Util.textMatch(haystack, filter.value, filter["match-type"]);
// Breaking on the first match
if (success)
break;
}
if (filter["negate-condition"])
success = !success;
if (success && test == "anyof")
return true;
if (!success && test == "allof")
return false;
}
// If we got all the way here, it means we haven't been able to
// determine early if the test failed or not.
//
// This implies for 'anyof' that the test failed, and for 'allof' that
// we succeeded. Sounds weird, but makes sense.
return test == "allof";
},
/**
* This event is triggered after webdav-properties have been retrieved.
*
* @return bool
*/
afterGetProperties: function(e, uri, properties) {
// If the request was made using the SOGO connector, we must rewrite
// the content-type property. By default jsDAV will send back
// text/x-vcard; charset=utf-8, but for SOGO we must strip that last
// part.
if (!properties["200"]["{DAV:}getcontenttype"])
return e.next();
if (this.handler.httpRequest.headers["user-agent"].indexOf("Thunderbird") === -1)
return e.next();
if (properties["200"]["{DAV:}getcontenttype"].indexOf("text/x-vcard") === 0)
properties["200"]["{DAV:}getcontenttype"] = "text/x-vcard";
e.next();
},
/**
* This method is used to generate HTML output for the
* Sabre\DAV\Browser\Plugin. This allows us to generate an interface users
* can use to create new calendars.
*
* @param DAV\INode node
* @param {String} output
* @return bool
*/
htmlActionsPanel: function(e, node, output) {
if (!node.hasFeature(jsCardDAV_UserAddressBooks))
return e.next();
output.html = '<tr><td colspan="2"><form method="post" action="">' +
'<h3>Create new address book</h3>' +
'<input type="hidden" name="jsdavAction" value="mkaddressbook" />' +
'<label>Name (uri):</label> <input type="text" name="name" /><br />' +
'<label>Display name:</label> <input type="text" name="{DAV:}displayname" /><br />' +
'<input type="submit" value="create" />' +
'</form>' +
'</td></tr>';
e.stop();
},
/**
* This method allows us to intercept the 'mkcalendar' sabreAction. This
* action enables the user to create new calendars from the browser plugin.
*
* @param {String} uri
* @param {String} action
* @param {Array} postVars
* @return bool
*/
browserPostAction: function(e, uri, action, postVars) {
if (action != "mkaddressbook")
return e.next();
var resourceType = ["{DAV:}collection", "{urn:ietf:params:xml:ns:carddav}addressbook"];
var properties = {};
if (postVars["{DAV:}displayname"])
properties["{DAV:}displayname"] = postVars["{DAV:}displayname"];
this.handler.createCollection(uri + "/" + postVars.name, resourceType, properties, function(err) {
if (err)
return e.next(err);
e.stop();
});
}
});
| pascience/cloxp-install | win/life_star/node_modules/lively-davfs/node_modules/jsDAV/lib/CardDAV/plugin.js | JavaScript | mit | 26,510 |
'@fixture click';
'@page http://example.com';
'@test'['Take a screenshot'] = {
'1.Click on non-existing element': function () {
act.screenshot();
},
};
'@test'['Screenshot on test code error'] = {
'1.Click on non-existing element': function () {
throw new Error('STOP');
},
};
| VasilyStrelyaev/testcafe | test/functional/legacy-fixtures/screenshots/testcafe-fixtures/screenshots.test.js | JavaScript | mit | 312 |
/////////////////////////////////
// Rich Newman
// http://richnewman.wordpress.com/about/code-listings-and-diagrams/hslcolor-class/
//
using System;
using System.Drawing;
namespace AldursLab.Essentials.Extensions.DotNet.Drawing
{
/// <summary>
/// Color with Hue/Saturation/Luminescense representation.
/// </summary>
public class HslColor
{
// Private data members below are on scale 0-1
// They are scaled for use externally based on scale
private double hue = 1.0;
private double saturation = 1.0;
private double luminosity = 1.0;
private const double scale = 240.0;
public double Hue
{
get { return hue * scale; }
set { hue = CheckRange(value / scale); }
}
public double Saturation
{
get { return saturation * scale; }
set { saturation = CheckRange(value / scale); }
}
public double Luminosity
{
get { return luminosity * scale; }
set { luminosity = CheckRange(value / scale); }
}
private double CheckRange(double value)
{
if (value < 0.0)
value = 0.0;
else if (value > 1.0)
value = 1.0;
return value;
}
public override string ToString()
{
return String.Format("H: {0:#0.##} S: {1:#0.##} L: {2:#0.##}", Hue, Saturation, Luminosity);
}
public string ToRGBString()
{
Color color = (Color)this;
return String.Format("R: {0:#0.##} G: {1:#0.##} B: {2:#0.##}", color.R, color.G, color.B);
}
#region Casts to/from System.Drawing.Color
public static implicit operator Color(HslColor hslColor)
{
double r = 0, g = 0, b = 0;
if (hslColor.luminosity != 0)
{
if (hslColor.saturation == 0)
r = g = b = hslColor.luminosity;
else
{
double temp2 = GetTemp2(hslColor);
double temp1 = 2.0 * hslColor.luminosity - temp2;
r = GetColorComponent(temp1, temp2, hslColor.hue + 1.0 / 3.0);
g = GetColorComponent(temp1, temp2, hslColor.hue);
b = GetColorComponent(temp1, temp2, hslColor.hue - 1.0 / 3.0);
}
}
return Color.FromArgb((int)(255 * r), (int)(255 * g), (int)(255 * b));
}
private static double GetColorComponent(double temp1, double temp2, double temp3)
{
temp3 = MoveIntoRange(temp3);
if (temp3 < 1.0 / 6.0)
return temp1 + (temp2 - temp1) * 6.0 * temp3;
else if (temp3 < 0.5)
return temp2;
else if (temp3 < 2.0 / 3.0)
return temp1 + ((temp2 - temp1) * ((2.0 / 3.0) - temp3) * 6.0);
else
return temp1;
}
private static double MoveIntoRange(double temp3)
{
if (temp3 < 0.0)
temp3 += 1.0;
else if (temp3 > 1.0)
temp3 -= 1.0;
return temp3;
}
private static double GetTemp2(HslColor hslColor)
{
double temp2;
if (hslColor.luminosity < 0.5) //<=??
temp2 = hslColor.luminosity * (1.0 + hslColor.saturation);
else
temp2 = hslColor.luminosity + hslColor.saturation - (hslColor.luminosity * hslColor.saturation);
return temp2;
}
public static implicit operator HslColor(Color color)
{
HslColor hslColor = new HslColor();
hslColor.hue = color.GetHue() / 360.0; // we store hue as 0-1 as opposed to 0-360
hslColor.luminosity = color.GetBrightness();
hslColor.saturation = color.GetSaturation();
return hslColor;
}
#endregion
public void SetRGB(int red, int green, int blue)
{
HslColor hslColor = (HslColor)Color.FromArgb(red, green, blue);
this.hue = hslColor.hue;
this.saturation = hslColor.saturation;
this.luminosity = hslColor.luminosity;
}
public HslColor() { }
public HslColor(Color color)
{
SetRGB(color.R, color.G, color.B);
}
public HslColor(int red, int green, int blue)
{
SetRGB(red, green, blue);
}
public HslColor(double hue, double saturation, double luminosity)
{
this.Hue = hue;
this.Saturation = saturation;
this.Luminosity = luminosity;
}
}
}
| mdsolver/WurmAssistant3 | src/Common/Essentials/Extensions/DotNet/Drawing/HslColor.cs | C# | mit | 4,774 |
using System;
using Marten.Services;
using Marten.Testing.Documents;
using Marten.Testing.Harness;
using Xunit;
namespace Marten.Testing.CoreFunctionality
{
public class foreign_key_persisting_Tests: IntegrationContext
{
[Fact]
public void persist_and_overwrite_foreign_key()
{
StoreOptions(_ =>
{
_.Schema.For<Issue>().ForeignKey<User>(x => x.AssigneeId);
});
var issue = new Issue();
var user = new User();
using (var session = theStore.OpenSession())
{
session.Store(user);
session.Store(issue);
session.SaveChanges();
}
issue.AssigneeId = user.Id;
using (var session = theStore.OpenSession())
{
session.Store(issue);
session.SaveChanges();
}
issue.AssigneeId = null;
using (var session = theStore.OpenSession())
{
session.Store(issue);
session.SaveChanges();
}
}
[Fact]
public void throws_exception_if_trying_to_delete_referenced_user()
{
StoreOptions(_ =>
{
_.Schema.For<Issue>()
.ForeignKey<User>(x => x.AssigneeId);
});
var issue = new Issue();
var user = new User();
issue.AssigneeId = user.Id;
using (var session = theStore.OpenSession())
{
session.Store(user);
session.Store(issue);
session.SaveChanges();
}
Exception<Marten.Exceptions.MartenCommandException>.ShouldBeThrownBy(() =>
{
using (var session = theStore.OpenSession())
{
session.Delete(user);
session.SaveChanges();
}
});
}
[Fact]
public void persist_without_referenced_user()
{
StoreOptions(_ =>
{
_.Schema.For<Issue>()
.ForeignKey<User>(x => x.AssigneeId);
});
using (var session = theStore.OpenSession())
{
session.Store(new Issue());
session.SaveChanges();
}
}
[Fact]
public void order_inserts()
{
StoreOptions(_ =>
{
_.Schema.For<Issue>()
.ForeignKey<User>(x => x.AssigneeId);
});
var issue = new Issue();
var user = new User();
issue.AssigneeId = user.Id;
using (var session = theStore.OpenSession())
{
session.Store(issue);
session.Store(user);
session.SaveChanges();
}
}
[Fact]
public void throws_exception_on_cyclic_dependency()
{
Exception<InvalidOperationException>.ShouldBeThrownBy(() =>
{
StoreOptions(_ =>
{
_.Schema.For<Node1>().ForeignKey<Node3>(x => x.Link);
_.Schema.For<Node2>().ForeignKey<Node1>(x => x.Link);
_.Schema.For<Node3>().ForeignKey<Node2>(x => x.Link);
});
}).Message.ShouldContain("Cyclic");
}
public class Node1
{
public Guid Id { get; set; }
public Guid Link { get; set; }
}
public class Node2
{
public Guid Id { get; set; }
public Guid Link { get; set; }
}
public class Node3
{
public Guid Id { get; set; }
public Guid Link { get; set; }
}
public foreign_key_persisting_Tests(DefaultStoreFixture fixture) : base(fixture)
{
DocumentTracking = DocumentTracking.IdentityOnly;
}
}
}
| ericgreenmix/marten | src/Marten.Testing/CoreFunctionality/foreign_key_persisting_Tests.cs | C# | mit | 4,074 |
/**
* @license
* Copyright Google LLC 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 {global} from '../../src/util/global';
// Not yet available in TypeScript: https://github.com/Microsoft/TypeScript/pull/29332
declare var globalThis: any /** TODO #9100 */;
{
describe('global', () => {
it('should be global this value', () => {
const _global = new Function('return this')();
expect(global).toBe(_global);
});
if (typeof globalThis !== 'undefined') {
it('should use globalThis as global reference', () => {
expect(global).toBe(globalThis);
});
}
});
}
| wKoza/angular | packages/core/test/util/global_spec.ts | TypeScript | mit | 732 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过下列属性集
// 控制。更改这些属性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("Dos.Tools")]
[assembly: AssemblyDescription("ITdos.com")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("ITdos.com")]
[assembly: AssemblyProduct("Dos.Tools")]
[assembly: AssemblyCopyright("Copyright © 2009-2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 属性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("014d6eaa-6f9d-4b8a-a4dc-9b992cd94cfa")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 内部版本号
// 修订号
//
// 可以指定所有这些值,也可以使用“内部版本号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.0.6.0")]
[assembly: AssemblyFileVersion("2.0.6.0")]
| itdos/Dos.Tool | Properties/AssemblyInfo.cs | C# | mit | 1,337 |
// implementation for sturm_equation.h
#include <cmath>
#include <algorithm>
#include <list>
#include <utils/array1d.h>
#include <algebra/vector.h>
#include <algebra/sparse_matrix.h>
#include <numerics/eigenvalues.h>
#include <numerics/gauss_data.h>
namespace WaveletTL
{
template <class WBASIS>
SturmEquation<WBASIS>::SturmEquation(const SimpleSturmBVP& bvp,
const bool precompute_f)
: bvp_(bvp), basis_(bvp.bc_left(), bvp.bc_right()), normA(0.0), normAinv(0.0)
{
#ifdef ENERGY
// compute_diagonal();
#endif
if (precompute_f) precompute_rhs();
//const int jmax = 12;
//basis_.set_jmax(jmax);
}
template <class WBASIS>
SturmEquation<WBASIS>::SturmEquation(const SimpleSturmBVP& bvp,
const WBASIS& basis,
const bool precompute_f)
: bvp_(bvp), basis_(basis), normA(0.0), normAinv(0.0)
{
#ifdef ENERGY
compute_diagonal();
#endif
if (precompute_f) precompute_rhs();
//const int jmax = 12;
//basis_.set_jmax(jmax);
}
template <class WBASIS>
void
SturmEquation<WBASIS>::precompute_rhs() const
{
typedef typename WaveletBasis::Index Index;
cout << "precompute rhs.." << endl;
// precompute the right-hand side on a fine level
InfiniteVector<double,Index> fhelp;
InfiniteVector<double,int> fhelp_int;
#ifdef FRAME
// cout << basis_.degrees_of_freedom() << endl;
for (int i=0; i<basis_.degrees_of_freedom();i++) {
// cout << "hallo" << endl;
// cout << *(basis_.get_quarklet(i)) << endl;
const double coeff = f(*(basis_.get_quarklet(i)))/D(*(basis_.get_quarklet(i)));
fhelp.set_coefficient(*(basis_.get_quarklet(i)), coeff);
fhelp_int.set_coefficient(i, coeff);
// cout << *(basis_.get_quarklet(i)) << endl;
}
// cout << "bin hier1" << endl;
#else
for (int i=0; i<basis_.degrees_of_freedom();i++) {
// cout << "bin hier: " << i << endl;
// cout << D(*(basis_.get_wavelet(i))) << endl;
// cout << *(basis_.get_wavelet(i)) << endl;
const double coeff = f(*(basis_.get_wavelet(i)))/D(*(basis_.get_wavelet(i)));
// cout << f(*(basis_.get_wavelet(i))) << endl;
// cout << coeff << endl;
fhelp.set_coefficient(*(basis_.get_wavelet(i)), coeff);
fhelp_int.set_coefficient(i, coeff);
// cout << *(basis_.get_wavelet(i)) << endl;
}
// const int j0 = basis().j0();
// for (Index lambda(basis_.first_generator(j0));;++lambda)
// {
// const double coeff = f(lambda)/D(lambda);
// if (fabs(coeff)>1e-15)
// fhelp.set_coefficient(lambda, coeff);
// fhelp_int.set_coefficient(i, coeff);
// if (lambda == basis_.last_wavelet(jmax))
// break;
//
//
// }
#endif
fnorm_sqr = l2_norm_sqr(fhelp);
// sort the coefficients into fcoeffs
fcoeffs.resize(fhelp.size());
fcoeffs_int.resize(fhelp_int.size());
unsigned int id(0), id2(0);
for (typename InfiniteVector<double,Index>::const_iterator it(fhelp.begin()), itend(fhelp.end());
it != itend; ++it, ++id)
fcoeffs[id] = std::pair<Index,double>(it.index(), *it);
sort(fcoeffs.begin(), fcoeffs.end(), typename InfiniteVector<double,Index>::decreasing_order());
for (typename InfiniteVector<double,int>::const_iterator it(fhelp_int.begin()), itend(fhelp_int.end());
it != itend; ++it, ++id2)
fcoeffs_int[id2] = std::pair<int,double>(it.index(), *it);
sort(fcoeffs_int.begin(), fcoeffs_int.end(), typename InfiniteVector<double,int>::decreasing_order());
rhs_precomputed = true;
cout << "end precompute rhs.." << endl;
// cout << fhelp << endl;
// cout << fcoeffs << endl;
}
template <class WBASIS>
inline
double
SturmEquation<WBASIS>::D(const typename WBASIS::Index& lambda) const
{
#ifdef FRAME
#ifdef DYADIC
return mypow((1<<lambda.j())*mypow(1+lambda.p(),6),operator_order())*mypow(1+lambda.p(),2); //2^j*(p+1)^6, falls operator_order()=1 (\delta=4)
// return 1<<(lambda.j()*(int) operator_order());
#endif
#ifdef TRIVIAL
return 1;
#endif
#ifdef ENERGY
return stiff_diagonal[lambda.number()]*(lambda.p()+1);
#endif
#endif
#ifdef BASIS
#ifdef DYADIC
return 1<<(lambda.j()*(int) operator_order());
// return pow(ldexp(1.0, lambda.j()),operator_order());
#else
#ifdef TRIVIAL
return 1;
#else
#ifdef ENERGY
// return sqrt(a(lambda, lambda));
return stiff_diagonal[lambda.number()];
#else
return sqrt(a(lambda, lambda));
#endif
#endif
#endif
#else
return 1;
#endif
// return 1;
// return lambda.e() == 0 ? 1.0 : ldexp(1.0, lambda.j()); // do not scale the generators
// return lambda.e() == 0 ? 1.0 : sqrt(a(lambda, lambda)); // do not scale the generators
}
template <class WBASIS>
inline
double
SturmEquation<WBASIS>::a(const typename WBASIS::Index& lambda,
const typename WBASIS::Index& nu) const
{
return a(lambda, nu, 2*WBASIS::primal_polynomial_degree());
}
template <class WBASIS>
double
SturmEquation<WBASIS>::a(const typename WBASIS::Index& lambda,
const typename WBASIS::Index& nu,
const unsigned int p) const
{
// a(u,v) = \int_0^1 [p(t)u'(t)v'(t)+q(t)u(t)v(t)] dt
double r = 0;
// Remark: There are of course many possibilities to evaluate
// a(u,v) numerically.
// In this implementation, we rely on the fact that the primal functions in
// WBASIS are splines with respect to a dyadic subgrid.
// We can then apply an appropriate composite quadrature rule.
// In the scope of WBASIS, the routines intersect_supports() and evaluate()
// must exist, which is the case for DSBasis<d,dT>.
// First we compute the support intersection of \psi_\lambda and \psi_\nu:
typedef typename WBASIS::Support Support;
Support supp;
if (intersect_supports(basis_, lambda, nu, supp))
{
// Set up Gauss points and weights for a composite quadrature formula:
// (TODO: maybe use an instance of MathTL::QuadratureRule instead of computing
// the Gauss points and weights)
#ifdef FRAME
const unsigned int N_Gauss = std::min((unsigned int)10,(p+1)/2+ (lambda.p()+nu.p()+1)/2);
// const unsigned int N_Gauss = 10;
// const unsigned int N_Gauss = (p+1)/2;
#else
const unsigned int N_Gauss = (p+1)/2;
#endif
const double h = ldexp(1.0, -supp.j);
Array1D<double> gauss_points (N_Gauss*(supp.k2-supp.k1)), func1values, func2values, der1values, der2values;
for (int patch = supp.k1, id = 0; patch < supp.k2; patch++) // refers to 2^{-j}[patch,patch+1]
for (unsigned int n = 0; n < N_Gauss; n++, id++)
gauss_points[id] = h*(2*patch+1+GaussPoints[N_Gauss-1][n])/2.;
// - compute point values of the integrands
evaluate(basis_, lambda, gauss_points, func1values, der1values);
evaluate(basis_, nu, gauss_points, func2values, der2values);
// if((lambda.number()==19 && nu.number()==19) || (lambda.number()==26 && nu.number()==26)){
// cout << lambda << endl;
// cout << gauss_points << endl;
// cout << func1values << endl;
// cout << func2values << endl;
// }
// - add all integral shares
for (int patch = supp.k1, id = 0; patch < supp.k2; patch++)
for (unsigned int n = 0; n < N_Gauss; n++, id++) {
const double t = gauss_points[id];
const double gauss_weight = GaussWeights[N_Gauss-1][n] * h;
const double pt = bvp_.p(t);
if (pt != 0)
r += pt * der1values[id] * der2values[id] * gauss_weight;
const double qt = bvp_.q(t);
if (qt != 0)
r += qt * func1values[id] * func2values[id] * gauss_weight;
}
}
return r;
}
template <class WBASIS>
double
SturmEquation<WBASIS>::norm_A() const
{
if (normA == 0.0) {
typedef typename WaveletBasis::Index Index;
std::set<Index> Lambda;
const int j0 = basis().j0();
const int jmax = j0+3;
#ifdef FRAME
const int pmax = std::min(basis().get_pmax_(),2);
//const int pmax = 0;
int p = 0;
for (Index lambda = basis().first_generator(j0,0);;) {
Lambda.insert(lambda);
if (lambda == basis().last_wavelet(jmax,pmax)) break;
//if (i==7) break;
if (lambda == basis().last_wavelet(jmax,p)){
++p;
lambda = basis().first_generator(j0,p);
}
else
++lambda;
}
#else
for (Index lambda = first_generator(&basis(), j0);; ++lambda) {
Lambda.insert(lambda);
if (lambda == last_wavelet(&basis(), jmax)) break;
}
#endif
SparseMatrix<double> A_Lambda;
setup_stiffness_matrix(*this, Lambda, A_Lambda);
#if 1
double help;
unsigned int iterations;
LanczosIteration(A_Lambda, 1e-6, help, normA, 200, iterations);
normAinv = 1./help;
#else
Vector<double> xk(Lambda.size(), false);
xk = 1;
unsigned int iterations;
normA = PowerIteration(A_Lambda, xk, 1e-6, 100, iterations);
#endif
}
return normA;
}
template <class WBASIS>
double
SturmEquation<WBASIS>::norm_Ainv() const
{
if (normAinv == 0.0) {
typedef typename WaveletBasis::Index Index;
std::set<Index> Lambda;
const int j0 = basis().j0();
const int jmax = j0+3;
#ifdef FRAME
const int pmax = std::min(basis().get_pmax_(),2);
//const int pmax = 0;
int p = 0;
for (Index lambda = basis().first_generator(j0,0);;) {
Lambda.insert(lambda);
if (lambda == basis().last_wavelet(jmax,pmax)) break;
//if (i==7) break;
if (lambda == basis().last_wavelet(jmax,p)){
++p;
lambda = basis().first_generator(j0,p);
}
else
++lambda;
}
#else
for (Index lambda = first_generator(&basis(), j0);; ++lambda) {
Lambda.insert(lambda);
if (lambda == last_wavelet(&basis(), jmax)) break;
}
#endif
SparseMatrix<double> A_Lambda;
setup_stiffness_matrix(*this, Lambda, A_Lambda);
#if 1
double help;
unsigned int iterations;
LanczosIteration(A_Lambda, 1e-6, help, normA, 200, iterations);
normAinv = 1./help;
#else
Vector<double> xk(Lambda.size(), false);
xk = 1;
unsigned int iterations;
normAinv = InversePowerIteration(A_Lambda, xk, 1e-6, 200, iterations);
#endif
}
return normAinv;
}
template <class WBASIS>
double
SturmEquation<WBASIS>::f(const typename WBASIS::Index& lambda) const
{
// f(v) = \int_0^1 g(t)v(t) dt
// cout << "bin in f" << endl;
double r = 0;
const int j = lambda.j()+lambda.e();
int k1, k2;
support(basis_, lambda, k1, k2);
// Set up Gauss points and weights for a composite quadrature formula:
const unsigned int N_Gauss = 7; //perhaps we need +lambda.p()/2 @PHK
const double h = ldexp(1.0, -j);
Array1D<double> gauss_points (N_Gauss*(k2-k1)), vvalues;
for (int patch = k1; patch < k2; patch++) // refers to 2^{-j}[patch,patch+1]
for (unsigned int n = 0; n < N_Gauss; n++)
gauss_points[(patch-k1)*N_Gauss+n] = h*(2*patch+1+GaussPoints[N_Gauss-1][n])/2;
// - compute point values of the integrand
evaluate(basis_, 0, lambda, gauss_points, vvalues);
// cout << "bin immer noch in f" << endl;
// - add all integral shares
for (int patch = k1, id = 0; patch < k2; patch++)
for (unsigned int n = 0; n < N_Gauss; n++, id++) {
const double t = gauss_points[id];
const double gauss_weight = GaussWeights[N_Gauss-1][n] * h;
const double gt = bvp_.g(t);
if (gt != 0)
r += gt
* vvalues[id]
* gauss_weight;
}
#ifdef DELTADIS
// double tmp = 1;
// Point<1> p1;
// p1[0] = 0.5;
// Point<1> p2;
// chart->map_point_inv(p1,p2);
// tmp = evaluate(basis_, 0,
// typename WBASIS::Index(lambda.j(),
// lambda.e()[0],
// lambda.k()[0],
// basis_),
// p2[0]);
// tmp /= chart->Gram_factor(p2);
//
//
// return 4.0*tmp + r;
#ifdef NONZERONEUMANN
return r + 4*basis_.evaluate(0, lambda, 0.5)+3*M_PI*(basis_.evaluate(0, lambda, 1)+basis_.evaluate(0, lambda, 0));
#else
return r+ 4*basis_.evaluate(0, lambda, 0.5);
#endif
#else
return r;
#endif
}
template <class WBASIS>
inline
void
SturmEquation<WBASIS>::RHS(const double eta,
InfiniteVector<double, typename WBASIS::Index>& coeffs) const
{
if (!rhs_precomputed) precompute_rhs();
coeffs.clear();
double coarsenorm(0);
double bound(fnorm_sqr - eta*eta);
typedef typename WBASIS::Index Index;
typename Array1D<std::pair<Index, double> >::const_iterator it(fcoeffs.begin());
do {
coarsenorm += it->second * it->second;
coeffs.set_coefficient(it->first, it->second);
++it;
} while (it != fcoeffs.end() && coarsenorm < bound);
}
template <class WBASIS>
inline
void
SturmEquation<WBASIS>::RHS(const double eta,
InfiniteVector<double,int>& coeffs) const
{
if (!rhs_precomputed) precompute_rhs();
coeffs.clear();
double coarsenorm(0);
double bound(fnorm_sqr - eta*eta);
typename Array1D<std::pair<int, double> >::const_iterator it(fcoeffs_int.begin());
do {
coarsenorm += it->second * it->second;
coeffs.set_coefficient(it->first, it->second);
++it;
} while (it != fcoeffs_int.end() && coarsenorm < bound);
}
template <class WBASIS>
void
SturmEquation<WBASIS>::compute_diagonal()
{
cout << "SturmEquation(): precompute diagonal of stiffness matrix..." << endl;
SparseMatrix<double> diag(1,basis_.degrees_of_freedom());
char filename[50];
char matrixname[50];
#ifdef ONE_D
int d = WBASIS::primal_polynomial_degree();
int dT = WBASIS::primal_vanishing_moments();
#else
#ifdef TWO_D
int d = WBASIS::primal_polynomial_degree();
int dT = WBASIS::primal_vanishing_moments();
#endif
#endif
// prepare filenames for 1D and 2D case
#ifdef ONE_D
sprintf(filename, "%s%d%s%d", "stiff_diagonal_poisson_interval_lap07_d", d, "_dT", dT);
sprintf(matrixname, "%s%d%s%d", "stiff_diagonal_poisson_1D_lap07_d", d, "_dT", dT);
#endif
#ifdef TWO_D
sprintf(filename, "%s%d%s%d", "stiff_diagonal_poisson_lshaped_lap1_d", d, "_dT", dT);
sprintf(matrixname, "%s%d%s%d", "stiff_diagonal_poisson_2D_lap1_d", d, "_dT", dT);
#endif
#ifndef PRECOMP_DIAG
std::list<Vector<double>::size_type> indices;
std::list<double> entries;
#endif
#ifdef PRECOMP_DIAG
cout << "reading in diagonal of unpreconditioned stiffness matrix from file "
<< filename << "..." << endl;
diag.matlab_input(filename);
cout << "...ready" << endl;
#endif
stiff_diagonal.resize(basis_.degrees_of_freedom());
for (int i = 0; i < basis_.degrees_of_freedom(); i++) {
#ifdef PRECOMP_DIAG
stiff_diagonal[i] = diag.get_entry(0,i);
#endif
#ifndef PRECOMP_DIAG
#ifdef FRAME
stiff_diagonal[i] = sqrt(a(*(basis_.get_quarklet(i)),*(basis_.get_quarklet(i))));
#endif
#ifdef BASIS
stiff_diagonal[i] = sqrt(a(*(basis_.get_wavelet(i)),*(basis_.get_wavelet(i))));
#endif
indices.push_back(i);
entries.push_back(stiff_diagonal[i]);
#endif
//cout << stiff_diagonal[i] << " " << *(basis_->get_wavelet(i)) << endl;
}
#ifndef PRECOMP_DIAG
diag.set_row(0,indices, entries);
diag.matlab_output(filename, matrixname, 1);
#endif
cout << "... done, diagonal of stiffness matrix computed" << endl;
}
}
| kedingagnumerikunimarburg/Marburg_Software_Library | WaveletTL/galerkin/sturm_equation.cpp | C++ | mit | 15,625 |
module NetSuite
module Records
class CustomerSubscriptionsList < Support::Sublist
include Namespaces::ListRel
sublist :subscriptions, CustomerSubscription
end
end
end
| jeperkins4/netsuite | lib/netsuite/records/customer_subscriptions_list.rb | Ruby | mit | 193 |
class Downvote < ActiveRecord::Base
validates :post, presence: true
validates :user, presence: true
belongs_to :user, counter_cache: true
belongs_to :post
end
| sudharti/2cents | app/models/downvote.rb | Ruby | mit | 169 |
<?php
/*
* This file is part of the ONGR package.
*
* (c) NFQ Technologies UAB <info@nfq.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace ONGR\ElasticsearchBundle\Serializer\Normalizer;
use Symfony\Component\Serializer\Normalizer\CustomNormalizer;
/**
* Normalizer used with referenced normalized objects.
*/
class CustomReferencedNormalizer extends CustomNormalizer
{
/**
* @var array
*/
private $references = [];
/**
* {@inheritdoc}
*/
public function normalize($object, $format = null, array $context = [])
{
$object->setReferences($this->references);
$data = parent::normalize($object, $format, $context);
$this->references = array_merge($this->references, $object->getReferences());
return $data;
}
/**
* {@inheritdoc}
*/
public function supportsNormalization($data, $format = null)
{
return $data instanceof AbstractNormalizable;
}
}
| lmikelionis/ElasticsearchBundle | Serializer/Normalizer/CustomReferencedNormalizer.php | PHP | mit | 1,062 |
<?php
namespace PuphpetBundle\Twig;
use RandomLib;
class BaseExtension extends \Twig_Extension
{
/** @var \RandomLib\Factory */
private $randomLib;
public function __construct(RandomLib\Factory $randomLib)
{
$this->randomLib = $randomLib;
}
public function getFunctions()
{
return [
new \Twig_SimpleFunction('mt_rand', [$this, 'mt_rand']),
new \Twig_SimpleFunction('uniqid', [$this, 'uniqid']),
new \Twig_SimpleFunction('merge_unique', [$this, 'mergeUnique']),
new \Twig_SimpleFunction('add_available', [$this, 'addAvailable']),
new \Twig_SimpleFunction('formValue', [$this, 'formValue']),
];
}
public function getFilters()
{
return [
'str_replace' => new \Twig_SimpleFilter('str_replace', 'str_replace'),
];
}
public function uniqid($prefix)
{
$random = $this->randomLib->getLowStrengthGenerator();
$characters = '0123456789abcdefghijklmnopqrstuvwxyz';
return $prefix . $random->generateString(12, $characters);
}
public function mt_rand($min, $max)
{
return mt_rand($min, $max);
}
public function str_replace($subject, $search, $replace)
{
return str_replace($search, $replace, $subject);
}
public function mergeUnique(array $arr1, array $arr2)
{
return array_unique(array_merge($arr1, $arr2));
}
public function addAvailable(array $arr1, array $arr2)
{
return array_merge($arr1, ['available' => $arr2]);
}
public function formValue($value)
{
if ($value === false) {
return 'false';
}
if ($value === null) {
return 'false';
}
return $value;
}
public function getName()
{
return 'base_extension';
}
}
| thedeedawg/puphpet | src/PuphpetBundle/Twig/BaseExtension.php | PHP | mit | 1,887 |
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi
*
* 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 hudson.model;
import hudson.model.MultiStageTimeSeries.TimeScale;
import hudson.model.queue.SubTask;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import org.jfree.chart.JFreeChart;
import org.junit.Test;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* @author Kohsuke Kawaguchi
*/
public class LoadStatisticsTest {
@Test
public void graph() throws IOException {
LoadStatistics ls = new LoadStatistics(0, 0) {
public int computeIdleExecutors() {
throw new UnsupportedOperationException();
}
public int computeTotalExecutors() {
throw new UnsupportedOperationException();
}
public int computeQueueLength() {
throw new UnsupportedOperationException();
}
@Override
protected Iterable<Node> getNodes() {
throw new UnsupportedOperationException();
}
@Override
protected boolean matches(Queue.Item item, SubTask subTask) {
throw new UnsupportedOperationException();
}
};
for (int i = 0; i < 50; i++) {
ls.onlineExecutors.update(4);
ls.busyExecutors.update(3);
ls.availableExecutors.update(1);
ls.queueLength.update(3);
}
for (int i = 0; i < 50; i++) {
ls.onlineExecutors.update(0);
ls.busyExecutors.update(0);
ls.availableExecutors.update(0);
ls.queueLength.update(1);
}
JFreeChart chart = ls.createTrendChart(TimeScale.SEC10).createChart();
BufferedImage image = chart.createBufferedImage(400, 200);
File tempFile = File.createTempFile("chart-", "png");
try (OutputStream os = Files.newOutputStream(tempFile.toPath(), StandardOpenOption.DELETE_ON_CLOSE)) {
ImageIO.write(image, "PNG", os);
} finally {
tempFile.delete();
}
}
@Test
public void isModernWorks() throws Exception {
assertThat(LoadStatistics.isModern(Modern.class), is(true));
assertThat(LoadStatistics.isModern(LoadStatistics.class), is(false));
}
private static class Modern extends LoadStatistics {
protected Modern(int initialOnlineExecutors, int initialBusyExecutors) {
super(initialOnlineExecutors, initialBusyExecutors);
}
@Override
public int computeIdleExecutors() {
return 0;
}
@Override
public int computeTotalExecutors() {
return 0;
}
@Override
public int computeQueueLength() {
return 0;
}
@Override
protected Iterable<Node> getNodes() {
return null;
}
@Override
protected boolean matches(Queue.Item item, SubTask subTask) {
return false;
}
}
}
| oleg-nenashev/jenkins | core/src/test/java/hudson/model/LoadStatisticsTest.java | Java | mit | 4,339 |
/// <reference path="../../../type-declarations/index.d.ts" />
import * as Phaser from 'phaser';
import { BootState } from './states/boot';
import { SplashState } from './states/splash';
import { GameState } from './states/game';
class Game extends Phaser.Game {
constructor() {
let width = document.documentElement.clientWidth > 768 * 1.4 // make room for chat
? 768
: document.documentElement.clientWidth * 0.7;
let height = document.documentElement.clientHeight > 1024 * 1.67 // give navbar some room
? 1024
: document.documentElement.clientHeight * 0.6;
super(width, height, Phaser.AUTO, 'game', null, false, false);
this.state.add('Boot', BootState, false);
this.state.add('Splash', SplashState, false);
this.state.add('Game', GameState, false);
this.state.start('Boot');
}
}
export const runGame = () => {
new Game();
} | fuzzwizard/builders-game | src/client/game/index.ts | TypeScript | mit | 890 |
<h1>Kitchen List</h1>
<div id="p_be_list">
<div class="table">
<div class="body">
<table>
<thead>
<tr>
<th colspan="2"><?php echo __('Name')?></th>
</tr>
</thead>
<tbody>
<?php if ($kitchen_list->count() !== false && $kitchen_list->count() == 0): ?>
<tr class="row_0">
<td colspan="2"><?php echo __('No Results') ?></td>
</tr>
<?php else: ?>
<?php foreach ($kitchen_list as $key => $kitchen): ?>
<tr class="<?php if ($key % 2 == 0) echo "row_0"; else echo "row_1"; ?>">
<td width="98%"><?php echo $kitchen->getName() ?></td>
<td width="2%"><a href="<?php echo url_for('kitchen/edit?id='.$kitchen->getId()) ?>"><?php echo image_tag('famfamicons/application_edit.png') ?></a></td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
<tfoot>
<tr>
<th colspan="2" class="textright">
<a href="<?php echo url_for('kitchen/new') ?>" title="New">New</a>
</th>
</tr>
</tfoot>
</table>
</div>
</div>
</div> | xop32/propertyx | apps/be/modules/kitchen/templates/indexSuccess.php | PHP | mit | 1,100 |
import { c } from 'ttag';
export class ImportFatalError extends Error {
error: Error;
constructor(error: Error) {
super(c('Error importing calendar').t`An unexpected error occurred. Import must be restarted.`);
this.error = error;
Object.setPrototypeOf(this, ImportFatalError.prototype);
}
}
| ProtonMail/WebClient | packages/shared/lib/contacts/errors/ImportFatalError.ts | TypeScript | mit | 330 |
package com.xruby.runtime.lang;
public abstract class RubyConstant extends RubyBasic {
public static RubyConstant QFALSE = new RubyConstant(RubyRuntime.FalseClassClass) {
public boolean isTrue() {
return false;
}
};
public static RubyConstant QTRUE = new RubyConstant(RubyRuntime.TrueClassClass) {
public boolean isTrue() {
return true;
}
};
public static RubyConstant QNIL = new RubyConstant(RubyRuntime.NilClassClass) {
public boolean isTrue() {
return false;
}
public String toStr() {
throw new RubyException(RubyRuntime.TypeErrorClass, "Cannot convert nil into String");
}
};
private RubyConstant(RubyClass c) {
super(c);
}
}
| Yashi100/rhodes3.3.2 | platform/bb/RubyVM/src/com/xruby/runtime/lang/RubyConstant.java | Java | mit | 802 |
// This file was generated based on '(multiple files)'.
// WARNING: Changes might be lost if you edit this file directly.
#include <Fuse.Drawing.Meshes.MeshGenerator.h>
#include <Fuse.Entities.Mesh.h>
#include <Fuse.Entities.MeshHitTestMode.h>
#include <Fuse.Entities.Primitives.ConeRenderer.h>
#include <Fuse.Entities.Primitives.CubeRenderer.h>
#include <Fuse.Entities.Primitives.CylinderRenderer.h>
#include <Fuse.Entities.Primitives.SphereRenderer.h>
#include <Uno.Bool.h>
#include <Uno.Content.Models.ModelMesh.h>
#include <Uno.Float.h>
#include <Uno.Float3.h>
#include <Uno.Int.h>
static uType* TYPES[1];
namespace g{
namespace Fuse{
namespace Entities{
namespace Primitives{
// C:\ProgramData\Uno\Packages\Fuse.Entities\0.18.8\$.uno(1788)
// ------------------------------------------------------------
// public sealed class ConeRenderer :1788
// {
::g::Fuse::Entities::MeshRenderer_type* ConeRenderer_typeof()
{
static uSStrong< ::g::Fuse::Entities::MeshRenderer_type*> type;
if (type != NULL) return type;
uTypeOptions options;
options.FieldCount = 6;
options.ObjectSize = sizeof(ConeRenderer);
options.TypeSize = sizeof(::g::Fuse::Entities::MeshRenderer_type);
type = (::g::Fuse::Entities::MeshRenderer_type*)uClassType::New("Fuse.Entities.Primitives.ConeRenderer", options);
type->SetBase(::g::Fuse::Entities::MeshRenderer_typeof());
type->fp_ctor_ = (void*)ConeRenderer__New2_fn;
::TYPES[0] = ::g::Fuse::Entities::MeshRenderer_typeof();
type->SetFields(6);
type->Reflection.SetFunctions(1,
new uFunction(".ctor", NULL, (void*)ConeRenderer__New2_fn, 0, true, ConeRenderer_typeof(), 0));
return type;
}
// public ConeRenderer() :1790
void ConeRenderer__ctor_2_fn(ConeRenderer* __this)
{
__this->ctor_2();
}
// public ConeRenderer New() :1790
void ConeRenderer__New2_fn(ConeRenderer** __retval)
{
*__retval = ConeRenderer::New2();
}
// public ConeRenderer() [instance] :1790
void ConeRenderer::ctor_2()
{
ctor_1();
Mesh(::g::Fuse::Entities::Mesh::New2(::g::Fuse::Drawing::Meshes::MeshGenerator::CreateCone(10.0f, 5.0f, 16, 16)));
}
// public ConeRenderer New() [static] :1790
ConeRenderer* ConeRenderer::New2()
{
ConeRenderer* obj1 = (ConeRenderer*)uNew(ConeRenderer_typeof());
obj1->ctor_2();
return obj1;
}
// }
// C:\ProgramData\Uno\Packages\Fuse.Entities\0.18.8\$.uno(1729)
// ------------------------------------------------------------
// public sealed class CubeRenderer :1729
// {
::g::Fuse::Entities::MeshRenderer_type* CubeRenderer_typeof()
{
static uSStrong< ::g::Fuse::Entities::MeshRenderer_type*> type;
if (type != NULL) return type;
uTypeOptions options;
options.FieldCount = 6;
options.ObjectSize = sizeof(CubeRenderer);
options.TypeSize = sizeof(::g::Fuse::Entities::MeshRenderer_type);
type = (::g::Fuse::Entities::MeshRenderer_type*)uClassType::New("Fuse.Entities.Primitives.CubeRenderer", options);
type->SetBase(::g::Fuse::Entities::MeshRenderer_typeof());
type->fp_ctor_ = (void*)CubeRenderer__New2_fn;
::TYPES[0] = ::g::Fuse::Entities::MeshRenderer_typeof();
type->SetFields(6);
type->Reflection.SetFunctions(1,
new uFunction(".ctor", NULL, (void*)CubeRenderer__New2_fn, 0, true, CubeRenderer_typeof(), 0));
return type;
}
// public CubeRenderer() :1731
void CubeRenderer__ctor_2_fn(CubeRenderer* __this)
{
__this->ctor_2();
}
// public CubeRenderer New() :1731
void CubeRenderer__New2_fn(CubeRenderer** __retval)
{
*__retval = CubeRenderer::New2();
}
// public CubeRenderer() [instance] :1731
void CubeRenderer::ctor_2()
{
ctor_1();
Mesh(::g::Fuse::Entities::Mesh::New2(::g::Fuse::Drawing::Meshes::MeshGenerator::CreateCube(::g::Uno::Float3__New1(0.0f), 5.0f)));
HitTestMode(1);
}
// public CubeRenderer New() [static] :1731
CubeRenderer* CubeRenderer::New2()
{
CubeRenderer* obj1 = (CubeRenderer*)uNew(CubeRenderer_typeof());
obj1->ctor_2();
return obj1;
}
// }
// C:\ProgramData\Uno\Packages\Fuse.Entities\0.18.8\$.uno(1797)
// ------------------------------------------------------------
// public sealed class CylinderRenderer :1797
// {
::g::Fuse::Entities::MeshRenderer_type* CylinderRenderer_typeof()
{
static uSStrong< ::g::Fuse::Entities::MeshRenderer_type*> type;
if (type != NULL) return type;
uTypeOptions options;
options.FieldCount = 6;
options.ObjectSize = sizeof(CylinderRenderer);
options.TypeSize = sizeof(::g::Fuse::Entities::MeshRenderer_type);
type = (::g::Fuse::Entities::MeshRenderer_type*)uClassType::New("Fuse.Entities.Primitives.CylinderRenderer", options);
type->SetBase(::g::Fuse::Entities::MeshRenderer_typeof());
type->fp_ctor_ = (void*)CylinderRenderer__New2_fn;
::TYPES[0] = ::g::Fuse::Entities::MeshRenderer_typeof();
type->SetFields(6);
type->Reflection.SetFunctions(1,
new uFunction(".ctor", NULL, (void*)CylinderRenderer__New2_fn, 0, true, CylinderRenderer_typeof(), 0));
return type;
}
// public CylinderRenderer() :1799
void CylinderRenderer__ctor_2_fn(CylinderRenderer* __this)
{
__this->ctor_2();
}
// public CylinderRenderer New() :1799
void CylinderRenderer__New2_fn(CylinderRenderer** __retval)
{
*__retval = CylinderRenderer::New2();
}
// public CylinderRenderer() [instance] :1799
void CylinderRenderer::ctor_2()
{
ctor_1();
Mesh(::g::Fuse::Entities::Mesh::New2(::g::Fuse::Drawing::Meshes::MeshGenerator::CreateCylinder(10.0f, 5.0f, 16, 16)));
}
// public CylinderRenderer New() [static] :1799
CylinderRenderer* CylinderRenderer::New2()
{
CylinderRenderer* obj1 = (CylinderRenderer*)uNew(CylinderRenderer_typeof());
obj1->ctor_2();
return obj1;
}
// }
// C:\ProgramData\Uno\Packages\Fuse.Entities\0.18.8\$.uno(1739)
// ------------------------------------------------------------
// public sealed class SphereRenderer :1739
// {
::g::Fuse::Entities::MeshRenderer_type* SphereRenderer_typeof()
{
static uSStrong< ::g::Fuse::Entities::MeshRenderer_type*> type;
if (type != NULL) return type;
uTypeOptions options;
options.FieldCount = 9;
options.ObjectSize = sizeof(SphereRenderer);
options.TypeSize = sizeof(::g::Fuse::Entities::MeshRenderer_type);
type = (::g::Fuse::Entities::MeshRenderer_type*)uClassType::New("Fuse.Entities.Primitives.SphereRenderer", options);
type->SetBase(::g::Fuse::Entities::MeshRenderer_typeof());
type->fp_ctor_ = (void*)SphereRenderer__New2_fn;
type->fp_Validate = (void(*)(::g::Fuse::Entities::MeshRenderer*))SphereRenderer__Validate_fn;
::TYPES[0] = ::g::Fuse::Entities::MeshRenderer_typeof();
type->SetFields(6,
::g::Uno::Bool_typeof(), offsetof(::g::Fuse::Entities::Primitives::SphereRenderer, _isDirty), 0,
::g::Uno::Int_typeof(), offsetof(::g::Fuse::Entities::Primitives::SphereRenderer, _quality), 0,
::g::Uno::Float_typeof(), offsetof(::g::Fuse::Entities::Primitives::SphereRenderer, _radius), 0);
type->Reflection.SetFunctions(5,
new uFunction(".ctor", NULL, (void*)SphereRenderer__New2_fn, 0, true, SphereRenderer_typeof(), 0),
new uFunction("get_Quality", NULL, (void*)SphereRenderer__get_Quality_fn, 0, false, ::g::Uno::Int_typeof(), 0),
new uFunction("set_Quality", NULL, (void*)SphereRenderer__set_Quality_fn, 0, false, uVoid_typeof(), 1, ::g::Uno::Int_typeof()),
new uFunction("get_Radius", NULL, (void*)SphereRenderer__get_Radius_fn, 0, false, ::g::Uno::Float_typeof(), 0),
new uFunction("set_Radius", NULL, (void*)SphereRenderer__set_Radius_fn, 0, false, uVoid_typeof(), 1, ::g::Uno::Float_typeof()));
return type;
}
// public SphereRenderer() :1771
void SphereRenderer__ctor_2_fn(SphereRenderer* __this)
{
__this->ctor_2();
}
// public SphereRenderer New() :1771
void SphereRenderer__New2_fn(SphereRenderer** __retval)
{
*__retval = SphereRenderer::New2();
}
// public int get_Quality() :1760
void SphereRenderer__get_Quality_fn(SphereRenderer* __this, int* __retval)
{
*__retval = __this->Quality();
}
// public void set_Quality(int value) :1761
void SphereRenderer__set_Quality_fn(SphereRenderer* __this, int* value)
{
__this->Quality(*value);
}
// public float get_Radius() :1746
void SphereRenderer__get_Radius_fn(SphereRenderer* __this, float* __retval)
{
*__retval = __this->Radius();
}
// public void set_Radius(float value) :1747
void SphereRenderer__set_Radius_fn(SphereRenderer* __this, float* value)
{
__this->Radius(*value);
}
// protected override sealed void Validate() :1776
void SphereRenderer__Validate_fn(SphereRenderer* __this)
{
if (__this->_isDirty || (__this->Mesh() == NULL))
{
if (__this->Mesh() != NULL)
uPtr(__this->Mesh())->Dispose();
__this->Mesh(::g::Fuse::Entities::Mesh::New2(::g::Fuse::Drawing::Meshes::MeshGenerator::CreateSphere(::g::Uno::Float3__New1(0.0f), __this->_radius, __this->_quality, __this->_quality)));
__this->_isDirty = false;
}
}
// public SphereRenderer() [instance] :1771
void SphereRenderer::ctor_2()
{
_radius = 5.0f;
_quality = 16;
ctor_1();
HitTestMode(2);
}
// public int get_Quality() [instance] :1760
int SphereRenderer::Quality()
{
return _quality;
}
// public void set_Quality(int value) [instance] :1761
void SphereRenderer::Quality(int value)
{
if (_quality != value)
{
_quality = value;
_isDirty = true;
}
}
// public float get_Radius() [instance] :1746
float SphereRenderer::Radius()
{
return _radius;
}
// public void set_Radius(float value) [instance] :1747
void SphereRenderer::Radius(float value)
{
if (_radius != value)
{
_radius = value;
_isDirty = true;
}
}
// public SphereRenderer New() [static] :1771
SphereRenderer* SphereRenderer::New2()
{
SphereRenderer* obj1 = (SphereRenderer*)uNew(SphereRenderer_typeof());
obj1->ctor_2();
return obj1;
}
// }
}}}} // ::g::Fuse::Entities::Primitives
| blyk/BlackCode-Fuse | TestApp/.build/Simulator/Android/jni/Fuse.Entities.Primitives.g.cpp | C++ | mit | 9,980 |
game.LoadProfile = me.ScreenObject.extend({
/**
* action to perform on state change
*/
onResetEvent: function() {
me.game.world.addChild(new me.Sprite(0, 0, me.loader.getImage('load-screen')), -10);
//puts load screen in when game starts
document.getElementById("input").style.visibility = "visible";
document.getElementById("load").style.visibility = "visible";
me.input.unbindKey(me.input.KEY.B);
me.input.unbindKey(me.input.KEY.I);
me.input.unbindKey(me.input.KEY.O);
me.input.unbindKey(me.input.KEY.P);
me.input.unbindKey(me.input.KEY.SPACE);
//unbinds keys
var exp1cost = ((game.data.exp1 + 1) * 10);
var exp2cost = ((game.data.exp2 + 1) * 10);
var exp3cost = ((game.data.exp3 + 1) * 10);
var exp4cost = ((game.data.exp4 + 1) * 10);
me.game.world.addChild(new (me.Renderable.extend({
init: function() {
this._super(me.Renderable, 'init', [10, 10, 300, 50]);
this.font = new me.Font("Arial", 26, "white");
},
draw: function(renderer) {
this.font.draw(renderer.getContext(), "Enter Username & Password", this.pos.x, this.pos.y);
}
})));
},
/**
* action to perform when leaving this screen (state change)
*/
onDestroyEvent: function() {
document.getElementById("input").style.visibility = "hidden";
document.getElementById("load").style.visibility = "hidden";
}
}); | MrLarrimore/MiguelRicardo | js/screens/loadProfile.js | JavaScript | mit | 1,578 |
/*
---
MooTools: the javascript framework
web build:
- http://mootools.net/core/8423c12ffd6a6bfcde9ea22554aec795
packager build:
- packager build Core/Core Core/Array Core/String Core/Number Core/Function Core/Object Core/Event Core/Browser Core/Class Core/Class.Extras Core/Slick.Parser Core/Slick.Finder Core/Element Core/Element.Style Core/Element.Event Core/Element.Delegation Core/Element.Dimensions Core/Fx Core/Fx.CSS Core/Fx.Tween Core/Fx.Morph Core/Fx.Transitions Core/Request Core/Request.HTML Core/Request.JSON Core/Cookie Core/JSON Core/DOMReady
...
*/
/*
---
name: Core
description: The heart of MooTools.
license: MIT-style license.
copyright: Copyright (c) 2006-2012 [Valerio Proietti](http://mad4milk.net/).
authors: The MooTools production team (http://mootools.net/developers/)
inspiration:
- Class implementation inspired by [Base.js](http://dean.edwards.name/weblog/2006/03/base/) Copyright (c) 2006 Dean Edwards, [GNU Lesser General Public License](http://opensource.org/licenses/lgpl-license.php)
- Some functionality inspired by [Prototype.js](http://prototypejs.org) Copyright (c) 2005-2007 Sam Stephenson, [MIT License](http://opensource.org/licenses/mit-license.php)
provides: [Core, MooTools, Type, typeOf, instanceOf, Native]
...
*/
(function(){
this.MooTools = {
version: '1.4.5',
build: 'ab8ea8824dc3b24b6666867a2c4ed58ebb762cf0'
};
// typeOf, instanceOf
var typeOf = this.typeOf = function(item){
if (item == null) return 'null';
if (item.$family != null) return item.$family();
if (item.nodeName){
if (item.nodeType == 1) return 'element';
if (item.nodeType == 3) return (/\S/).test(item.nodeValue) ? 'textnode' : 'whitespace';
} else if (typeof item.length == 'number'){
if (item.callee) return 'arguments';
if ('item' in item) return 'collection';
}
return typeof item;
};
var instanceOf = this.instanceOf = function(item, object){
if (item == null) return false;
var constructor = item.$constructor || item.constructor;
while (constructor){
if (constructor === object) return true;
constructor = constructor.parent;
}
/*<ltIE8>*/
if (!item.hasOwnProperty) return false;
/*</ltIE8>*/
return item instanceof object;
};
// Function overloading
var Function = this.Function;
var enumerables = true;
for (var i in {toString: 1}) enumerables = null;
if (enumerables) enumerables = ['hasOwnProperty', 'valueOf', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'constructor'];
Function.prototype.overloadSetter = function(usePlural){
var self = this;
return function(a, b){
if (a == null) return this;
if (usePlural || typeof a != 'string'){
for (var k in a) self.call(this, k, a[k]);
if (enumerables) for (var i = enumerables.length; i--;){
k = enumerables[i];
if (a.hasOwnProperty(k)) self.call(this, k, a[k]);
}
} else {
self.call(this, a, b);
}
return this;
};
};
Function.prototype.overloadGetter = function(usePlural){
var self = this;
return function(a){
var args, result;
if (typeof a != 'string') args = a;
else if (arguments.length > 1) args = arguments;
else if (usePlural) args = [a];
if (args){
result = {};
for (var i = 0; i < args.length; i++) result[args[i]] = self.call(this, args[i]);
} else {
result = self.call(this, a);
}
return result;
};
};
Function.prototype.extend = function(key, value){
this[key] = value;
}.overloadSetter();
Function.prototype.implement = function(key, value){
this.prototype[key] = value;
}.overloadSetter();
// From
var slice = Array.prototype.slice;
Function.from = function(item){
return (typeOf(item) == 'function') ? item : function(){
return item;
};
};
Array.from = function(item){
if (item == null) return [];
return (Type.isEnumerable(item) && typeof item != 'string') ? (typeOf(item) == 'array') ? item : slice.call(item) : [item];
};
Number.from = function(item){
var number = parseFloat(item);
return isFinite(number) ? number : null;
};
String.from = function(item){
return item + '';
};
// hide, protect
Function.implement({
hide: function(){
this.$hidden = true;
return this;
},
protect: function(){
this.$protected = true;
return this;
}
});
// Type
var Type = this.Type = function(name, object){
if (name){
var lower = name.toLowerCase();
var typeCheck = function(item){
return (typeOf(item) == lower);
};
Type['is' + name] = typeCheck;
if (object != null){
object.prototype.$family = (function(){
return lower;
}).hide();
}
}
if (object == null) return null;
object.extend(this);
object.$constructor = Type;
object.prototype.$constructor = object;
return object;
};
var toString = Object.prototype.toString;
Type.isEnumerable = function(item){
return (item != null && typeof item.length == 'number' && toString.call(item) != '[object Function]' );
};
var hooks = {};
var hooksOf = function(object){
var type = typeOf(object.prototype);
return hooks[type] || (hooks[type] = []);
};
var implement = function(name, method){
if (method && method.$hidden) return;
var hooks = hooksOf(this);
for (var i = 0; i < hooks.length; i++){
var hook = hooks[i];
if (typeOf(hook) == 'type') implement.call(hook, name, method);
else hook.call(this, name, method);
}
var previous = this.prototype[name];
if (previous == null || !previous.$protected) this.prototype[name] = method;
if (this[name] == null && typeOf(method) == 'function') extend.call(this, name, function(item){
return method.apply(item, slice.call(arguments, 1));
});
};
var extend = function(name, method){
if (method && method.$hidden) return;
var previous = this[name];
if (previous == null || !previous.$protected) this[name] = method;
};
Type.implement({
implement: implement.overloadSetter(),
extend: extend.overloadSetter(),
alias: function(name, existing){
implement.call(this, name, this.prototype[existing]);
}.overloadSetter(),
mirror: function(hook){
hooksOf(this).push(hook);
return this;
}
});
new Type('Type', Type);
// Default Types
var force = function(name, object, methods){
var isType = (object != Object),
prototype = object.prototype;
if (isType) object = new Type(name, object);
for (var i = 0, l = methods.length; i < l; i++){
var key = methods[i],
generic = object[key],
proto = prototype[key];
if (generic) generic.protect();
if (isType && proto) object.implement(key, proto.protect());
}
if (isType){
var methodsEnumerable = prototype.propertyIsEnumerable(methods[0]);
object.forEachMethod = function(fn){
if (!methodsEnumerable) for (var i = 0, l = methods.length; i < l; i++){
fn.call(prototype, prototype[methods[i]], methods[i]);
}
for (var key in prototype) fn.call(prototype, prototype[key], key)
};
}
return force;
};
force('String', String, [
'charAt', 'charCodeAt', 'concat', 'indexOf', 'lastIndexOf', 'match', 'quote', 'replace', 'search',
'slice', 'split', 'substr', 'substring', 'trim', 'toLowerCase', 'toUpperCase'
])('Array', Array, [
'pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift', 'concat', 'join', 'slice',
'indexOf', 'lastIndexOf', 'filter', 'forEach', 'every', 'map', 'some', 'reduce', 'reduceRight'
])('Number', Number, [
'toExponential', 'toFixed', 'toLocaleString', 'toPrecision'
])('Function', Function, [
'apply', 'call', 'bind'
])('RegExp', RegExp, [
'exec', 'test'
])('Object', Object, [
'create', 'defineProperty', 'defineProperties', 'keys',
'getPrototypeOf', 'getOwnPropertyDescriptor', 'getOwnPropertyNames',
'preventExtensions', 'isExtensible', 'seal', 'isSealed', 'freeze', 'isFrozen'
])('Date', Date, ['now']);
Object.extend = extend.overloadSetter();
Date.extend('now', function(){
return +(new Date);
});
new Type('Boolean', Boolean);
// fixes NaN returning as Number
Number.prototype.$family = function(){
return isFinite(this) ? 'number' : 'null';
}.hide();
// Number.random
Number.extend('random', function(min, max){
return Math.floor(Math.random() * (max - min + 1) + min);
});
// forEach, each
var hasOwnProperty = Object.prototype.hasOwnProperty;
Object.extend('forEach', function(object, fn, bind){
for (var key in object){
if (hasOwnProperty.call(object, key)) fn.call(bind, object[key], key, object);
}
});
Object.each = Object.forEach;
Array.implement({
forEach: function(fn, bind){
for (var i = 0, l = this.length; i < l; i++){
if (i in this) fn.call(bind, this[i], i, this);
}
},
each: function(fn, bind){
Array.forEach(this, fn, bind);
return this;
}
});
// Array & Object cloning, Object merging and appending
var cloneOf = function(item){
switch (typeOf(item)){
case 'array': return item.clone();
case 'object': return Object.clone(item);
default: return item;
}
};
Array.implement('clone', function(){
var i = this.length, clone = new Array(i);
while (i--) clone[i] = cloneOf(this[i]);
return clone;
});
var mergeOne = function(source, key, current){
switch (typeOf(current)){
case 'object':
if (typeOf(source[key]) == 'object') Object.merge(source[key], current);
else source[key] = Object.clone(current);
break;
case 'array': source[key] = current.clone(); break;
default: source[key] = current;
}
return source;
};
Object.extend({
merge: function(source, k, v){
if (typeOf(k) == 'string') return mergeOne(source, k, v);
for (var i = 1, l = arguments.length; i < l; i++){
var object = arguments[i];
for (var key in object) mergeOne(source, key, object[key]);
}
return source;
},
clone: function(object){
var clone = {};
for (var key in object) clone[key] = cloneOf(object[key]);
return clone;
},
append: function(original){
for (var i = 1, l = arguments.length; i < l; i++){
var extended = arguments[i] || {};
for (var key in extended) original[key] = extended[key];
}
return original;
}
});
// Object-less types
['Object', 'WhiteSpace', 'TextNode', 'Collection', 'Arguments'].each(function(name){
new Type(name);
});
// Unique ID
var UID = Date.now();
String.extend('uniqueID', function(){
return (UID++).toString(36);
});
})();
/*
---
name: Array
description: Contains Array Prototypes like each, contains, and erase.
license: MIT-style license.
requires: Type
provides: Array
...
*/
Array.implement({
/*<!ES5>*/
every: function(fn, bind){
for (var i = 0, l = this.length >>> 0; i < l; i++){
if ((i in this) && !fn.call(bind, this[i], i, this)) return false;
}
return true;
},
filter: function(fn, bind){
var results = [];
for (var value, i = 0, l = this.length >>> 0; i < l; i++) if (i in this){
value = this[i];
if (fn.call(bind, value, i, this)) results.push(value);
}
return results;
},
indexOf: function(item, from){
var length = this.length >>> 0;
for (var i = (from < 0) ? Math.max(0, length + from) : from || 0; i < length; i++){
if (this[i] === item) return i;
}
return -1;
},
map: function(fn, bind){
var length = this.length >>> 0, results = Array(length);
for (var i = 0; i < length; i++){
if (i in this) results[i] = fn.call(bind, this[i], i, this);
}
return results;
},
some: function(fn, bind){
for (var i = 0, l = this.length >>> 0; i < l; i++){
if ((i in this) && fn.call(bind, this[i], i, this)) return true;
}
return false;
},
/*</!ES5>*/
clean: function(){
return this.filter(function(item){
return item != null;
});
},
invoke: function(methodName){
var args = Array.slice(arguments, 1);
return this.map(function(item){
return item[methodName].apply(item, args);
});
},
associate: function(keys){
var obj = {}, length = Math.min(this.length, keys.length);
for (var i = 0; i < length; i++) obj[keys[i]] = this[i];
return obj;
},
link: function(object){
var result = {};
for (var i = 0, l = this.length; i < l; i++){
for (var key in object){
if (object[key](this[i])){
result[key] = this[i];
delete object[key];
break;
}
}
}
return result;
},
contains: function(item, from){
return this.indexOf(item, from) != -1;
},
append: function(array){
this.push.apply(this, array);
return this;
},
getLast: function(){
return (this.length) ? this[this.length - 1] : null;
},
getRandom: function(){
return (this.length) ? this[Number.random(0, this.length - 1)] : null;
},
include: function(item){
if (!this.contains(item)) this.push(item);
return this;
},
combine: function(array){
for (var i = 0, l = array.length; i < l; i++) this.include(array[i]);
return this;
},
erase: function(item){
for (var i = this.length; i--;){
if (this[i] === item) this.splice(i, 1);
}
return this;
},
empty: function(){
this.length = 0;
return this;
},
flatten: function(){
var array = [];
for (var i = 0, l = this.length; i < l; i++){
var type = typeOf(this[i]);
if (type == 'null') continue;
array = array.concat((type == 'array' || type == 'collection' || type == 'arguments' || instanceOf(this[i], Array)) ? Array.flatten(this[i]) : this[i]);
}
return array;
},
pick: function(){
for (var i = 0, l = this.length; i < l; i++){
if (this[i] != null) return this[i];
}
return null;
},
hexToRgb: function(array){
if (this.length != 3) return null;
var rgb = this.map(function(value){
if (value.length == 1) value += value;
return value.toInt(16);
});
return (array) ? rgb : 'rgb(' + rgb + ')';
},
rgbToHex: function(array){
if (this.length < 3) return null;
if (this.length == 4 && this[3] == 0 && !array) return 'transparent';
var hex = [];
for (var i = 0; i < 3; i++){
var bit = (this[i] - 0).toString(16);
hex.push((bit.length == 1) ? '0' + bit : bit);
}
return (array) ? hex : '#' + hex.join('');
}
});
/*
---
name: String
description: Contains String Prototypes like camelCase, capitalize, test, and toInt.
license: MIT-style license.
requires: Type
provides: String
...
*/
String.implement({
test: function(regex, params){
return ((typeOf(regex) == 'regexp') ? regex : new RegExp('' + regex, params)).test(this);
},
contains: function(string, separator){
return (separator) ? (separator + this + separator).indexOf(separator + string + separator) > -1 : String(this).indexOf(string) > -1;
},
trim: function(){
return String(this).replace(/^\s+|\s+$/g, '');
},
clean: function(){
return String(this).replace(/\s+/g, ' ').trim();
},
camelCase: function(){
return String(this).replace(/-\D/g, function(match){
return match.charAt(1).toUpperCase();
});
},
hyphenate: function(){
return String(this).replace(/[A-Z]/g, function(match){
return ('-' + match.charAt(0).toLowerCase());
});
},
capitalize: function(){
return String(this).replace(/\b[a-z]/g, function(match){
return match.toUpperCase();
});
},
escapeRegExp: function(){
return String(this).replace(/([-.*+?^${}()|[\]\/\\])/g, '\\$1');
},
toInt: function(base){
return parseInt(this, base || 10);
},
toFloat: function(){
return parseFloat(this);
},
hexToRgb: function(array){
var hex = String(this).match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/);
return (hex) ? hex.slice(1).hexToRgb(array) : null;
},
rgbToHex: function(array){
var rgb = String(this).match(/\d{1,3}/g);
return (rgb) ? rgb.rgbToHex(array) : null;
},
substitute: function(object, regexp){
return String(this).replace(regexp || (/\\?\{([^{}]+)\}/g), function(match, name){
if (match.charAt(0) == '\\') return match.slice(1);
return (object[name] != null) ? object[name] : '';
});
}
});
/*
---
name: Number
description: Contains Number Prototypes like limit, round, times, and ceil.
license: MIT-style license.
requires: Type
provides: Number
...
*/
Number.implement({
limit: function(min, max){
return Math.min(max, Math.max(min, this));
},
round: function(precision){
precision = Math.pow(10, precision || 0).toFixed(precision < 0 ? -precision : 0);
return Math.round(this * precision) / precision;
},
times: function(fn, bind){
for (var i = 0; i < this; i++) fn.call(bind, i, this);
},
toFloat: function(){
return parseFloat(this);
},
toInt: function(base){
return parseInt(this, base || 10);
}
});
Number.alias('each', 'times');
(function(math){
var methods = {};
math.each(function(name){
if (!Number[name]) methods[name] = function(){
return Math[name].apply(null, [this].concat(Array.from(arguments)));
};
});
Number.implement(methods);
})(['abs', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'exp', 'floor', 'log', 'max', 'min', 'pow', 'sin', 'sqrt', 'tan']);
/*
---
name: Function
description: Contains Function Prototypes like create, bind, pass, and delay.
license: MIT-style license.
requires: Type
provides: Function
...
*/
Function.extend({
attempt: function(){
for (var i = 0, l = arguments.length; i < l; i++){
try {
return arguments[i]();
} catch (e){}
}
return null;
}
});
Function.implement({
attempt: function(args, bind){
try {
return this.apply(bind, Array.from(args));
} catch (e){}
return null;
},
/*<!ES5-bind>*/
bind: function(that){
var self = this,
args = arguments.length > 1 ? Array.slice(arguments, 1) : null,
F = function(){};
var bound = function(){
var context = that, length = arguments.length;
if (this instanceof bound){
F.prototype = self.prototype;
context = new F;
}
var result = (!args && !length)
? self.call(context)
: self.apply(context, args && length ? args.concat(Array.slice(arguments)) : args || arguments);
return context == that ? result : context;
};
return bound;
},
/*</!ES5-bind>*/
pass: function(args, bind){
var self = this;
if (args != null) args = Array.from(args);
return function(){
return self.apply(bind, args || arguments);
};
},
delay: function(delay, bind, args){
return setTimeout(this.pass((args == null ? [] : args), bind), delay);
},
periodical: function(periodical, bind, args){
return setInterval(this.pass((args == null ? [] : args), bind), periodical);
}
});
/*
---
name: Object
description: Object generic methods
license: MIT-style license.
requires: Type
provides: [Object, Hash]
...
*/
(function(){
var hasOwnProperty = Object.prototype.hasOwnProperty;
Object.extend({
subset: function(object, keys){
var results = {};
for (var i = 0, l = keys.length; i < l; i++){
var k = keys[i];
if (k in object) results[k] = object[k];
}
return results;
},
map: function(object, fn, bind){
var results = {};
for (var key in object){
if (hasOwnProperty.call(object, key)) results[key] = fn.call(bind, object[key], key, object);
}
return results;
},
filter: function(object, fn, bind){
var results = {};
for (var key in object){
var value = object[key];
if (hasOwnProperty.call(object, key) && fn.call(bind, value, key, object)) results[key] = value;
}
return results;
},
every: function(object, fn, bind){
for (var key in object){
if (hasOwnProperty.call(object, key) && !fn.call(bind, object[key], key)) return false;
}
return true;
},
some: function(object, fn, bind){
for (var key in object){
if (hasOwnProperty.call(object, key) && fn.call(bind, object[key], key)) return true;
}
return false;
},
keys: function(object){
var keys = [];
for (var key in object){
if (hasOwnProperty.call(object, key)) keys.push(key);
}
return keys;
},
values: function(object){
var values = [];
for (var key in object){
if (hasOwnProperty.call(object, key)) values.push(object[key]);
}
return values;
},
getLength: function(object){
return Object.keys(object).length;
},
keyOf: function(object, value){
for (var key in object){
if (hasOwnProperty.call(object, key) && object[key] === value) return key;
}
return null;
},
contains: function(object, value){
return Object.keyOf(object, value) != null;
},
toQueryString: function(object, base){
var queryString = [];
Object.each(object, function(value, key){
if (base) key = base + '[' + key + ']';
var result;
switch (typeOf(value)){
case 'object': result = Object.toQueryString(value, key); break;
case 'array':
var qs = {};
value.each(function(val, i){
qs[i] = val;
});
result = Object.toQueryString(qs, key);
break;
default: result = key + '=' + encodeURIComponent(value);
}
if (value != null) queryString.push(result);
});
return queryString.join('&');
}
});
})();
/*
---
name: Browser
description: The Browser Object. Contains Browser initialization, Window and Document, and the Browser Hash.
license: MIT-style license.
requires: [Array, Function, Number, String]
provides: [Browser, Window, Document]
...
*/
(function(){
var document = this.document;
var window = document.window = this;
var ua = navigator.userAgent.toLowerCase(),
platform = navigator.platform.toLowerCase(),
UA = ua.match(/(opera|ie|firefox|chrome|version)[\s\/:]([\w\d\.]+)?.*?(safari|version[\s\/:]([\w\d\.]+)|$)/) || [null, 'unknown', 0],
mode = UA[1] == 'ie' && document.documentMode;
var Browser = this.Browser = {
extend: Function.prototype.extend,
name: (UA[1] == 'version') ? UA[3] : UA[1],
version: mode || parseFloat((UA[1] == 'opera' && UA[4]) ? UA[4] : UA[2]),
Platform: {
name: ua.match(/ip(?:ad|od|hone)/) ? 'ios' : (ua.match(/(?:webos|android)/) || platform.match(/mac|win|linux/) || ['other'])[0]
},
Features: {
xpath: !!(document.evaluate),
air: !!(window.runtime),
query: !!(document.querySelector),
json: !!(window.JSON)
},
Plugins: {}
};
Browser[Browser.name] = true;
Browser[Browser.name + parseInt(Browser.version, 10)] = true;
Browser.Platform[Browser.Platform.name] = true;
// Request
Browser.Request = (function(){
var XMLHTTP = function(){
return new XMLHttpRequest();
};
var MSXML2 = function(){
return new ActiveXObject('MSXML2.XMLHTTP');
};
var MSXML = function(){
return new ActiveXObject('Microsoft.XMLHTTP');
};
return Function.attempt(function(){
XMLHTTP();
return XMLHTTP;
}, function(){
MSXML2();
return MSXML2;
}, function(){
MSXML();
return MSXML;
});
})();
Browser.Features.xhr = !!(Browser.Request);
// Flash detection
var version = (Function.attempt(function(){
return navigator.plugins['Shockwave Flash'].description;
}, function(){
return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version');
}) || '0 r0').match(/\d+/g);
Browser.Plugins.Flash = {
version: Number(version[0] || '0.' + version[1]) || 0,
build: Number(version[2]) || 0
};
// String scripts
Browser.exec = function(text){
if (!text) return text;
if (window.execScript){
window.execScript(text);
} else {
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.text = text;
document.head.appendChild(script);
document.head.removeChild(script);
}
return text;
};
String.implement('stripScripts', function(exec){
var scripts = '';
var text = this.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi, function(all, code){
scripts += code + '\n';
return '';
});
if (exec === true) Browser.exec(scripts);
else if (typeOf(exec) == 'function') exec(scripts, text);
return text;
});
// Window, Document
Browser.extend({
Document: this.Document,
Window: this.Window,
Element: this.Element,
Event: this.Event
});
this.Window = this.$constructor = new Type('Window', function(){});
this.$family = Function.from('window').hide();
Window.mirror(function(name, method){
window[name] = method;
});
this.Document = document.$constructor = new Type('Document', function(){});
document.$family = Function.from('document').hide();
Document.mirror(function(name, method){
document[name] = method;
});
document.html = document.documentElement;
if (!document.head) document.head = document.getElementsByTagName('head')[0];
if (document.execCommand) try {
document.execCommand("BackgroundImageCache", false, true);
} catch (e){}
/*<ltIE9>*/
if (this.attachEvent && !this.addEventListener){
var unloadEvent = function(){
this.detachEvent('onunload', unloadEvent);
document.head = document.html = document.window = null;
};
this.attachEvent('onunload', unloadEvent);
}
// IE fails on collections and <select>.options (refers to <select>)
var arrayFrom = Array.from;
try {
arrayFrom(document.html.childNodes);
} catch(e){
Array.from = function(item){
if (typeof item != 'string' && Type.isEnumerable(item) && typeOf(item) != 'array'){
var i = item.length, array = new Array(i);
while (i--) array[i] = item[i];
return array;
}
return arrayFrom(item);
};
var prototype = Array.prototype,
slice = prototype.slice;
['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift', 'concat', 'join', 'slice'].each(function(name){
var method = prototype[name];
Array[name] = function(item){
return method.apply(Array.from(item), slice.call(arguments, 1));
};
});
}
/*</ltIE9>*/
})();
/*
---
name: Event
description: Contains the Event Type, to make the event object cross-browser.
license: MIT-style license.
requires: [Window, Document, Array, Function, String, Object]
provides: Event
...
*/
(function() {
var _keys = {};
var DOMEvent = this.DOMEvent = new Type('DOMEvent', function(event, win){
if (!win) win = window;
event = event || win.event;
if (event.$extended) return event;
this.event = event;
this.$extended = true;
this.shift = event.shiftKey;
this.control = event.ctrlKey;
this.alt = event.altKey;
this.meta = event.metaKey;
var type = this.type = event.type;
var target = event.target || event.srcElement;
while (target && target.nodeType == 3) target = target.parentNode;
this.target = document.id(target);
if (type.indexOf('key') == 0){
var code = this.code = (event.which || event.keyCode);
this.key = _keys[code];
if (type == 'keydown'){
if (code > 111 && code < 124) this.key = 'f' + (code - 111);
else if (code > 95 && code < 106) this.key = code - 96;
}
if (this.key == null) this.key = String.fromCharCode(code).toLowerCase();
} else if (type == 'click' || type == 'dblclick' || type == 'contextmenu' || type == 'DOMMouseScroll' || type.indexOf('mouse') == 0){
var doc = win.document;
doc = (!doc.compatMode || doc.compatMode == 'CSS1Compat') ? doc.html : doc.body;
this.page = {
x: (event.pageX != null) ? event.pageX : event.clientX + doc.scrollLeft,
y: (event.pageY != null) ? event.pageY : event.clientY + doc.scrollTop
};
this.client = {
x: (event.pageX != null) ? event.pageX - win.pageXOffset : event.clientX,
y: (event.pageY != null) ? event.pageY - win.pageYOffset : event.clientY
};
if (type == 'DOMMouseScroll' || type == 'mousewheel')
this.wheel = (event.wheelDelta) ? event.wheelDelta / 120 : -(event.detail || 0) / 3;
this.rightClick = (event.which == 3 || event.button == 2);
if (type == 'mouseover' || type == 'mouseout'){
var related = event.relatedTarget || event[(type == 'mouseover' ? 'from' : 'to') + 'Element'];
while (related && related.nodeType == 3) related = related.parentNode;
this.relatedTarget = document.id(related);
}
} else if (type.indexOf('touch') == 0 || type.indexOf('gesture') == 0){
this.rotation = event.rotation;
this.scale = event.scale;
this.targetTouches = event.targetTouches;
this.changedTouches = event.changedTouches;
var touches = this.touches = event.touches;
if (touches && touches[0]){
var touch = touches[0];
this.page = {x: touch.pageX, y: touch.pageY};
this.client = {x: touch.clientX, y: touch.clientY};
}
}
if (!this.client) this.client = {};
if (!this.page) this.page = {};
});
DOMEvent.implement({
stop: function(){
return this.preventDefault().stopPropagation();
},
stopPropagation: function(){
if (this.event.stopPropagation) this.event.stopPropagation();
else this.event.cancelBubble = true;
return this;
},
preventDefault: function(){
if (this.event.preventDefault) this.event.preventDefault();
else this.event.returnValue = false;
return this;
}
});
DOMEvent.defineKey = function(code, key){
_keys[code] = key;
return this;
};
DOMEvent.defineKeys = DOMEvent.defineKey.overloadSetter(true);
DOMEvent.defineKeys({
'38': 'up', '40': 'down', '37': 'left', '39': 'right',
'27': 'esc', '32': 'space', '8': 'backspace', '9': 'tab',
'46': 'delete', '13': 'enter'
});
})();
/*
---
name: Class
description: Contains the Class Function for easily creating, extending, and implementing reusable Classes.
license: MIT-style license.
requires: [Array, String, Function, Number]
provides: Class
...
*/
(function(){
var Class = this.Class = new Type('Class', function(params){
if (instanceOf(params, Function)) params = {initialize: params};
var newClass = function(){
reset(this);
if (newClass.$prototyping) return this;
this.$caller = null;
var value = (this.initialize) ? this.initialize.apply(this, arguments) : this;
this.$caller = this.caller = null;
return value;
}.extend(this).implement(params);
newClass.$constructor = Class;
newClass.prototype.$constructor = newClass;
newClass.prototype.parent = parent;
return newClass;
});
var parent = function(){
if (!this.$caller) throw new Error('The method "parent" cannot be called.');
var name = this.$caller.$name,
parent = this.$caller.$owner.parent,
previous = (parent) ? parent.prototype[name] : null;
if (!previous) throw new Error('The method "' + name + '" has no parent.');
return previous.apply(this, arguments);
};
var reset = function(object){
for (var key in object){
var value = object[key];
switch (typeOf(value)){
case 'object':
var F = function(){};
F.prototype = value;
object[key] = reset(new F);
break;
case 'array': object[key] = value.clone(); break;
}
}
return object;
};
var wrap = function(self, key, method){
if (method.$origin) method = method.$origin;
var wrapper = function(){
if (method.$protected && this.$caller == null) throw new Error('The method "' + key + '" cannot be called.');
var caller = this.caller, current = this.$caller;
this.caller = current; this.$caller = wrapper;
var result = method.apply(this, arguments);
this.$caller = current; this.caller = caller;
return result;
}.extend({$owner: self, $origin: method, $name: key});
return wrapper;
};
var implement = function(key, value, retain){
if (Class.Mutators.hasOwnProperty(key)){
value = Class.Mutators[key].call(this, value);
if (value == null) return this;
}
if (typeOf(value) == 'function'){
if (value.$hidden) return this;
this.prototype[key] = (retain) ? value : wrap(this, key, value);
} else {
Object.merge(this.prototype, key, value);
}
return this;
};
var getInstance = function(klass){
klass.$prototyping = true;
var proto = new klass;
delete klass.$prototyping;
return proto;
};
Class.implement('implement', implement.overloadSetter());
Class.Mutators = {
Extends: function(parent){
this.parent = parent;
this.prototype = getInstance(parent);
},
Implements: function(items){
Array.from(items).each(function(item){
var instance = new item;
for (var key in instance) implement.call(this, key, instance[key], true);
}, this);
}
};
})();
/*
---
name: Class.Extras
description: Contains Utility Classes that can be implemented into your own Classes to ease the execution of many common tasks.
license: MIT-style license.
requires: Class
provides: [Class.Extras, Chain, Events, Options]
...
*/
(function(){
this.Chain = new Class({
$chain: [],
chain: function(){
this.$chain.append(Array.flatten(arguments));
return this;
},
callChain: function(){
return (this.$chain.length) ? this.$chain.shift().apply(this, arguments) : false;
},
clearChain: function(){
this.$chain.empty();
return this;
}
});
var removeOn = function(string){
return string.replace(/^on([A-Z])/, function(full, first){
return first.toLowerCase();
});
};
this.Events = new Class({
$events: {},
addEvent: function(type, fn, internal){
type = removeOn(type);
this.$events[type] = (this.$events[type] || []).include(fn);
if (internal) fn.internal = true;
return this;
},
addEvents: function(events){
for (var type in events) this.addEvent(type, events[type]);
return this;
},
fireEvent: function(type, args, delay){
type = removeOn(type);
var events = this.$events[type];
if (!events) return this;
args = Array.from(args);
events.each(function(fn){
if (delay) fn.delay(delay, this, args);
else fn.apply(this, args);
}, this);
return this;
},
removeEvent: function(type, fn){
type = removeOn(type);
var events = this.$events[type];
if (events && !fn.internal){
var index = events.indexOf(fn);
if (index != -1) delete events[index];
}
return this;
},
removeEvents: function(events){
var type;
if (typeOf(events) == 'object'){
for (type in events) this.removeEvent(type, events[type]);
return this;
}
if (events) events = removeOn(events);
for (type in this.$events){
if (events && events != type) continue;
var fns = this.$events[type];
for (var i = fns.length; i--;) if (i in fns){
this.removeEvent(type, fns[i]);
}
}
return this;
}
});
this.Options = new Class({
setOptions: function(){
var options = this.options = Object.merge.apply(null, [{}, this.options].append(arguments));
if (this.addEvent) for (var option in options){
if (typeOf(options[option]) != 'function' || !(/^on[A-Z]/).test(option)) continue;
this.addEvent(option, options[option]);
delete options[option];
}
return this;
}
});
})();
/*
---
name: Slick.Parser
description: Standalone CSS3 Selector parser
provides: Slick.Parser
...
*/
;(function(){
var parsed,
separatorIndex,
combinatorIndex,
reversed,
cache = {},
reverseCache = {},
reUnescape = /\\/g;
var parse = function(expression, isReversed){
if (expression == null) return null;
if (expression.Slick === true) return expression;
expression = ('' + expression).replace(/^\s+|\s+$/g, '');
reversed = !!isReversed;
var currentCache = (reversed) ? reverseCache : cache;
if (currentCache[expression]) return currentCache[expression];
parsed = {
Slick: true,
expressions: [],
raw: expression,
reverse: function(){
return parse(this.raw, true);
}
};
separatorIndex = -1;
while (expression != (expression = expression.replace(regexp, parser)));
parsed.length = parsed.expressions.length;
return currentCache[parsed.raw] = (reversed) ? reverse(parsed) : parsed;
};
var reverseCombinator = function(combinator){
if (combinator === '!') return ' ';
else if (combinator === ' ') return '!';
else if ((/^!/).test(combinator)) return combinator.replace(/^!/, '');
else return '!' + combinator;
};
var reverse = function(expression){
var expressions = expression.expressions;
for (var i = 0; i < expressions.length; i++){
var exp = expressions[i];
var last = {parts: [], tag: '*', combinator: reverseCombinator(exp[0].combinator)};
for (var j = 0; j < exp.length; j++){
var cexp = exp[j];
if (!cexp.reverseCombinator) cexp.reverseCombinator = ' ';
cexp.combinator = cexp.reverseCombinator;
delete cexp.reverseCombinator;
}
exp.reverse().push(last);
}
return expression;
};
var escapeRegExp = function(string){// Credit: XRegExp 0.6.1 (c) 2007-2008 Steven Levithan <http://stevenlevithan.com/regex/xregexp/> MIT License
return string.replace(/[-[\]{}()*+?.\\^$|,#\s]/g, function(match){
return '\\' + match;
});
};
var regexp = new RegExp(
/*
#!/usr/bin/env ruby
puts "\t\t" + DATA.read.gsub(/\(\?x\)|\s+#.*$|\s+|\\$|\\n/,'')
__END__
"(?x)^(?:\
\\s* ( , ) \\s* # Separator \n\
| \\s* ( <combinator>+ ) \\s* # Combinator \n\
| ( \\s+ ) # CombinatorChildren \n\
| ( <unicode>+ | \\* ) # Tag \n\
| \\# ( <unicode>+ ) # ID \n\
| \\. ( <unicode>+ ) # ClassName \n\
| # Attribute \n\
\\[ \
\\s* (<unicode1>+) (?: \
\\s* ([*^$!~|]?=) (?: \
\\s* (?:\
([\"']?)(.*?)\\9 \
)\
) \
)? \\s* \
\\](?!\\]) \n\
| :+ ( <unicode>+ )(?:\
\\( (?:\
(?:([\"'])([^\\12]*)\\12)|((?:\\([^)]+\\)|[^()]*)+)\
) \\)\
)?\
)"
*/
"^(?:\\s*(,)\\s*|\\s*(<combinator>+)\\s*|(\\s+)|(<unicode>+|\\*)|\\#(<unicode>+)|\\.(<unicode>+)|\\[\\s*(<unicode1>+)(?:\\s*([*^$!~|]?=)(?:\\s*(?:([\"']?)(.*?)\\9)))?\\s*\\](?!\\])|(:+)(<unicode>+)(?:\\((?:(?:([\"'])([^\\13]*)\\13)|((?:\\([^)]+\\)|[^()]*)+))\\))?)"
.replace(/<combinator>/, '[' + escapeRegExp(">+~`!@$%^&={}\\;</") + ']')
.replace(/<unicode>/g, '(?:[\\w\\u00a1-\\uFFFF-]|\\\\[^\\s0-9a-f])')
.replace(/<unicode1>/g, '(?:[:\\w\\u00a1-\\uFFFF-]|\\\\[^\\s0-9a-f])')
);
function parser(
rawMatch,
separator,
combinator,
combinatorChildren,
tagName,
id,
className,
attributeKey,
attributeOperator,
attributeQuote,
attributeValue,
pseudoMarker,
pseudoClass,
pseudoQuote,
pseudoClassQuotedValue,
pseudoClassValue
){
if (separator || separatorIndex === -1){
parsed.expressions[++separatorIndex] = [];
combinatorIndex = -1;
if (separator) return '';
}
if (combinator || combinatorChildren || combinatorIndex === -1){
combinator = combinator || ' ';
var currentSeparator = parsed.expressions[separatorIndex];
if (reversed && currentSeparator[combinatorIndex])
currentSeparator[combinatorIndex].reverseCombinator = reverseCombinator(combinator);
currentSeparator[++combinatorIndex] = {combinator: combinator, tag: '*'};
}
var currentParsed = parsed.expressions[separatorIndex][combinatorIndex];
if (tagName){
currentParsed.tag = tagName.replace(reUnescape, '');
} else if (id){
currentParsed.id = id.replace(reUnescape, '');
} else if (className){
className = className.replace(reUnescape, '');
if (!currentParsed.classList) currentParsed.classList = [];
if (!currentParsed.classes) currentParsed.classes = [];
currentParsed.classList.push(className);
currentParsed.classes.push({
value: className,
regexp: new RegExp('(^|\\s)' + escapeRegExp(className) + '(\\s|$)')
});
} else if (pseudoClass){
pseudoClassValue = pseudoClassValue || pseudoClassQuotedValue;
pseudoClassValue = pseudoClassValue ? pseudoClassValue.replace(reUnescape, '') : null;
if (!currentParsed.pseudos) currentParsed.pseudos = [];
currentParsed.pseudos.push({
key: pseudoClass.replace(reUnescape, ''),
value: pseudoClassValue,
type: pseudoMarker.length == 1 ? 'class' : 'element'
});
} else if (attributeKey){
attributeKey = attributeKey.replace(reUnescape, '');
attributeValue = (attributeValue || '').replace(reUnescape, '');
var test, regexp;
switch (attributeOperator){
case '^=' : regexp = new RegExp( '^'+ escapeRegExp(attributeValue) ); break;
case '$=' : regexp = new RegExp( escapeRegExp(attributeValue) +'$' ); break;
case '~=' : regexp = new RegExp( '(^|\\s)'+ escapeRegExp(attributeValue) +'(\\s|$)' ); break;
case '|=' : regexp = new RegExp( '^'+ escapeRegExp(attributeValue) +'(-|$)' ); break;
case '=' : test = function(value){
return attributeValue == value;
}; break;
case '*=' : test = function(value){
return value && value.indexOf(attributeValue) > -1;
}; break;
case '!=' : test = function(value){
return attributeValue != value;
}; break;
default : test = function(value){
return !!value;
};
}
if (attributeValue == '' && (/^[*$^]=$/).test(attributeOperator)) test = function(){
return false;
};
if (!test) test = function(value){
return value && regexp.test(value);
};
if (!currentParsed.attributes) currentParsed.attributes = [];
currentParsed.attributes.push({
key: attributeKey,
operator: attributeOperator,
value: attributeValue,
test: test
});
}
return '';
};
// Slick NS
var Slick = (this.Slick || {});
Slick.parse = function(expression){
return parse(expression);
};
Slick.escapeRegExp = escapeRegExp;
if (!this.Slick) this.Slick = Slick;
}).apply(/*<CommonJS>*/(typeof exports != 'undefined') ? exports : /*</CommonJS>*/this);
/*
---
name: Slick.Finder
description: The new, superfast css selector engine.
provides: Slick.Finder
requires: Slick.Parser
...
*/
;(function(){
var local = {},
featuresCache = {},
toString = Object.prototype.toString;
// Feature / Bug detection
local.isNativeCode = function(fn){
return (/\{\s*\[native code\]\s*\}/).test('' + fn);
};
local.isXML = function(document){
return (!!document.xmlVersion) || (!!document.xml) || (toString.call(document) == '[object XMLDocument]') ||
(document.nodeType == 9 && document.documentElement.nodeName != 'HTML');
};
local.setDocument = function(document){
// convert elements / window arguments to document. if document cannot be extrapolated, the function returns.
var nodeType = document.nodeType;
if (nodeType == 9); // document
else if (nodeType) document = document.ownerDocument; // node
else if (document.navigator) document = document.document; // window
else return;
// check if it's the old document
if (this.document === document) return;
this.document = document;
// check if we have done feature detection on this document before
var root = document.documentElement,
rootUid = this.getUIDXML(root),
features = featuresCache[rootUid],
feature;
if (features){
for (feature in features){
this[feature] = features[feature];
}
return;
}
features = featuresCache[rootUid] = {};
features.root = root;
features.isXMLDocument = this.isXML(document);
features.brokenStarGEBTN
= features.starSelectsClosedQSA
= features.idGetsName
= features.brokenMixedCaseQSA
= features.brokenGEBCN
= features.brokenCheckedQSA
= features.brokenEmptyAttributeQSA
= features.isHTMLDocument
= features.nativeMatchesSelector
= false;
var starSelectsClosed, starSelectsComments,
brokenSecondClassNameGEBCN, cachedGetElementsByClassName,
brokenFormAttributeGetter;
var selected, id = 'slick_uniqueid';
var testNode = document.createElement('div');
var testRoot = document.body || document.getElementsByTagName('body')[0] || root;
testRoot.appendChild(testNode);
// on non-HTML documents innerHTML and getElementsById doesnt work properly
try {
testNode.innerHTML = '<a id="'+id+'"></a>';
features.isHTMLDocument = !!document.getElementById(id);
} catch(e){};
if (features.isHTMLDocument){
testNode.style.display = 'none';
// IE returns comment nodes for getElementsByTagName('*') for some documents
testNode.appendChild(document.createComment(''));
starSelectsComments = (testNode.getElementsByTagName('*').length > 1);
// IE returns closed nodes (EG:"</foo>") for getElementsByTagName('*') for some documents
try {
testNode.innerHTML = 'foo</foo>';
selected = testNode.getElementsByTagName('*');
starSelectsClosed = (selected && !!selected.length && selected[0].nodeName.charAt(0) == '/');
} catch(e){};
features.brokenStarGEBTN = starSelectsComments || starSelectsClosed;
// IE returns elements with the name instead of just id for getElementsById for some documents
try {
testNode.innerHTML = '<a name="'+ id +'"></a><b id="'+ id +'"></b>';
features.idGetsName = document.getElementById(id) === testNode.firstChild;
} catch(e){};
if (testNode.getElementsByClassName){
// Safari 3.2 getElementsByClassName caches results
try {
testNode.innerHTML = '<a class="f"></a><a class="b"></a>';
testNode.getElementsByClassName('b').length;
testNode.firstChild.className = 'b';
cachedGetElementsByClassName = (testNode.getElementsByClassName('b').length != 2);
} catch(e){};
// Opera 9.6 getElementsByClassName doesnt detects the class if its not the first one
try {
testNode.innerHTML = '<a class="a"></a><a class="f b a"></a>';
brokenSecondClassNameGEBCN = (testNode.getElementsByClassName('a').length != 2);
} catch(e){};
features.brokenGEBCN = cachedGetElementsByClassName || brokenSecondClassNameGEBCN;
}
if (testNode.querySelectorAll){
// IE 8 returns closed nodes (EG:"</foo>") for querySelectorAll('*') for some documents
try {
testNode.innerHTML = 'foo</foo>';
selected = testNode.querySelectorAll('*');
features.starSelectsClosedQSA = (selected && !!selected.length && selected[0].nodeName.charAt(0) == '/');
} catch(e){};
// Safari 3.2 querySelectorAll doesnt work with mixedcase on quirksmode
try {
testNode.innerHTML = '<a class="MiX"></a>';
features.brokenMixedCaseQSA = !testNode.querySelectorAll('.MiX').length;
} catch(e){};
// Webkit and Opera dont return selected options on querySelectorAll
try {
testNode.innerHTML = '<select><option selected="selected">a</option></select>';
features.brokenCheckedQSA = (testNode.querySelectorAll(':checked').length == 0);
} catch(e){};
// IE returns incorrect results for attr[*^$]="" selectors on querySelectorAll
try {
testNode.innerHTML = '<a class=""></a>';
features.brokenEmptyAttributeQSA = (testNode.querySelectorAll('[class*=""]').length != 0);
} catch(e){};
}
// IE6-7, if a form has an input of id x, form.getAttribute(x) returns a reference to the input
try {
testNode.innerHTML = '<form action="s"><input id="action"/></form>';
brokenFormAttributeGetter = (testNode.firstChild.getAttribute('action') != 's');
} catch(e){};
// native matchesSelector function
features.nativeMatchesSelector = root.matchesSelector || /*root.msMatchesSelector ||*/ root.mozMatchesSelector || root.webkitMatchesSelector;
if (features.nativeMatchesSelector) try {
// if matchesSelector trows errors on incorrect sintaxes we can use it
features.nativeMatchesSelector.call(root, ':slick');
features.nativeMatchesSelector = null;
} catch(e){};
}
try {
root.slick_expando = 1;
delete root.slick_expando;
features.getUID = this.getUIDHTML;
} catch(e) {
features.getUID = this.getUIDXML;
}
testRoot.removeChild(testNode);
testNode = selected = testRoot = null;
// getAttribute
features.getAttribute = (features.isHTMLDocument && brokenFormAttributeGetter) ? function(node, name){
var method = this.attributeGetters[name];
if (method) return method.call(node);
var attributeNode = node.getAttributeNode(name);
return (attributeNode) ? attributeNode.nodeValue : null;
} : function(node, name){
var method = this.attributeGetters[name];
return (method) ? method.call(node) : node.getAttribute(name);
};
// hasAttribute
features.hasAttribute = (root && this.isNativeCode(root.hasAttribute)) ? function(node, attribute) {
return node.hasAttribute(attribute);
} : function(node, attribute) {
node = node.getAttributeNode(attribute);
return !!(node && (node.specified || node.nodeValue));
};
// contains
// FIXME: Add specs: local.contains should be different for xml and html documents?
var nativeRootContains = root && this.isNativeCode(root.contains),
nativeDocumentContains = document && this.isNativeCode(document.contains);
features.contains = (nativeRootContains && nativeDocumentContains) ? function(context, node){
return context.contains(node);
} : (nativeRootContains && !nativeDocumentContains) ? function(context, node){
// IE8 does not have .contains on document.
return context === node || ((context === document) ? document.documentElement : context).contains(node);
} : (root && root.compareDocumentPosition) ? function(context, node){
return context === node || !!(context.compareDocumentPosition(node) & 16);
} : function(context, node){
if (node) do {
if (node === context) return true;
} while ((node = node.parentNode));
return false;
};
// document order sorting
// credits to Sizzle (http://sizzlejs.com/)
features.documentSorter = (root.compareDocumentPosition) ? function(a, b){
if (!a.compareDocumentPosition || !b.compareDocumentPosition) return 0;
return a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1;
} : ('sourceIndex' in root) ? function(a, b){
if (!a.sourceIndex || !b.sourceIndex) return 0;
return a.sourceIndex - b.sourceIndex;
} : (document.createRange) ? function(a, b){
if (!a.ownerDocument || !b.ownerDocument) return 0;
var aRange = a.ownerDocument.createRange(), bRange = b.ownerDocument.createRange();
aRange.setStart(a, 0);
aRange.setEnd(a, 0);
bRange.setStart(b, 0);
bRange.setEnd(b, 0);
return aRange.compareBoundaryPoints(Range.START_TO_END, bRange);
} : null ;
root = null;
for (feature in features){
this[feature] = features[feature];
}
};
// Main Method
var reSimpleSelector = /^([#.]?)((?:[\w-]+|\*))$/,
reEmptyAttribute = /\[.+[*$^]=(?:""|'')?\]/,
qsaFailExpCache = {};
local.search = function(context, expression, append, first){
var found = this.found = (first) ? null : (append || []);
if (!context) return found;
else if (context.navigator) context = context.document; // Convert the node from a window to a document
else if (!context.nodeType) return found;
// setup
var parsed, i,
uniques = this.uniques = {},
hasOthers = !!(append && append.length),
contextIsDocument = (context.nodeType == 9);
if (this.document !== (contextIsDocument ? context : context.ownerDocument)) this.setDocument(context);
// avoid duplicating items already in the append array
if (hasOthers) for (i = found.length; i--;) uniques[this.getUID(found[i])] = true;
// expression checks
if (typeof expression == 'string'){ // expression is a string
/*<simple-selectors-override>*/
var simpleSelector = expression.match(reSimpleSelector);
simpleSelectors: if (simpleSelector) {
var symbol = simpleSelector[1],
name = simpleSelector[2],
node, nodes;
if (!symbol){
if (name == '*' && this.brokenStarGEBTN) break simpleSelectors;
nodes = context.getElementsByTagName(name);
if (first) return nodes[0] || null;
for (i = 0; node = nodes[i++];){
if (!(hasOthers && uniques[this.getUID(node)])) found.push(node);
}
} else if (symbol == '#'){
if (!this.isHTMLDocument || !contextIsDocument) break simpleSelectors;
node = context.getElementById(name);
if (!node) return found;
if (this.idGetsName && node.getAttributeNode('id').nodeValue != name) break simpleSelectors;
if (first) return node || null;
if (!(hasOthers && uniques[this.getUID(node)])) found.push(node);
} else if (symbol == '.'){
if (!this.isHTMLDocument || ((!context.getElementsByClassName || this.brokenGEBCN) && context.querySelectorAll)) break simpleSelectors;
if (context.getElementsByClassName && !this.brokenGEBCN){
nodes = context.getElementsByClassName(name);
if (first) return nodes[0] || null;
for (i = 0; node = nodes[i++];){
if (!(hasOthers && uniques[this.getUID(node)])) found.push(node);
}
} else {
var matchClass = new RegExp('(^|\\s)'+ Slick.escapeRegExp(name) +'(\\s|$)');
nodes = context.getElementsByTagName('*');
for (i = 0; node = nodes[i++];){
className = node.className;
if (!(className && matchClass.test(className))) continue;
if (first) return node;
if (!(hasOthers && uniques[this.getUID(node)])) found.push(node);
}
}
}
if (hasOthers) this.sort(found);
return (first) ? null : found;
}
/*</simple-selectors-override>*/
/*<query-selector-override>*/
querySelector: if (context.querySelectorAll) {
if (!this.isHTMLDocument
|| qsaFailExpCache[expression]
//TODO: only skip when expression is actually mixed case
|| this.brokenMixedCaseQSA
|| (this.brokenCheckedQSA && expression.indexOf(':checked') > -1)
|| (this.brokenEmptyAttributeQSA && reEmptyAttribute.test(expression))
|| (!contextIsDocument //Abort when !contextIsDocument and...
// there are multiple expressions in the selector
// since we currently only fix non-document rooted QSA for single expression selectors
&& expression.indexOf(',') > -1
)
|| Slick.disableQSA
) break querySelector;
var _expression = expression, _context = context;
if (!contextIsDocument){
// non-document rooted QSA
// credits to Andrew Dupont
var currentId = _context.getAttribute('id'), slickid = 'slickid__';
_context.setAttribute('id', slickid);
_expression = '#' + slickid + ' ' + _expression;
context = _context.parentNode;
}
try {
if (first) return context.querySelector(_expression) || null;
else nodes = context.querySelectorAll(_expression);
} catch(e) {
qsaFailExpCache[expression] = 1;
break querySelector;
} finally {
if (!contextIsDocument){
if (currentId) _context.setAttribute('id', currentId);
else _context.removeAttribute('id');
context = _context;
}
}
if (this.starSelectsClosedQSA) for (i = 0; node = nodes[i++];){
if (node.nodeName > '@' && !(hasOthers && uniques[this.getUID(node)])) found.push(node);
} else for (i = 0; node = nodes[i++];){
if (!(hasOthers && uniques[this.getUID(node)])) found.push(node);
}
if (hasOthers) this.sort(found);
return found;
}
/*</query-selector-override>*/
parsed = this.Slick.parse(expression);
if (!parsed.length) return found;
} else if (expression == null){ // there is no expression
return found;
} else if (expression.Slick){ // expression is a parsed Slick object
parsed = expression;
} else if (this.contains(context.documentElement || context, expression)){ // expression is a node
(found) ? found.push(expression) : found = expression;
return found;
} else { // other junk
return found;
}
/*<pseudo-selectors>*//*<nth-pseudo-selectors>*/
// cache elements for the nth selectors
this.posNTH = {};
this.posNTHLast = {};
this.posNTHType = {};
this.posNTHTypeLast = {};
/*</nth-pseudo-selectors>*//*</pseudo-selectors>*/
// if append is null and there is only a single selector with one expression use pushArray, else use pushUID
this.push = (!hasOthers && (first || (parsed.length == 1 && parsed.expressions[0].length == 1))) ? this.pushArray : this.pushUID;
if (found == null) found = [];
// default engine
var j, m, n;
var combinator, tag, id, classList, classes, attributes, pseudos;
var currentItems, currentExpression, currentBit, lastBit, expressions = parsed.expressions;
search: for (i = 0; (currentExpression = expressions[i]); i++) for (j = 0; (currentBit = currentExpression[j]); j++){
combinator = 'combinator:' + currentBit.combinator;
if (!this[combinator]) continue search;
tag = (this.isXMLDocument) ? currentBit.tag : currentBit.tag.toUpperCase();
id = currentBit.id;
classList = currentBit.classList;
classes = currentBit.classes;
attributes = currentBit.attributes;
pseudos = currentBit.pseudos;
lastBit = (j === (currentExpression.length - 1));
this.bitUniques = {};
if (lastBit){
this.uniques = uniques;
this.found = found;
} else {
this.uniques = {};
this.found = [];
}
if (j === 0){
this[combinator](context, tag, id, classes, attributes, pseudos, classList);
if (first && lastBit && found.length) break search;
} else {
if (first && lastBit) for (m = 0, n = currentItems.length; m < n; m++){
this[combinator](currentItems[m], tag, id, classes, attributes, pseudos, classList);
if (found.length) break search;
} else for (m = 0, n = currentItems.length; m < n; m++) this[combinator](currentItems[m], tag, id, classes, attributes, pseudos, classList);
}
currentItems = this.found;
}
// should sort if there are nodes in append and if you pass multiple expressions.
if (hasOthers || (parsed.expressions.length > 1)) this.sort(found);
return (first) ? (found[0] || null) : found;
};
// Utils
local.uidx = 1;
local.uidk = 'slick-uniqueid';
local.getUIDXML = function(node){
var uid = node.getAttribute(this.uidk);
if (!uid){
uid = this.uidx++;
node.setAttribute(this.uidk, uid);
}
return uid;
};
local.getUIDHTML = function(node){
return node.uniqueNumber || (node.uniqueNumber = this.uidx++);
};
// sort based on the setDocument documentSorter method.
local.sort = function(results){
if (!this.documentSorter) return results;
results.sort(this.documentSorter);
return results;
};
/*<pseudo-selectors>*//*<nth-pseudo-selectors>*/
local.cacheNTH = {};
local.matchNTH = /^([+-]?\d*)?([a-z]+)?([+-]\d+)?$/;
local.parseNTHArgument = function(argument){
var parsed = argument.match(this.matchNTH);
if (!parsed) return false;
var special = parsed[2] || false;
var a = parsed[1] || 1;
if (a == '-') a = -1;
var b = +parsed[3] || 0;
parsed =
(special == 'n') ? {a: a, b: b} :
(special == 'odd') ? {a: 2, b: 1} :
(special == 'even') ? {a: 2, b: 0} : {a: 0, b: a};
return (this.cacheNTH[argument] = parsed);
};
local.createNTHPseudo = function(child, sibling, positions, ofType){
return function(node, argument){
var uid = this.getUID(node);
if (!this[positions][uid]){
var parent = node.parentNode;
if (!parent) return false;
var el = parent[child], count = 1;
if (ofType){
var nodeName = node.nodeName;
do {
if (el.nodeName != nodeName) continue;
this[positions][this.getUID(el)] = count++;
} while ((el = el[sibling]));
} else {
do {
if (el.nodeType != 1) continue;
this[positions][this.getUID(el)] = count++;
} while ((el = el[sibling]));
}
}
argument = argument || 'n';
var parsed = this.cacheNTH[argument] || this.parseNTHArgument(argument);
if (!parsed) return false;
var a = parsed.a, b = parsed.b, pos = this[positions][uid];
if (a == 0) return b == pos;
if (a > 0){
if (pos < b) return false;
} else {
if (b < pos) return false;
}
return ((pos - b) % a) == 0;
};
};
/*</nth-pseudo-selectors>*//*</pseudo-selectors>*/
local.pushArray = function(node, tag, id, classes, attributes, pseudos){
if (this.matchSelector(node, tag, id, classes, attributes, pseudos)) this.found.push(node);
};
local.pushUID = function(node, tag, id, classes, attributes, pseudos){
var uid = this.getUID(node);
if (!this.uniques[uid] && this.matchSelector(node, tag, id, classes, attributes, pseudos)){
this.uniques[uid] = true;
this.found.push(node);
}
};
local.matchNode = function(node, selector){
if (this.isHTMLDocument && this.nativeMatchesSelector){
try {
return this.nativeMatchesSelector.call(node, selector.replace(/\[([^=]+)=\s*([^'"\]]+?)\s*\]/g, '[$1="$2"]'));
} catch(matchError) {}
}
var parsed = this.Slick.parse(selector);
if (!parsed) return true;
// simple (single) selectors
var expressions = parsed.expressions, simpleExpCounter = 0, i;
for (i = 0; (currentExpression = expressions[i]); i++){
if (currentExpression.length == 1){
var exp = currentExpression[0];
if (this.matchSelector(node, (this.isXMLDocument) ? exp.tag : exp.tag.toUpperCase(), exp.id, exp.classes, exp.attributes, exp.pseudos)) return true;
simpleExpCounter++;
}
}
if (simpleExpCounter == parsed.length) return false;
var nodes = this.search(this.document, parsed), item;
for (i = 0; item = nodes[i++];){
if (item === node) return true;
}
return false;
};
local.matchPseudo = function(node, name, argument){
var pseudoName = 'pseudo:' + name;
if (this[pseudoName]) return this[pseudoName](node, argument);
var attribute = this.getAttribute(node, name);
return (argument) ? argument == attribute : !!attribute;
};
local.matchSelector = function(node, tag, id, classes, attributes, pseudos){
if (tag){
var nodeName = (this.isXMLDocument) ? node.nodeName : node.nodeName.toUpperCase();
if (tag == '*'){
if (nodeName < '@') return false; // Fix for comment nodes and closed nodes
} else {
if (nodeName != tag) return false;
}
}
if (id && node.getAttribute('id') != id) return false;
var i, part, cls;
if (classes) for (i = classes.length; i--;){
cls = this.getAttribute(node, 'class');
if (!(cls && classes[i].regexp.test(cls))) return false;
}
if (attributes) for (i = attributes.length; i--;){
part = attributes[i];
if (part.operator ? !part.test(this.getAttribute(node, part.key)) : !this.hasAttribute(node, part.key)) return false;
}
if (pseudos) for (i = pseudos.length; i--;){
part = pseudos[i];
if (!this.matchPseudo(node, part.key, part.value)) return false;
}
return true;
};
var combinators = {
' ': function(node, tag, id, classes, attributes, pseudos, classList){ // all child nodes, any level
var i, item, children;
if (this.isHTMLDocument){
getById: if (id){
item = this.document.getElementById(id);
if ((!item && node.all) || (this.idGetsName && item && item.getAttributeNode('id').nodeValue != id)){
// all[id] returns all the elements with that name or id inside node
// if theres just one it will return the element, else it will be a collection
children = node.all[id];
if (!children) return;
if (!children[0]) children = [children];
for (i = 0; item = children[i++];){
var idNode = item.getAttributeNode('id');
if (idNode && idNode.nodeValue == id){
this.push(item, tag, null, classes, attributes, pseudos);
break;
}
}
return;
}
if (!item){
// if the context is in the dom we return, else we will try GEBTN, breaking the getById label
if (this.contains(this.root, node)) return;
else break getById;
} else if (this.document !== node && !this.contains(node, item)) return;
this.push(item, tag, null, classes, attributes, pseudos);
return;
}
getByClass: if (classes && node.getElementsByClassName && !this.brokenGEBCN){
children = node.getElementsByClassName(classList.join(' '));
if (!(children && children.length)) break getByClass;
for (i = 0; item = children[i++];) this.push(item, tag, id, null, attributes, pseudos);
return;
}
}
getByTag: {
children = node.getElementsByTagName(tag);
if (!(children && children.length)) break getByTag;
if (!this.brokenStarGEBTN) tag = null;
for (i = 0; item = children[i++];) this.push(item, tag, id, classes, attributes, pseudos);
}
},
'>': function(node, tag, id, classes, attributes, pseudos){ // direct children
if ((node = node.firstChild)) do {
if (node.nodeType == 1) this.push(node, tag, id, classes, attributes, pseudos);
} while ((node = node.nextSibling));
},
'+': function(node, tag, id, classes, attributes, pseudos){ // next sibling
while ((node = node.nextSibling)) if (node.nodeType == 1){
this.push(node, tag, id, classes, attributes, pseudos);
break;
}
},
'^': function(node, tag, id, classes, attributes, pseudos){ // first child
node = node.firstChild;
if (node){
if (node.nodeType == 1) this.push(node, tag, id, classes, attributes, pseudos);
else this['combinator:+'](node, tag, id, classes, attributes, pseudos);
}
},
'~': function(node, tag, id, classes, attributes, pseudos){ // next siblings
while ((node = node.nextSibling)){
if (node.nodeType != 1) continue;
var uid = this.getUID(node);
if (this.bitUniques[uid]) break;
this.bitUniques[uid] = true;
this.push(node, tag, id, classes, attributes, pseudos);
}
},
'++': function(node, tag, id, classes, attributes, pseudos){ // next sibling and previous sibling
this['combinator:+'](node, tag, id, classes, attributes, pseudos);
this['combinator:!+'](node, tag, id, classes, attributes, pseudos);
},
'~~': function(node, tag, id, classes, attributes, pseudos){ // next siblings and previous siblings
this['combinator:~'](node, tag, id, classes, attributes, pseudos);
this['combinator:!~'](node, tag, id, classes, attributes, pseudos);
},
'!': function(node, tag, id, classes, attributes, pseudos){ // all parent nodes up to document
while ((node = node.parentNode)) if (node !== this.document) this.push(node, tag, id, classes, attributes, pseudos);
},
'!>': function(node, tag, id, classes, attributes, pseudos){ // direct parent (one level)
node = node.parentNode;
if (node !== this.document) this.push(node, tag, id, classes, attributes, pseudos);
},
'!+': function(node, tag, id, classes, attributes, pseudos){ // previous sibling
while ((node = node.previousSibling)) if (node.nodeType == 1){
this.push(node, tag, id, classes, attributes, pseudos);
break;
}
},
'!^': function(node, tag, id, classes, attributes, pseudos){ // last child
node = node.lastChild;
if (node){
if (node.nodeType == 1) this.push(node, tag, id, classes, attributes, pseudos);
else this['combinator:!+'](node, tag, id, classes, attributes, pseudos);
}
},
'!~': function(node, tag, id, classes, attributes, pseudos){ // previous siblings
while ((node = node.previousSibling)){
if (node.nodeType != 1) continue;
var uid = this.getUID(node);
if (this.bitUniques[uid]) break;
this.bitUniques[uid] = true;
this.push(node, tag, id, classes, attributes, pseudos);
}
}
};
for (var c in combinators) local['combinator:' + c] = combinators[c];
var pseudos = {
/*<pseudo-selectors>*/
'empty': function(node){
var child = node.firstChild;
return !(child && child.nodeType == 1) && !(node.innerText || node.textContent || '').length;
},
'not': function(node, expression){
return !this.matchNode(node, expression);
},
'contains': function(node, text){
return (node.innerText || node.textContent || '').indexOf(text) > -1;
},
'first-child': function(node){
while ((node = node.previousSibling)) if (node.nodeType == 1) return false;
return true;
},
'last-child': function(node){
while ((node = node.nextSibling)) if (node.nodeType == 1) return false;
return true;
},
'only-child': function(node){
var prev = node;
while ((prev = prev.previousSibling)) if (prev.nodeType == 1) return false;
var next = node;
while ((next = next.nextSibling)) if (next.nodeType == 1) return false;
return true;
},
/*<nth-pseudo-selectors>*/
'nth-child': local.createNTHPseudo('firstChild', 'nextSibling', 'posNTH'),
'nth-last-child': local.createNTHPseudo('lastChild', 'previousSibling', 'posNTHLast'),
'nth-of-type': local.createNTHPseudo('firstChild', 'nextSibling', 'posNTHType', true),
'nth-last-of-type': local.createNTHPseudo('lastChild', 'previousSibling', 'posNTHTypeLast', true),
'index': function(node, index){
return this['pseudo:nth-child'](node, '' + (index + 1));
},
'even': function(node){
return this['pseudo:nth-child'](node, '2n');
},
'odd': function(node){
return this['pseudo:nth-child'](node, '2n+1');
},
/*</nth-pseudo-selectors>*/
/*<of-type-pseudo-selectors>*/
'first-of-type': function(node){
var nodeName = node.nodeName;
while ((node = node.previousSibling)) if (node.nodeName == nodeName) return false;
return true;
},
'last-of-type': function(node){
var nodeName = node.nodeName;
while ((node = node.nextSibling)) if (node.nodeName == nodeName) return false;
return true;
},
'only-of-type': function(node){
var prev = node, nodeName = node.nodeName;
while ((prev = prev.previousSibling)) if (prev.nodeName == nodeName) return false;
var next = node;
while ((next = next.nextSibling)) if (next.nodeName == nodeName) return false;
return true;
},
/*</of-type-pseudo-selectors>*/
// custom pseudos
'enabled': function(node){
return !node.disabled;
},
'disabled': function(node){
return node.disabled;
},
'checked': function(node){
return node.checked || node.selected;
},
'focus': function(node){
return this.isHTMLDocument && this.document.activeElement === node && (node.href || node.type || this.hasAttribute(node, 'tabindex'));
},
'root': function(node){
return (node === this.root);
},
'selected': function(node){
return node.selected;
}
/*</pseudo-selectors>*/
};
for (var p in pseudos) local['pseudo:' + p] = pseudos[p];
// attributes methods
var attributeGetters = local.attributeGetters = {
'for': function(){
return ('htmlFor' in this) ? this.htmlFor : this.getAttribute('for');
},
'href': function(){
return ('href' in this) ? this.getAttribute('href', 2) : this.getAttribute('href');
},
'style': function(){
return (this.style) ? this.style.cssText : this.getAttribute('style');
},
'tabindex': function(){
var attributeNode = this.getAttributeNode('tabindex');
return (attributeNode && attributeNode.specified) ? attributeNode.nodeValue : null;
},
'type': function(){
return this.getAttribute('type');
},
'maxlength': function(){
var attributeNode = this.getAttributeNode('maxLength');
return (attributeNode && attributeNode.specified) ? attributeNode.nodeValue : null;
}
};
attributeGetters.MAXLENGTH = attributeGetters.maxLength = attributeGetters.maxlength;
// Slick
var Slick = local.Slick = (this.Slick || {});
Slick.version = '1.1.7';
// Slick finder
Slick.search = function(context, expression, append){
return local.search(context, expression, append);
};
Slick.find = function(context, expression){
return local.search(context, expression, null, true);
};
// Slick containment checker
Slick.contains = function(container, node){
local.setDocument(container);
return local.contains(container, node);
};
// Slick attribute getter
Slick.getAttribute = function(node, name){
local.setDocument(node);
return local.getAttribute(node, name);
};
Slick.hasAttribute = function(node, name){
local.setDocument(node);
return local.hasAttribute(node, name);
};
// Slick matcher
Slick.match = function(node, selector){
if (!(node && selector)) return false;
if (!selector || selector === node) return true;
local.setDocument(node);
return local.matchNode(node, selector);
};
// Slick attribute accessor
Slick.defineAttributeGetter = function(name, fn){
local.attributeGetters[name] = fn;
return this;
};
Slick.lookupAttributeGetter = function(name){
return local.attributeGetters[name];
};
// Slick pseudo accessor
Slick.definePseudo = function(name, fn){
local['pseudo:' + name] = function(node, argument){
return fn.call(node, argument);
};
return this;
};
Slick.lookupPseudo = function(name){
var pseudo = local['pseudo:' + name];
if (pseudo) return function(argument){
return pseudo.call(this, argument);
};
return null;
};
// Slick overrides accessor
Slick.override = function(regexp, fn){
local.override(regexp, fn);
return this;
};
Slick.isXML = local.isXML;
Slick.uidOf = function(node){
return local.getUIDHTML(node);
};
if (!this.Slick) this.Slick = Slick;
}).apply(/*<CommonJS>*/(typeof exports != 'undefined') ? exports : /*</CommonJS>*/this);
/*
---
name: Element
description: One of the most important items in MooTools. Contains the dollar function, the dollars function, and an handful of cross-browser, time-saver methods to let you easily work with HTML Elements.
license: MIT-style license.
requires: [Window, Document, Array, String, Function, Object, Number, Slick.Parser, Slick.Finder]
provides: [Element, Elements, $, $$, Iframe, Selectors]
...
*/
var Element = function(tag, props){
var konstructor = Element.Constructors[tag];
if (konstructor) return konstructor(props);
if (typeof tag != 'string') return document.id(tag).set(props);
if (!props) props = {};
if (!(/^[\w-]+$/).test(tag)){
var parsed = Slick.parse(tag).expressions[0][0];
tag = (parsed.tag == '*') ? 'div' : parsed.tag;
if (parsed.id && props.id == null) props.id = parsed.id;
var attributes = parsed.attributes;
if (attributes) for (var attr, i = 0, l = attributes.length; i < l; i++){
attr = attributes[i];
if (props[attr.key] != null) continue;
if (attr.value != null && attr.operator == '=') props[attr.key] = attr.value;
else if (!attr.value && !attr.operator) props[attr.key] = true;
}
if (parsed.classList && props['class'] == null) props['class'] = parsed.classList.join(' ');
}
return document.newElement(tag, props);
};
if (Browser.Element){
Element.prototype = Browser.Element.prototype;
// IE8 and IE9 require the wrapping.
Element.prototype._fireEvent = (function(fireEvent){
return function(type, event){
return fireEvent.call(this, type, event);
};
})(Element.prototype.fireEvent);
}
new Type('Element', Element).mirror(function(name){
if (Array.prototype[name]) return;
var obj = {};
obj[name] = function(){
var results = [], args = arguments, elements = true;
for (var i = 0, l = this.length; i < l; i++){
var element = this[i], result = results[i] = element[name].apply(element, args);
elements = (elements && typeOf(result) == 'element');
}
return (elements) ? new Elements(results) : results;
};
Elements.implement(obj);
});
if (!Browser.Element){
Element.parent = Object;
Element.Prototype = {
'$constructor': Element,
'$family': Function.from('element').hide()
};
Element.mirror(function(name, method){
Element.Prototype[name] = method;
});
}
Element.Constructors = {};
var IFrame = new Type('IFrame', function(){
var params = Array.link(arguments, {
properties: Type.isObject,
iframe: function(obj){
return (obj != null);
}
});
var props = params.properties || {}, iframe;
if (params.iframe) iframe = document.id(params.iframe);
var onload = props.onload || function(){};
delete props.onload;
props.id = props.name = [props.id, props.name, iframe ? (iframe.id || iframe.name) : 'IFrame_' + String.uniqueID()].pick();
iframe = new Element(iframe || 'iframe', props);
var onLoad = function(){
onload.call(iframe.contentWindow);
};
if (window.frames[props.id]) onLoad();
else iframe.addListener('load', onLoad);
return iframe;
});
var Elements = this.Elements = function(nodes){
if (nodes && nodes.length){
var uniques = {}, node;
for (var i = 0; node = nodes[i++];){
var uid = Slick.uidOf(node);
if (!uniques[uid]){
uniques[uid] = true;
this.push(node);
}
}
}
};
Elements.prototype = {length: 0};
Elements.parent = Array;
new Type('Elements', Elements).implement({
filter: function(filter, bind){
if (!filter) return this;
return new Elements(Array.filter(this, (typeOf(filter) == 'string') ? function(item){
return item.match(filter);
} : filter, bind));
}.protect(),
push: function(){
var length = this.length;
for (var i = 0, l = arguments.length; i < l; i++){
var item = document.id(arguments[i]);
if (item) this[length++] = item;
}
return (this.length = length);
}.protect(),
unshift: function(){
var items = [];
for (var i = 0, l = arguments.length; i < l; i++){
var item = document.id(arguments[i]);
if (item) items.push(item);
}
return Array.prototype.unshift.apply(this, items);
}.protect(),
concat: function(){
var newElements = new Elements(this);
for (var i = 0, l = arguments.length; i < l; i++){
var item = arguments[i];
if (Type.isEnumerable(item)) newElements.append(item);
else newElements.push(item);
}
return newElements;
}.protect(),
append: function(collection){
for (var i = 0, l = collection.length; i < l; i++) this.push(collection[i]);
return this;
}.protect(),
empty: function(){
while (this.length) delete this[--this.length];
return this;
}.protect()
});
(function(){
// FF, IE
var splice = Array.prototype.splice, object = {'0': 0, '1': 1, length: 2};
splice.call(object, 1, 1);
if (object[1] == 1) Elements.implement('splice', function(){
var length = this.length;
var result = splice.apply(this, arguments);
while (length >= this.length) delete this[length--];
return result;
}.protect());
Array.forEachMethod(function(method, name){
Elements.implement(name, method);
});
Array.mirror(Elements);
/*<ltIE8>*/
var createElementAcceptsHTML;
try {
createElementAcceptsHTML = (document.createElement('<input name=x>').name == 'x');
} catch (e){}
var escapeQuotes = function(html){
return ('' + html).replace(/&/g, '&').replace(/"/g, '"');
};
/*</ltIE8>*/
Document.implement({
newElement: function(tag, props){
if (props && props.checked != null) props.defaultChecked = props.checked;
/*<ltIE8>*/// Fix for readonly name and type properties in IE < 8
if (createElementAcceptsHTML && props){
tag = '<' + tag;
if (props.name) tag += ' name="' + escapeQuotes(props.name) + '"';
if (props.type) tag += ' type="' + escapeQuotes(props.type) + '"';
tag += '>';
delete props.name;
delete props.type;
}
/*</ltIE8>*/
return this.id(this.createElement(tag)).set(props);
}
});
})();
(function(){
Slick.uidOf(window);
Slick.uidOf(document);
Document.implement({
newTextNode: function(text){
return this.createTextNode(text);
},
getDocument: function(){
return this;
},
getWindow: function(){
return this.window;
},
id: (function(){
var types = {
string: function(id, nocash, doc){
id = Slick.find(doc, '#' + id.replace(/(\W)/g, '\\$1'));
return (id) ? types.element(id, nocash) : null;
},
element: function(el, nocash){
Slick.uidOf(el);
if (!nocash && !el.$family && !(/^(?:object|embed)$/i).test(el.tagName)){
var fireEvent = el.fireEvent;
// wrapping needed in IE7, or else crash
el._fireEvent = function(type, event){
return fireEvent(type, event);
};
Object.append(el, Element.Prototype);
}
return el;
},
object: function(obj, nocash, doc){
if (obj.toElement) return types.element(obj.toElement(doc), nocash);
return null;
}
};
types.textnode = types.whitespace = types.window = types.document = function(zero){
return zero;
};
return function(el, nocash, doc){
if (el && el.$family && el.uniqueNumber) return el;
var type = typeOf(el);
return (types[type]) ? types[type](el, nocash, doc || document) : null;
};
})()
});
if (window.$ == null) Window.implement('$', function(el, nc){
return document.id(el, nc, this.document);
});
Window.implement({
getDocument: function(){
return this.document;
},
getWindow: function(){
return this;
}
});
[Document, Element].invoke('implement', {
getElements: function(expression){
return Slick.search(this, expression, new Elements);
},
getElement: function(expression){
return document.id(Slick.find(this, expression));
}
});
var contains = {contains: function(element){
return Slick.contains(this, element);
}};
if (!document.contains) Document.implement(contains);
if (!document.createElement('div').contains) Element.implement(contains);
// tree walking
var injectCombinator = function(expression, combinator){
if (!expression) return combinator;
expression = Object.clone(Slick.parse(expression));
var expressions = expression.expressions;
for (var i = expressions.length; i--;)
expressions[i][0].combinator = combinator;
return expression;
};
Object.forEach({
getNext: '~',
getPrevious: '!~',
getParent: '!'
}, function(combinator, method){
Element.implement(method, function(expression){
return this.getElement(injectCombinator(expression, combinator));
});
});
Object.forEach({
getAllNext: '~',
getAllPrevious: '!~',
getSiblings: '~~',
getChildren: '>',
getParents: '!'
}, function(combinator, method){
Element.implement(method, function(expression){
return this.getElements(injectCombinator(expression, combinator));
});
});
Element.implement({
getFirst: function(expression){
return document.id(Slick.search(this, injectCombinator(expression, '>'))[0]);
},
getLast: function(expression){
return document.id(Slick.search(this, injectCombinator(expression, '>')).getLast());
},
getWindow: function(){
return this.ownerDocument.window;
},
getDocument: function(){
return this.ownerDocument;
},
getElementById: function(id){
return document.id(Slick.find(this, '#' + ('' + id).replace(/(\W)/g, '\\$1')));
},
match: function(expression){
return !expression || Slick.match(this, expression);
}
});
if (window.$$ == null) Window.implement('$$', function(selector){
if (arguments.length == 1){
if (typeof selector == 'string') return Slick.search(this.document, selector, new Elements);
else if (Type.isEnumerable(selector)) return new Elements(selector);
}
return new Elements(arguments);
});
// Inserters
var inserters = {
before: function(context, element){
var parent = element.parentNode;
if (parent) parent.insertBefore(context, element);
},
after: function(context, element){
var parent = element.parentNode;
if (parent) parent.insertBefore(context, element.nextSibling);
},
bottom: function(context, element){
element.appendChild(context);
},
top: function(context, element){
element.insertBefore(context, element.firstChild);
}
};
inserters.inside = inserters.bottom;
// getProperty / setProperty
var propertyGetters = {}, propertySetters = {};
// properties
var properties = {};
Array.forEach([
'type', 'value', 'defaultValue', 'accessKey', 'cellPadding', 'cellSpacing', 'colSpan',
'frameBorder', 'rowSpan', 'tabIndex', 'useMap'
], function(property){
properties[property.toLowerCase()] = property;
});
properties.html = 'innerHTML';
properties.text = (document.createElement('div').textContent == null) ? 'innerText': 'textContent';
Object.forEach(properties, function(real, key){
propertySetters[key] = function(node, value){
node[real] = value;
};
propertyGetters[key] = function(node){
return node[real];
};
});
// Booleans
var bools = [
'compact', 'nowrap', 'ismap', 'declare', 'noshade', 'checked',
'disabled', 'readOnly', 'multiple', 'selected', 'noresize',
'defer', 'defaultChecked', 'autofocus', 'controls', 'autoplay',
'loop'
];
var booleans = {};
Array.forEach(bools, function(bool){
var lower = bool.toLowerCase();
booleans[lower] = bool;
propertySetters[lower] = function(node, value){
node[bool] = !!value;
};
propertyGetters[lower] = function(node){
return !!node[bool];
};
});
// Special cases
Object.append(propertySetters, {
'class': function(node, value){
('className' in node) ? node.className = (value || '') : node.setAttribute('class', value);
},
'for': function(node, value){
('htmlFor' in node) ? node.htmlFor = value : node.setAttribute('for', value);
},
'style': function(node, value){
(node.style) ? node.style.cssText = value : node.setAttribute('style', value);
},
'value': function(node, value){
node.value = (value != null) ? value : '';
}
});
propertyGetters['class'] = function(node){
return ('className' in node) ? node.className || null : node.getAttribute('class');
};
/* <webkit> */
var el = document.createElement('button');
// IE sets type as readonly and throws
try { el.type = 'button'; } catch(e){}
if (el.type != 'button') propertySetters.type = function(node, value){
node.setAttribute('type', value);
};
el = null;
/* </webkit> */
/*<IE>*/
var input = document.createElement('input');
input.value = 't';
input.type = 'submit';
if (input.value != 't') propertySetters.type = function(node, type){
var value = node.value;
node.type = type;
node.value = value;
};
input = null;
/*</IE>*/
/* getProperty, setProperty */
/* <ltIE9> */
var pollutesGetAttribute = (function(div){
div.random = 'attribute';
return (div.getAttribute('random') == 'attribute');
})(document.createElement('div'));
/* <ltIE9> */
Element.implement({
setProperty: function(name, value){
var setter = propertySetters[name.toLowerCase()];
if (setter){
setter(this, value);
} else {
/* <ltIE9> */
if (pollutesGetAttribute) var attributeWhiteList = this.retrieve('$attributeWhiteList', {});
/* </ltIE9> */
if (value == null){
this.removeAttribute(name);
/* <ltIE9> */
if (pollutesGetAttribute) delete attributeWhiteList[name];
/* </ltIE9> */
} else {
this.setAttribute(name, '' + value);
/* <ltIE9> */
if (pollutesGetAttribute) attributeWhiteList[name] = true;
/* </ltIE9> */
}
}
return this;
},
setProperties: function(attributes){
for (var attribute in attributes) this.setProperty(attribute, attributes[attribute]);
return this;
},
getProperty: function(name){
var getter = propertyGetters[name.toLowerCase()];
if (getter) return getter(this);
/* <ltIE9> */
if (pollutesGetAttribute){
var attr = this.getAttributeNode(name), attributeWhiteList = this.retrieve('$attributeWhiteList', {});
if (!attr) return null;
if (attr.expando && !attributeWhiteList[name]){
var outer = this.outerHTML;
// segment by the opening tag and find mention of attribute name
if (outer.substr(0, outer.search(/\/?['"]?>(?![^<]*<['"])/)).indexOf(name) < 0) return null;
attributeWhiteList[name] = true;
}
}
/* </ltIE9> */
var result = Slick.getAttribute(this, name);
return (!result && !Slick.hasAttribute(this, name)) ? null : result;
},
getProperties: function(){
var args = Array.from(arguments);
return args.map(this.getProperty, this).associate(args);
},
removeProperty: function(name){
return this.setProperty(name, null);
},
removeProperties: function(){
Array.each(arguments, this.removeProperty, this);
return this;
},
set: function(prop, value){
var property = Element.Properties[prop];
(property && property.set) ? property.set.call(this, value) : this.setProperty(prop, value);
}.overloadSetter(),
get: function(prop){
var property = Element.Properties[prop];
return (property && property.get) ? property.get.apply(this) : this.getProperty(prop);
}.overloadGetter(),
erase: function(prop){
var property = Element.Properties[prop];
(property && property.erase) ? property.erase.apply(this) : this.removeProperty(prop);
return this;
},
hasClass: function(className){
return this.className.clean().contains(className, ' ');
},
addClass: function(className){
if (!this.hasClass(className)) this.className = (this.className + ' ' + className).clean();
return this;
},
removeClass: function(className){
this.className = this.className.replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)'), '$1');
return this;
},
toggleClass: function(className, force){
if (force == null) force = !this.hasClass(className);
return (force) ? this.addClass(className) : this.removeClass(className);
},
adopt: function(){
var parent = this, fragment, elements = Array.flatten(arguments), length = elements.length;
if (length > 1) parent = fragment = document.createDocumentFragment();
for (var i = 0; i < length; i++){
var element = document.id(elements[i], true);
if (element) parent.appendChild(element);
}
if (fragment) this.appendChild(fragment);
return this;
},
appendText: function(text, where){
return this.grab(this.getDocument().newTextNode(text), where);
},
grab: function(el, where){
inserters[where || 'bottom'](document.id(el, true), this);
return this;
},
inject: function(el, where){
inserters[where || 'bottom'](this, document.id(el, true));
return this;
},
replaces: function(el){
el = document.id(el, true);
el.parentNode.replaceChild(this, el);
return this;
},
wraps: function(el, where){
el = document.id(el, true);
return this.replaces(el).grab(el, where);
},
getSelected: function(){
this.selectedIndex; // Safari 3.2.1
return new Elements(Array.from(this.options).filter(function(option){
return option.selected;
}));
},
toQueryString: function(){
var queryString = [];
this.getElements('input, select, textarea').each(function(el){
var type = el.type;
if (!el.name || el.disabled || type == 'submit' || type == 'reset' || type == 'file' || type == 'image') return;
var value = (el.get('tag') == 'select') ? el.getSelected().map(function(opt){
// IE
return document.id(opt).get('value');
}) : ((type == 'radio' || type == 'checkbox') && !el.checked) ? null : el.get('value');
Array.from(value).each(function(val){
if (typeof val != 'undefined') queryString.push(encodeURIComponent(el.name) + '=' + encodeURIComponent(val));
});
});
return queryString.join('&');
}
});
var collected = {}, storage = {};
var get = function(uid){
return (storage[uid] || (storage[uid] = {}));
};
var clean = function(item){
var uid = item.uniqueNumber;
if (item.removeEvents) item.removeEvents();
if (item.clearAttributes) item.clearAttributes();
if (uid != null){
delete collected[uid];
delete storage[uid];
}
return item;
};
var formProps = {input: 'checked', option: 'selected', textarea: 'value'};
Element.implement({
destroy: function(){
var children = clean(this).getElementsByTagName('*');
Array.each(children, clean);
Element.dispose(this);
return null;
},
empty: function(){
Array.from(this.childNodes).each(Element.dispose);
return this;
},
dispose: function(){
return (this.parentNode) ? this.parentNode.removeChild(this) : this;
},
clone: function(contents, keepid){
contents = contents !== false;
var clone = this.cloneNode(contents), ce = [clone], te = [this], i;
if (contents){
ce.append(Array.from(clone.getElementsByTagName('*')));
te.append(Array.from(this.getElementsByTagName('*')));
}
for (i = ce.length; i--;){
var node = ce[i], element = te[i];
if (!keepid) node.removeAttribute('id');
/*<ltIE9>*/
if (node.clearAttributes){
node.clearAttributes();
node.mergeAttributes(element);
node.removeAttribute('uniqueNumber');
if (node.options){
var no = node.options, eo = element.options;
for (var j = no.length; j--;) no[j].selected = eo[j].selected;
}
}
/*</ltIE9>*/
var prop = formProps[element.tagName.toLowerCase()];
if (prop && element[prop]) node[prop] = element[prop];
}
/*<ltIE9>*/
if (Browser.ie){
var co = clone.getElementsByTagName('object'), to = this.getElementsByTagName('object');
for (i = co.length; i--;) co[i].outerHTML = to[i].outerHTML;
}
/*</ltIE9>*/
return document.id(clone);
}
});
[Element, Window, Document].invoke('implement', {
addListener: function(type, fn){
if (type == 'unload'){
var old = fn, self = this;
fn = function(){
self.removeListener('unload', fn);
old();
};
} else {
collected[Slick.uidOf(this)] = this;
}
if (this.addEventListener) this.addEventListener(type, fn, !!arguments[2]);
else this.attachEvent('on' + type, fn);
return this;
},
removeListener: function(type, fn){
if (this.removeEventListener) this.removeEventListener(type, fn, !!arguments[2]);
else this.detachEvent('on' + type, fn);
return this;
},
retrieve: function(property, dflt){
var storage = get(Slick.uidOf(this)), prop = storage[property];
if (dflt != null && prop == null) prop = storage[property] = dflt;
return prop != null ? prop : null;
},
store: function(property, value){
var storage = get(Slick.uidOf(this));
storage[property] = value;
return this;
},
eliminate: function(property){
var storage = get(Slick.uidOf(this));
delete storage[property];
return this;
}
});
/*<ltIE9>*/
if (window.attachEvent && !window.addEventListener) window.addListener('unload', function(){
Object.each(collected, clean);
if (window.CollectGarbage) CollectGarbage();
});
/*</ltIE9>*/
Element.Properties = {};
Element.Properties.style = {
set: function(style){
this.style.cssText = style;
},
get: function(){
return this.style.cssText;
},
erase: function(){
this.style.cssText = '';
}
};
Element.Properties.tag = {
get: function(){
return this.tagName.toLowerCase();
}
};
Element.Properties.html = {
set: function(html){
if (html == null) html = '';
else if (typeOf(html) == 'array') html = html.join('');
this.innerHTML = html;
},
erase: function(){
this.innerHTML = '';
}
};
/*<ltIE9>*/
// technique by jdbarlett - http://jdbartlett.com/innershiv/
var div = document.createElement('div');
div.innerHTML = '<nav></nav>';
var supportsHTML5Elements = (div.childNodes.length == 1);
if (!supportsHTML5Elements){
var tags = 'abbr article aside audio canvas datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video'.split(' '),
fragment = document.createDocumentFragment(), l = tags.length;
while (l--) fragment.createElement(tags[l]);
}
div = null;
/*</ltIE9>*/
/*<IE>*/
var supportsTableInnerHTML = Function.attempt(function(){
var table = document.createElement('table');
table.innerHTML = '<tr><td></td></tr>';
return true;
});
/*<ltFF4>*/
var tr = document.createElement('tr'), html = '<td></td>';
tr.innerHTML = html;
var supportsTRInnerHTML = (tr.innerHTML == html);
tr = null;
/*</ltFF4>*/
if (!supportsTableInnerHTML || !supportsTRInnerHTML || !supportsHTML5Elements){
Element.Properties.html.set = (function(set){
var translations = {
table: [1, '<table>', '</table>'],
select: [1, '<select>', '</select>'],
tbody: [2, '<table><tbody>', '</tbody></table>'],
tr: [3, '<table><tbody><tr>', '</tr></tbody></table>']
};
translations.thead = translations.tfoot = translations.tbody;
return function(html){
var wrap = translations[this.get('tag')];
if (!wrap && !supportsHTML5Elements) wrap = [0, '', ''];
if (!wrap) return set.call(this, html);
var level = wrap[0], wrapper = document.createElement('div'), target = wrapper;
if (!supportsHTML5Elements) fragment.appendChild(wrapper);
wrapper.innerHTML = [wrap[1], html, wrap[2]].flatten().join('');
while (level--) target = target.firstChild;
this.empty().adopt(target.childNodes);
if (!supportsHTML5Elements) fragment.removeChild(wrapper);
wrapper = null;
};
})(Element.Properties.html.set);
}
/*</IE>*/
/*<ltIE9>*/
var testForm = document.createElement('form');
testForm.innerHTML = '<select><option>s</option></select>';
if (testForm.firstChild.value != 's') Element.Properties.value = {
set: function(value){
var tag = this.get('tag');
if (tag != 'select') return this.setProperty('value', value);
var options = this.getElements('option');
for (var i = 0; i < options.length; i++){
var option = options[i],
attr = option.getAttributeNode('value'),
optionValue = (attr && attr.specified) ? option.value : option.get('text');
if (optionValue == value) return option.selected = true;
}
},
get: function(){
var option = this, tag = option.get('tag');
if (tag != 'select' && tag != 'option') return this.getProperty('value');
if (tag == 'select' && !(option = option.getSelected()[0])) return '';
var attr = option.getAttributeNode('value');
return (attr && attr.specified) ? option.value : option.get('text');
}
};
testForm = null;
/*</ltIE9>*/
/*<IE>*/
if (document.createElement('div').getAttributeNode('id')) Element.Properties.id = {
set: function(id){
this.id = this.getAttributeNode('id').value = id;
},
get: function(){
return this.id || null;
},
erase: function(){
this.id = this.getAttributeNode('id').value = '';
}
};
/*</IE>*/
})();
/*
---
name: Element.Style
description: Contains methods for interacting with the styles of Elements in a fashionable way.
license: MIT-style license.
requires: Element
provides: Element.Style
...
*/
(function(){
var html = document.html;
//<ltIE9>
// Check for oldIE, which does not remove styles when they're set to null
var el = document.createElement('div');
el.style.color = 'red';
el.style.color = null;
var doesNotRemoveStyles = el.style.color == 'red';
el = null;
//</ltIE9>
Element.Properties.styles = {set: function(styles){
this.setStyles(styles);
}};
var hasOpacity = (html.style.opacity != null),
hasFilter = (html.style.filter != null),
reAlpha = /alpha\(opacity=([\d.]+)\)/i;
var setVisibility = function(element, opacity){
element.store('$opacity', opacity);
element.style.visibility = opacity > 0 || opacity == null ? 'visible' : 'hidden';
};
var setOpacity = (hasOpacity ? function(element, opacity){
element.style.opacity = opacity;
} : (hasFilter ? function(element, opacity){
var style = element.style;
if (!element.currentStyle || !element.currentStyle.hasLayout) style.zoom = 1;
if (opacity == null || opacity == 1) opacity = '';
else opacity = 'alpha(opacity=' + (opacity * 100).limit(0, 100).round() + ')';
var filter = style.filter || element.getComputedStyle('filter') || '';
style.filter = reAlpha.test(filter) ? filter.replace(reAlpha, opacity) : filter + opacity;
if (!style.filter) style.removeAttribute('filter');
} : setVisibility));
var getOpacity = (hasOpacity ? function(element){
var opacity = element.style.opacity || element.getComputedStyle('opacity');
return (opacity == '') ? 1 : opacity.toFloat();
} : (hasFilter ? function(element){
var filter = (element.style.filter || element.getComputedStyle('filter')),
opacity;
if (filter) opacity = filter.match(reAlpha);
return (opacity == null || filter == null) ? 1 : (opacity[1] / 100);
} : function(element){
var opacity = element.retrieve('$opacity');
if (opacity == null) opacity = (element.style.visibility == 'hidden' ? 0 : 1);
return opacity;
}));
var floatName = (html.style.cssFloat == null) ? 'styleFloat' : 'cssFloat';
Element.implement({
getComputedStyle: function(property){
if (this.currentStyle) return this.currentStyle[property.camelCase()];
var defaultView = Element.getDocument(this).defaultView,
computed = defaultView ? defaultView.getComputedStyle(this, null) : null;
return (computed) ? computed.getPropertyValue((property == floatName) ? 'float' : property.hyphenate()) : null;
},
setStyle: function(property, value){
if (property == 'opacity'){
if (value != null) value = parseFloat(value);
setOpacity(this, value);
return this;
}
property = (property == 'float' ? floatName : property).camelCase();
if (typeOf(value) != 'string'){
var map = (Element.Styles[property] || '@').split(' ');
value = Array.from(value).map(function(val, i){
if (!map[i]) return '';
return (typeOf(val) == 'number') ? map[i].replace('@', Math.round(val)) : val;
}).join(' ');
} else if (value == String(Number(value))){
value = Math.round(value);
}
this.style[property] = value;
//<ltIE9>
if ((value == '' || value == null) && doesNotRemoveStyles && this.style.removeAttribute){
this.style.removeAttribute(property);
}
//</ltIE9>
return this;
},
getStyle: function(property){
if (property == 'opacity') return getOpacity(this);
property = (property == 'float' ? floatName : property).camelCase();
var result = this.style[property];
if (!result || property == 'zIndex'){
result = [];
for (var style in Element.ShortStyles){
if (property != style) continue;
for (var s in Element.ShortStyles[style]) result.push(this.getStyle(s));
return result.join(' ');
}
result = this.getComputedStyle(property);
}
if (result){
result = String(result);
var color = result.match(/rgba?\([\d\s,]+\)/);
if (color) result = result.replace(color[0], color[0].rgbToHex());
}
if (Browser.opera || Browser.ie){
if ((/^(height|width)$/).test(property) && !(/px$/.test(result))){
var values = (property == 'width') ? ['left', 'right'] : ['top', 'bottom'], size = 0;
values.each(function(value){
size += this.getStyle('border-' + value + '-width').toInt() + this.getStyle('padding-' + value).toInt();
}, this);
return this['offset' + property.capitalize()] - size + 'px';
}
if (Browser.ie && (/^border(.+)Width|margin|padding/).test(property) && isNaN(parseFloat(result))){
return '0px';
}
}
return result;
},
setStyles: function(styles){
for (var style in styles) this.setStyle(style, styles[style]);
return this;
},
getStyles: function(){
var result = {};
Array.flatten(arguments).each(function(key){
result[key] = this.getStyle(key);
}, this);
return result;
}
});
Element.Styles = {
left: '@px', top: '@px', bottom: '@px', right: '@px',
width: '@px', height: '@px', maxWidth: '@px', maxHeight: '@px', minWidth: '@px', minHeight: '@px',
backgroundColor: 'rgb(@, @, @)', backgroundPosition: '@px @px', color: 'rgb(@, @, @)',
fontSize: '@px', letterSpacing: '@px', lineHeight: '@px', clip: 'rect(@px @px @px @px)',
margin: '@px @px @px @px', padding: '@px @px @px @px', border: '@px @ rgb(@, @, @) @px @ rgb(@, @, @) @px @ rgb(@, @, @)',
borderWidth: '@px @px @px @px', borderStyle: '@ @ @ @', borderColor: 'rgb(@, @, @) rgb(@, @, @) rgb(@, @, @) rgb(@, @, @)',
zIndex: '@', 'zoom': '@', fontWeight: '@', textIndent: '@px', opacity: '@'
};
Element.ShortStyles = {margin: {}, padding: {}, border: {}, borderWidth: {}, borderStyle: {}, borderColor: {}};
['Top', 'Right', 'Bottom', 'Left'].each(function(direction){
var Short = Element.ShortStyles;
var All = Element.Styles;
['margin', 'padding'].each(function(style){
var sd = style + direction;
Short[style][sd] = All[sd] = '@px';
});
var bd = 'border' + direction;
Short.border[bd] = All[bd] = '@px @ rgb(@, @, @)';
var bdw = bd + 'Width', bds = bd + 'Style', bdc = bd + 'Color';
Short[bd] = {};
Short.borderWidth[bdw] = Short[bd][bdw] = All[bdw] = '@px';
Short.borderStyle[bds] = Short[bd][bds] = All[bds] = '@';
Short.borderColor[bdc] = Short[bd][bdc] = All[bdc] = 'rgb(@, @, @)';
});
})();
/*
---
name: Element.Event
description: Contains Element methods for dealing with events. This file also includes mouseenter and mouseleave custom Element Events, if necessary.
license: MIT-style license.
requires: [Element, Event]
provides: Element.Event
...
*/
(function(){
Element.Properties.events = {set: function(events){
this.addEvents(events);
}};
[Element, Window, Document].invoke('implement', {
addEvent: function(type, fn){
var events = this.retrieve('events', {});
if (!events[type]) events[type] = {keys: [], values: []};
if (events[type].keys.contains(fn)) return this;
events[type].keys.push(fn);
var realType = type,
custom = Element.Events[type],
condition = fn,
self = this;
if (custom){
if (custom.onAdd) custom.onAdd.call(this, fn, type);
if (custom.condition){
condition = function(event){
if (custom.condition.call(this, event, type)) return fn.call(this, event);
return true;
};
}
if (custom.base) realType = Function.from(custom.base).call(this, type);
}
var defn = function(){
return fn.call(self);
};
var nativeEvent = Element.NativeEvents[realType];
if (nativeEvent){
if (nativeEvent == 2){
defn = function(event){
event = new DOMEvent(event, self.getWindow());
if (condition.call(self, event) === false) event.stop();
};
}
this.addListener(realType, defn, arguments[2]);
}
events[type].values.push(defn);
return this;
},
removeEvent: function(type, fn){
var events = this.retrieve('events');
if (!events || !events[type]) return this;
var list = events[type];
var index = list.keys.indexOf(fn);
if (index == -1) return this;
var value = list.values[index];
delete list.keys[index];
delete list.values[index];
var custom = Element.Events[type];
if (custom){
if (custom.onRemove) custom.onRemove.call(this, fn, type);
if (custom.base) type = Function.from(custom.base).call(this, type);
}
return (Element.NativeEvents[type]) ? this.removeListener(type, value, arguments[2]) : this;
},
addEvents: function(events){
for (var event in events) this.addEvent(event, events[event]);
return this;
},
removeEvents: function(events){
var type;
if (typeOf(events) == 'object'){
for (type in events) this.removeEvent(type, events[type]);
return this;
}
var attached = this.retrieve('events');
if (!attached) return this;
if (!events){
for (type in attached) this.removeEvents(type);
this.eliminate('events');
} else if (attached[events]){
attached[events].keys.each(function(fn){
this.removeEvent(events, fn);
}, this);
delete attached[events];
}
return this;
},
fireEvent: function(type, args, delay){
var events = this.retrieve('events');
if (!events || !events[type]) return this;
args = Array.from(args);
events[type].keys.each(function(fn){
if (delay) fn.delay(delay, this, args);
else fn.apply(this, args);
}, this);
return this;
},
cloneEvents: function(from, type){
from = document.id(from);
var events = from.retrieve('events');
if (!events) return this;
if (!type){
for (var eventType in events) this.cloneEvents(from, eventType);
} else if (events[type]){
events[type].keys.each(function(fn){
this.addEvent(type, fn);
}, this);
}
return this;
}
});
Element.NativeEvents = {
click: 2, dblclick: 2, mouseup: 2, mousedown: 2, contextmenu: 2, //mouse buttons
mousewheel: 2, DOMMouseScroll: 2, //mouse wheel
mouseover: 2, mouseout: 2, mousemove: 2, selectstart: 2, selectend: 2, //mouse movement
keydown: 2, keypress: 2, keyup: 2, //keyboard
orientationchange: 2, // mobile
touchstart: 2, touchmove: 2, touchend: 2, touchcancel: 2, // touch
gesturestart: 2, gesturechange: 2, gestureend: 2, // gesture
focus: 2, blur: 2, change: 2, reset: 2, select: 2, submit: 2, paste: 2, input: 2, //form elements
load: 2, unload: 1, beforeunload: 2, resize: 1, move: 1, DOMContentLoaded: 1, readystatechange: 1, //window
error: 1, abort: 1, scroll: 1 //misc
};
Element.Events = {mousewheel: {
base: (Browser.firefox) ? 'DOMMouseScroll' : 'mousewheel'
}};
if ('onmouseenter' in document.documentElement){
Element.NativeEvents.mouseenter = Element.NativeEvents.mouseleave = 2;
} else {
var check = function(event){
var related = event.relatedTarget;
if (related == null) return true;
if (!related) return false;
return (related != this && related.prefix != 'xul' && typeOf(this) != 'document' && !this.contains(related));
};
Element.Events.mouseenter = {
base: 'mouseover',
condition: check
};
Element.Events.mouseleave = {
base: 'mouseout',
condition: check
};
}
/*<ltIE9>*/
if (!window.addEventListener){
Element.NativeEvents.propertychange = 2;
Element.Events.change = {
base: function(){
var type = this.type;
return (this.get('tag') == 'input' && (type == 'radio' || type == 'checkbox')) ? 'propertychange' : 'change'
},
condition: function(event){
return this.type != 'radio' || (event.event.propertyName == 'checked' && this.checked);
}
}
}
/*</ltIE9>*/
})();
/*
---
name: Element.Delegation
description: Extends the Element native object to include the delegate method for more efficient event management.
license: MIT-style license.
requires: [Element.Event]
provides: [Element.Delegation]
...
*/
(function(){
var eventListenerSupport = !!window.addEventListener;
Element.NativeEvents.focusin = Element.NativeEvents.focusout = 2;
var bubbleUp = function(self, match, fn, event, target){
while (target && target != self){
if (match(target, event)) return fn.call(target, event, target);
target = document.id(target.parentNode);
}
};
var map = {
mouseenter: {
base: 'mouseover'
},
mouseleave: {
base: 'mouseout'
},
focus: {
base: 'focus' + (eventListenerSupport ? '' : 'in'),
capture: true
},
blur: {
base: eventListenerSupport ? 'blur' : 'focusout',
capture: true
}
};
/*<ltIE9>*/
var _key = '$delegation:';
var formObserver = function(type){
return {
base: 'focusin',
remove: function(self, uid){
var list = self.retrieve(_key + type + 'listeners', {})[uid];
if (list && list.forms) for (var i = list.forms.length; i--;){
list.forms[i].removeEvent(type, list.fns[i]);
}
},
listen: function(self, match, fn, event, target, uid){
var form = (target.get('tag') == 'form') ? target : event.target.getParent('form');
if (!form) return;
var listeners = self.retrieve(_key + type + 'listeners', {}),
listener = listeners[uid] || {forms: [], fns: []},
forms = listener.forms, fns = listener.fns;
if (forms.indexOf(form) != -1) return;
forms.push(form);
var _fn = function(event){
bubbleUp(self, match, fn, event, target);
};
form.addEvent(type, _fn);
fns.push(_fn);
listeners[uid] = listener;
self.store(_key + type + 'listeners', listeners);
}
};
};
var inputObserver = function(type){
return {
base: 'focusin',
listen: function(self, match, fn, event, target){
var events = {blur: function(){
this.removeEvents(events);
}};
events[type] = function(event){
bubbleUp(self, match, fn, event, target);
};
event.target.addEvents(events);
}
};
};
if (!eventListenerSupport) Object.append(map, {
submit: formObserver('submit'),
reset: formObserver('reset'),
change: inputObserver('change'),
select: inputObserver('select')
});
/*</ltIE9>*/
var proto = Element.prototype,
addEvent = proto.addEvent,
removeEvent = proto.removeEvent;
var relay = function(old, method){
return function(type, fn, useCapture){
if (type.indexOf(':relay') == -1) return old.call(this, type, fn, useCapture);
var parsed = Slick.parse(type).expressions[0][0];
if (parsed.pseudos[0].key != 'relay') return old.call(this, type, fn, useCapture);
var newType = parsed.tag;
parsed.pseudos.slice(1).each(function(pseudo){
newType += ':' + pseudo.key + (pseudo.value ? '(' + pseudo.value + ')' : '');
});
old.call(this, type, fn);
return method.call(this, newType, parsed.pseudos[0].value, fn);
};
};
var delegation = {
addEvent: function(type, match, fn){
var storage = this.retrieve('$delegates', {}), stored = storage[type];
if (stored) for (var _uid in stored){
if (stored[_uid].fn == fn && stored[_uid].match == match) return this;
}
var _type = type, _match = match, _fn = fn, _map = map[type] || {};
type = _map.base || _type;
match = function(target){
return Slick.match(target, _match);
};
var elementEvent = Element.Events[_type];
if (elementEvent && elementEvent.condition){
var __match = match, condition = elementEvent.condition;
match = function(target, event){
return __match(target, event) && condition.call(target, event, type);
};
}
var self = this, uid = String.uniqueID();
var delegator = _map.listen ? function(event, target){
if (!target && event && event.target) target = event.target;
if (target) _map.listen(self, match, fn, event, target, uid);
} : function(event, target){
if (!target && event && event.target) target = event.target;
if (target) bubbleUp(self, match, fn, event, target);
};
if (!stored) stored = {};
stored[uid] = {
match: _match,
fn: _fn,
delegator: delegator
};
storage[_type] = stored;
return addEvent.call(this, type, delegator, _map.capture);
},
removeEvent: function(type, match, fn, _uid){
var storage = this.retrieve('$delegates', {}), stored = storage[type];
if (!stored) return this;
if (_uid){
var _type = type, delegator = stored[_uid].delegator, _map = map[type] || {};
type = _map.base || _type;
if (_map.remove) _map.remove(this, _uid);
delete stored[_uid];
storage[_type] = stored;
return removeEvent.call(this, type, delegator);
}
var __uid, s;
if (fn) for (__uid in stored){
s = stored[__uid];
if (s.match == match && s.fn == fn) return delegation.removeEvent.call(this, type, match, fn, __uid);
} else for (__uid in stored){
s = stored[__uid];
if (s.match == match) delegation.removeEvent.call(this, type, match, s.fn, __uid);
}
return this;
}
};
[Element, Window, Document].invoke('implement', {
addEvent: relay(addEvent, delegation.addEvent),
removeEvent: relay(removeEvent, delegation.removeEvent)
});
})();
/*
---
name: Element.Dimensions
description: Contains methods to work with size, scroll, or positioning of Elements and the window object.
license: MIT-style license.
credits:
- Element positioning based on the [qooxdoo](http://qooxdoo.org/) code and smart browser fixes, [LGPL License](http://www.gnu.org/licenses/lgpl.html).
- Viewport dimensions based on [YUI](http://developer.yahoo.com/yui/) code, [BSD License](http://developer.yahoo.com/yui/license.html).
requires: [Element, Element.Style]
provides: [Element.Dimensions]
...
*/
(function(){
var element = document.createElement('div'),
child = document.createElement('div');
element.style.height = '0';
element.appendChild(child);
var brokenOffsetParent = (child.offsetParent === element);
element = child = null;
var isOffset = function(el){
return styleString(el, 'position') != 'static' || isBody(el);
};
var isOffsetStatic = function(el){
return isOffset(el) || (/^(?:table|td|th)$/i).test(el.tagName);
};
Element.implement({
scrollTo: function(x, y){
if (isBody(this)){
this.getWindow().scrollTo(x, y);
} else {
this.scrollLeft = x;
this.scrollTop = y;
}
return this;
},
getSize: function(){
if (isBody(this)) return this.getWindow().getSize();
return {x: this.offsetWidth, y: this.offsetHeight};
},
getScrollSize: function(){
if (isBody(this)) return this.getWindow().getScrollSize();
return {x: this.scrollWidth, y: this.scrollHeight};
},
getScroll: function(){
if (isBody(this)) return this.getWindow().getScroll();
return {x: this.scrollLeft, y: this.scrollTop};
},
getScrolls: function(){
var element = this.parentNode, position = {x: 0, y: 0};
while (element && !isBody(element)){
position.x += element.scrollLeft;
position.y += element.scrollTop;
element = element.parentNode;
}
return position;
},
getOffsetParent: brokenOffsetParent ? function(){
var element = this;
if (isBody(element) || styleString(element, 'position') == 'fixed') return null;
var isOffsetCheck = (styleString(element, 'position') == 'static') ? isOffsetStatic : isOffset;
while ((element = element.parentNode)){
if (isOffsetCheck(element)) return element;
}
return null;
} : function(){
var element = this;
if (isBody(element) || styleString(element, 'position') == 'fixed') return null;
try {
return element.offsetParent;
} catch(e) {}
return null;
},
getOffsets: function(){
if (this.getBoundingClientRect && !Browser.Platform.ios){
var bound = this.getBoundingClientRect(),
html = document.id(this.getDocument().documentElement),
htmlScroll = html.getScroll(),
elemScrolls = this.getScrolls(),
isFixed = (styleString(this, 'position') == 'fixed');
return {
x: bound.left.toInt() + elemScrolls.x + ((isFixed) ? 0 : htmlScroll.x) - html.clientLeft,
y: bound.top.toInt() + elemScrolls.y + ((isFixed) ? 0 : htmlScroll.y) - html.clientTop
};
}
var element = this, position = {x: 0, y: 0};
if (isBody(this)) return position;
while (element && !isBody(element)){
position.x += element.offsetLeft;
position.y += element.offsetTop;
if (Browser.firefox){
if (!borderBox(element)){
position.x += leftBorder(element);
position.y += topBorder(element);
}
var parent = element.parentNode;
if (parent && styleString(parent, 'overflow') != 'visible'){
position.x += leftBorder(parent);
position.y += topBorder(parent);
}
} else if (element != this && Browser.safari){
position.x += leftBorder(element);
position.y += topBorder(element);
}
element = element.offsetParent;
}
if (Browser.firefox && !borderBox(this)){
position.x -= leftBorder(this);
position.y -= topBorder(this);
}
return position;
},
getPosition: function(relative){
var offset = this.getOffsets(),
scroll = this.getScrolls();
var position = {
x: offset.x - scroll.x,
y: offset.y - scroll.y
};
if (relative && (relative = document.id(relative))){
var relativePosition = relative.getPosition();
return {x: position.x - relativePosition.x - leftBorder(relative), y: position.y - relativePosition.y - topBorder(relative)};
}
return position;
},
getCoordinates: function(element){
if (isBody(this)) return this.getWindow().getCoordinates();
var position = this.getPosition(element),
size = this.getSize();
var obj = {
left: position.x,
top: position.y,
width: size.x,
height: size.y
};
obj.right = obj.left + obj.width;
obj.bottom = obj.top + obj.height;
return obj;
},
computePosition: function(obj){
return {
left: obj.x - styleNumber(this, 'margin-left'),
top: obj.y - styleNumber(this, 'margin-top')
};
},
setPosition: function(obj){
return this.setStyles(this.computePosition(obj));
}
});
[Document, Window].invoke('implement', {
getSize: function(){
var doc = getCompatElement(this);
return {x: doc.clientWidth, y: doc.clientHeight};
},
getScroll: function(){
var win = this.getWindow(), doc = getCompatElement(this);
return {x: win.pageXOffset || doc.scrollLeft, y: win.pageYOffset || doc.scrollTop};
},
getScrollSize: function(){
var doc = getCompatElement(this),
min = this.getSize(),
body = this.getDocument().body;
return {x: Math.max(doc.scrollWidth, body.scrollWidth, min.x), y: Math.max(doc.scrollHeight, body.scrollHeight, min.y)};
},
getPosition: function(){
return {x: 0, y: 0};
},
getCoordinates: function(){
var size = this.getSize();
return {top: 0, left: 0, bottom: size.y, right: size.x, height: size.y, width: size.x};
}
});
// private methods
var styleString = Element.getComputedStyle;
function styleNumber(element, style){
return styleString(element, style).toInt() || 0;
}
function borderBox(element){
return styleString(element, '-moz-box-sizing') == 'border-box';
}
function topBorder(element){
return styleNumber(element, 'border-top-width');
}
function leftBorder(element){
return styleNumber(element, 'border-left-width');
}
function isBody(element){
return (/^(?:body|html)$/i).test(element.tagName);
}
function getCompatElement(element){
var doc = element.getDocument();
return (!doc.compatMode || doc.compatMode == 'CSS1Compat') ? doc.html : doc.body;
}
})();
//aliases
Element.alias({position: 'setPosition'}); //compatability
[Window, Document, Element].invoke('implement', {
getHeight: function(){
return this.getSize().y;
},
getWidth: function(){
return this.getSize().x;
},
getScrollTop: function(){
return this.getScroll().y;
},
getScrollLeft: function(){
return this.getScroll().x;
},
getScrollHeight: function(){
return this.getScrollSize().y;
},
getScrollWidth: function(){
return this.getScrollSize().x;
},
getTop: function(){
return this.getPosition().y;
},
getLeft: function(){
return this.getPosition().x;
}
});
/*
---
name: Fx
description: Contains the basic animation logic to be extended by all other Fx Classes.
license: MIT-style license.
requires: [Chain, Events, Options]
provides: Fx
...
*/
(function(){
var Fx = this.Fx = new Class({
Implements: [Chain, Events, Options],
options: {
/*
onStart: nil,
onCancel: nil,
onComplete: nil,
*/
fps: 60,
unit: false,
duration: 500,
frames: null,
frameSkip: true,
link: 'ignore'
},
initialize: function(options){
this.subject = this.subject || this;
this.setOptions(options);
},
getTransition: function(){
return function(p){
return -(Math.cos(Math.PI * p) - 1) / 2;
};
},
step: function(now){
if (this.options.frameSkip){
var diff = (this.time != null) ? (now - this.time) : 0, frames = diff / this.frameInterval;
this.time = now;
this.frame += frames;
} else {
this.frame++;
}
if (this.frame < this.frames){
var delta = this.transition(this.frame / this.frames);
this.set(this.compute(this.from, this.to, delta));
} else {
this.frame = this.frames;
this.set(this.compute(this.from, this.to, 1));
this.stop();
}
},
set: function(now){
return now;
},
compute: function(from, to, delta){
return Fx.compute(from, to, delta);
},
check: function(){
if (!this.isRunning()) return true;
switch (this.options.link){
case 'cancel': this.cancel(); return true;
case 'chain': this.chain(this.caller.pass(arguments, this)); return false;
}
return false;
},
start: function(from, to){
if (!this.check(from, to)) return this;
this.from = from;
this.to = to;
this.frame = (this.options.frameSkip) ? 0 : -1;
this.time = null;
this.transition = this.getTransition();
var frames = this.options.frames, fps = this.options.fps, duration = this.options.duration;
this.duration = Fx.Durations[duration] || duration.toInt();
this.frameInterval = 1000 / fps;
this.frames = frames || Math.round(this.duration / this.frameInterval);
this.fireEvent('start', this.subject);
pushInstance.call(this, fps);
return this;
},
stop: function(){
if (this.isRunning()){
this.time = null;
pullInstance.call(this, this.options.fps);
if (this.frames == this.frame){
this.fireEvent('complete', this.subject);
if (!this.callChain()) this.fireEvent('chainComplete', this.subject);
} else {
this.fireEvent('stop', this.subject);
}
}
return this;
},
cancel: function(){
if (this.isRunning()){
this.time = null;
pullInstance.call(this, this.options.fps);
this.frame = this.frames;
this.fireEvent('cancel', this.subject).clearChain();
}
return this;
},
pause: function(){
if (this.isRunning()){
this.time = null;
pullInstance.call(this, this.options.fps);
}
return this;
},
resume: function(){
if ((this.frame < this.frames) && !this.isRunning()) pushInstance.call(this, this.options.fps);
return this;
},
isRunning: function(){
var list = instances[this.options.fps];
return list && list.contains(this);
}
});
Fx.compute = function(from, to, delta){
return (to - from) * delta + from;
};
Fx.Durations = {'short': 250, 'normal': 500, 'long': 1000};
// global timers
var instances = {}, timers = {};
var loop = function(){
var now = Date.now();
for (var i = this.length; i--;){
var instance = this[i];
if (instance) instance.step(now);
}
};
var pushInstance = function(fps){
var list = instances[fps] || (instances[fps] = []);
list.push(this);
if (!timers[fps]) timers[fps] = loop.periodical(Math.round(1000 / fps), list);
};
var pullInstance = function(fps){
var list = instances[fps];
if (list){
list.erase(this);
if (!list.length && timers[fps]){
delete instances[fps];
timers[fps] = clearInterval(timers[fps]);
}
}
};
})();
/*
---
name: Fx.CSS
description: Contains the CSS animation logic. Used by Fx.Tween, Fx.Morph, Fx.Elements.
license: MIT-style license.
requires: [Fx, Element.Style]
provides: Fx.CSS
...
*/
Fx.CSS = new Class({
Extends: Fx,
//prepares the base from/to object
prepare: function(element, property, values){
values = Array.from(values);
var from = values[0], to = values[1];
if (to == null){
to = from;
from = element.getStyle(property);
var unit = this.options.unit;
// adapted from: https://github.com/ryanmorr/fx/blob/master/fx.js#L299
if (unit && from.slice(-unit.length) != unit && parseFloat(from) != 0){
element.setStyle(property, to + unit);
var value = element.getComputedStyle(property);
// IE and Opera support pixelLeft or pixelWidth
if (!(/px$/.test(value))){
value = element.style[('pixel-' + property).camelCase()];
if (value == null){
// adapted from Dean Edwards' http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
var left = element.style.left;
element.style.left = to + unit;
value = element.style.pixelLeft;
element.style.left = left;
}
}
from = (to || 1) / (parseFloat(value) || 1) * (parseFloat(from) || 0);
element.setStyle(property, from + unit);
}
}
return {from: this.parse(from), to: this.parse(to)};
},
//parses a value into an array
parse: function(value){
value = Function.from(value)();
value = (typeof value == 'string') ? value.split(' ') : Array.from(value);
return value.map(function(val){
val = String(val);
var found = false;
Object.each(Fx.CSS.Parsers, function(parser, key){
if (found) return;
var parsed = parser.parse(val);
if (parsed || parsed === 0) found = {value: parsed, parser: parser};
});
found = found || {value: val, parser: Fx.CSS.Parsers.String};
return found;
});
},
//computes by a from and to prepared objects, using their parsers.
compute: function(from, to, delta){
var computed = [];
(Math.min(from.length, to.length)).times(function(i){
computed.push({value: from[i].parser.compute(from[i].value, to[i].value, delta), parser: from[i].parser});
});
computed.$family = Function.from('fx:css:value');
return computed;
},
//serves the value as settable
serve: function(value, unit){
if (typeOf(value) != 'fx:css:value') value = this.parse(value);
var returned = [];
value.each(function(bit){
returned = returned.concat(bit.parser.serve(bit.value, unit));
});
return returned;
},
//renders the change to an element
render: function(element, property, value, unit){
element.setStyle(property, this.serve(value, unit));
},
//searches inside the page css to find the values for a selector
search: function(selector){
if (Fx.CSS.Cache[selector]) return Fx.CSS.Cache[selector];
var to = {}, selectorTest = new RegExp('^' + selector.escapeRegExp() + '$');
Array.each(document.styleSheets, function(sheet, j){
var href = sheet.href;
if (href && href.contains('://') && !href.contains(document.domain)) return;
var rules = sheet.rules || sheet.cssRules;
Array.each(rules, function(rule, i){
if (!rule.style) return;
var selectorText = (rule.selectorText) ? rule.selectorText.replace(/^\w+/, function(m){
return m.toLowerCase();
}) : null;
if (!selectorText || !selectorTest.test(selectorText)) return;
Object.each(Element.Styles, function(value, style){
if (!rule.style[style] || Element.ShortStyles[style]) return;
value = String(rule.style[style]);
to[style] = ((/^rgb/).test(value)) ? value.rgbToHex() : value;
});
});
});
return Fx.CSS.Cache[selector] = to;
}
});
Fx.CSS.Cache = {};
Fx.CSS.Parsers = {
Color: {
parse: function(value){
if (value.match(/^#[0-9a-f]{3,6}$/i)) return value.hexToRgb(true);
return ((value = value.match(/(\d+),\s*(\d+),\s*(\d+)/))) ? [value[1], value[2], value[3]] : false;
},
compute: function(from, to, delta){
return from.map(function(value, i){
return Math.round(Fx.compute(from[i], to[i], delta));
});
},
serve: function(value){
return value.map(Number);
}
},
Number: {
parse: parseFloat,
compute: Fx.compute,
serve: function(value, unit){
return (unit) ? value + unit : value;
}
},
String: {
parse: Function.from(false),
compute: function(zero, one){
return one;
},
serve: function(zero){
return zero;
}
}
};
/*
---
name: Fx.Tween
description: Formerly Fx.Style, effect to transition any CSS property for an element.
license: MIT-style license.
requires: Fx.CSS
provides: [Fx.Tween, Element.fade, Element.highlight]
...
*/
Fx.Tween = new Class({
Extends: Fx.CSS,
initialize: function(element, options){
this.element = this.subject = document.id(element);
this.parent(options);
},
set: function(property, now){
if (arguments.length == 1){
now = property;
property = this.property || this.options.property;
}
this.render(this.element, property, now, this.options.unit);
return this;
},
start: function(property, from, to){
if (!this.check(property, from, to)) return this;
var args = Array.flatten(arguments);
this.property = this.options.property || args.shift();
var parsed = this.prepare(this.element, this.property, args);
return this.parent(parsed.from, parsed.to);
}
});
Element.Properties.tween = {
set: function(options){
this.get('tween').cancel().setOptions(options);
return this;
},
get: function(){
var tween = this.retrieve('tween');
if (!tween){
tween = new Fx.Tween(this, {link: 'cancel'});
this.store('tween', tween);
}
return tween;
}
};
Element.implement({
tween: function(property, from, to){
this.get('tween').start(property, from, to);
return this;
},
fade: function(how){
var fade = this.get('tween'), method, args = ['opacity'].append(arguments), toggle;
if (args[1] == null) args[1] = 'toggle';
switch (args[1]){
case 'in': method = 'start'; args[1] = 1; break;
case 'out': method = 'start'; args[1] = 0; break;
case 'show': method = 'set'; args[1] = 1; break;
case 'hide': method = 'set'; args[1] = 0; break;
case 'toggle':
var flag = this.retrieve('fade:flag', this.getStyle('opacity') == 1);
method = 'start';
args[1] = flag ? 0 : 1;
this.store('fade:flag', !flag);
toggle = true;
break;
default: method = 'start';
}
if (!toggle) this.eliminate('fade:flag');
fade[method].apply(fade, args);
var to = args[args.length - 1];
if (method == 'set' || to != 0) this.setStyle('visibility', to == 0 ? 'hidden' : 'visible');
else fade.chain(function(){
this.element.setStyle('visibility', 'hidden');
this.callChain();
});
return this;
},
highlight: function(start, end){
if (!end){
end = this.retrieve('highlight:original', this.getStyle('background-color'));
end = (end == 'transparent') ? '#fff' : end;
}
var tween = this.get('tween');
tween.start('background-color', start || '#ffff88', end).chain(function(){
this.setStyle('background-color', this.retrieve('highlight:original'));
tween.callChain();
}.bind(this));
return this;
}
});
/*
---
name: Fx.Morph
description: Formerly Fx.Styles, effect to transition any number of CSS properties for an element using an object of rules, or CSS based selector rules.
license: MIT-style license.
requires: Fx.CSS
provides: Fx.Morph
...
*/
Fx.Morph = new Class({
Extends: Fx.CSS,
initialize: function(element, options){
this.element = this.subject = document.id(element);
this.parent(options);
},
set: function(now){
if (typeof now == 'string') now = this.search(now);
for (var p in now) this.render(this.element, p, now[p], this.options.unit);
return this;
},
compute: function(from, to, delta){
var now = {};
for (var p in from) now[p] = this.parent(from[p], to[p], delta);
return now;
},
start: function(properties){
if (!this.check(properties)) return this;
if (typeof properties == 'string') properties = this.search(properties);
var from = {}, to = {};
for (var p in properties){
var parsed = this.prepare(this.element, p, properties[p]);
from[p] = parsed.from;
to[p] = parsed.to;
}
return this.parent(from, to);
}
});
Element.Properties.morph = {
set: function(options){
this.get('morph').cancel().setOptions(options);
return this;
},
get: function(){
var morph = this.retrieve('morph');
if (!morph){
morph = new Fx.Morph(this, {link: 'cancel'});
this.store('morph', morph);
}
return morph;
}
};
Element.implement({
morph: function(props){
this.get('morph').start(props);
return this;
}
});
/*
---
name: Fx.Transitions
description: Contains a set of advanced transitions to be used with any of the Fx Classes.
license: MIT-style license.
credits:
- Easing Equations by Robert Penner, <http://www.robertpenner.com/easing/>, modified and optimized to be used with MooTools.
requires: Fx
provides: Fx.Transitions
...
*/
Fx.implement({
getTransition: function(){
var trans = this.options.transition || Fx.Transitions.Sine.easeInOut;
if (typeof trans == 'string'){
var data = trans.split(':');
trans = Fx.Transitions;
trans = trans[data[0]] || trans[data[0].capitalize()];
if (data[1]) trans = trans['ease' + data[1].capitalize() + (data[2] ? data[2].capitalize() : '')];
}
return trans;
}
});
Fx.Transition = function(transition, params){
params = Array.from(params);
var easeIn = function(pos){
return transition(pos, params);
};
return Object.append(easeIn, {
easeIn: easeIn,
easeOut: function(pos){
return 1 - transition(1 - pos, params);
},
easeInOut: function(pos){
return (pos <= 0.5 ? transition(2 * pos, params) : (2 - transition(2 * (1 - pos), params))) / 2;
}
});
};
Fx.Transitions = {
linear: function(zero){
return zero;
}
};
Fx.Transitions.extend = function(transitions){
for (var transition in transitions) Fx.Transitions[transition] = new Fx.Transition(transitions[transition]);
};
Fx.Transitions.extend({
Pow: function(p, x){
return Math.pow(p, x && x[0] || 6);
},
Expo: function(p){
return Math.pow(2, 8 * (p - 1));
},
Circ: function(p){
return 1 - Math.sin(Math.acos(p));
},
Sine: function(p){
return 1 - Math.cos(p * Math.PI / 2);
},
Back: function(p, x){
x = x && x[0] || 1.618;
return Math.pow(p, 2) * ((x + 1) * p - x);
},
Bounce: function(p){
var value;
for (var a = 0, b = 1; 1; a += b, b /= 2){
if (p >= (7 - 4 * a) / 11){
value = b * b - Math.pow((11 - 6 * a - 11 * p) / 4, 2);
break;
}
}
return value;
},
Elastic: function(p, x){
return Math.pow(2, 10 * --p) * Math.cos(20 * p * Math.PI * (x && x[0] || 1) / 3);
}
});
['Quad', 'Cubic', 'Quart', 'Quint'].each(function(transition, i){
Fx.Transitions[transition] = new Fx.Transition(function(p){
return Math.pow(p, i + 2);
});
});
/*
---
name: Request
description: Powerful all purpose Request Class. Uses XMLHTTPRequest.
license: MIT-style license.
requires: [Object, Element, Chain, Events, Options, Browser]
provides: Request
...
*/
(function(){
var empty = function(){},
progressSupport = ('onprogress' in new Browser.Request);
var Request = this.Request = new Class({
Implements: [Chain, Events, Options],
options: {/*
onRequest: function(){},
onLoadstart: function(event, xhr){},
onProgress: function(event, xhr){},
onUploadProgress: function(event, xhr){},
onComplete: function(){},
onCancel: function(){},
onSuccess: function(responseText, responseXML){},
onFailure: function(xhr){},
onException: function(headerName, value){},
onTimeout: function(){},
user: '',
password: '',*/
url: '',
data: '',
processData: true,
responseType: null,
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
},
async: true,
format: false,
method: 'post',
link: 'ignore',
isSuccess: null,
emulation: true,
urlEncoded: true,
encoding: 'utf-8',
evalScripts: false,
evalResponse: false,
timeout: 0,
noCache: false
},
initialize: function(options){
this.xhr = new Browser.Request();
this.setOptions(options);
if ((typeof ArrayBuffer != 'undefined' && options.data instanceof ArrayBuffer) || (typeof Blob != 'undefined' && options.data instanceof Blob) || (typeof Uint8Array != 'undefined' && options.data instanceof Uint8Array)){
// set data in directly if we're passing binary data because
// otherwise setOptions will convert the data into an empty object
this.options.data = options.data;
}
this.headers = this.options.headers;
},
onStateChange: function(){
var xhr = this.xhr;
if (xhr.readyState != 4 || !this.running) return;
this.running = false;
this.status = 0;
Function.attempt(function(){
var status = xhr.status;
this.status = (status == 1223) ? 204 : status;
}.bind(this));
xhr.onreadystatechange = empty;
if (progressSupport) xhr.onprogress = xhr.onloadstart = empty;
clearTimeout(this.timer);
this.response = {text: (!this.options.responseType && this.xhr.responseText) || '', xml: (!this.options.responseType && this.xhr.responseXML)};
if (this.options.isSuccess.call(this, this.status))
this.success(this.options.responseType ? this.xhr.response : this.response.text, this.response.xml);
else
this.failure();
},
isSuccess: function(){
var status = this.status;
return (status >= 200 && status < 300);
},
isRunning: function(){
return !!this.running;
},
processScripts: function(text){
if (typeof text != 'string') return text;
if (this.options.evalResponse || (/(ecma|java)script/).test(this.getHeader('Content-type'))) return Browser.exec(text);
return text.stripScripts(this.options.evalScripts);
},
success: function(text, xml){
this.onSuccess(this.processScripts(text), xml);
},
onSuccess: function(){
this.fireEvent('complete', arguments).fireEvent('success', arguments).callChain();
},
failure: function(){
this.onFailure();
},
onFailure: function(){
this.fireEvent('complete').fireEvent('failure', this.xhr);
},
loadstart: function(event){
this.fireEvent('loadstart', [event, this.xhr]);
},
progress: function(event){
this.fireEvent('progress', [event, this.xhr]);
},
uploadprogress: function(event){
this.fireEvent('uploadprogress', [event, this.xhr]);
},
timeout: function(){
this.fireEvent('timeout', this.xhr);
},
setHeader: function(name, value){
this.headers[name] = value;
return this;
},
getHeader: function(name){
return Function.attempt(function(){
return this.xhr.getResponseHeader(name);
}.bind(this));
},
check: function(){
if (!this.running) return true;
switch (this.options.link){
case 'cancel': this.cancel(); return true;
case 'chain': this.chain(this.caller.pass(arguments, this)); return false;
}
return false;
},
send: function(options){
if (!this.check(options)) return this;
this.options.isSuccess = this.options.isSuccess || this.isSuccess;
this.running = true;
var type = typeOf(options);
if (type == 'string' || type == 'element') options = {data: options};
var old = this.options;
options = Object.append({data: old.data, url: old.url, method: old.method}, options);
var data = options.data, url = String(options.url), method = options.method.toLowerCase();
if (this.options.processData || method == 'get' || method == 'delete'){
switch (typeOf(data)){
case 'element': data = document.id(data).toQueryString(); break;
case 'object': case 'hash': data = Object.toQueryString(data);
}
if (this.options.format){
var format = 'format=' + this.options.format;
data = (data) ? format + '&' + data : format;
}
if (this.options.emulation && !['get', 'post'].contains(method)){
var _method = '_method=' + method;
data = (data) ? _method + '&' + data : _method;
method = 'post';
}
}
if (this.options.urlEncoded && ['post', 'put'].contains(method)){
var encoding = (this.options.encoding) ? '; charset=' + this.options.encoding : '';
this.headers['Content-type'] = 'application/x-www-form-urlencoded' + encoding;
}
if (!url) url = document.location.pathname;
var trimPosition = url.lastIndexOf('/');
if (trimPosition > -1 && (trimPosition = url.indexOf('#')) > -1) url = url.substr(0, trimPosition);
if (this.options.noCache)
url += (url.contains('?') ? '&' : '?') + String.uniqueID();
if (data && method == 'get'){
url += (url.contains('?') ? '&' : '?') + data;
data = null;
}
var xhr = this.xhr;
if (progressSupport){
xhr.onloadstart = this.loadstart.bind(this);
xhr.onprogress = this.progress.bind(this);
if(xhr.upload) xhr.upload.onprogress = this.uploadprogress.bind(this);
}
xhr.open(method.toUpperCase(), url, this.options.async, this.options.user, this.options.password);
if (this.options.user && 'withCredentials' in xhr) xhr.withCredentials = true;
xhr.onreadystatechange = this.onStateChange.bind(this);
Object.each(this.headers, function(value, key){
try {
xhr.setRequestHeader(key, value);
} catch (e){
this.fireEvent('exception', [key, value]);
}
}, this);
if (this.options.responseType){
xhr.responseType = this.options.responseType.toLowerCase();
}
this.fireEvent('request');
xhr.send(data);
if (!this.options.async) this.onStateChange();
else if (this.options.timeout) this.timer = this.timeout.delay(this.options.timeout, this);
return this;
},
cancel: function(){
if (!this.running) return this;
this.running = false;
var xhr = this.xhr;
xhr.abort();
clearTimeout(this.timer);
xhr.onreadystatechange = empty;
if (progressSupport) xhr.onprogress = xhr.onloadstart = empty;
this.xhr = new Browser.Request();
this.fireEvent('cancel');
return this;
}
});
var methods = {};
['get', 'post', 'put', 'delete', 'GET', 'POST', 'PUT', 'DELETE'].each(function(method){
methods[method] = function(data){
var object = {
method: method
};
if (data != null) object.data = data;
return this.send(object);
};
});
Request.implement(methods);
Element.Properties.send = {
set: function(options){
var send = this.get('send').cancel();
send.setOptions(options);
return this;
},
get: function(){
var send = this.retrieve('send');
if (!send){
send = new Request({
data: this, link: 'cancel', method: this.get('method') || 'post', url: this.get('action')
});
this.store('send', send);
}
return send;
}
};
Element.implement({
send: function(url){
var sender = this.get('send');
sender.send({data: this, url: url || sender.options.url});
return this;
}
});
})();
/*
---
name: Request.HTML
description: Extends the basic Request Class with additional methods for interacting with HTML responses.
license: MIT-style license.
requires: [Element, Request]
provides: Request.HTML
...
*/
Request.HTML = new Class({
Extends: Request,
options: {
update: false,
append: false,
evalScripts: true,
filter: false,
headers: {
Accept: 'text/html, application/xml, text/xml, */*'
}
},
success: function(text){
var options = this.options, response = this.response;
response.html = text.stripScripts(function(script){
response.javascript = script;
});
var match = response.html.match(/<body[^>]*>([\s\S]*?)<\/body>/i);
if (match) response.html = match[1];
var temp = new Element('div').set('html', response.html);
response.tree = temp.childNodes;
response.elements = temp.getElements(options.filter || '*');
if (options.filter) response.tree = response.elements;
if (options.update){
var update = document.id(options.update).empty();
if (options.filter) update.adopt(response.elements);
else update.set('html', response.html);
} else if (options.append){
var append = document.id(options.append);
if (options.filter) response.elements.reverse().inject(append);
else append.adopt(temp.getChildren());
}
if (options.evalScripts) Browser.exec(response.javascript);
this.onSuccess(response.tree, response.elements, response.html, response.javascript);
}
});
Element.Properties.load = {
set: function(options){
var load = this.get('load').cancel();
load.setOptions(options);
return this;
},
get: function(){
var load = this.retrieve('load');
if (!load){
load = new Request.HTML({data: this, link: 'cancel', update: this, method: 'get'});
this.store('load', load);
}
return load;
}
};
Element.implement({
load: function(){
this.get('load').send(Array.link(arguments, {data: Type.isObject, url: Type.isString}));
return this;
}
});
/*
---
name: JSON
description: JSON encoder and decoder.
license: MIT-style license.
SeeAlso: <http://www.json.org/>
requires: [Array, String, Number, Function]
provides: JSON
...
*/
if (typeof JSON == 'undefined') this.JSON = {};
(function(){
var special = {'\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\'};
var escape = function(chr){
return special[chr] || '\\u' + ('0000' + chr.charCodeAt(0).toString(16)).slice(-4);
};
JSON.validate = function(string){
string = string.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, '');
return (/^[\],:{}\s]*$/).test(string);
};
JSON.encode = JSON.stringify ? function(obj){
return JSON.stringify(obj);
} : function(obj){
if (obj && obj.toJSON) obj = obj.toJSON();
switch (typeOf(obj)){
case 'string':
return '"' + obj.replace(/[\x00-\x1f\\"]/g, escape) + '"';
case 'array':
return '[' + obj.map(JSON.encode).clean() + ']';
case 'object': case 'hash':
var string = [];
Object.each(obj, function(value, key){
var json = JSON.encode(value);
if (json) string.push(JSON.encode(key) + ':' + json);
});
return '{' + string + '}';
case 'number': case 'boolean': return '' + obj;
case 'null': return 'null';
}
return null;
};
JSON.decode = function(string, secure){
if (!string || typeOf(string) != 'string') return null;
if (secure || JSON.secure){
if (JSON.parse) return JSON.parse(string);
if (!JSON.validate(string)) throw new Error('JSON could not decode the input; security is enabled and the value is not secure.');
}
return eval('(' + string + ')');
};
})();
/*
---
name: Request.JSON
description: Extends the basic Request Class with additional methods for sending and receiving JSON data.
license: MIT-style license.
requires: [Request, JSON]
provides: Request.JSON
...
*/
Request.JSON = new Class({
Extends: Request,
options: {
/*onError: function(text, error){},*/
secure: true
},
initialize: function(options){
this.parent(options);
Object.append(this.headers, {
'Accept': 'application/json',
'X-Request': 'JSON'
});
},
success: function(text){
var json;
try {
json = this.response.json = JSON.decode(text, this.options.secure);
} catch (error){
this.fireEvent('error', [text, error]);
return;
}
if (json == null) this.onFailure();
else this.onSuccess(json, text);
}
});
/*
---
name: Cookie
description: Class for creating, reading, and deleting browser Cookies.
license: MIT-style license.
credits:
- Based on the functions by Peter-Paul Koch (http://quirksmode.org).
requires: [Options, Browser]
provides: Cookie
...
*/
var Cookie = new Class({
Implements: Options,
options: {
path: '/',
domain: false,
duration: false,
secure: false,
document: document,
encode: true
},
initialize: function(key, options){
this.key = key;
this.setOptions(options);
},
write: function(value){
if (this.options.encode) value = encodeURIComponent(value);
if (this.options.domain) value += '; domain=' + this.options.domain;
if (this.options.path) value += '; path=' + this.options.path;
if (this.options.duration){
var date = new Date();
date.setTime(date.getTime() + this.options.duration * 24 * 60 * 60 * 1000);
value += '; expires=' + date.toGMTString();
}
if (this.options.secure) value += '; secure';
this.options.document.cookie = this.key + '=' + value;
return this;
},
read: function(){
var value = this.options.document.cookie.match('(?:^|;)\\s*' + this.key.escapeRegExp() + '=([^;]*)');
return (value) ? decodeURIComponent(value[1]) : null;
},
dispose: function(){
new Cookie(this.key, Object.merge({}, this.options, {duration: -1})).write('');
return this;
}
});
Cookie.write = function(key, value, options){
return new Cookie(key, options).write(value);
};
Cookie.read = function(key){
return new Cookie(key).read();
};
Cookie.dispose = function(key, options){
return new Cookie(key, options).dispose();
};
/*
---
name: DOMReady
description: Contains the custom event domready.
license: MIT-style license.
requires: [Browser, Element, Element.Event]
provides: [DOMReady, DomReady]
...
*/
(function(window, document){
var ready,
loaded,
checks = [],
shouldPoll,
timer,
testElement = document.createElement('div');
var domready = function(){
clearTimeout(timer);
if (ready) return;
Browser.loaded = ready = true;
document.removeListener('DOMContentLoaded', domready).removeListener('readystatechange', check);
document.fireEvent('domready');
window.fireEvent('domready');
};
var check = function(){
for (var i = checks.length; i--;) if (checks[i]()){
domready();
return true;
}
return false;
};
var poll = function(){
clearTimeout(timer);
if (!check()) timer = setTimeout(poll, 10);
};
document.addListener('DOMContentLoaded', domready);
/*<ltIE8>*/
// doScroll technique by Diego Perini http://javascript.nwbox.com/IEContentLoaded/
// testElement.doScroll() throws when the DOM is not ready, only in the top window
var doScrollWorks = function(){
try {
testElement.doScroll();
return true;
} catch (e){}
return false;
};
// If doScroll works already, it can't be used to determine domready
// e.g. in an iframe
if (testElement.doScroll && !doScrollWorks()){
checks.push(doScrollWorks);
shouldPoll = true;
}
/*</ltIE8>*/
if (document.readyState) checks.push(function(){
var state = document.readyState;
return (state == 'loaded' || state == 'complete');
});
if ('onreadystatechange' in document) document.addListener('readystatechange', check);
else shouldPoll = true;
if (shouldPoll) poll();
Element.Events.domready = {
onAdd: function(fn){
if (ready) fn.call(this);
}
};
// Make sure that domready fires before load
Element.Events.load = {
base: 'load',
onAdd: function(fn){
if (loaded && this == window) fn.call(this);
},
condition: function(){
if (this == window){
domready();
delete Element.Events.load;
}
return true;
}
};
// This is based on the custom load event
window.addEvent('load', function(){
loaded = true;
});
})(window, document);
| lyonbros/composer.js | test/lib/mootools-core-1.4.5.js | JavaScript | mit | 149,108 |
using System;
namespace TestAPI.Areas.HelpPage
{
/// <summary>
/// This represents an invalid sample on the help page. There's a display template named InvalidSample associated with this class.
/// </summary>
public class InvalidSample
{
public InvalidSample(string errorMessage)
{
if (errorMessage == null)
{
throw new ArgumentNullException("errorMessage");
}
ErrorMessage = errorMessage;
}
public string ErrorMessage { get; private set; }
public override bool Equals(object obj)
{
InvalidSample other = obj as InvalidSample;
return other != null && ErrorMessage == other.ErrorMessage;
}
public override int GetHashCode()
{
return ErrorMessage.GetHashCode();
}
public override string ToString()
{
return ErrorMessage;
}
}
} | OasesOng/TestVS | TestAPI/TestAPI/Areas/HelpPage/SampleGeneration/InvalidSample.cs | C# | mit | 969 |
//
//Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions
//are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// Neither the name of 3Dlabs Inc. Ltd. 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 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//POSSIBILITY OF SUCH DAMAGE.
//
#include "osinclude.h"
#define STRICT
#define VC_EXTRALEAN 1
#include <windows.h>
#include <assert.h>
#include <process.h>
#include <psapi.h>
#include <stdio.h>
//
// This file contains contains the Window-OS-specific functions
//
#if !(defined(_WIN32) || defined(_WIN64))
#error Trying to build a windows specific file in a non windows build.
#endif
namespace glslang {
//
// Thread Local Storage Operations
//
OS_TLSIndex OS_AllocTLSIndex()
{
DWORD dwIndex = TlsAlloc();
if (dwIndex == TLS_OUT_OF_INDEXES) {
assert(0 && "OS_AllocTLSIndex(): Unable to allocate Thread Local Storage");
return OS_INVALID_TLS_INDEX;
}
return dwIndex;
}
bool OS_SetTLSValue(OS_TLSIndex nIndex, void *lpvValue)
{
if (nIndex == OS_INVALID_TLS_INDEX) {
assert(0 && "OS_SetTLSValue(): Invalid TLS Index");
return false;
}
if (TlsSetValue(nIndex, lpvValue))
return true;
else
return false;
}
void* OS_GetTLSValue(OS_TLSIndex nIndex)
{
assert(nIndex != OS_INVALID_TLS_INDEX);
return TlsGetValue(nIndex);
}
bool OS_FreeTLSIndex(OS_TLSIndex nIndex)
{
if (nIndex == OS_INVALID_TLS_INDEX) {
assert(0 && "OS_SetTLSValue(): Invalid TLS Index");
return false;
}
if (TlsFree(nIndex))
return true;
else
return false;
}
HANDLE GlobalLock;
void InitGlobalLock()
{
GlobalLock = CreateMutex(0, false, 0);
}
void GetGlobalLock()
{
WaitForSingleObject(GlobalLock, INFINITE);
}
void ReleaseGlobalLock()
{
ReleaseMutex(GlobalLock);
}
void* OS_CreateThread(TThreadEntrypoint entry)
{
return (void*)_beginthreadex(0, 0, entry, 0, 0, 0);
//return CreateThread(0, 0, entry, 0, 0, 0);
}
void OS_WaitForAllThreads(void* threads, int numThreads)
{
WaitForMultipleObjects(numThreads, (HANDLE*)threads, true, INFINITE);
}
void OS_Sleep(int milliseconds)
{
Sleep(milliseconds);
}
void OS_DumpMemoryCounters()
{
#ifdef DUMP_COUNTERS
PROCESS_MEMORY_COUNTERS counters;
GetProcessMemoryInfo(GetCurrentProcess(), &counters, sizeof(counters));
printf("Working set size: %d\n", counters.WorkingSetSize);
#else
printf("Recompile with DUMP_COUNTERS defined to see counters.\n");
#endif
}
} // namespace glslang
| TimNN/glslang-sys | extern/glslang/glslang/OSDependent/Windows/ossource.cpp | C++ | mit | 3,734 |
Template.HostList.events({
});
Template.HostList.helpers({
// Get list of Hosts sorted by the sort field.
hosts: function () {
return Hosts.find({}, {sort: {sort: 1}});
}
});
Template.HostList.rendered = function () {
// Make rows sortable/draggable using Jquery-UI.
this.$('#sortable').sortable({
stop: function (event, ui) {
// Define target row items.
target = ui.item.get(0);
before = ui.item.prev().get(0);
after = ui.item.next().get(0);
// Change the sort value dependnig on target location.
// If target is now first, subtract 1 from sort value.
if (!before) {
newSort = Blaze.getData(after).sort - 1;
// If target is now last, add 1 to sort value.
} else if (!after) {
newSort = Blaze.getData(before).sort + 1;
// Get value of prev and next elements
// to determine new target sort value.
} else {
newSort = (Blaze.getData(after).sort +
Blaze.getData(before).sort) / 2;
}
// Update the database with new sort value.
Hosts.update({_id: Blaze.getData(target)._id}, {
$set: {
sort: newSort
}
});
}
});
};
| bfodeke/syrinx | client/views/hosts/hostList/hostList.js | JavaScript | mit | 1,204 |
import Helper, { states } from './_helper';
import { module, test } from 'qunit';
module('Integration | ORM | Has Many | Named Reflexive | association #set', function(hooks) {
hooks.beforeEach(function() {
this.helper = new Helper();
});
/*
The model can update its association via parent, for all states
*/
states.forEach((state) => {
test(`a ${state} can update its association to a list of saved children`, function(assert) {
let [ tag, originalTags ] = this.helper[state]();
let savedTag = this.helper.savedChild();
tag.labels = [ savedTag ];
assert.ok(tag.labels.includes(savedTag));
assert.equal(tag.labelIds[0], savedTag.id);
assert.ok(savedTag.labels.includes(tag), 'the inverse was set');
tag.save();
originalTags.forEach(originalTag => {
originalTag.reload();
assert.notOk(originalTag.labels.includes(tag), 'old inverses were cleared');
});
});
test(`a ${state} can update its association to a new parent`, function(assert) {
let [ tag, originalTags ] = this.helper[state]();
let newTag = this.helper.newChild();
tag.labels = [ newTag ];
assert.ok(tag.labels.includes(newTag));
assert.equal(tag.labelIds[0], undefined);
assert.ok(newTag.labels.includes(tag), 'the inverse was set');
tag.save();
originalTags.forEach(originalTag => {
originalTag.reload();
assert.notOk(originalTag.labels.includes(tag), 'old inverses were cleared');
});
});
test(`a ${state} can clear its association via an empty list`, function(assert) {
let [ tag, originalTags ] = this.helper[state]();
tag.labels = [ ];
assert.deepEqual(tag.labelIds, [ ]);
assert.equal(tag.labels.models.length, 0);
tag.save();
originalTags.forEach(originalTag => {
originalTag.reload();
assert.notOk(originalTag.labels.includes(tag), 'old inverses were cleared');
});
});
test(`a ${state} can clear its association via an empty list`, function(assert) {
let [ tag, originalTags ] = this.helper[state]();
tag.labels = null;
assert.deepEqual(tag.labelIds, [ ]);
assert.equal(tag.labels.models.length, 0);
tag.save();
originalTags.forEach(originalTag => {
originalTag.reload();
assert.notOk(originalTag.labels.includes(tag), 'old inverses were cleared');
});
});
});
});
| jherdman/ember-cli-mirage | tests/integration/orm/has-many/4-named-reflexive/association-set-test.js | JavaScript | mit | 2,462 |
import * as React from 'react';
export interface LabelDetailProps {
[key: string]: any;
/** An element type to render as (string or function). */
as?: any;
/** Primary content. */
children?: React.ReactNode;
/** Additional classes. */
className?: string;
/** Shorthand for primary content. */
content?: React.ReactNode;
}
declare const LabelDetail: React.StatelessComponent<LabelDetailProps>;
export default LabelDetail;
| aabustamante/Semantic-UI-React | src/elements/Label/LabelDetail.d.ts | TypeScript | mit | 446 |
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Orleans;
using Orleans.Runtime;
using Orleans.Runtime.Scheduler;
using UnitTests.GrainInterfaces;
using UnitTests.Grains;
namespace UnitTestGrains
{
public class TimerGrain : Grain, ITimerGrain
{
private bool deactivating;
int counter = 0;
Dictionary<string, IDisposable> allTimers;
IDisposable defaultTimer;
private static readonly TimeSpan period = TimeSpan.FromMilliseconds(100);
string DefaultTimerName = "DEFAULT TIMER";
ISchedulingContext context;
private Logger logger;
public override Task OnActivateAsync()
{
ThrowIfDeactivating();
logger = this.GetLogger("TimerGrain_" + base.Data.Address.ToString());
context = RuntimeContext.Current.ActivationContext;
defaultTimer = this.RegisterTimer(Tick, DefaultTimerName, period, period);
allTimers = new Dictionary<string, IDisposable>();
return Task.CompletedTask;
}
public Task StopDefaultTimer()
{
ThrowIfDeactivating();
defaultTimer.Dispose();
return Task.CompletedTask;
}
private Task Tick(object data)
{
counter++;
logger.Info(data.ToString() + " Tick # " + counter + " RuntimeContext = " + RuntimeContext.Current.ActivationContext.ToString());
// make sure we run in the right activation context.
if(!Equals(context, RuntimeContext.Current.ActivationContext))
logger.Error((int)ErrorCode.Runtime_Error_100146, "grain not running in the right activation context");
string name = (string)data;
IDisposable timer = null;
if (name == DefaultTimerName)
{
timer = defaultTimer;
}
else
{
timer = allTimers[(string)data];
}
if(timer == null)
logger.Error((int)ErrorCode.Runtime_Error_100146, "Timer is null");
if (timer != null && counter > 10000)
{
// do not let orphan timers ticking for long periods
timer.Dispose();
}
return Task.CompletedTask;
}
public Task<TimeSpan> GetTimerPeriod()
{
return Task.FromResult(period);
}
public Task<int> GetCounter()
{
ThrowIfDeactivating();
return Task.FromResult(counter);
}
public Task SetCounter(int value)
{
ThrowIfDeactivating();
lock (this)
{
counter = value;
}
return Task.CompletedTask;
}
public Task StartTimer(string timerName)
{
ThrowIfDeactivating();
IDisposable timer = this.RegisterTimer(Tick, timerName, TimeSpan.Zero, period);
allTimers.Add(timerName, timer);
return Task.CompletedTask;
}
public Task StopTimer(string timerName)
{
ThrowIfDeactivating();
IDisposable timer = allTimers[timerName];
timer.Dispose();
return Task.CompletedTask;
}
public Task LongWait(TimeSpan time)
{
ThrowIfDeactivating();
Thread.Sleep(time);
return Task.CompletedTask;
}
public Task Deactivate()
{
deactivating = true;
DeactivateOnIdle();
return Task.CompletedTask;
}
private void ThrowIfDeactivating()
{
if (deactivating) throw new InvalidOperationException("This activation is deactivating");
}
}
public class TimerCallGrain : Grain, ITimerCallGrain
{
private int tickCount;
private Exception tickException;
private IDisposable timer;
private string timerName;
private ISchedulingContext context;
private TaskScheduler activationTaskScheduler;
private Logger logger;
public Task<int> GetTickCount() { return Task.FromResult(tickCount); }
public Task<Exception> GetException() { return Task.FromResult(tickException); }
public override Task OnActivateAsync()
{
logger = this.GetLogger("TimerCallGrain_" + base.Data.Address);
context = RuntimeContext.Current.ActivationContext;
activationTaskScheduler = TaskScheduler.Current;
return Task.CompletedTask;
}
public Task StartTimer(string name, TimeSpan delay)
{
logger.Info("StartTimer Name={0} Delay={1}", name, delay);
this.timerName = name;
this.timer = base.RegisterTimer(TimerTick, name, delay, Constants.INFINITE_TIMESPAN); // One shot timer
return Task.CompletedTask;
}
public Task StopTimer(string name)
{
logger.Info("StopTimer Name={0}", name);
if (name != this.timerName)
{
throw new ArgumentException(string.Format("Wrong timer name: Expected={0} Actual={1}", this.timerName, name));
}
timer.Dispose();
return Task.CompletedTask;
}
private async Task TimerTick(object data)
{
try
{
await ProcessTimerTick(data);
}
catch (Exception exc)
{
this.tickException = exc;
throw;
}
}
private async Task ProcessTimerTick(object data)
{
string step = "TimerTick";
LogStatus(step);
// make sure we run in the right activation context.
CheckRuntimeContext(step);
string name = (string)data;
if (name != this.timerName)
{
throw new ArgumentException(string.Format("Wrong timer name: Expected={0} Actual={1}", this.timerName, name));
}
ISimpleGrain grain = GrainFactory.GetGrain<ISimpleGrain>(0, SimpleGrain.SimpleGrainNamePrefix);
LogStatus("Before grain call #1");
await grain.SetA(tickCount);
step = "After grain call #1";
LogStatus(step);
CheckRuntimeContext(step);
LogStatus("Before Delay");
await Task.Delay(TimeSpan.FromSeconds(1));
step = "After Delay";
LogStatus(step);
CheckRuntimeContext(step);
LogStatus("Before grain call #2");
await grain.SetB(tickCount);
step = "After grain call #2";
LogStatus(step);
CheckRuntimeContext(step);
LogStatus("Before grain call #3");
int res = await grain.GetAxB();
step = "After grain call #3 - Result = " + res;
LogStatus(step);
CheckRuntimeContext(step);
tickCount++;
}
private void CheckRuntimeContext(string what)
{
if (RuntimeContext.Current.ActivationContext == null
|| !RuntimeContext.Current.ActivationContext.Equals(context))
{
throw new InvalidOperationException(
string.Format("{0} in timer callback with unexpected activation context: Expected={1} Actual={2}",
what, context, RuntimeContext.Current.ActivationContext));
}
if (TaskScheduler.Current.Equals(activationTaskScheduler) && TaskScheduler.Current is ActivationTaskScheduler)
{
// Everything is as expected
}
else
{
throw new InvalidOperationException(
string.Format("{0} in timer callback with unexpected TaskScheduler.Current context: Expected={1} Actual={2}",
what, activationTaskScheduler, TaskScheduler.Current));
}
}
private void LogStatus(string what)
{
logger.Info("{0} Tick # {1} - {2} - RuntimeContext.Current={3} TaskScheduler.Current={4} CurrentWorkerThread={5}",
timerName, tickCount, what, RuntimeContext.Current, TaskScheduler.Current,
WorkerPoolThread.CurrentWorkerThread);
}
}
}
| jokin/orleans | test/TestInternalGrains/TimerGrain.cs | C# | mit | 8,499 |
#!/usr/bin/env python
import sys
def fix_terminator(tokens):
if not tokens:
return
last = tokens[-1]
if last not in ('.', '?', '!') and last.endswith('.'):
tokens[-1] = last[:-1]
tokens.append('.')
def balance_quotes(tokens):
count = tokens.count("'")
if not count:
return
processed = 0
for i, token in enumerate(tokens):
if token == "'":
if processed % 2 == 0 and (i == 0 or processed != count - 1):
tokens[i] = "`"
processed += 1
def output(tokens):
if not tokens:
return
# fix_terminator(tokens)
balance_quotes(tokens)
print ' '.join(tokens)
prev = None
for line in sys.stdin:
tokens = line.split()
if len(tokens) == 1 and tokens[0] in ('"', "'", ')', ']'):
prev.append(tokens[0])
else:
output(prev)
prev = tokens
output(prev)
| TeamSPoon/logicmoo_workspace | packs_sys/logicmoo_nlu/ext/candc/src/lib/tokeniser/fixes.py | Python | mit | 820 |
<?php
namespace YOOtheme\Widgetkit\Framework\View\Asset;
interface AssetInterface
{
/**
* Gets the name.
*
* @return string
*/
public function getName();
/**
* Gets the source.
*
* @return string
*/
public function getSource();
/**
* Gets the dependencies.
*
* @return array
*/
public function getDependencies();
/**
* Gets the content.
*
* @return string
*/
public function getContent();
/**
* Sets the content.
*
* @param string $content
*/
public function setContent($content);
/**
* Gets all options.
*
* @return array
*/
public function getOptions();
/**
* Gets a option.
*
* @param string $name
* @return mixed
*/
public function getOption($name);
/**
* Sets a option.
*
* @param string $name
* @param mixed $value
*/
public function setOption($name, $value);
/**
* Gets the unique hash.
*
* @param string $salt
* @return string
*/
public function hash($salt = '');
/**
* Applies filters and returns the asset as a string.
*
* @param array $filters
* @return string
*/
public function dump(array $filters = array());
}
| yaelduckwen/libriastore | joomla/administrator/components/com_widgetkit/src/Framework/src/View/Asset/AssetInterface.php | PHP | mit | 1,339 |
class Item < ActiveRecord::Base
serialize :raw_info , Hash
has_many :ownerships , foreign_key: "item_id" , dependent: :destroy
has_many :users , through: :ownerships
has_many :wants, class_name: "Want", foreign_key: "item_id", dependent: :destroy
has_many :want_users, through: :wants, source: :user
has_many :haves, class_name: "Have", foreign_key: "item_id", dependent: :destroy
has_many :have_users, through: :haves, source: :user
end
| nekocreate/monolist | app/models/item.rb | Ruby | mit | 460 |
/* describe, it, afterEach, beforeEach */
import './snoocore-mocha';
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
chai.use(chaiAsPromised);
let expect = chai.expect;
import config from '../config';
import util from './util';
import ResponseError from '../../src/ResponseError';
import Endpoint from '../../src/Endpoint';
describe(__filename, function () {
this.timeout(config.testTimeout);
it('should get a proper response error', function() {
var message = 'oh hello there';
var response = { _status: 200, _body: 'a response body' };
var userConfig = util.getScriptUserConfig();
var endpoint = new Endpoint(userConfig,
userConfig.serverOAuth,
'get',
'/some/path',
{}, // headers
{ some: 'args' });
var responseError = new ResponseError(message,
response,
endpoint);
expect(responseError instanceof ResponseError);
expect(responseError.status).to.eql(200);
expect(responseError.url).to.eql('https://oauth.reddit.com/some/path');
expect(responseError.args).to.eql({ some: 'args', api_type: 'json' });
expect(responseError.message.indexOf('oh hello there')).to.not.eql(-1);
expect(responseError.message.indexOf('Response Status')).to.not.eql(-1);
expect(responseError.message.indexOf('Endpoint URL')).to.not.eql(-1);
expect(responseError.message.indexOf('Arguments')).to.not.eql(-1);
expect(responseError.message.indexOf('Response Body')).to.not.eql(-1);
});
});
| empyrical/snoocore | test/src/ResponseError-test.js | JavaScript | mit | 1,705 |
using System;
using System.Collections.Generic;
using Csla;
namespace Templates
{
[Serializable]
public class DynamicRootBindingList :
DynamicBindingListBase<DynamicRoot>
{
protected override object AddNewCore()
{
DynamicRoot item = DataPortal.Create<DynamicRoot>();
Add(item);
return item;
}
private static void AddObjectAuthorizationRules()
{
// TODO: add authorization rules
//AuthorizationRules.AllowGet(typeof(DynamicRootBindingList), "Role");
//AuthorizationRules.AllowEdit(typeof(DynamicRootBindingList), "Role");
}
[Fetch]
private void Fetch()
{
// TODO: load values
RaiseListChangedEvents = false;
object listData = null;
foreach (var item in (List<object>)listData)
Add(DataPortal.Fetch<DynamicRoot>(item));
RaiseListChangedEvents = true;
}
}
} | MarimerLLC/csla | Support/Templates/cs/Files/DynamicRootBindingList.cs | C# | mit | 883 |
<?php
/**
* Created by PhpStorm.
* User: faustos
* Date: 05.06.14
* Time: 13:58
*/
namespace Tixi\App\AppBundle\Interfaces;
class DrivingOrderHandleDTO {
public $id;
public $anchorDate;
public $lookaheadaddressFrom;
public $lookaheadaddressTo;
public $zoneStatus;
public $zoneId;
public $zoneName;
public $orderTime;
public $isRepeated;
public $compagnion;
public $memo;
//repeated part
public $endDate;
public $mondayOrderTime;
public $tuesdayOrderTime;
public $wednesdayOrderTime;
public $thursdayOrderTime;
public $fridayOrderTime;
public $saturdayOrderTime;
public $sundayOrderTime;
} | Martin-Jonasse/sfitixi | src/Tixi/App/AppBundle/Interfaces/DrivingOrderHandleDTO.php | PHP | mit | 679 |
package org.jsondoc.core.issues.issue151;
import org.jsondoc.core.annotation.Api;
import org.jsondoc.core.annotation.ApiMethod;
import org.jsondoc.core.annotation.ApiResponseObject;
@Api(name = "Foo Services", description = "bla, bla, bla ...", group = "foogroup")
public class FooController {
@ApiMethod(path = { "/api/foo" }, description = "Main foo service")
@ApiResponseObject
public FooWrapper<BarPojo> getBar() {
return null;
}
@ApiMethod(path = { "/api/foo-wildcard" }, description = "Main foo service with wildcard")
@ApiResponseObject
public FooWrapper<?> wildcard() {
return null;
}
} | sarhanm/jsondoc | jsondoc-core/src/test/java/org/jsondoc/core/issues/issue151/FooController.java | Java | mit | 612 |
namespace Porter2Stemmer
{
public interface IStemmer
{
/// <summary>
/// Stem a word.
/// </summary>
/// <param name="word">Word to stem.</param>
/// <returns>
/// The stemmed word, with a reference to the original unstemmed word.
/// </returns>
StemmedWord Stem(string word);
}
}
| SDCAAU/P7_Helpdesk | sw704e17.Database/sw704e17.Database/Stemmer/IStemmer.cs | C# | mit | 361 |
function someFunctionWithAVeryLongName(firstParameter='something',
secondParameter='booooo',
third=null, fourthParameter=false,
fifthParameter=123.12,
sixthParam=true
){
}
function someFunctionWithAVeryLongName2(
firstParameter='something',
secondParameter='booooo',
) {
}
function blah() {
}
function blah()
{
}
var object =
{
someFunctionWithAVeryLongName: function(
firstParameter='something',
secondParameter='booooo',
third=null,
fourthParameter=false,
fifthParameter=123.12,
sixthParam=true
) /** w00t */ {
}
someFunctionWithAVeryLongName2: function (firstParameter='something',
secondParameter='booooo',
third=null
) {
}
someFunctionWithAVeryLongName3: function (
firstParameter, secondParameter, third=null
) {
}
someFunctionWithAVeryLongName4: function (
firstParameter, secondParameter
) {
}
someFunctionWithAVeryLongName5: function (
firstParameter,
secondParameter=array(1,2,3),
third=null
) {
}
}
var a = Function('return 1+1');
| oknoorap/wpcs | scripts/phpcs/CodeSniffer/Standards/Squiz/Tests/Functions/MultiLineFunctionDeclarationUnitTest.js | JavaScript | mit | 1,148 |
#!/usr/bin/env node
require("babel/register")({
"stage": 1
});
var fs = require("fs");
GLOBAL.WALLACEVERSION = "Err";
GLOBAL.PLUGIN_CONTRIBUTORS = [];
try {
var p = JSON.parse(fs.readFileSync(__dirname+"/package.json"));
GLOBAL.WALLACEVERSION = p.version;
}
catch(e) {}
var Core = require("./core/Core.js");
process.on('uncaughtException', function (err) {
console.error(err);
});
GLOBAL.core = new Core();
| Reanmachine/Wallace | main.js | JavaScript | mit | 432 |
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::group([ 'middleware' => 'guest' ], function () {
Route::get('login', 'Auth\AuthController@getLogin');
Route::post('login', 'Auth\AuthController@postLogin');
// Password reset link request routes...
Route::get('password/email', 'Auth\PasswordController@getEmail');
Route::post('password/email', 'Auth\PasswordController@postEmail');
// Password reset routes...
Route::get('password/reset/{token}', 'Auth\PasswordController@getReset');
Route::post('password/reset', 'Auth\PasswordController@postReset');
});
Route::group([ 'middleware' => 'auth' ], function () {
Route::get('/', [
'as' => 'home',
'uses' => 'ProjectController@index'
]);
Route::get('/project/create', [
'as' => 'project.create',
'uses' => 'ProjectController@create'
]);
Route::post('/project/create', [
'as' => 'project.store',
'uses' => 'ProjectController@store'
]);
Route::post('/project/search', [
'as' => 'project.search',
'uses' => 'ProjectController@search'
]);
Route::get('/project/{project}/graph', [
'as' => 'detail.graph',
'uses' => 'ProjectDetailController@graph'
]);
Route::get('/project/{project}/overview', [
'as' => 'detail.overview',
'uses' => 'ProjectDetailController@overview'
]);
Route::get('/project/{project}/activity', [
'as' => 'detail.activity',
'uses' => 'ProjectDetailController@activity'
]);
Route::get('/project/{project}/inspection-{issue}/{category}', [
'as' => 'detail.issue',
'uses' => 'ProjectDetailController@issue'
]);
Route::post('/project/{project}/inspection-{issue}/', [
'as' => 'detail.issue.category',
'uses' => 'ProjectDetailController@issueByCategory'
]);
Route::delete('/project/{project}', [
'as' => 'project.destroy',
'uses' => 'ProjectController@destroy'
]);
Route::get('/project/{project}/inspect', [
'as' => 'inspection.create',
'uses' => 'ProjectDetailController@create'
]);
Route::post('/project/{project}/inspect', [
'as' => 'inspection.store',
'uses' => 'ProjectDetailController@store'
]);
Route::get('logout', 'Auth\AuthController@getLogout');
Route::group([ 'middleware' => 'role' ], function () {
Route::resource('user', 'UserController');
});
});
| suitmedia/suitcoda | app/Http/routes.php | PHP | mit | 2,811 |
// Copyright (c) 2015 Uber Technologies, Inc.
//
// 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.
'use strict';
var EventEmitter = require('./lib/event_emitter');
var stat = require('./lib/stat');
var inherits = require('util').inherits;
var errors = require('./errors');
var States = require('./reqres_states');
function TChannelOutResponse(id, options) {
options = options || {};
var self = this;
EventEmitter.call(self);
self.errorEvent = self.defineEvent('error');
self.spanEvent = self.defineEvent('span');
self.finishEvent = self.defineEvent('finish');
self.channel = options.channel;
self.inreq = options.inreq;
self.logger = options.logger;
self.random = options.random;
self.timers = options.timers;
self.start = 0;
self.end = 0;
self.state = States.Initial;
self.id = id || 0;
self.code = options.code || 0;
self.tracing = options.tracing || null;
self.headers = options.headers || {};
self.checksumType = options.checksumType || 0;
self.checksum = options.checksum || null;
self.ok = self.code === 0;
self.span = options.span || null;
self.streamed = false;
self._argstream = null;
self.arg1 = null;
self.arg2 = null;
self.arg3 = null;
self.codeString = null;
self.message = null;
}
inherits(TChannelOutResponse, EventEmitter);
TChannelOutResponse.prototype.type = 'tchannel.outgoing-response';
TChannelOutResponse.prototype._sendCallResponse = function _sendCallResponse(args, isLast) {
var self = this;
throw errors.UnimplementedMethod({
className: self.constructor.name,
methodName: '_sendCallResponse'
});
};
TChannelOutResponse.prototype._sendCallResponseCont = function _sendCallResponseCont(args, isLast) {
var self = this;
throw errors.UnimplementedMethod({
className: self.constructor.name,
methodName: '_sendCallResponseCont'
});
};
TChannelOutResponse.prototype._sendError = function _sendError(codeString, message) {
var self = this;
throw errors.UnimplementedMethod({
className: self.constructor.name,
methodName: '_sendError'
});
};
TChannelOutResponse.prototype.sendParts = function sendParts(parts, isLast) {
var self = this;
switch (self.state) {
case States.Initial:
self.sendCallResponseFrame(parts, isLast);
break;
case States.Streaming:
self.sendCallResponseContFrame(parts, isLast);
break;
case States.Done:
self.errorEvent.emit(self, errors.ResponseFrameState({
attempted: 'arg parts',
state: 'Done'
}));
break;
case States.Error:
// TODO: log warn
break;
default:
self.channel.logger.error('TChannelOutResponse is in a wrong state', {
state: self.state
});
break;
}
};
TChannelOutResponse.prototype.sendCallResponseFrame = function sendCallResponseFrame(args, isLast) {
var self = this;
switch (self.state) {
case States.Initial:
self.start = self.timers.now();
self._sendCallResponse(args, isLast);
if (self.span) {
self.span.annotate('ss');
}
if (isLast) self.state = States.Done;
else self.state = States.Streaming;
break;
case States.Streaming:
self.errorEvent.emit(self, errors.ResponseFrameState({
attempted: 'call response',
state: 'Streaming'
}));
break;
case States.Done:
case States.Error:
var arg2 = args[1] || '';
var arg3 = args[2] || '';
self.errorEvent.emit(self, errors.ResponseAlreadyDone({
attempted: 'call response',
state: self.state,
method: 'sendCallResponseFrame',
bufArg2: arg2.slice(0, 50),
arg2: String(arg2).slice(0, 50),
bufArg3: arg3.slice(0, 50),
arg3: String(arg3).slice(0, 50)
}));
}
};
TChannelOutResponse.prototype.sendCallResponseContFrame = function sendCallResponseContFrame(args, isLast) {
var self = this;
switch (self.state) {
case States.Initial:
self.errorEvent.emit(self, errors.ResponseFrameState({
attempted: 'call response continuation',
state: 'Initial'
}));
break;
case States.Streaming:
self._sendCallResponseCont(args, isLast);
if (isLast) self.state = States.Done;
break;
case States.Done:
case States.Error:
self.errorEvent.emit(self, errors.ResponseAlreadyDone({
attempted: 'call response continuation',
state: self.state,
method: 'sendCallResponseContFrame'
}));
}
};
TChannelOutResponse.prototype.sendError = function sendError(codeString, message) {
var self = this;
if (self.state === States.Done || self.state === States.Error) {
self.errorEvent.emit(self, errors.ResponseAlreadyDone({
attempted: 'send error frame: ' + codeString + ': ' + message,
currentState: self.state,
method: 'sendError',
codeString: codeString,
errMessage: message
}));
} else {
if (self.span) {
self.span.annotate('ss');
}
self.state = States.Error;
self.codeString = codeString;
self.message = message;
self.channel.inboundCallsSystemErrorsStat.increment(1, {
'calling-service': self.inreq.headers.cn,
'service': self.inreq.serviceName,
'endpoint': String(self.inreq.arg1),
'type': self.codeString
});
self._sendError(codeString, message);
self.emitFinish();
}
};
TChannelOutResponse.prototype.emitFinish = function emitFinish() {
var self = this;
var now = self.timers.now();
if (self.end) {
self.logger.warn('out response double emitFinish', {
end: self.end,
now: now,
serviceName: self.inreq.serviceName,
cn: self.inreq.headers.cn,
endpoint: String(self.inreq.arg1),
codeString: self.codeString,
errorMessage: self.message,
remoteAddr: self.inreq.connection.socketRemoteAddr,
state: self.state,
isOk: self.ok
});
return;
}
self.end = now;
var latency = self.end - self.inreq.start;
self.channel.emitFastStat(self.channel.buildStat(
'tchannel.inbound.calls.latency',
'timing',
latency,
new stat.InboundCallsLatencyTags(
self.inreq.headers.cn,
self.inreq.serviceName,
self.inreq.endpoint
)
));
if (self.span) {
self.spanEvent.emit(self, self.span);
}
self.finishEvent.emit(self);
};
TChannelOutResponse.prototype.setOk = function setOk(ok) {
var self = this;
if (self.state !== States.Initial) {
self.errorEvent.emit(self, errors.ResponseAlreadyStarted({
state: self.state,
method: 'setOk',
ok: ok
}));
return false;
}
self.ok = ok;
self.code = ok ? 0 : 1; // TODO: too coupled to v2 specifics?
return true;
};
TChannelOutResponse.prototype.sendOk = function sendOk(res1, res2) {
var self = this;
self.setOk(true);
self.send(res1, res2);
};
TChannelOutResponse.prototype.sendNotOk = function sendNotOk(res1, res2) {
var self = this;
if (self.state === States.Error) {
self.logger.error('cannot send application error, already sent error frame', {
res1: res1,
res2: res2
});
} else {
self.setOk(false);
self.send(res1, res2);
}
};
TChannelOutResponse.prototype.send = function send(res1, res2) {
var self = this;
/* send calls after finish() should be swallowed */
if (self.end) {
var logOptions = {
serviceName: self.inreq.serviceName,
cn: self.inreq.headers.cn,
endpoint: self.inreq.endpoint,
remoteAddr: self.inreq.remoteAddr,
end: self.end,
codeString: self.codeString,
errorMessage: self.message,
isOk: self.ok,
hasResponse: !!self.arg3,
state: self.state
};
if (self.inreq && self.inreq.timedOut) {
self.logger.info('OutResponse.send() after inreq timed out', logOptions);
} else {
self.logger.warn('OutResponse called send() after end', logOptions);
}
return;
}
self.arg2 = res1;
self.arg3 = res2;
if (self.ok) {
self.channel.emitFastStat(self.channel.buildStat(
'tchannel.inbound.calls.success',
'counter',
1,
new stat.InboundCallsSuccessTags(
self.inreq.headers.cn,
self.inreq.serviceName,
self.inreq.endpoint
)
));
} else {
// TODO: add outResponse.setErrorType()
self.channel.emitFastStat(self.channel.buildStat(
'tchannel.inbound.calls.app-errors',
'counter',
1,
new stat.InboundCallsAppErrorsTags(
self.inreq.headers.cn,
self.inreq.serviceName,
self.inreq.endpoint,
'unknown'
)
));
}
self.sendCallResponseFrame([self.arg1, res1, res2], true);
self.emitFinish();
return self;
};
module.exports = TChannelOutResponse;
| davewhat/tchannel | out_response.js | JavaScript | mit | 10,872 |
<div class="alert alert-{{$type}}">
<h1>{{$title}}</h1>
<p>{{$content}}</p>
</div>
| chromabits/illuminated | resources/views/alerts/alert.blade.php | PHP | mit | 92 |
using RedditSharp.Things;
using System.Threading.Tasks;
namespace RedditSharp
{
partial class Helpers
{
private const string GetThingUrl = "/api/info.json?id={0}";
/// <summary>
/// Get a <see cref="Thing"/> by full name.
/// </summary>
/// <param name="agent">IWebAgent to use to make request</param>
/// <param name="fullname">fullname including kind + underscore. EG ("t1_######")</param>
/// <returns></returns>
public static async Task<Thing> GetThingByFullnameAsync(IWebAgent agent, string fullname)
{
var json = await agent.Get(string.Format(GetThingUrl, fullname)).ConfigureAwait(false);
return Thing.Parse(agent, json["data"]["children"][0]);
}
}
}
| justcool393/RedditSharp-1 | RedditSharp/Helpers/Helpers.GetThingByFullnameAsync.cs | C# | mit | 779 |
#!/usr/bin/env node
/**
* Release this package.
*/
"use strict";
process.chdir(__dirname + '/..');
const apeTasking = require('ape-tasking'),
apeReleasing = require('ape-releasing');
apeTasking.runTasks('release', [
(callback) => {
apeReleasing.releasePackage({
beforeRelease: [
'./ci/build.js',
'./ci/test.js'
]
}, callback);
}
], true);
| ape-repo/ape-scraping | ci/release.js | JavaScript | mit | 430 |
/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package app
import (
"fmt"
"os"
"k8s.io/kubernetes/federation/pkg/kubefed"
_ "k8s.io/kubernetes/pkg/client/metrics/prometheus" // for client metric registration
cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
"k8s.io/kubernetes/pkg/util/logs"
"k8s.io/kubernetes/pkg/version"
_ "k8s.io/kubernetes/pkg/version/prometheus" // for version metric registration
)
const hyperkubeImageName = "gcr.io/google_containers/hyperkube-amd64"
func Run() error {
logs.InitLogs()
defer logs.FlushLogs()
defaultImage := fmt.Sprintf("%s:%s", hyperkubeImageName, version.Get())
cmd := kubefed.NewKubeFedCommand(cmdutil.NewFactory(nil), os.Stdin, os.Stdout, os.Stderr, defaultImage)
return cmd.Execute()
}
| pragkent/aliyun-disk | vendor/k8s.io/kubernetes/federation/cmd/kubefed/app/kubefed.go | GO | mit | 1,274 |
import os, scrapy, argparse
from realclearpolitics.spiders.spider import RcpSpider
from scrapy.crawler import CrawlerProcess
parser = argparse.ArgumentParser('Scrap realclearpolitics polls data')
parser.add_argument('url', action="store")
parser.add_argument('--locale', action="store", default='')
parser.add_argument('--race', action="store", default='primary')
parser.add_argument('--csv', dest='to_csv', action='store_true')
parser.add_argument('--output', dest='output', action='store')
args = parser.parse_args()
url = args.url
extra_fields = { 'locale': args.locale, 'race': args.race }
if (args.to_csv):
if args.output is None:
filename = url.split('/')[-1].split('.')[0]
output = filename + ".csv"
print("No output file specified : using " + output)
else:
output = args.output
if not output.endswith(".csv"):
output = output + ".csv"
if os.path.isfile(output):
os.remove(output)
os.system("scrapy crawl realclearpoliticsSpider -a url="+url+" -o "+output)
else:
settings = {
'ITEM_PIPELINES' : {
'realclearpolitics.pipeline.PollPipeline': 300,
},
'LOG_LEVEL' : 'ERROR',
'DOWNLOAD_HANDLERS' : {'s3': None,}
}
process = CrawlerProcess(settings);
process.crawl(RcpSpider, url, extra_fields)
process.start()
| dpxxdp/berniemetrics | private/scrapers/realclearpolitics-scraper/scraper.py | Python | mit | 1,355 |
/*global d3 */
// asynchronously load data from the Lagotto API
queue()
.defer(d3.json, encodeURI("/api/agents/"))
.await(function(error, a) {
if (error) { return console.warn(error); }
agentsViz(a.agents);
});
// add data to page
function agentsViz(data) {
for (var i=0; i<data.length; i++) {
var agent = data[i];
// responses tab
d3.select("#response_count_" + agent.id)
.text(numberWithDelimiter(agent.responses.count));
d3.select("#average_count_" + agent.id)
.text(numberWithDelimiter(agent.responses.average));
}
}
| CrossRef/lagotto | app/assets/javascripts/agents/index.js | JavaScript | mit | 569 |
describe 'font' do
before do
@rmq = RubyMotionQuery::RMQ
end
it 'should return font from RMQ or an instance of rmq' do
@rmq.font.should == RubyMotionQuery::Font
rmq = RubyMotionQuery::RMQ.new
rmq.font.should == RubyMotionQuery::Font
end
it 'should return a list of font families' do
@rmq.font.family_list.grep(/Helvetica/).length.should > 0
end
it 'should return a list of fonts for one family' do
@rmq.font.for_family('Arial').grep(/Arial/).length.should > 0
end
it 'should return a system font given a size' do
@rmq.font.system(11).is_a?(UIFont).should == true
end
it 'should return a system font with system default font size' do
@rmq.font.system.pointSize.should == UIFont.systemFontSize
end
it 'should return font with name' do
@rmq.font.with_name('American Typewriter', 11).is_a?(UIFont).should == true
end
it "should return fonts that have been named" do
@rmq.font.add_named('awesome_font', 'American Typewriter', 12)
@rmq.font.awesome_font.is_a?(UIFont).should.be.true
end
end
| infinitered/rmq | spec/font.rb | Ruby | mit | 1,069 |
/*================================================================================
code generated by: java2cpp
author: Zoran Angelov, mailto://baldzar@gmail.com
class: java.io.WriteAbortedException
================================================================================*/
#ifndef J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_JAVA_IO_WRITEABORTEDEXCEPTION_HPP_DECL
#define J2CPP_JAVA_IO_WRITEABORTEDEXCEPTION_HPP_DECL
namespace j2cpp { namespace java { namespace lang { class Exception; } } }
namespace j2cpp { namespace java { namespace lang { class String; } } }
namespace j2cpp { namespace java { namespace lang { class Throwable; } } }
namespace j2cpp { namespace java { namespace lang { class Object; } } }
namespace j2cpp { namespace java { namespace io { class IOException; } } }
namespace j2cpp { namespace java { namespace io { class Serializable; } } }
namespace j2cpp { namespace java { namespace io { class ObjectStreamException; } } }
#include <java/io/IOException.hpp>
#include <java/io/ObjectStreamException.hpp>
#include <java/io/Serializable.hpp>
#include <java/lang/Exception.hpp>
#include <java/lang/Object.hpp>
#include <java/lang/String.hpp>
#include <java/lang/Throwable.hpp>
namespace j2cpp {
namespace java { namespace io {
class WriteAbortedException;
class WriteAbortedException
: public object<WriteAbortedException>
{
public:
J2CPP_DECLARE_CLASS
J2CPP_DECLARE_METHOD(0)
J2CPP_DECLARE_METHOD(1)
J2CPP_DECLARE_METHOD(2)
J2CPP_DECLARE_FIELD(0)
explicit WriteAbortedException(jobject jobj)
: object<WriteAbortedException>(jobj)
, detail(jobj)
{
}
operator local_ref<java::lang::Exception>() const;
operator local_ref<java::lang::Throwable>() const;
operator local_ref<java::lang::Object>() const;
operator local_ref<java::io::IOException>() const;
operator local_ref<java::io::Serializable>() const;
operator local_ref<java::io::ObjectStreamException>() const;
WriteAbortedException(local_ref< java::lang::String > const&, local_ref< java::lang::Exception > const&);
local_ref< java::lang::String > getMessage();
local_ref< java::lang::Throwable > getCause();
field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(0), J2CPP_FIELD_SIGNATURE(0), local_ref< java::lang::Exception > > detail;
}; //class WriteAbortedException
} //namespace io
} //namespace java
} //namespace j2cpp
#endif //J2CPP_JAVA_IO_WRITEABORTEDEXCEPTION_HPP_DECL
#else //J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_JAVA_IO_WRITEABORTEDEXCEPTION_HPP_IMPL
#define J2CPP_JAVA_IO_WRITEABORTEDEXCEPTION_HPP_IMPL
namespace j2cpp {
java::io::WriteAbortedException::operator local_ref<java::lang::Exception>() const
{
return local_ref<java::lang::Exception>(get_jobject());
}
java::io::WriteAbortedException::operator local_ref<java::lang::Throwable>() const
{
return local_ref<java::lang::Throwable>(get_jobject());
}
java::io::WriteAbortedException::operator local_ref<java::lang::Object>() const
{
return local_ref<java::lang::Object>(get_jobject());
}
java::io::WriteAbortedException::operator local_ref<java::io::IOException>() const
{
return local_ref<java::io::IOException>(get_jobject());
}
java::io::WriteAbortedException::operator local_ref<java::io::Serializable>() const
{
return local_ref<java::io::Serializable>(get_jobject());
}
java::io::WriteAbortedException::operator local_ref<java::io::ObjectStreamException>() const
{
return local_ref<java::io::ObjectStreamException>(get_jobject());
}
java::io::WriteAbortedException::WriteAbortedException(local_ref< java::lang::String > const &a0, local_ref< java::lang::Exception > const &a1)
: object<java::io::WriteAbortedException>(
call_new_object<
java::io::WriteAbortedException::J2CPP_CLASS_NAME,
java::io::WriteAbortedException::J2CPP_METHOD_NAME(0),
java::io::WriteAbortedException::J2CPP_METHOD_SIGNATURE(0)
>(a0, a1)
)
, detail(get_jobject())
{
}
local_ref< java::lang::String > java::io::WriteAbortedException::getMessage()
{
return call_method<
java::io::WriteAbortedException::J2CPP_CLASS_NAME,
java::io::WriteAbortedException::J2CPP_METHOD_NAME(1),
java::io::WriteAbortedException::J2CPP_METHOD_SIGNATURE(1),
local_ref< java::lang::String >
>(get_jobject());
}
local_ref< java::lang::Throwable > java::io::WriteAbortedException::getCause()
{
return call_method<
java::io::WriteAbortedException::J2CPP_CLASS_NAME,
java::io::WriteAbortedException::J2CPP_METHOD_NAME(2),
java::io::WriteAbortedException::J2CPP_METHOD_SIGNATURE(2),
local_ref< java::lang::Throwable >
>(get_jobject());
}
J2CPP_DEFINE_CLASS(java::io::WriteAbortedException,"java/io/WriteAbortedException")
J2CPP_DEFINE_METHOD(java::io::WriteAbortedException,0,"<init>","(Ljava/lang/String;Ljava/lang/Exception;)V")
J2CPP_DEFINE_METHOD(java::io::WriteAbortedException,1,"getMessage","()Ljava/lang/String;")
J2CPP_DEFINE_METHOD(java::io::WriteAbortedException,2,"getCause","()Ljava/lang/Throwable;")
J2CPP_DEFINE_FIELD(java::io::WriteAbortedException,0,"detail","Ljava/lang/Exception;")
} //namespace j2cpp
#endif //J2CPP_JAVA_IO_WRITEABORTEDEXCEPTION_HPP_IMPL
#endif //J2CPP_INCLUDE_IMPLEMENTATION
| hyEvans/ph-open | proj.android/jni/puzzleHero/platforms/android-9/java/io/WriteAbortedException.hpp | C++ | mit | 5,303 |
package com.tale.model;
import com.blade.jdbc.annotation.Table;
import java.io.Serializable;
//
@Table(name = "t_comments", pk = "coid")
public class Comments implements Serializable {
private static final long serialVersionUID = 1L;
// comment表主键
private Integer coid;
// post表主键,关联字段
private Integer cid;
// 评论生成时的GMT unix时间戳
private Integer created;
// 评论作者
private String author;
// 评论所属用户id
private Integer author_id;
// 评论所属内容作者id
private Integer owner_id;
// 评论者邮件
private String mail;
// 评论者网址
private String url;
// 评论者ip地址
private String ip;
// 评论者客户端
private String agent;
// 评论内容
private String content;
// 评论类型
private String type;
// 评论状态
private String status;
// 父级评论
private Integer parent;
public Comments() {
}
public Integer getCoid() {
return coid;
}
public void setCoid(Integer coid) {
this.coid = coid;
}
public Integer getCid() {
return cid;
}
public void setCid(Integer cid) {
this.cid = cid;
}
public Integer getCreated() {
return created;
}
public void setCreated(Integer created) {
this.created = created;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getAgent() {
return agent;
}
public void setAgent(String agent) {
this.agent = agent;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Integer getParent() {
return parent;
}
public void setParent(Integer parent) {
this.parent = parent;
}
public Integer getAuthor_id() {
return author_id;
}
public void setAuthor_id(Integer author_id) {
this.author_id = author_id;
}
public Integer getOwner_id() {
return owner_id;
}
public void setOwner_id(Integer owner_id) {
this.owner_id = owner_id;
}
} | sanmubird/yuanjihua_blog | src/main/java/com/tale/model/Comments.java | Java | mit | 2,962 |
"use strict";
const lua = require("../src/lua.js");
const lauxlib = require("../src/lauxlib.js");
const {to_luastring} = require("../src/fengaricore.js");
const toByteCode = function(luaCode) {
let L = lauxlib.luaL_newstate();
if (!L) throw Error("failed to create lua state");
if (lauxlib.luaL_loadstring(L, to_luastring(luaCode)) !== lua.LUA_OK)
throw Error(lua.lua_tojsstring(L, -1));
let b = [];
if (lua.lua_dump(L, function(L, b, size, B) {
B.push(...b.slice(0, size));
return 0;
}, b, false) !== 0)
throw Error("unable to dump given function");
return Uint8Array.from(b);
};
module.exports.toByteCode = toByteCode;
| daurnimator/fengari | test/tests.js | JavaScript | mit | 690 |
require 'active_support/inflector'
module Trello
class BasicData
include ActiveModel::Validations
include ActiveModel::Dirty
include ActiveModel::Serializers::JSON
include Trello::JsonUtils
class << self
def path_name
name.split("::").last.underscore
end
def find(id, params = {})
client.find(path_name, id, params)
end
def create(options)
client.create(path_name, options)
end
def save(options)
new(options).tap do |basic_data|
yield basic_data if block_given?
end.save
end
def parse(response)
from_response(response).tap do |basic_data|
yield basic_data if block_given?
end
end
def parse_many(response)
from_response(response).map do |data|
data.tap do |d|
yield d if block_given?
end
end
end
end
def self.register_attributes(*names)
options = { readonly: [] }
options.merge!(names.pop) if names.last.kind_of? Hash
# Defines the attribute getter and setters.
class_eval do
define_method :attributes do
@attributes ||= names.reduce({}) { |hash, k| hash.merge(k.to_sym => nil) }
end
names.each do |key|
define_method(:"#{key}") { @attributes[key] }
unless options[:readonly].include?(key.to_sym)
define_method :"#{key}=" do |val|
send(:"#{key}_will_change!") unless val == @attributes[key]
@attributes[key] = val
end
end
end
define_attribute_methods names
end
end
def self.one(name, opts = {})
class_eval do
define_method(:"#{name}") do |*args|
options = opts.dup
klass = options.delete(:via) || Trello.const_get(name.to_s.camelize)
ident = options.delete(:using) || :id
path = options.delete(:path)
if path
client.find(path, self.send(ident))
else
klass.find(self.send(ident))
end
end
end
end
def self.many(name, opts = {})
class_eval do
define_method(:"#{name}") do |*args|
options = opts.dup
resource = options.delete(:in) || self.class.to_s.split("::").last.downcase.pluralize
klass = options.delete(:via) || Trello.const_get(name.to_s.singularize.camelize)
params = options.merge(args[0] || {})
resources = client.find_many(klass, "/#{resource}/#{id}/#{name}", params)
MultiAssociation.new(self, resources).proxy
end
end
end
def self.client
Trello.client
end
register_attributes :id, readonly: [ :id ]
attr_writer :client
def initialize(fields = {})
update_fields(fields)
end
def update_fields(fields)
raise NotImplementedError, "#{self.class} does not implement update_fields."
end
# Refresh the contents of our object.
def refresh!
self.class.find(id)
end
# Two objects are equal if their _id_ methods are equal.
def ==(other)
id == other.id
end
def client
@client ||= self.class.client
end
end
end
| brycemcd/ruby-trello | lib/trello/basic_data.rb | Ruby | mit | 3,268 |
from panda3d.core import NodePath, DecalEffect
import DNANode
import DNAWall
import random
class DNAFlatBuilding(DNANode.DNANode):
COMPONENT_CODE = 9
currentWallHeight = 0
def __init__(self, name):
DNANode.DNANode.__init__(self, name)
self.width = 0
self.hasDoor = False
def setWidth(self, width):
self.width = width
def getWidth(self):
return self.width
def setCurrentWallHeight(self, currentWallHeight):
DNAFlatBuilding.currentWallHeight = currentWallHeight
def getCurrentWallHeight(self):
return DNAFlatBuilding.currentWallHeight
def setHasDoor(self, hasDoor):
self.hasDoor = hasDoor
def getHasDoor(self):
return self.hasDoor
def makeFromDGI(self, dgi):
DNANode.DNANode.makeFromDGI(self, dgi)
self.width = dgi.getInt16() / 100.0
self.hasDoor = dgi.getBool()
def setupSuitFlatBuilding(self, nodePath, dnaStorage):
name = self.getName()
if name[:2] != 'tb':
return
name = 'sb' + name[2:]
node = nodePath.attachNewNode(name)
node.setPosHpr(self.getPos(), self.getHpr())
numCodes = dnaStorage.getNumCatalogCodes('suit_wall')
if numCodes < 1:
return
code = dnaStorage.getCatalogCode(
'suit_wall', random.randint(0, numCodes - 1))
wallNode = dnaStorage.findNode(code)
if not wallNode:
return
wallNode = wallNode.copyTo(node, 0)
wallScale = wallNode.getScale()
wallScale.setX(self.width)
wallScale.setZ(DNAFlatBuilding.currentWallHeight)
wallNode.setScale(wallScale)
if self.getHasDoor():
wallNodePath = node.find('wall_*')
doorNode = dnaStorage.findNode('suit_door')
doorNode = doorNode.copyTo(wallNodePath, 0)
doorNode.setScale(NodePath(), (1, 1, 1))
doorNode.setPosHpr(0.5, 0, 0, 0, 0, 0)
wallNodePath.setEffect(DecalEffect.make())
node.flattenMedium()
node.stash()
def setupCogdoFlatBuilding(self, nodePath, dnaStorage):
name = self.getName()
if name[:2] != 'tb':
return
name = 'cb' + name[2:]
node = nodePath.attachNewNode(name)
node.setPosHpr(self.getPos(), self.getHpr())
numCodes = dnaStorage.getNumCatalogCodes('cogdo_wall')
if numCodes < 1:
return
code = dnaStorage.getCatalogCode(
'cogdo_wall', random.randint(0, numCodes - 1))
wallNode = dnaStorage.findNode(code)
if not wallNode:
return
wallNode = wallNode.copyTo(node, 0)
wallScale = wallNode.getScale()
wallScale.setX(self.width)
wallScale.setZ(DNAFlatBuilding.currentWallHeight)
wallNode.setScale(wallScale)
if self.getHasDoor():
wallNodePath = node.find('wall_*')
doorNode = dnaStorage.findNode('suit_door')
doorNode = doorNode.copyTo(wallNodePath, 0)
doorNode.setScale(NodePath(), (1, 1, 1))
doorNode.setPosHpr(0.5, 0, 0, 0, 0, 0)
wallNodePath.setEffect(DecalEffect.make())
node.flattenMedium()
node.stash()
def traverse(self, nodePath, dnaStorage):
DNAFlatBuilding.currentWallHeight = 0
node = nodePath.attachNewNode(self.getName())
internalNode = node.attachNewNode(self.getName() + '-internal')
scale = self.getScale()
scale.setX(self.width)
internalNode.setScale(scale)
node.setPosHpr(self.getPos(), self.getHpr())
for child in self.children:
if isinstance(child, DNAWall.DNAWall):
child.traverse(internalNode, dnaStorage)
else:
child.traverse(node, dnaStorage)
if DNAFlatBuilding.currentWallHeight == 0:
print 'empty flat building with no walls'
else:
cameraBarrier = dnaStorage.findNode('wall_camera_barrier')
if cameraBarrier is None:
raise DNAError.DNAError('DNAFlatBuilding requires that there is a wall_camera_barrier in storage')
cameraBarrier = cameraBarrier.copyTo(internalNode, 0)
cameraBarrier.setScale((1, 1, DNAFlatBuilding.currentWallHeight))
internalNode.flattenStrong()
collisionNode = node.find('**/door_*/+CollisionNode')
if not collisionNode.isEmpty():
collisionNode.setName('KnockKnockDoorSphere_' + dnaStorage.getBlock(self.getName()))
cameraBarrier.wrtReparentTo(nodePath, 0)
wallCollection = internalNode.findAllMatches('wall*')
wallHolder = node.attachNewNode('wall_holder')
wallDecal = node.attachNewNode('wall_decal')
windowCollection = internalNode.findAllMatches('**/window*')
doorCollection = internalNode.findAllMatches('**/door*')
corniceCollection = internalNode.findAllMatches('**/cornice*_d')
wallCollection.reparentTo(wallHolder)
windowCollection.reparentTo(wallDecal)
doorCollection.reparentTo(wallDecal)
corniceCollection.reparentTo(wallDecal)
for i in xrange(wallHolder.getNumChildren()):
iNode = wallHolder.getChild(i)
iNode.clearTag('DNACode')
iNode.clearTag('DNARoot')
wallHolder.flattenStrong()
wallDecal.flattenStrong()
holderChild0 = wallHolder.getChild(0)
wallDecal.getChildren().reparentTo(holderChild0)
holderChild0.reparentTo(internalNode)
holderChild0.setEffect(DecalEffect.make())
wallHolder.removeNode()
wallDecal.removeNode()
self.setupSuitFlatBuilding(nodePath, dnaStorage)
self.setupCogdoFlatBuilding(nodePath, dnaStorage)
node.flattenStrong()
| Spiderlover/Toontown | toontown/dna/DNAFlatBuilding.py | Python | mit | 5,943 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MvcThrottle")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("stefanprodan.eu")]
[assembly: AssemblyProduct("MvcThrottle")]
[assembly: AssemblyCopyright("Copyright © Stefan Prodan 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b78fdf2f-12cf-49fb-a9ea-bc72ddafec19")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| modulexcite/MvcThrottle | MvcThrottle/Properties/AssemblyInfo.cs | C# | mit | 1,426 |
/* Get Programming with JavaScript
* Listing 4.01
* Displaying an object's properties on the console
*/
var movie1;
movie1 = {
title: "Inside Out",
actors: "Amy Poehler, Bill Hader",
directors: "Pete Doctor, Ronaldo Del Carmen"
};
console.log("Movie information for " + movie1.title);
console.log("------------------------------");
console.log("Actors: " + movie1.actors);
console.log("Directors: " + movie1.directors);
console.log("------------------------------");
/* Further Adventures
*
* 1) Add a second movie and display the same info for it.
*
* 2) Create an object to represent a blog post.
*
* 3) Write code to display info about the blog post.
*
*/
| jrlarsen/GetProgramming | Ch04_Functions/listing4.01.js | JavaScript | mit | 688 |
describe('Component: Product Search', function(){
var scope,
q,
oc,
state,
_ocParameters,
parameters,
mockProductList
;
beforeEach(module(function($provide) {
$provide.value('Parameters', {searchTerm: null, page: null, pageSize: null, sortBy: null});
}));
beforeEach(module('orderCloud'));
beforeEach(module('orderCloud.sdk'));
beforeEach(inject(function($rootScope, $q, OrderCloud, ocParameters, $state, Parameters){
scope = $rootScope.$new();
q = $q;
oc = OrderCloud;
state = $state;
_ocParameters = ocParameters;
parameters = Parameters;
mockProductList = {
Items:['product1', 'product2'],
Meta:{
ItemRange:[1, 3],
TotalCount: 50
}
};
}));
describe('State: productSearchResults', function(){
var state;
beforeEach(inject(function($state){
state = $state.get('productSearchResults');
spyOn(_ocParameters, 'Get');
spyOn(oc.Me, 'ListProducts');
}));
it('should resolve Parameters', inject(function($injector){
$injector.invoke(state.resolve.Parameters);
expect(_ocParameters.Get).toHaveBeenCalled();
}));
it('should resolve ProductList', inject(function($injector){
parameters.filters = {ParentID:'12'};
$injector.invoke(state.resolve.ProductList);
expect(oc.Me.ListProducts).toHaveBeenCalled();
}));
});
describe('Controller: ProductSearchController', function(){
var productSearchCtrl;
beforeEach(inject(function($state, $controller){
var state = $state;
productSearchCtrl = $controller('ProductSearchCtrl', {
$state: state,
ocParameters: _ocParameters,
$scope: scope,
ProductList: mockProductList
});
spyOn(_ocParameters, 'Create');
spyOn(state, 'go');
}));
describe('filter', function(){
it('should reload state and call ocParameters.Create with any parameters', function(){
productSearchCtrl.parameters = {pageSize: 1};
productSearchCtrl.filter(true);
expect(state.go).toHaveBeenCalled();
expect(_ocParameters.Create).toHaveBeenCalledWith({pageSize:1}, true);
});
});
describe('updateSort', function(){
it('should reload page with value and sort order, if both are defined', function(){
productSearchCtrl.updateSort('!ID');
expect(state.go).toHaveBeenCalled();
expect(_ocParameters.Create).toHaveBeenCalledWith({searchTerm: null, page: null, pageSize: null, sortBy: '!ID'}, false);
});
it('should reload page with just value, if no order is defined', function(){
productSearchCtrl.updateSort('ID');
expect(state.go).toHaveBeenCalled();
expect(_ocParameters.Create).toHaveBeenCalledWith({searchTerm: null, page: null, pageSize: null, sortBy: 'ID'}, false);
});
});
describe('updatePageSize', function(){
it('should reload state with the new pageSize', function(){
productSearchCtrl.updatePageSize('25');
expect(state.go).toHaveBeenCalled();
expect(_ocParameters.Create).toHaveBeenCalledWith({searchTerm: null, page: null, pageSize: '25', sortBy: null}, true);
});
});
describe('pageChanged', function(){
it('should reload state with the new page', function(){
productSearchCtrl.pageChanged('newPage');
expect(state.go).toHaveBeenCalled();
expect(_ocParameters.Create).toHaveBeenCalledWith({searchTerm: null, page: 'newPage', pageSize: null, sortBy: null}, false);
});
});
describe('reverseSort', function(){
it('should reload state with a reverse sort call', function(){
productSearchCtrl.parameters.sortBy = 'ID';
productSearchCtrl.reverseSort();
expect(_ocParameters.Create).toHaveBeenCalledWith({searchTerm: null, page: null, pageSize: null, sortBy: '!ID'}, false);
});
});
});
describe('Component Directive: ordercloudProductSearch', function(){
var productSearchComponentCtrl,
timeout
;
beforeEach(inject(function($componentController, $timeout){
timeout = $timeout;
productSearchComponentCtrl = $componentController('ordercloudProductSearch', {
$state:state,
$timeout: timeout,
$scope: scope,
OrderCloud:oc
});
spyOn(state, 'go');
}));
describe('getSearchResults', function(){
beforeEach(function(){
var defer = q.defer();
defer.resolve();
spyOn(oc.Me, 'ListProducts').and.returnValue(defer.promise);
});
it('should call Me.ListProducts with given search term and max products', function(){
productSearchComponentCtrl.searchTerm = 'Product1';
productSearchComponentCtrl.maxProducts = 12;
productSearchComponentCtrl.getSearchResults();
expect(oc.Me.ListProducts).toHaveBeenCalledWith('Product1', 1, 12);
});
it('should default max products to five, if none is provided', function(){
productSearchComponentCtrl.searchTerm = 'Product1';
productSearchComponentCtrl.getSearchResults();
expect(oc.Me.ListProducts).toHaveBeenCalledWith('Product1', 1, 5);
});
});
describe('onSelect', function(){
it('should route user to productDetail state for the selected product id', function(){
productSearchComponentCtrl.onSelect(12);
expect(state.go).toHaveBeenCalledWith('productDetail', {productid:12});
});
});
describe('onHardEnter', function(){
it('should route user to search results page for the provided search term', function(){
productSearchComponentCtrl.onHardEnter('bikes');
expect(state.go).toHaveBeenCalledWith('productSearchResults', {searchTerm: 'bikes'});
});
});
});
}); | Four51SteveDavis/JohnsonBros | src/app/productSearch/tests/productSearch.spec.js | JavaScript | mit | 6,607 |
(function () {
'use strict';
angular.module('common')
.directive('svLumxUsersDropdown', function () {
return {
templateUrl: 'scripts/common/directives/sv-lumx-users-dropdown.html',
scope: {
btnTitle: '@',
actionCounter: '@',
userAvatar: '@',
userName: '@',
userFirstName: '@',
userLastName: '@',
iconType: '@',
iconName: '@'
},
link: function ($scope, el, attrs) {
}
};
});
})();
| SvitlanaShepitsena/cl-poster | app/scripts/common/directives/sv-lumx-users-dropdown.js | JavaScript | mit | 689 |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
using FluentAssertions;
using Microsoft.OData.Edm;
using Microsoft.OData.Edm.Csdl;
using Microsoft.OData.Edm.Library;
using Microsoft.OData.Edm.Library.Values;
using Microsoft.OData.Edm.Validation;
using Microsoft.OData.Edm.Values;
using Xunit;
using Vipr.Reader.OData.v4;
using Vipr.Core.CodeModel;
using Vipr.Core.CodeModel.Vocabularies.Capabilities;
namespace ODataReader.v4UnitTests
{
public class Given_An_ODataVocabularyParser
{
public Given_An_ODataVocabularyParser()
{
}
[Xunit.Fact]
public void Boolean_constant_values_map_to_their_clr_values()
{
Func<object, IEdmValue> booleanConstantPredicate = o => new EdmBooleanConstant((bool) o);
ConstantValueShouldRoundtrip(true, booleanConstantPredicate);
ConstantValueShouldRoundtrip(false, booleanConstantPredicate);
}
[Fact]
public void String_constant_values_map_to_their_clr_values()
{
Func<object, IEdmValue> stringPredicate = o => new EdmStringConstant((string) o);
ConstantValueShouldRoundtrip("♪♪ unicode test string ♪♪", stringPredicate);
}
[Fact]
public void Guid_constant_values_map_to_their_clr_values()
{
Func<object, IEdmValue> guidConstantPredicate = o => new EdmGuidConstant((Guid) o);
ConstantValueShouldRoundtrip(Guid.NewGuid(), guidConstantPredicate);
}
[Fact]
public void Binary_constant_values_map_to_their_clr_values()
{
Func<object, IEdmValue> binaryConstantPredicate = o => new EdmBinaryConstant((byte[]) o);
ConstantValueShouldRoundtrip(new byte[] {1, 3, 3, 7}, binaryConstantPredicate);
}
[Fact]
public void Date_constant_values_map_to_their_clr_values()
{
Func<object, IEdmValue> dateConstantPredicate = o => new EdmDateConstant((Date) o);
ConstantValueShouldRoundtrip(Date.Now, dateConstantPredicate);
}
[Fact]
public void DateOffset_constant_values_map_to_their_clr_values()
{
Func<object, IEdmValue> dateTimeOffsetConstantPredicate =
o => new EdmDateTimeOffsetConstant((DateTimeOffset) o);
ConstantValueShouldRoundtrip(DateTimeOffset.Now, dateTimeOffsetConstantPredicate);
ConstantValueShouldRoundtrip(DateTimeOffset.UtcNow, dateTimeOffsetConstantPredicate);
}
[Fact]
public void Decimal_constant_values_map_to_their_clr_values()
{
Func<object, IEdmValue> decimalConstantValuePredicate = o => new EdmDecimalConstant((decimal) o);
ConstantValueShouldRoundtrip((decimal) 1.234, decimalConstantValuePredicate);
}
[Fact]
public void Floating_constant_values_map_to_their_clr_values()
{
Func<object, IEdmValue> floatingConstantValuePredicate = o => new EdmFloatingConstant((double) o);
ConstantValueShouldRoundtrip(1.234d, floatingConstantValuePredicate);
}
[Fact]
public void Integer_constant_values_map_to_their_clr_values()
{
Func<object, IEdmValue> integerConstantValuePredicate = o => new EdmIntegerConstant((long) o);
ConstantValueShouldRoundtrip(123400L, integerConstantValuePredicate);
}
[Fact]
public void Duration_constant_values_map_to_their_clr_values()
{
Func<object, IEdmValue> durationConstantValuePredicate = o => new EdmDurationConstant((TimeSpan) o);
ConstantValueShouldRoundtrip(new TimeSpan(1, 2, 3, 4), durationConstantValuePredicate);
}
[Fact]
public void TimeOfDay_contant_values_map_to_their_clr_values()
{
Func<object, IEdmValue> timeOfDayConstantValuePredicate = o => new EdmTimeOfDayConstant((TimeOfDay) o);
ConstantValueShouldRoundtrip(TimeOfDay.Now, timeOfDayConstantValuePredicate);
}
private void ConstantValueShouldRoundtrip(object originalValue, Func<object, IEdmValue> valuePredicate)
{
// Map our original value to an IEdmValue with the supplied predicate
var iEdmValue = valuePredicate(originalValue);
var result = ODataVocabularyReader.MapToClr(iEdmValue);
result.Should()
.Be(originalValue, "because a given clr value should roundtrip through its appropriate edm value ");
}
[Fact]
public void Validly_annotated_Edm_will_correctly_parse_insert_restrictions()
{
var annotations = GetAnnotationsFromOneNoteSampleEntitySet("sections");
annotations.Should().HaveCount(4, "because sections have four annotations");
annotations.Should().Contain(x => x.Name == "InsertRestrictions");
var insertRestrictions = annotations.First(x => x.Name == "InsertRestrictions");
insertRestrictions.Namespace.Should().Be("Org.OData.Capabilities.V1");
insertRestrictions.Value.Should().BeOfType<InsertRestrictionsType>();
var insertValue = insertRestrictions.Value as InsertRestrictionsType;
insertValue.Insertable.Should().BeFalse();
insertValue.NonInsertableNavigationProperties.Should().HaveCount(2);
insertValue.NonInsertableNavigationProperties.Should().Contain("parentNotebook");
insertValue.NonInsertableNavigationProperties.Should().Contain("parentSectionGroup");
}
[Fact]
public void Validly_annotated_edm_will_correctly_parse_update_restrictions()
{
var annotations = GetAnnotationsFromOneNoteSampleEntitySet("sections");
annotations.Should().Contain(x => x.Name == "UpdateRestrictions");
var update = annotations.First(x => x.Name == "UpdateRestrictions");
update.Namespace.Should().Be("Org.OData.Capabilities.V1");
update.Value.Should().BeOfType<UpdateRestrictionsType>();
var updateValue = update.Value as UpdateRestrictionsType;
updateValue.Updatable.Should().BeFalse();
updateValue.NonUpdatableNavigationProperties.Should().HaveCount(3);
updateValue.NonUpdatableNavigationProperties.Should().Contain("pages");
updateValue.NonUpdatableNavigationProperties.Should().Contain("parentNotebook");
updateValue.NonUpdatableNavigationProperties.Should().Contain("parentSectionGroup");
}
[Fact]
public void Validly_annotated_edm_will_correctly_parse_delete_restrictions()
{
var annotations = GetAnnotationsFromOneNoteSampleEntitySet("sections");
annotations.Should().Contain(x => x.Name == "DeleteRestrictions");
var delete = annotations.First(x => x.Name == "DeleteRestrictions");
delete.Namespace.Should().Be("Org.OData.Capabilities.V1");
delete.Value.Should().BeOfType<DeleteRestrictionsType>();
var deleteValue = delete.Value as DeleteRestrictionsType;
deleteValue.Deletable.Should().BeFalse();
deleteValue.NonDeletableNavigationProperties.Should().HaveCount(3);
deleteValue.NonDeletableNavigationProperties.Should().Contain("pages");
deleteValue.NonDeletableNavigationProperties.Should().Contain("parentNotebook");
deleteValue.NonDeletableNavigationProperties.Should().Contain("parentSectionGroup");
}
[Fact]
public void Validly_annotated_edm_will_correctly_parse_annotations_with_primitive_values()
{
var annotations = GetAnnotationsFromOneNoteSampleEntityContainer();
annotations.Should().HaveCount(3);
annotations.Should().Contain(x => x.Name == "BatchSupported");
annotations.Should().Contain(x => x.Name == "AsynchronousRequestsSupported");
annotations.Should().Contain(x => x.Name == "BatchContinueOnErrorSupported");
// In this case, all of the value and namespaces for these annotaion are the same
// We'll loop over them for brevity.
foreach (var annotation in annotations)
{
annotation.Namespace.Should().Be("Org.OData.Capabilities.V1");
annotation.Value.Should().BeOfType<bool>();
((bool) annotation.Value).Should().BeFalse();
}
}
private List<OdcmVocabularyAnnotation> GetAnnotationsFromOneNoteSampleEntitySet(string entitySet)
{
IEdmModel model = SampleParsedEdmModel;
IEdmEntitySet sampleEntitySet = model.FindEntityContainer("OneNoteApi").FindEntitySet(entitySet);
return ODataVocabularyReader.GetOdcmAnnotations(model, sampleEntitySet).ToList();
}
private List<OdcmVocabularyAnnotation> GetAnnotationsFromOneNoteSampleEntityContainer()
{
IEdmModel model = SampleParsedEdmModel;
var sampleContainer = model.FindEntityContainer("OneNoteApi");
return ODataVocabularyReader.GetOdcmAnnotations(model, sampleContainer).ToList();
}
#region Helper methods
private static readonly IEdmModel SampleParsedEdmModel = GetSampleParsedEdmModel();
private static IEdmModel GetSampleParsedEdmModel()
{
IEdmModel edmModel;
IEnumerable<EdmError> errors;
if (!EdmxReader.TryParse(XmlReader.Create(new StringReader(ODataReader.v4UnitTests.Properties.Resources.OneNoteExampleEdmx)), out edmModel, out errors))
{
throw new InvalidOperationException("Failed to parse Edm model");
}
return edmModel;
}
}
#endregion
} | ysanghi/Vipr | test/ODataReader.v4UnitTests/Given_an_ODataVocabularyReader.cs | C# | mit | 10,044 |
/*================================================================================
code generated by: java2cpp
author: Zoran Angelov, mailto://baldzar@gmail.com
class: com.tencent.mm.sdk.openapi.SendAuth
================================================================================*/
#ifndef J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_COM_TENCENT_MM_SDK_OPENAPI_SENDAUTH_HPP_DECL
#define J2CPP_COM_TENCENT_MM_SDK_OPENAPI_SENDAUTH_HPP_DECL
namespace j2cpp { namespace android { namespace os { class Bundle; } } }
namespace j2cpp { namespace java { namespace lang { class String; } } }
namespace j2cpp { namespace java { namespace lang { class Object; } } }
namespace j2cpp { namespace com { namespace tencent { namespace mm { namespace sdk { namespace openapi { class BaseReq; } } } } } }
namespace j2cpp { namespace com { namespace tencent { namespace mm { namespace sdk { namespace openapi { class BaseResp; } } } } } }
#include <android/os/Bundle.hpp>
#include <com/tencent/mm/sdk/openapi/BaseReq.hpp>
#include <com/tencent/mm/sdk/openapi/BaseResp.hpp>
#include <java/lang/Object.hpp>
#include <java/lang/String.hpp>
namespace j2cpp {
namespace com { namespace tencent { namespace mm { namespace sdk { namespace openapi {
class SendAuth;
namespace SendAuth_ {
class Req;
class Req
: public object<Req>
{
public:
J2CPP_DECLARE_CLASS
J2CPP_DECLARE_METHOD(0)
J2CPP_DECLARE_METHOD(1)
J2CPP_DECLARE_METHOD(2)
J2CPP_DECLARE_METHOD(3)
J2CPP_DECLARE_METHOD(4)
J2CPP_DECLARE_METHOD(5)
J2CPP_DECLARE_FIELD(0)
J2CPP_DECLARE_FIELD(1)
explicit Req(jobject jobj)
: object<Req>(jobj)
, scope(jobj)
, state(jobj)
{
}
operator local_ref<java::lang::Object>() const;
operator local_ref<com::tencent::mm::sdk::openapi::BaseReq>() const;
Req();
Req(local_ref< android::os::Bundle > const&);
jint getType();
void fromBundle(local_ref< android::os::Bundle > const&);
void toBundle(local_ref< android::os::Bundle > const&);
field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(0), J2CPP_FIELD_SIGNATURE(0), local_ref< java::lang::String > > scope;
field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(1), J2CPP_FIELD_SIGNATURE(1), local_ref< java::lang::String > > state;
}; //class Req
class Resp;
class Resp
: public object<Resp>
{
public:
J2CPP_DECLARE_CLASS
J2CPP_DECLARE_METHOD(0)
J2CPP_DECLARE_METHOD(1)
J2CPP_DECLARE_METHOD(2)
J2CPP_DECLARE_METHOD(3)
J2CPP_DECLARE_METHOD(4)
J2CPP_DECLARE_METHOD(5)
J2CPP_DECLARE_FIELD(0)
J2CPP_DECLARE_FIELD(1)
J2CPP_DECLARE_FIELD(2)
J2CPP_DECLARE_FIELD(3)
J2CPP_DECLARE_FIELD(4)
explicit Resp(jobject jobj)
: object<Resp>(jobj)
, userName(jobj)
, token(jobj)
, expireDate(jobj)
, state(jobj)
, resultUrl(jobj)
{
}
operator local_ref<java::lang::Object>() const;
operator local_ref<com::tencent::mm::sdk::openapi::BaseResp>() const;
Resp();
Resp(local_ref< android::os::Bundle > const&);
jint getType();
void fromBundle(local_ref< android::os::Bundle > const&);
void toBundle(local_ref< android::os::Bundle > const&);
field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(0), J2CPP_FIELD_SIGNATURE(0), local_ref< java::lang::String > > userName;
field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(1), J2CPP_FIELD_SIGNATURE(1), local_ref< java::lang::String > > token;
field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(2), J2CPP_FIELD_SIGNATURE(2), jint > expireDate;
field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(3), J2CPP_FIELD_SIGNATURE(3), local_ref< java::lang::String > > state;
field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(4), J2CPP_FIELD_SIGNATURE(4), local_ref< java::lang::String > > resultUrl;
}; //class Resp
} //namespace SendAuth_
class SendAuth
: public object<SendAuth>
{
public:
J2CPP_DECLARE_CLASS
J2CPP_DECLARE_METHOD(0)
typedef SendAuth_::Req Req;
typedef SendAuth_::Resp Resp;
explicit SendAuth(jobject jobj)
: object<SendAuth>(jobj)
{
}
operator local_ref<java::lang::Object>() const;
}; //class SendAuth
} //namespace openapi
} //namespace sdk
} //namespace mm
} //namespace tencent
} //namespace com
} //namespace j2cpp
#endif //J2CPP_COM_TENCENT_MM_SDK_OPENAPI_SENDAUTH_HPP_DECL
#else //J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_COM_TENCENT_MM_SDK_OPENAPI_SENDAUTH_HPP_IMPL
#define J2CPP_COM_TENCENT_MM_SDK_OPENAPI_SENDAUTH_HPP_IMPL
namespace j2cpp {
com::tencent::mm::sdk::openapi::SendAuth_::Req::operator local_ref<java::lang::Object>() const
{
return local_ref<java::lang::Object>(get_jobject());
}
com::tencent::mm::sdk::openapi::SendAuth_::Req::operator local_ref<com::tencent::mm::sdk::openapi::BaseReq>() const
{
return local_ref<com::tencent::mm::sdk::openapi::BaseReq>(get_jobject());
}
com::tencent::mm::sdk::openapi::SendAuth_::Req::Req()
: object<com::tencent::mm::sdk::openapi::SendAuth_::Req>(
call_new_object<
com::tencent::mm::sdk::openapi::SendAuth_::Req::J2CPP_CLASS_NAME,
com::tencent::mm::sdk::openapi::SendAuth_::Req::J2CPP_METHOD_NAME(0),
com::tencent::mm::sdk::openapi::SendAuth_::Req::J2CPP_METHOD_SIGNATURE(0)
>()
)
, scope(get_jobject())
, state(get_jobject())
{
}
com::tencent::mm::sdk::openapi::SendAuth_::Req::Req(local_ref< android::os::Bundle > const &a0)
: object<com::tencent::mm::sdk::openapi::SendAuth_::Req>(
call_new_object<
com::tencent::mm::sdk::openapi::SendAuth_::Req::J2CPP_CLASS_NAME,
com::tencent::mm::sdk::openapi::SendAuth_::Req::J2CPP_METHOD_NAME(1),
com::tencent::mm::sdk::openapi::SendAuth_::Req::J2CPP_METHOD_SIGNATURE(1)
>(a0)
)
, scope(get_jobject())
, state(get_jobject())
{
}
jint com::tencent::mm::sdk::openapi::SendAuth_::Req::getType()
{
return call_method<
com::tencent::mm::sdk::openapi::SendAuth_::Req::J2CPP_CLASS_NAME,
com::tencent::mm::sdk::openapi::SendAuth_::Req::J2CPP_METHOD_NAME(2),
com::tencent::mm::sdk::openapi::SendAuth_::Req::J2CPP_METHOD_SIGNATURE(2),
jint
>(get_jobject());
}
void com::tencent::mm::sdk::openapi::SendAuth_::Req::fromBundle(local_ref< android::os::Bundle > const &a0)
{
return call_method<
com::tencent::mm::sdk::openapi::SendAuth_::Req::J2CPP_CLASS_NAME,
com::tencent::mm::sdk::openapi::SendAuth_::Req::J2CPP_METHOD_NAME(3),
com::tencent::mm::sdk::openapi::SendAuth_::Req::J2CPP_METHOD_SIGNATURE(3),
void
>(get_jobject(), a0);
}
void com::tencent::mm::sdk::openapi::SendAuth_::Req::toBundle(local_ref< android::os::Bundle > const &a0)
{
return call_method<
com::tencent::mm::sdk::openapi::SendAuth_::Req::J2CPP_CLASS_NAME,
com::tencent::mm::sdk::openapi::SendAuth_::Req::J2CPP_METHOD_NAME(4),
com::tencent::mm::sdk::openapi::SendAuth_::Req::J2CPP_METHOD_SIGNATURE(4),
void
>(get_jobject(), a0);
}
J2CPP_DEFINE_CLASS(com::tencent::mm::sdk::openapi::SendAuth_::Req,"com/tencent/mm/sdk/openapi/SendAuth$Req")
J2CPP_DEFINE_METHOD(com::tencent::mm::sdk::openapi::SendAuth_::Req,0,"<init>","()V")
J2CPP_DEFINE_METHOD(com::tencent::mm::sdk::openapi::SendAuth_::Req,1,"<init>","(Landroid/os/Bundle;)V")
J2CPP_DEFINE_METHOD(com::tencent::mm::sdk::openapi::SendAuth_::Req,2,"getType","()I")
J2CPP_DEFINE_METHOD(com::tencent::mm::sdk::openapi::SendAuth_::Req,3,"fromBundle","(Landroid/os/Bundle;)V")
J2CPP_DEFINE_METHOD(com::tencent::mm::sdk::openapi::SendAuth_::Req,4,"toBundle","(Landroid/os/Bundle;)V")
J2CPP_DEFINE_METHOD(com::tencent::mm::sdk::openapi::SendAuth_::Req,5,"checkArgs","()Z")
J2CPP_DEFINE_FIELD(com::tencent::mm::sdk::openapi::SendAuth_::Req,0,"scope","Ljava/lang/String;")
J2CPP_DEFINE_FIELD(com::tencent::mm::sdk::openapi::SendAuth_::Req,1,"state","Ljava/lang/String;")
com::tencent::mm::sdk::openapi::SendAuth_::Resp::operator local_ref<java::lang::Object>() const
{
return local_ref<java::lang::Object>(get_jobject());
}
com::tencent::mm::sdk::openapi::SendAuth_::Resp::operator local_ref<com::tencent::mm::sdk::openapi::BaseResp>() const
{
return local_ref<com::tencent::mm::sdk::openapi::BaseResp>(get_jobject());
}
com::tencent::mm::sdk::openapi::SendAuth_::Resp::Resp()
: object<com::tencent::mm::sdk::openapi::SendAuth_::Resp>(
call_new_object<
com::tencent::mm::sdk::openapi::SendAuth_::Resp::J2CPP_CLASS_NAME,
com::tencent::mm::sdk::openapi::SendAuth_::Resp::J2CPP_METHOD_NAME(0),
com::tencent::mm::sdk::openapi::SendAuth_::Resp::J2CPP_METHOD_SIGNATURE(0)
>()
)
, userName(get_jobject())
, token(get_jobject())
, expireDate(get_jobject())
, state(get_jobject())
, resultUrl(get_jobject())
{
}
com::tencent::mm::sdk::openapi::SendAuth_::Resp::Resp(local_ref< android::os::Bundle > const &a0)
: object<com::tencent::mm::sdk::openapi::SendAuth_::Resp>(
call_new_object<
com::tencent::mm::sdk::openapi::SendAuth_::Resp::J2CPP_CLASS_NAME,
com::tencent::mm::sdk::openapi::SendAuth_::Resp::J2CPP_METHOD_NAME(1),
com::tencent::mm::sdk::openapi::SendAuth_::Resp::J2CPP_METHOD_SIGNATURE(1)
>(a0)
)
, userName(get_jobject())
, token(get_jobject())
, expireDate(get_jobject())
, state(get_jobject())
, resultUrl(get_jobject())
{
}
jint com::tencent::mm::sdk::openapi::SendAuth_::Resp::getType()
{
return call_method<
com::tencent::mm::sdk::openapi::SendAuth_::Resp::J2CPP_CLASS_NAME,
com::tencent::mm::sdk::openapi::SendAuth_::Resp::J2CPP_METHOD_NAME(2),
com::tencent::mm::sdk::openapi::SendAuth_::Resp::J2CPP_METHOD_SIGNATURE(2),
jint
>(get_jobject());
}
void com::tencent::mm::sdk::openapi::SendAuth_::Resp::fromBundle(local_ref< android::os::Bundle > const &a0)
{
return call_method<
com::tencent::mm::sdk::openapi::SendAuth_::Resp::J2CPP_CLASS_NAME,
com::tencent::mm::sdk::openapi::SendAuth_::Resp::J2CPP_METHOD_NAME(3),
com::tencent::mm::sdk::openapi::SendAuth_::Resp::J2CPP_METHOD_SIGNATURE(3),
void
>(get_jobject(), a0);
}
void com::tencent::mm::sdk::openapi::SendAuth_::Resp::toBundle(local_ref< android::os::Bundle > const &a0)
{
return call_method<
com::tencent::mm::sdk::openapi::SendAuth_::Resp::J2CPP_CLASS_NAME,
com::tencent::mm::sdk::openapi::SendAuth_::Resp::J2CPP_METHOD_NAME(4),
com::tencent::mm::sdk::openapi::SendAuth_::Resp::J2CPP_METHOD_SIGNATURE(4),
void
>(get_jobject(), a0);
}
J2CPP_DEFINE_CLASS(com::tencent::mm::sdk::openapi::SendAuth_::Resp,"com/tencent/mm/sdk/openapi/SendAuth$Resp")
J2CPP_DEFINE_METHOD(com::tencent::mm::sdk::openapi::SendAuth_::Resp,0,"<init>","()V")
J2CPP_DEFINE_METHOD(com::tencent::mm::sdk::openapi::SendAuth_::Resp,1,"<init>","(Landroid/os/Bundle;)V")
J2CPP_DEFINE_METHOD(com::tencent::mm::sdk::openapi::SendAuth_::Resp,2,"getType","()I")
J2CPP_DEFINE_METHOD(com::tencent::mm::sdk::openapi::SendAuth_::Resp,3,"fromBundle","(Landroid/os/Bundle;)V")
J2CPP_DEFINE_METHOD(com::tencent::mm::sdk::openapi::SendAuth_::Resp,4,"toBundle","(Landroid/os/Bundle;)V")
J2CPP_DEFINE_METHOD(com::tencent::mm::sdk::openapi::SendAuth_::Resp,5,"checkArgs","()Z")
J2CPP_DEFINE_FIELD(com::tencent::mm::sdk::openapi::SendAuth_::Resp,0,"userName","Ljava/lang/String;")
J2CPP_DEFINE_FIELD(com::tencent::mm::sdk::openapi::SendAuth_::Resp,1,"token","Ljava/lang/String;")
J2CPP_DEFINE_FIELD(com::tencent::mm::sdk::openapi::SendAuth_::Resp,2,"expireDate","I")
J2CPP_DEFINE_FIELD(com::tencent::mm::sdk::openapi::SendAuth_::Resp,3,"state","Ljava/lang/String;")
J2CPP_DEFINE_FIELD(com::tencent::mm::sdk::openapi::SendAuth_::Resp,4,"resultUrl","Ljava/lang/String;")
com::tencent::mm::sdk::openapi::SendAuth::operator local_ref<java::lang::Object>() const
{
return local_ref<java::lang::Object>(get_jobject());
}
J2CPP_DEFINE_CLASS(com::tencent::mm::sdk::openapi::SendAuth,"com/tencent/mm/sdk/openapi/SendAuth")
J2CPP_DEFINE_METHOD(com::tencent::mm::sdk::openapi::SendAuth,0,"<init>","()V")
} //namespace j2cpp
#endif //J2CPP_COM_TENCENT_MM_SDK_OPENAPI_SENDAUTH_HPP_IMPL
#endif //J2CPP_INCLUDE_IMPLEMENTATION
| hyEvans/ph-open | proj.android/jni/puzzleHero/com/tencent/mm/sdk/openapi/SendAuth.hpp | C++ | mit | 11,739 |
# -*- coding: utf-8 -*-
"""
Various i18n functions.
Helper functions for both the internal translation system
and for TranslateWiki-based translations.
By default messages are assumed to reside in a package called
'scripts.i18n'. In pywikibot 2.0, that package is not packaged
with pywikibot, and pywikibot 2.0 does not have a hard dependency
on any i18n messages. However, there are three user input questions
in pagegenerators which will use i18 messages if they can be loaded.
The default message location may be changed by calling
L{set_message_package} with a package name. The package must contain
an __init__.py, and a message bundle called 'pywikibot' containing
messages. See L{twntranslate} for more information on the messages.
"""
#
# (C) Pywikibot team, 2004-2015
#
# Distributed under the terms of the MIT license.
#
from __future__ import unicode_literals
__version__ = '$Id$'
#
import sys
import re
import locale
import json
import os
import pkgutil
from collections import defaultdict
from pywikibot import Error
from .plural import plural_rules
import pywikibot
from . import config2 as config
if sys.version_info[0] > 2:
basestring = (str, )
PLURAL_PATTERN = r'{{PLURAL:(?:%\()?([^\)]*?)(?:\)d)?\|(.*?)}}'
# Package name for the translation messages. The messages data must loaded
# relative to that package name. In the top of this package should be
# directories named after for each script/message bundle, and each directory
# should contain JSON files called <lang>.json
_messages_package_name = 'scripts.i18n'
# Flag to indicate whether translation messages are available
_messages_available = None
# Cache of translated messages
_cache = defaultdict(dict)
def set_messages_package(package_name):
"""Set the package name where i18n messages are located."""
global _messages_package_name
global _messages_available
_messages_package_name = package_name
_messages_available = None
def messages_available():
"""
Return False if there are no i18n messages available.
To determine if messages are available, it looks for the package name
set using L{set_messages_package} for a message bundle called 'pywikibot'
containing messages.
@rtype: bool
"""
global _messages_available
if _messages_available is not None:
return _messages_available
try:
__import__(_messages_package_name)
except ImportError:
_messages_available = False
return False
_messages_available = True
return True
def _altlang(code):
"""Define fallback languages for particular languages.
If no translation is available to a specified language, translate() will
try each of the specified fallback languages, in order, until it finds
one with a translation, with 'en' and '_default' as a last resort.
For example, if for language 'xx', you want the preference of languages
to be: xx > fr > ru > en, you let this method return ['fr', 'ru'].
This code is used by other translating methods below.
@param code: The language code
@type code: string
@return: language codes
@rtype: list of str
"""
# Akan
if code in ['ak', 'tw']:
return ['ak', 'tw']
# Amharic
if code in ['aa', 'ti']:
return ['am']
# Arab
if code in ['arc', 'arz', 'so']:
return ['ar']
if code == 'kab':
return ['ar', 'fr']
# Bulgarian
if code in ['cu', 'mk']:
return ['bg', 'sr', 'sh']
# Czech
if code in ['cs', 'sk']:
return ['cs', 'sk']
# German
if code in ['bar', 'frr', 'ksh', 'pdc', 'pfl']:
return ['de']
if code == 'lb':
return ['de', 'fr']
if code in ['als', 'gsw']:
return ['als', 'gsw', 'de']
if code == 'nds':
return ['nds-nl', 'de']
if code in ['dsb', 'hsb']:
return ['hsb', 'dsb', 'de']
if code == 'sli':
return ['de', 'pl']
if code == 'rm':
return ['de', 'it']
if code == 'stq':
return ['nds', 'de']
# Greek
if code in ['grc', 'pnt']:
return ['el']
# Esperanto
if code in ['io', 'nov']:
return ['eo']
# Spanish
if code in ['an', 'arn', 'ast', 'ay', 'ca', 'ext', 'lad', 'nah', 'nv', 'qu',
'yua']:
return ['es']
if code in ['gl', 'gn']:
return ['es', 'pt']
if code == 'eu':
return ['es', 'fr']
if code == 'cbk-zam':
return ['es', 'tl']
# Estonian
if code in ['fiu-vro', 'vro']:
return ['fiu-vro', 'vro', 'et']
if code == 'liv':
return ['et', 'lv']
# Persian (Farsi)
if code == 'ps':
return ['fa']
if code in ['glk', 'mzn']:
return ['glk', 'mzn', 'fa', 'ar']
# Finnish
if code == 'vep':
return ['fi', 'ru']
if code == 'fit':
return ['fi', 'sv']
# French
if code in ['bm', 'br', 'ht', 'kg', 'ln', 'mg', 'nrm', 'pcd',
'rw', 'sg', 'ty', 'wa']:
return ['fr']
if code == 'oc':
return ['fr', 'ca', 'es']
if code in ['co', 'frp']:
return ['fr', 'it']
# Hindi
if code in ['sa']:
return ['hi']
if code in ['ne', 'new']:
return ['ne', 'new', 'hi']
if code in ['bh', 'bho']:
return ['bh', 'bho']
# Indonesian and Malay
if code in ['ace', 'bug', 'bjn', 'id', 'jv', 'ms', 'su']:
return ['id', 'ms', 'jv']
if code == 'map-bms':
return ['jv', 'id', 'ms']
# Inuit languages
if code in ['ik', 'iu']:
return ['iu', 'kl']
if code == 'kl':
return ['da', 'iu', 'no', 'nb']
# Italian
if code in ['eml', 'fur', 'lij', 'lmo', 'nap', 'pms', 'roa-tara', 'sc',
'scn', 'vec']:
return ['it']
# Lithuanian
if code in ['bat-smg', 'sgs']:
return ['bat-smg', 'sgs', 'lt']
# Latvian
if code == 'ltg':
return ['lv']
# Dutch
if code in ['af', 'fy', 'li', 'pap', 'srn', 'vls', 'zea']:
return ['nl']
if code == ['nds-nl']:
return ['nds', 'nl']
# Polish
if code in ['csb', 'szl']:
return ['pl']
# Portuguese
if code in ['fab', 'mwl', 'tet']:
return ['pt']
# Romanian
if code in ['roa-rup', 'rup']:
return ['roa-rup', 'rup', 'ro']
if code == 'mo':
return ['ro']
# Russian and Belarusian
if code in ['ab', 'av', 'ba', 'bxr', 'ce', 'cv', 'inh', 'kk', 'koi', 'krc',
'kv', 'ky', 'lbe', 'lez', 'mdf', 'mhr', 'mn', 'mrj', 'myv',
'os', 'sah', 'tg', 'udm', 'uk', 'xal']:
return ['ru']
if code in ['kbd', 'ady']:
return ['kbd', 'ady', 'ru']
if code == 'tt':
return ['tt-cyrl', 'ru']
if code in ['be', 'be-x-old', 'be-tarask']:
return ['be', 'be-x-old', 'be-tarask', 'ru']
if code == 'kaa':
return ['uz', 'ru']
# Serbocroatian
if code in ['bs', 'hr', 'sh']:
return ['sh', 'hr', 'bs', 'sr', 'sr-el']
if code == 'sr':
return ['sr-el', 'sh', 'hr', 'bs']
# Tagalog
if code in ['bcl', 'ceb', 'ilo', 'pag', 'pam', 'war']:
return ['tl']
# Turkish and Kurdish
if code in ['diq', 'ku']:
return ['ku', 'ku-latn', 'tr']
if code == 'gag':
return ['tr']
if code == 'ckb':
return ['ku']
# Ukrainian
if code in ['crh', 'crh-latn']:
return ['crh', 'crh-latn', 'uk', 'ru']
if code in ['rue']:
return ['uk', 'ru']
# Chinese
if code in ['zh-classical', 'lzh', 'minnan', 'zh-min-nan', 'nan', 'zh-tw',
'zh', 'zh-hans']:
return ['zh', 'zh-hans', 'zh-tw', 'zh-cn', 'zh-classical', 'lzh']
if code in ['cdo', 'gan', 'hak', 'ii', 'wuu', 'za', 'zh-classical', 'lzh',
'zh-cn', 'zh-yue', 'yue']:
return ['zh', 'zh-hans' 'zh-cn', 'zh-tw', 'zh-classical', 'lzh']
# Scandinavian languages
if code in ['da', 'sv']:
return ['da', 'no', 'nb', 'sv', 'nn']
if code in ['fo', 'is']:
return ['da', 'no', 'nb', 'nn', 'sv']
if code == 'nn':
return ['no', 'nb', 'sv', 'da']
if code in ['no', 'nb']:
return ['no', 'nb', 'da', 'nn', 'sv']
if code == 'se':
return ['sv', 'no', 'nb', 'nn', 'fi']
# Other languages
if code in ['bi', 'tpi']:
return ['bi', 'tpi']
if code == 'yi':
return ['he', 'de']
if code in ['ia', 'ie']:
return ['ia', 'la', 'it', 'fr', 'es']
if code == 'xmf':
return ['ka']
if code in ['nso', 'st']:
return ['st', 'nso']
if code in ['kj', 'ng']:
return ['kj', 'ng']
if code in ['meu', 'hmo']:
return ['meu', 'hmo']
if code == ['as']:
return ['bn']
# Default value
return []
class TranslationError(Error, ImportError):
"""Raised when no correct translation could be found."""
# Inherits from ImportError, as this exception is now used
# where previously an ImportError would have been raised,
# and may have been caught by scripts as such.
pass
def _get_translation(lang, twtitle):
"""
Return message of certain twtitle if exists.
For internal use, don't use it directly.
"""
if twtitle in _cache[lang]:
return _cache[lang][twtitle]
message_bundle = twtitle.split('-')[0]
trans_text = None
filename = '%s/%s.json' % (message_bundle, lang)
try:
trans_text = pkgutil.get_data(
_messages_package_name, filename).decode('utf-8')
except (OSError, IOError): # file open can cause several exceptions
_cache[lang][twtitle] = None
return
transdict = json.loads(trans_text)
_cache[lang].update(transdict)
try:
return transdict[twtitle]
except KeyError:
return
def _extract_plural(code, message, parameters):
"""Check for the plural variants in message and replace them.
@param message: the message to be replaced
@type message: unicode string
@param parameters: plural parameters passed from other methods
@type parameters: int, basestring, tuple, list, dict
"""
plural_items = re.findall(PLURAL_PATTERN, message)
if plural_items: # we found PLURAL patterns, process it
if len(plural_items) > 1 and isinstance(parameters, (tuple, list)) and \
len(plural_items) != len(parameters):
raise ValueError("Length of parameter does not match PLURAL "
"occurrences.")
i = 0
for selector, variants in plural_items:
if isinstance(parameters, dict):
num = int(parameters[selector])
elif isinstance(parameters, basestring):
num = int(parameters)
elif isinstance(parameters, (tuple, list)):
num = int(parameters[i])
i += 1
else:
num = parameters
# TODO: check against plural_rules[code]['nplurals']
try:
index = plural_rules[code]['plural'](num)
except KeyError:
index = plural_rules['_default']['plural'](num)
except TypeError:
# we got an int, not a function
index = plural_rules[code]['plural']
repl = variants.split('|')[index]
message = re.sub(PLURAL_PATTERN, repl, message, count=1)
return message
DEFAULT_FALLBACK = ('_default', )
def translate(code, xdict, parameters=None, fallback=False):
"""Return the most appropriate translation from a translation dict.
Given a language code and a dictionary, returns the dictionary's value for
key 'code' if this key exists; otherwise tries to return a value for an
alternative language that is most applicable to use on the wiki in
language 'code' except fallback is False.
The language itself is always checked first, then languages that
have been defined to be alternatives, and finally English. If none of
the options gives result, we just take the one language from xdict which may
not be always the same. When fallback is iterable it'll return None if no
code applies (instead of returning one).
For PLURAL support have a look at the twntranslate method
@param code: The language code
@type code: string or Site object
@param xdict: dictionary with language codes as keys or extended dictionary
with family names as keys containing language dictionaries or
a single (unicode) string. May contain PLURAL tags as
described in twntranslate
@type xdict: dict, string, unicode
@param parameters: For passing (plural) parameters
@type parameters: dict, string, unicode, int
@param fallback: Try an alternate language code. If it's iterable it'll
also try those entries and choose the first match.
@type fallback: boolean or iterable
"""
family = pywikibot.config.family
# If a site is given instead of a code, use its language
if hasattr(code, 'code'):
family = code.family.name
code = code.code
# Check whether xdict has multiple projects
if isinstance(xdict, dict):
if family in xdict:
xdict = xdict[family]
elif 'wikipedia' in xdict:
xdict = xdict['wikipedia']
# Get the translated string
if not isinstance(xdict, dict):
trans = xdict
elif not xdict:
trans = None
else:
codes = [code]
if fallback is True:
codes += _altlang(code) + ['_default', 'en']
elif fallback is not False:
codes += list(fallback)
for code in codes:
if code in xdict:
trans = xdict[code]
break
else:
if fallback is not True:
# this shouldn't simply return "any one" code but when fallback
# was True before 65518573d2b0, it did just that. When False it
# did just return None. It's now also returning None in the new
# iterable mode.
return
code = list(xdict.keys())[0]
trans = xdict[code]
if trans is None:
return # return None if we have no translation found
if parameters is None:
return trans
# else we check for PLURAL variants
trans = _extract_plural(code, trans, parameters)
if parameters:
try:
return trans % parameters
except (KeyError, TypeError):
# parameter is for PLURAL variants only, don't change the string
pass
return trans
def twtranslate(code, twtitle, parameters=None, fallback=True):
"""
Translate a message.
The translations are retrieved from json files in messages_package_name.
fallback parameter must be True for i18n and False for L10N or testing
purposes.
@param code: The language code
@param twtitle: The TranslateWiki string title, in <package>-<key> format
@param parameters: For passing parameters.
@param fallback: Try an alternate language code
@type fallback: boolean
"""
if not messages_available():
raise TranslationError(
'Unable to load messages package %s for bundle %s'
'\nIt can happen due to lack of i18n submodule or files. '
'Read https://mediawiki.org/wiki/PWB/i18n'
% (_messages_package_name, twtitle))
code_needed = False
# If a site is given instead of a code, use its language
if hasattr(code, 'code'):
lang = code.code
# check whether we need the language code back
elif isinstance(code, list):
lang = code.pop()
code_needed = True
else:
lang = code
# There are two possible failure modes: the translation dict might not have
# the language altogether, or a specific key could be untranslated. Both
# modes are caught with the KeyError.
langs = [lang]
if fallback:
langs += _altlang(lang) + ['en']
for alt in langs:
trans = _get_translation(alt, twtitle)
if trans:
break
else:
raise TranslationError(
'No English translation has been defined for TranslateWiki key'
' %r\nIt can happen due to lack of i18n submodule or files. '
'Read https://mediawiki.org/wiki/PWB/i18n' % twtitle)
# send the language code back via the given list
if code_needed:
code.append(alt)
if parameters:
return trans % parameters
else:
return trans
# Maybe this function should be merged with twtranslate
def twntranslate(code, twtitle, parameters=None):
r"""Translate a message with plural support.
Support is implemented like in MediaWiki extension. If the TranslateWiki
message contains a plural tag inside which looks like::
{{PLURAL:<number>|<variant1>|<variant2>[|<variantn>]}}
it takes that variant calculated by the plural_rules depending on the number
value. Multiple plurals are allowed.
As an examples, if we had several json dictionaries in test folder like:
en.json:
{
"test-plural": "Bot: Changing %(num)s {{PLURAL:%(num)d|page|pages}}.",
}
fr.json:
{
"test-plural": "Robot: Changer %(descr)s {{PLURAL:num|une page|quelques pages}}.",
}
and so on.
>>> from pywikibot import i18n
>>> i18n.set_messages_package('tests.i18n')
>>> # use a number
>>> str(i18n.twntranslate('en', 'test-plural', 0) % {'num': 'no'})
'Bot: Changing no pages.'
>>> # use a string
>>> str(i18n.twntranslate('en', 'test-plural', '1') % {'num': 'one'})
'Bot: Changing one page.'
>>> # use a dictionary
>>> str(i18n.twntranslate('en', 'test-plural', {'num':2}))
'Bot: Changing 2 pages.'
>>> # use additional format strings
>>> str(i18n.twntranslate('fr', 'test-plural', {'num': 1, 'descr': 'seulement'}))
'Robot: Changer seulement une page.'
>>> # use format strings also outside
>>> str(i18n.twntranslate('fr', 'test-plural', 10) % {'descr': 'seulement'})
'Robot: Changer seulement quelques pages.'
The translations are retrieved from i18n.<package>, based on the callers
import table.
@param code: The language code
@param twtitle: The TranslateWiki string title, in <package>-<key> format
@param parameters: For passing (plural) parameters.
"""
# If a site is given instead of a code, use its language
if hasattr(code, 'code'):
code = code.code
# we send the code via list and get the alternate code back
code = [code]
trans = twtranslate(code, twtitle)
# get the alternate language code modified by twtranslate
lang = code.pop()
# check for PLURAL variants
trans = _extract_plural(lang, trans, parameters)
# we always have a dict for replacement of translatewiki messages
if parameters and isinstance(parameters, dict):
try:
return trans % parameters
except KeyError:
# parameter is for PLURAL variants only, don't change the string
pass
return trans
def twhas_key(code, twtitle):
"""
Check if a message has a translation in the specified language code.
The translations are retrieved from i18n.<package>, based on the callers
import table.
No code fallback is made.
@param code: The language code
@param twtitle: The TranslateWiki string title, in <package>-<key> format
"""
# If a site is given instead of a code, use its language
if hasattr(code, 'code'):
code = code.code
transdict = _get_translation(code, twtitle)
if transdict is None:
return False
return True
def twget_keys(twtitle):
"""
Return all language codes for a special message.
@param twtitle: The TranslateWiki string title, in <package>-<key> format
"""
# obtain the directory containing all the json files for this package
package = twtitle.split("-")[0]
mod = __import__(_messages_package_name, fromlist=[str('__file__')])
pathname = os.path.join(os.path.dirname(mod.__file__), package)
# build a list of languages in that directory
langs = [filename.partition('.')[0]
for filename in sorted(os.listdir(pathname))
if filename.endswith('.json')]
# exclude languages does not have this specific message in that package
# i.e. an incomplete set of translated messages.
return [lang for lang in langs
if lang != 'qqq' and
_get_translation(lang, twtitle)]
def input(twtitle, parameters=None, password=False, fallback_prompt=None):
"""
Ask the user a question, return the user's answer.
The prompt message is retrieved via L{twtranslate} and either uses the
config variable 'userinterface_lang' or the default locale as the language
code.
@param twtitle: The TranslateWiki string title, in <package>-<key> format
@param parameters: The values which will be applied to the translated text
@param password: Hides the user's input (for password entry)
@param fallback_prompt: The English prompt if i18n is not available.
@rtype: unicode string
"""
if not messages_available():
if not fallback_prompt:
raise TranslationError(
'Unable to load messages package %s for bundle %s'
% (_messages_package_name, twtitle))
else:
prompt = fallback_prompt
else:
code = config.userinterface_lang or \
locale.getdefaultlocale()[0].split('_')[0]
prompt = twtranslate(code, twtitle, parameters)
return pywikibot.input(prompt, password)
| emijrp/pywikibot-core | pywikibot/i18n.py | Python | mit | 21,745 |
/*
* Copyright (c) 2015 by Rafael Angel Aznar Aparici (rafaaznar at gmail dot com)
*
* sisane: The stunning micro-library that helps you to develop easily
* AJAX web applications by using Angular.js 1.x & sisane-server
* sisane is distributed under the MIT License (MIT)
* Sources at https://github.com/rafaelaznar/
*
* 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.
*
*/
'use strict';
moduloEpisodio.controller('EpisodioViewpopController', ['$scope', '$routeParams', 'serverService', 'episodioService', '$location', '$uibModalInstance', 'id',
function ($scope, $routeParams, serverService, episodioService, $location, $uibModalInstance, id) {
$scope.fields = episodioService.getFields();
$scope.obtitle = episodioService.getObTitle();
$scope.icon = episodioService.getIcon();
$scope.ob = episodioService.getTitle();
$scope.title = "Vista de " + $scope.obtitle;
$scope.id = id;
$scope.status = null;
$scope.debugging = serverService.debugging();
serverService.promise_getOne($scope.ob, $scope.id).then(function (response) {
if (response.status == 200) {
if (response.data.status == 200) {
$scope.status = null;
$scope.bean = response.data.message;
var filter = "and,id_medico,equa," + $scope.bean.obj_medico.id;
serverService.promise_getPage("usuario", 1, 1, filter).then(function (data) {
if (data.data.message.length > 0)
$scope.medico = data.data.message[0];
});
} else {
$scope.status = "Error en la recepción de datos del servidor";
}
} else {
$scope.status = "Error en la recepción de datos del servidor";
}
}).catch(function (data) {
$scope.status = "Error en la recepción de datos del servidor";
});
$scope.cancel = function () {
$uibModalInstance.dismiss('cancel');
}
}]); | Ecoivan/sisane-client | public_html/js/episodio/viewpop.js | JavaScript | mit | 3,146 |
'use strict';
var path = require('path');
var gulp = require('gulp');
var conf = require('./conf');
var browserSync = require('browser-sync');
function isOnlyChange(event) {
return event.type === 'changed';
}
gulp.task('watch', ['inject'], function () {
gulp.watch([path.join(conf.paths.src, '/*.html'), 'bower.json'], ['inject']);
gulp.watch([
path.join(conf.paths.src, '/assets/styles/css/**/*.css'),
path.join(conf.paths.src, '/assets/styles/less/**/*.less')
], function(event) {
if(isOnlyChange(event)) {
gulp.start('own-styles');
} else {
gulp.start('inject');
}
});
gulp.watch([
path.join(conf.paths.src, '/app/**/*.css'),
path.join(conf.paths.src, '/app/**/*.less')
], function(event) {
if(isOnlyChange(event)) {
gulp.start('styles');
} else {
gulp.start('inject');
}
});
gulp.watch(path.join(conf.paths.src, '/app/**/*.js'), function(event) {
if(isOnlyChange(event)) {
gulp.start('scripts');
} else {
gulp.start('inject');
}
});
gulp.watch(path.join(conf.paths.src, '/app/**/*.html'), function(event) {
browserSync.reload(event.path);
});
});
| devmark/laravel-angular-cms | backend/gulp/watch.js | JavaScript | mit | 1,176 |
<?php
/**
* @copyright Copyright (c) 2018 Robin Appelman <robin@icewind.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace Icewind\SMB;
use Icewind\SMB\Exception\DependencyException;
use Icewind\SMB\Exception\Exception;
/**
* Use existing kerberos ticket to authenticate and reuse the apache ticket cache (mod_auth_kerb)
*/
class KerberosApacheAuth extends KerberosAuth implements IAuth {
/** @var string */
private $ticketPath = "";
/** @var bool */
private $init = false;
/** @var string|false */
private $ticketName;
public function __construct() {
$this->ticketName = getenv("KRB5CCNAME");
}
/**
* Copy the ticket to a temporary location and use that ticket for authentication
*
* @return void
*/
public function copyTicket(): void {
if (!$this->checkTicket()) {
return;
}
$krb5 = new \KRB5CCache();
$krb5->open($this->ticketName);
$tmpFilename = tempnam("/tmp", "krb5cc_php_");
$tmpCacheFile = "FILE:" . $tmpFilename;
$krb5->save($tmpCacheFile);
$this->ticketPath = $tmpFilename;
$this->ticketName = $tmpCacheFile;
}
/**
* Pass the ticket to smbclient by memory instead of path
*
* @return void
*/
public function passTicketFromMemory(): void {
if (!$this->checkTicket()) {
return;
}
$krb5 = new \KRB5CCache();
$krb5->open($this->ticketName);
$this->ticketName = (string)$krb5->getName();
}
/**
* Check if a valid kerberos ticket is present
*
* @return bool
* @psalm-assert-if-true string $this->ticketName
*/
public function checkTicket(): bool {
//read apache kerberos ticket cache
if (!$this->ticketName) {
return false;
}
$krb5 = new \KRB5CCache();
$krb5->open($this->ticketName);
/** @psalm-suppress MixedArgument */
return count($krb5->getEntries()) > 0;
}
private function init(): void {
if ($this->init) {
return;
}
$this->init = true;
// inspired by https://git.typo3.org/TYPO3CMS/Extensions/fal_cifs.git
if (!extension_loaded("krb5")) {
// https://pecl.php.net/package/krb5
throw new DependencyException('Ensure php-krb5 is installed.');
}
//read apache kerberos ticket cache
if (!$this->checkTicket()) {
throw new Exception('No kerberos ticket cache environment variable (KRB5CCNAME) found.');
}
// note that even if the ticketname is the value we got from `getenv("KRB5CCNAME")` we still need to set the env variable ourselves
// this is because `getenv` also reads the variables passed from the SAPI (apache-php) and we need to set the variable in the OS's env
putenv("KRB5CCNAME=" . $this->ticketName);
}
public function getExtraCommandLineArguments(): string {
$this->init();
return parent::getExtraCommandLineArguments();
}
public function setExtraSmbClientOptions($smbClientState): void {
$this->init();
try {
parent::setExtraSmbClientOptions($smbClientState);
} catch (Exception $e) {
// suppress
}
}
public function __destruct() {
if (!empty($this->ticketPath) && file_exists($this->ticketPath) && is_file($this->ticketPath)) {
unlink($this->ticketPath);
}
}
}
| icewind1991/SMB | src/KerberosApacheAuth.php | PHP | mit | 3,766 |
require "heroku/command/base"
require "base64"
require "excon"
# manage organization accounts
#
class Heroku::Command::Orgs < Heroku::Command::Base
# orgs
#
# lists the orgs that you are a member of.
#
#
def index
response = org_api.get_orgs.body
orgs = []
response.fetch('organizations', []).each do |org|
orgs << org
org.fetch('child_orgs', []).each do |child|
orgs << child
end
end
default = response['user']['default_organization'] || ""
orgs.map! do |org|
name = org["organization_name"]
t = []
t << org["role"]
t << 'default' if name == default
[name, t.join(', ')]
end
if orgs.empty?
display("You are not a member of any organizations.")
else
styled_array(orgs)
end
end
# orgs:open --org ORG
#
# opens the org interface in a browser
#
#
def open
launchy("Opening web interface for #{org}", "https://dashboard.heroku.com/orgs/#{org}/apps")
end
# orgs:default [TARGET]
#
# sets the default org.
# TARGET can be an org you belong to or it can be "personal"
# for your personal account. If no argument or option is given,
# the default org is displayed
#
#
def default
options[:ignore_no_org] = true
if target = shift_argument
options[:org] = target
end
if org == "personal" || options[:personal]
action("Setting personal account as default") do
org_api.remove_default_org
end
elsif org && !options[:using_default_org]
action("Setting #{org} as the default organization") do
org_api.set_default_org(org)
end
elsif org
display("#{org} is the default organization.")
else
display("Personal account is default.")
end
end
end
| soilforlifeforms/forms | vendor/bundle/ruby/2.0.0/gems/heroku-3.3.0/lib/heroku/command/orgs.rb | Ruby | mit | 1,786 |
var assert = require('assert');
var _ = require('@sailshq/lodash');
var SchemaBuilder = require('../lib/waterline-schema');
describe('Has Many Through :: ', function() {
describe('Junction Tables', function() {
var schema;
before(function() {
var fixtures = [
{
identity: 'user',
primaryKey: 'id',
attributes: {
id: {
type: 'number'
},
cars: {
collection: 'car',
through: 'drive',
via: 'user'
}
}
},
{
identity: 'drive',
primaryKey: 'id',
attributes: {
id: {
type: 'number'
},
car: {
model: 'car'
},
user: {
model: 'user'
}
}
},
{
identity: 'car',
primaryKey: 'id',
attributes: {
id: {
type: 'number'
},
drivers: {
collection: 'user',
through: 'drive',
via: 'car'
}
}
}
];
var collections = _.map(fixtures, function(obj) {
var collection = function() {};
collection.prototype = obj;
return collection;
});
// Build the schema
schema = SchemaBuilder(collections);
});
it('should flag the "through" table and not mark it as a junction table', function() {
assert(schema.drive);
assert(!schema.drive.junctionTable);
assert(schema.drive.throughTable);
});
});
describe('Reference Mapping', function() {
var schema;
before(function() {
var fixtures = [
{
identity: 'foo',
primaryKey: 'id',
attributes: {
id: {
type: 'number'
},
bars: {
collection: 'bar',
through: 'foobar',
via: 'foo'
}
}
},
{
identity: 'foobar',
primaryKey: 'id',
attributes: {
id: {
type: 'number'
},
type: {
type: 'string'
},
foo: {
model: 'foo',
columnName: 'foo_id'
},
bar: {
model: 'bar',
columnName: 'bar_id'
}
}
},
{
identity: 'bar',
primaryKey: 'id',
attributes: {
id: {
type: 'number'
},
foo: {
collection: 'foo',
through: 'foobar',
via: 'bar'
}
}
}
];
var collections = _.map(fixtures, function(obj) {
var collection = function() {};
collection.prototype = obj;
return collection;
});
// Build the schema
schema = SchemaBuilder(collections);
});
it('should update the parent collection to point to the join table', function() {
assert.equal(schema.foo.schema.bars.references, 'foobar');
assert.equal(schema.foo.schema.bars.on, 'foo_id');
});
});
});
| jhelbig/postman-linux-app | app/resources/app/node_modules/waterline-schema/test/hasManyThrough.js | JavaScript | mit | 3,283 |
package sacloud
// IPv6Addr IPアドレス(IPv6)
type IPv6Addr struct {
HostName string `json:",omitempty"` // ホスト名
IPv6Addr string `json:",omitempty"` // IPv6アドレス
Interface *Interface `json:",omitempty"` // インターフェース
IPv6Net *IPv6Net `json:",omitempty"` // IPv6サブネット
}
// GetIPv6NetID IPv6アドレスが所属するIPv6NetのIDを取得
func (a *IPv6Addr) GetIPv6NetID() int64 {
if a.IPv6Net != nil {
return a.IPv6Net.ID
}
return 0
}
// GetInternetID IPv6アドレスを所有するルータ+スイッチ(Internet)のIDを取得
func (a *IPv6Addr) GetInternetID() int64 {
if a.IPv6Net != nil && a.IPv6Net.Switch != nil && a.IPv6Net.Switch.Internet != nil {
return a.IPv6Net.Switch.Internet.ID
}
return 0
}
// CreateNewIPv6Addr IPv6アドレス作成
func CreateNewIPv6Addr() *IPv6Addr {
return &IPv6Addr{
IPv6Net: &IPv6Net{
Resource: &Resource{},
},
}
}
| aantono/traefik | vendor/github.com/sacloud/libsacloud/sacloud/ipv6addr.go | GO | mit | 939 |
using System;
using System.Runtime.InteropServices;
using Duality;
using Duality.Drawing;
using Duality.Resources;
namespace DynamicLighting
{
[StructLayout(LayoutKind.Sequential)]
public struct VertexC1P3T2A4 : IVertexData
{
public static readonly VertexDeclaration Declaration = VertexDeclaration.Get<VertexC1P3T2A4>();
[VertexElement(VertexElementRole.Color)]
public ColorRgba Color;
[VertexElement(VertexElementRole.Position)]
public Vector3 Pos;
[VertexElement(VertexElementRole.TexCoord)]
public Vector2 TexCoord;
public Vector4 Attrib;
// Add Vector3 for lighting world position, see note in Light.cs
Vector3 IVertexData.Pos
{
get { return this.Pos; }
set { this.Pos = value; }
}
ColorRgba IVertexData.Color
{
get { return this.Color; }
set { this.Color = value; }
}
VertexDeclaration IVertexData.Declaration
{
get { return Declaration; }
}
}
}
| RockyTV/duality | Samples/DynamicLighting/Core/VertexC1P3T2A4.cs | C# | mit | 914 |
package engine.actions;
import engine.gameObject.GameObject;
import authoring.model.collections.GameObjectsCollection;
public class FixedCollisionTypeAction extends PhysicsTypeAction {
public FixedCollisionTypeAction (String type, String secondType, Double value) {
super(type, secondType, value);
// TODO Auto-generated constructor stub
}
@Override
public void applyPhysics (GameObjectsCollection myObjects) {
GameObject firstCollisionObject = null;
GameObject secondCollisionObject = null;
for (GameObject g : myObjects){
if (g.getIdentifier().getType().equals(myType) && g.isCollisionEnabled()){
firstCollisionObject = g;
}
if (g.getIdentifier().getType().equals(mySecondType) && g.isCollisionEnabled()){
secondCollisionObject = g;
}
}
myCollision.fixedCollision(firstCollisionObject, secondCollisionObject);
}
}
| goose2460/game_author_cs308 | src/engine/actions/FixedCollisionTypeAction.java | Java | mit | 989 |
<?php
phpinfo(); | u8lvavhel/lemp-base-docker | www/index.php | PHP | mit | 18 |
module('lively.ide.DirectoryWatcher').requires('lively.Network').toRun(function() {
// depends on the DirectoryWatcherServer
Object.extend(lively.ide.DirectoryWatcher, {
watchServerURL: new URL(Config.nodeJSURL+'/DirectoryWatchServer/'),
dirs: {},
reset: function() {
// lively.ide.DirectoryWatcher.reset()
this.dirs = {};
this.watchServerURL.withFilename('reset').asWebResource().post();
},
request: function(url, thenDo) {
return url.asWebResource().beAsync().withJSONWhenDone(function(json, status) {
thenDo(!json || json.error, json); }).get();
},
getFiles: function(dir, thenDo) {
this.request(this.watchServerURL.withFilename('files').withQuery({dir: dir}), thenDo);
},
getChanges: function(dir, since, startWatchTime, thenDo) {
this.request(this.watchServerURL.withFilename('changes').withQuery({
startWatchTime: startWatchTime, since: since, dir: dir}), thenDo);
},
withFilesOfDir: function(dir, doFunc) {
// Retrieves efficiently the files of dir. Uses a server side watcher that
// sends infos about file changes, deletions, creations.
// This methods synchs those with the cached state held in this object
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// dir = lively.shell.exec('pwd', {sync:true}).resultString()
// lively.ide.DirectoryWatcher.dirs
// lively.ide.DirectoryWatcher.withFilesOfDir(dir, function(files) { show(Object.keys(files).length); })
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
var watchState = this.dirs[dir] || (this.dirs[dir] = {updateInProgress: false, callbacks: []});
doFunc && watchState.callbacks.push(doFunc);
if (watchState.updateInProgress) { return; }
watchState.updateInProgress = true;
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
if (!watchState.files) { // first time called
this.getFiles(dir, function(err, result) {
if (err) show("dir watch error: %s", err);
result.files && Properties.forEachOwn(result.files, function(path, stat) { extend(stat); })
Object.extend(watchState, {
files: result.files,
lastUpdated: result.startTime,
startTime: result.startTime
});
whenDone();
});
return;
}
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
var timeSinceLastUpdate = Date.now() - (watchState.lastUpdated || 0);
if (timeSinceLastUpdate < 10 * 1000) { whenDone(); } // recently updated
// get updates
this.getChanges(dir, watchState.lastUpdated, watchState.startTime, function(err, result) {
if (!result.changes || result.changes.length === 0) { whenDone(); return; }
watchState.lastUpdated = result.changes[0].time;
console.log('%s files changed in %s: %s', result.changes.length, dir, result.changes.pluck('path').join('\n'));
result.changes.forEach(function(change) {
switch (change.type) {
case 'removal': delete watchState.files[change.path]; break;
case 'creation': case 'change': watchState.files[change.path] = extend(change.stat); break;
}
});
whenDone();
});
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
function whenDone() {
watchState.updateInProgress = false;
var cb;
while ((cb = watchState.callbacks.shift())) cb(watchState.files);
}
function extend(statObj) { // convert date string into a date object
if (!statObj) statObj = {};
statObj.isDirectory = !!(statObj.mode & 0x4000);
['atime', 'mtime', 'ctime'].forEach(function(field) {
if (statObj[field]) statObj[field] = new Date(statObj[field]); });
return statObj;
}
}
});
}) // end of module
| pascience/LivelyKernel | core/lively/ide/DirectoryWatcher.js | JavaScript | mit | 4,138 |
// Generated by CoffeeScript 1.3.1
| trela/qikify | qikify/views/resources/scripts/js/statistics.js | JavaScript | mit | 37 |
package com.jvm_bloggers.core.data_fetching.blog_posts;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.routing.RoundRobinPool;
import com.jvm_bloggers.core.data_fetching.blogs.PreventConcurrentExecutionSafeguard;
import com.jvm_bloggers.core.rss.SyndFeedProducer;
import com.jvm_bloggers.entities.blog.Blog;
import com.jvm_bloggers.entities.blog.BlogRepository;
import com.jvm_bloggers.entities.metadata.Metadata;
import com.jvm_bloggers.entities.metadata.MetadataKeys;
import com.jvm_bloggers.entities.metadata.MetadataRepository;
import com.jvm_bloggers.utils.NowProvider;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
@Component
@NoArgsConstructor
public class BlogPostsFetcher {
private BlogRepository blogRepository;
private ActorRef rssCheckingActor;
private MetadataRepository metadataRepository;
private NowProvider nowProvider;
private PreventConcurrentExecutionSafeguard concurrentExecutionSafeguard
= new PreventConcurrentExecutionSafeguard();
@Autowired
public BlogPostsFetcher(ActorSystem actorSystem, BlogRepository blogRepository,
BlogPostService blogPostService,
SyndFeedProducer syndFeedFactory,
MetadataRepository metadataRepository,
NowProvider nowProvider) {
this.blogRepository = blogRepository;
final ActorRef blogPostStoringActor = actorSystem
.actorOf(NewBlogPostStoringActor.props(blogPostService));
rssCheckingActor = actorSystem.actorOf(new RoundRobinPool(10)
.props(RssCheckingActor.props(blogPostStoringActor, syndFeedFactory)), "rss-checkers");
this.metadataRepository = metadataRepository;
this.nowProvider = nowProvider;
}
void refreshPosts() {
concurrentExecutionSafeguard.preventConcurrentExecution(this::startFetchingProcess);
}
@Async("singleThreadExecutor")
public void refreshPostsAsynchronously() {
refreshPosts();
}
private Void startFetchingProcess() {
blogRepository.findAllActiveBlogs()
.filter(Blog::isActive)
.forEach(person -> rssCheckingActor.tell(new RssLink(person), ActorRef.noSender()));
final Metadata dateOfLastFetch = metadataRepository
.findByName(MetadataKeys.DATE_OF_LAST_FETCHING_BLOG_POSTS);
dateOfLastFetch.setValue(nowProvider.now().toString());
metadataRepository.save(dateOfLastFetch);
return null;
}
public boolean isFetchingProcessInProgress() {
return concurrentExecutionSafeguard.isExecuting();
}
}
| jvm-bloggers/jvm-bloggers | src/main/java/com/jvm_bloggers/core/data_fetching/blog_posts/BlogPostsFetcher.java | Java | mit | 2,766 |
'use strict';
require('../common');
// This test ensures that zlib throws a RangeError if the final buffer needs to
// be larger than kMaxLength and concatenation fails.
// https://github.com/nodejs/node/pull/1811
const assert = require('assert');
// Change kMaxLength for zlib to trigger the error without having to allocate
// large Buffers.
const buffer = require('buffer');
const oldkMaxLength = buffer.kMaxLength;
buffer.kMaxLength = 64;
const zlib = require('zlib');
buffer.kMaxLength = oldkMaxLength;
const encoded = Buffer.from('G38A+CXCIrFAIAM=', 'base64');
// Async
zlib.brotliDecompress(encoded, function(err) {
assert.ok(err instanceof RangeError);
});
// Sync
assert.throws(function() {
zlib.brotliDecompressSync(encoded);
}, RangeError);
| enclose-io/compiler | current/test/parallel/test-zlib-brotli-kmaxlength-rangeerror.js | JavaScript | mit | 762 |
const {createAddColumnMigration} = require('../../utils');
module.exports = createAddColumnMigration('posts_meta', 'email_only', {
type: 'bool',
nullable: false,
defaultTo: false
});
| ErisDS/Ghost | core/server/data/migrations/versions/4.12/01-add-email-only-column-to-posts-meta-table.js | JavaScript | mit | 196 |
import { EventsKey } from '../events';
import BaseEvent from '../events/Event';
import { Extent } from '../extent';
import Feature from '../Feature';
import Geometry from '../geom/Geometry';
import Point from '../geom/Point';
import { ObjectEvent } from '../Object';
import Projection from '../proj/Projection';
import { AttributionLike } from './Source';
import VectorSource, { VectorSourceEvent } from './Vector';
export interface Options {
attributions?: AttributionLike;
distance?: number;
geometryFunction?: (p0: Feature<Geometry>) => Point;
source?: VectorSource<Geometry>;
wrapX?: boolean;
}
export default class Cluster extends VectorSource {
constructor(options: Options);
protected distance: number;
protected features: Feature<Geometry>[];
protected geometryFunction: (feature: Feature<Geometry>) => Point;
protected resolution: number;
protected cluster(): void;
protected createCluster(features: Feature<Geometry>[]): Feature<Geometry>;
/**
* Remove all features from the source.
*/
clear(opt_fast?: boolean): void;
/**
* Get the distance in pixels between clusters.
*/
getDistance(): number;
getResolutions(): number[] | undefined;
/**
* Get a reference to the wrapped source.
*/
getSource(): VectorSource<Geometry>;
loadFeatures(extent: Extent, resolution: number, projection: Projection): void;
/**
* Handle the source changing.
*/
refresh(): void;
/**
* Set the distance in pixels between clusters.
*/
setDistance(distance: number): void;
/**
* Replace the wrapped source.
*/
setSource(source: VectorSource<Geometry>): void;
on(type: string | string[], listener: (p0: any) => any): EventsKey | EventsKey[];
once(type: string | string[], listener: (p0: any) => any): EventsKey | EventsKey[];
un(type: string | string[], listener: (p0: any) => any): void;
on(type: 'addfeature', listener: (evt: VectorSourceEvent<Geometry>) => void): EventsKey;
once(type: 'addfeature', listener: (evt: VectorSourceEvent<Geometry>) => void): EventsKey;
un(type: 'addfeature', listener: (evt: VectorSourceEvent<Geometry>) => void): void;
on(type: 'change', listener: (evt: BaseEvent) => void): EventsKey;
once(type: 'change', listener: (evt: BaseEvent) => void): EventsKey;
un(type: 'change', listener: (evt: BaseEvent) => void): void;
on(type: 'changefeature', listener: (evt: VectorSourceEvent<Geometry>) => void): EventsKey;
once(type: 'changefeature', listener: (evt: VectorSourceEvent<Geometry>) => void): EventsKey;
un(type: 'changefeature', listener: (evt: VectorSourceEvent<Geometry>) => void): void;
on(type: 'clear', listener: (evt: VectorSourceEvent<Geometry>) => void): EventsKey;
once(type: 'clear', listener: (evt: VectorSourceEvent<Geometry>) => void): EventsKey;
un(type: 'clear', listener: (evt: VectorSourceEvent<Geometry>) => void): void;
on(type: 'error', listener: (evt: BaseEvent) => void): EventsKey;
once(type: 'error', listener: (evt: BaseEvent) => void): EventsKey;
un(type: 'error', listener: (evt: BaseEvent) => void): void;
on(type: 'featuresloadend', listener: (evt: VectorSourceEvent<Geometry>) => void): EventsKey;
once(type: 'featuresloadend', listener: (evt: VectorSourceEvent<Geometry>) => void): EventsKey;
un(type: 'featuresloadend', listener: (evt: VectorSourceEvent<Geometry>) => void): void;
on(type: 'featuresloaderror', listener: (evt: VectorSourceEvent<Geometry>) => void): EventsKey;
once(type: 'featuresloaderror', listener: (evt: VectorSourceEvent<Geometry>) => void): EventsKey;
un(type: 'featuresloaderror', listener: (evt: VectorSourceEvent<Geometry>) => void): void;
on(type: 'featuresloadstart', listener: (evt: VectorSourceEvent<Geometry>) => void): EventsKey;
once(type: 'featuresloadstart', listener: (evt: VectorSourceEvent<Geometry>) => void): EventsKey;
un(type: 'featuresloadstart', listener: (evt: VectorSourceEvent<Geometry>) => void): void;
on(type: 'propertychange', listener: (evt: ObjectEvent) => void): EventsKey;
once(type: 'propertychange', listener: (evt: ObjectEvent) => void): EventsKey;
un(type: 'propertychange', listener: (evt: ObjectEvent) => void): void;
on(type: 'removefeature', listener: (evt: VectorSourceEvent<Geometry>) => void): EventsKey;
once(type: 'removefeature', listener: (evt: VectorSourceEvent<Geometry>) => void): EventsKey;
un(type: 'removefeature', listener: (evt: VectorSourceEvent<Geometry>) => void): void;
}
| georgemarshall/DefinitelyTyped | types/ol/source/Cluster.d.ts | TypeScript | mit | 4,599 |
<?php
require_once($argv[1]); // type.php
require_once($argv[2]); // program.php
$file_prefix = $argv[3];
?>
[apps..default]
run = true
count = 1
network.server.0.RPC_CHANNEL_TCP = NET_HDR_HTTP, dsn::tools::asio_network_provider, 65536
[apps.server]
name = server
type = server
arguments =
ports = 27001
run = true
pools = THREAD_POOL_DEFAULT
[apps.client]
name = client
type = client
arguments = localhost 27001
count = 0
run = true
pools = THREAD_POOL_DEFAULT
<?php foreach ($_PROG->services as $svc) { ?>
[apps.client.perf.<?=$svc->name?>]
name = client.perf.<?=$svc->name?>
type = client.perf.<?=$svc->name?>
arguments = localhost 27001
count = 1
run = false
<?php } ?>
[core]
;tool = simulator
tool = nativerun
;toollets = tracer
;toollets = tracer, profiler, fault_injector
pause_on_start = false
logging_factory_name = dsn::tools::screen_logger
[tools.simulator]
random_seed = 0
[network]
; how many network threads for network library(used by asio)
io_service_worker_count = 2
; specification for each thread pool
[threadpool..default]
[threadpool.THREAD_POOL_DEFAULT]
name = default
partitioned = false
worker_count = 1
max_input_queue_length = 1024
worker_priority = THREAD_xPRIORITY_NORMAL
[task..default]
is_trace = true
is_profile = true
allow_inline = false
rpc_call_channel = RPC_CHANNEL_TCP
fast_execution_in_network_thread = false
rpc_call_header_format_name = dsn
rpc_timeout_milliseconds = 5000
perf_test_rounds = 10000
rpc_call_header_format = NET_HDR_HTTP
[task.LPC_AIO_IMMEDIATE_CALLBACK]
is_trace = false
is_profile = false
allow_inline = false
[task.LPC_RPC_TIMEOUT]
is_trace = false
is_profile = false
| glglwty/rDSN | bin/dsn.templates/js/single/config.ini.php | PHP | mit | 1,649 |