repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
dgoodwin/origin
vendor/k8s.io/kubernetes/pkg/kubelet/cm/container_manager.go
5313
/* Copyright 2015 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 cm import ( "time" "k8s.io/apimachinery/pkg/util/sets" // TODO: Migrate kubelet to either use its own internal objects or client library. "k8s.io/api/core/v1" internalapi "k8s.io/kubernetes/pkg/kubelet/apis/cri" "k8s.io/kubernetes/pkg/kubelet/apis/kubeletconfig" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" evictionapi "k8s.io/kubernetes/pkg/kubelet/eviction/api" "k8s.io/kubernetes/pkg/kubelet/status" "fmt" "strconv" "strings" ) type ActivePodsFunc func() []*v1.Pod // Manages the containers running on a machine. type ContainerManager interface { // Runs the container manager's housekeeping. // - Ensures that the Docker daemon is in a container. // - Creates the system container where all non-containerized processes run. Start(*v1.Node, ActivePodsFunc, status.PodStatusProvider, internalapi.RuntimeService) error // Returns resources allocated to system cgroups in the machine. // These cgroups include the system and Kubernetes services. SystemCgroupsLimit() v1.ResourceList // Returns a NodeConfig that is being used by the container manager. GetNodeConfig() NodeConfig // Returns internal Status. Status() Status // NewPodContainerManager is a factory method which returns a podContainerManager object // Returns a noop implementation if qos cgroup hierarchy is not enabled NewPodContainerManager() PodContainerManager // GetMountedSubsystems returns the mounted cgroup subsystems on the node GetMountedSubsystems() *CgroupSubsystems // GetQOSContainersInfo returns the names of top level QoS containers GetQOSContainersInfo() QOSContainersInfo // GetNodeAllocatable returns the amount of compute resources that have to be reserved from scheduling. GetNodeAllocatableReservation() v1.ResourceList // GetCapacity returns the amount of compute resources tracked by container manager available on the node. GetCapacity() v1.ResourceList // UpdateQOSCgroups performs housekeeping updates to ensure that the top // level QoS containers have their desired state in a thread-safe way UpdateQOSCgroups() error // Returns RunContainerOptions with devices, mounts, and env fields populated for // extended resources required by container. GetResources(pod *v1.Pod, container *v1.Container, activePods []*v1.Pod) (*kubecontainer.RunContainerOptions, error) InternalContainerLifecycle() InternalContainerLifecycle } type NodeConfig struct { RuntimeCgroupsName string SystemCgroupsName string KubeletCgroupsName string ContainerRuntime string CgroupsPerQOS bool CgroupRoot string CgroupDriver string ProtectKernelDefaults bool NodeAllocatableConfig ExperimentalQOSReserved map[v1.ResourceName]int64 ExperimentalCPUManagerPolicy string ExperimentalCPUManagerReconcilePeriod time.Duration } type NodeAllocatableConfig struct { KubeReservedCgroupName string SystemReservedCgroupName string EnforceNodeAllocatable sets.String KubeReserved v1.ResourceList SystemReserved v1.ResourceList HardEvictionThresholds []evictionapi.Threshold } type Status struct { // Any soft requirements that were unsatisfied. SoftRequirements error } const ( // Uer visible keys for managing node allocatable enforcement on the node. NodeAllocatableEnforcementKey = "pods" SystemReservedEnforcementKey = "system-reserved" KubeReservedEnforcementKey = "kube-reserved" ) // containerManager for the kubelet is currently an injected dependency. // We need to parse the --qos-reserve-requests option in // cmd/kubelet/app/server.go and there isn't really a good place to put // the code. If/When the kubelet dependency injection gets worked out, // maybe there will be a better place for it. func parsePercentage(v string) (int64, error) { if !strings.HasSuffix(v, "%") { return 0, fmt.Errorf("percentage expected, got '%s'", v) } percentage, err := strconv.ParseInt(strings.TrimRight(v, "%"), 10, 0) if err != nil { return 0, fmt.Errorf("invalid number in percentage '%s'", v) } if percentage < 0 || percentage > 100 { return 0, fmt.Errorf("percentage must be between 0 and 100") } return percentage, nil } // ParseQOSReserved parses the --qos-reserve-requests option func ParseQOSReserved(m kubeletconfig.ConfigurationMap) (*map[v1.ResourceName]int64, error) { reservations := make(map[v1.ResourceName]int64) for k, v := range m { switch v1.ResourceName(k) { // Only memory resources are supported. case v1.ResourceMemory: q, err := parsePercentage(v) if err != nil { return nil, err } reservations[v1.ResourceName(k)] = q default: return nil, fmt.Errorf("cannot reserve %q resource", k) } } return &reservations, nil }
apache-2.0
adeelmahmood/ignite
modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheLifecycleAwareSelfTest.java
10413
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal.processors.cache; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.UUID; import javax.cache.Cache; import javax.cache.integration.CacheLoaderException; import org.apache.ignite.cache.CacheInterceptor; import org.apache.ignite.cache.CacheMode; import org.apache.ignite.cache.affinity.AffinityFunction; import org.apache.ignite.cache.affinity.AffinityFunctionContext; import org.apache.ignite.cache.affinity.AffinityKeyMapper; import org.apache.ignite.cache.eviction.EvictableEntry; import org.apache.ignite.cache.eviction.EvictionFilter; import org.apache.ignite.cache.eviction.EvictionPolicy; import org.apache.ignite.cache.store.CacheStore; import org.apache.ignite.cluster.ClusterNode; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.configuration.NearCacheConfiguration; import org.apache.ignite.lang.IgniteBiInClosure; import org.apache.ignite.lang.IgniteBiTuple; import org.apache.ignite.lifecycle.LifecycleAware; import org.apache.ignite.resources.CacheNameResource; import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi; import org.apache.ignite.testframework.junits.common.GridAbstractLifecycleAwareSelfTest; import org.jetbrains.annotations.Nullable; import static org.apache.ignite.cache.CacheMode.PARTITIONED; /** * Test for {@link LifecycleAware} support in {@link CacheConfiguration}. */ public class GridCacheLifecycleAwareSelfTest extends GridAbstractLifecycleAwareSelfTest { /** */ private static final String CACHE_NAME = "cache"; /** */ private boolean near; /** */ private boolean writeBehind; /** */ private static class TestStore implements CacheStore, LifecycleAware { /** */ private final TestLifecycleAware lifecycleAware = new TestLifecycleAware(CACHE_NAME); /** {@inheritDoc} */ @Override public void start() { lifecycleAware.start(); } /** {@inheritDoc} */ @Override public void stop() { lifecycleAware.stop(); } /** * @param cacheName Cache name. */ @CacheNameResource public void setCacheName(String cacheName) { lifecycleAware.cacheName(cacheName); } /** {@inheritDoc} */ @Nullable @Override public Object load(Object key) { return null; } /** {@inheritDoc} */ @Override public void loadCache(IgniteBiInClosure clo, @Nullable Object... args) { // No-op. } /** {@inheritDoc} */ @Override public Map loadAll(Iterable keys) throws CacheLoaderException { return Collections.emptyMap(); } /** {@inheritDoc} */ @Override public void write(Cache.Entry entry) { // No-op. } /** {@inheritDoc} */ @Override public void writeAll(Collection col) { // No-op. } /** {@inheritDoc} */ @Override public void delete(Object key) { // No-op. } /** {@inheritDoc} */ @Override public void deleteAll(Collection keys) { // No-op. } /** {@inheritDoc} */ @Override public void sessionEnd(boolean commit) { // No-op. } } /** */ public static class TestAffinityFunction extends TestLifecycleAware implements AffinityFunction { /** */ public TestAffinityFunction() { super(CACHE_NAME); } /** {@inheritDoc} */ @Override public void reset() { // No-op. } /** {@inheritDoc} */ @Override public int partitions() { return 1; } /** {@inheritDoc} */ @Override public int partition(Object key) { return 0; } /** {@inheritDoc} */ @Override public List<List<ClusterNode>> assignPartitions(AffinityFunctionContext affCtx) { List<List<ClusterNode>> res = new ArrayList<>(); res.add(nodes(0, affCtx.currentTopologySnapshot())); return res; } /** {@inheritDoc} */ public List<ClusterNode> nodes(int part, Collection<ClusterNode> nodes) { return new ArrayList<>(nodes); } /** {@inheritDoc} */ @Override public void removeNode(UUID nodeId) { // No-op. } } /** */ public static class TestEvictionPolicy extends TestLifecycleAware implements EvictionPolicy, Serializable { /** */ public TestEvictionPolicy() { super(CACHE_NAME); } /** {@inheritDoc} */ @Override public void onEntryAccessed(boolean rmv, EvictableEntry entry) { // No-op. } } /** */ private static class TestEvictionFilter extends TestLifecycleAware implements EvictionFilter { /** */ TestEvictionFilter() { super(CACHE_NAME); } /** {@inheritDoc} */ @Override public boolean evictAllowed(Cache.Entry entry) { return false; } } /** */ private static class TestAffinityKeyMapper extends TestLifecycleAware implements AffinityKeyMapper { /** */ TestAffinityKeyMapper() { super(CACHE_NAME); } /** {@inheritDoc} */ @Override public Object affinityKey(Object key) { return key; } /** {@inheritDoc} */ @Override public void reset() { // No-op. } } /** */ private static class TestInterceptor extends TestLifecycleAware implements CacheInterceptor { /** */ private TestInterceptor() { super(CACHE_NAME); } /** {@inheritDoc} */ @Nullable @Override public Object onGet(Object key, @Nullable Object val) { return val; } /** {@inheritDoc} */ @Nullable @Override public Object onBeforePut(Cache.Entry entry, Object newVal) { return newVal; } /** {@inheritDoc} */ @Override public void onAfterPut(Cache.Entry entry) { // No-op. } /** {@inheritDoc} */ @SuppressWarnings("unchecked") @Nullable @Override public IgniteBiTuple onBeforeRemove(Cache.Entry entry) { return new IgniteBiTuple(false, entry.getValue()); } /** {@inheritDoc} */ @Override public void onAfterRemove(Cache.Entry entry) { // No-op. } } /** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override protected final IgniteConfiguration getConfiguration(String gridName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(gridName); cfg.setDiscoverySpi(new TcpDiscoverySpi()); CacheConfiguration ccfg = defaultCacheConfiguration(); ccfg.setCacheMode(PARTITIONED); ccfg.setWriteBehindEnabled(writeBehind); ccfg.setCacheMode(CacheMode.PARTITIONED); ccfg.setName(CACHE_NAME); TestStore store = new TestStore(); ccfg.setCacheStoreFactory(singletonFactory(store)); ccfg.setReadThrough(true); ccfg.setWriteThrough(true); ccfg.setLoadPreviousValue(true); lifecycleAwares.add(store.lifecycleAware); TestAffinityFunction affinity = new TestAffinityFunction(); ccfg.setAffinity(affinity); lifecycleAwares.add(affinity); TestEvictionPolicy evictionPlc = new TestEvictionPolicy(); ccfg.setEvictionPolicy(evictionPlc); lifecycleAwares.add(evictionPlc); if (near) { TestEvictionPolicy nearEvictionPlc = new TestEvictionPolicy(); NearCacheConfiguration nearCfg = new NearCacheConfiguration(); nearCfg.setNearEvictionPolicy(nearEvictionPlc); ccfg.setNearConfiguration(nearCfg); lifecycleAwares.add(nearEvictionPlc); } TestEvictionFilter evictionFilter = new TestEvictionFilter(); ccfg.setEvictionFilter(evictionFilter); lifecycleAwares.add(evictionFilter); TestAffinityKeyMapper mapper = new TestAffinityKeyMapper(); ccfg.setAffinityMapper(mapper); lifecycleAwares.add(mapper); TestInterceptor interceptor = new TestInterceptor(); lifecycleAwares.add(interceptor); ccfg.setInterceptor(interceptor); cfg.setCacheConfiguration(ccfg); return cfg; } /** {@inheritDoc} */ @SuppressWarnings("ErrorNotRethrown") @Override public void testLifecycleAware() throws Exception { for (boolean nearEnabled : new boolean[] {true, false}) { near = nearEnabled; writeBehind = false; try { super.testLifecycleAware(); } catch (AssertionError e) { throw new AssertionError("Failed for [near=" + near + ", writeBehind=" + writeBehind + ']', e); } writeBehind = true; try { super.testLifecycleAware(); } catch (AssertionError e) { throw new AssertionError("Failed for [near=" + near + ", writeBehind=" + writeBehind + ']', e); } } } }
apache-2.0
tejima/OP3PKG
lib/vendor/PEAR/Net/UserAgent/Mobile/Error.php
2855
<?php /* vim: set expandtab tabstop=4 shiftwidth=4: */ /** * PHP versions 4 and 5 * * Copyright (c) 2009 KUBO Atsuhiro <[email protected]>, * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. * * @category Networking * @package Net_UserAgent_Mobile * @author KUBO Atsuhiro <[email protected]> * @copyright 2009 KUBO Atsuhiro <[email protected]> * @license http://www.opensource.org/licenses/bsd-license.php New BSD License * @version CVS: $Id: Error.php,v 1.1 2009/05/26 08:48:16 kuboa Exp $ * @since File available since Release 1.0.0RC3 */ require_once 'PEAR.php'; // {{{ constants /** * Constants for error handling. */ define('NET_USERAGENT_MOBILE_OK', 1); define('NET_USERAGENT_MOBILE_ERROR', -1); define('NET_USERAGENT_MOBILE_ERROR_NOMATCH', -2); define('NET_USERAGENT_MOBILE_ERROR_NOT_FOUND', -3); // }}} // {{{ Net_UserAgent_Mobile_Error /** * Net_UserAgent_Mobile_Error implements a class for reporting user agent error * messages * * @category Networking * @package Net_UserAgent_Mobile * @author KUBO Atsuhiro <[email protected]> * @copyright 2003-2009 KUBO Atsuhiro <[email protected]> * @license http://www.opensource.org/licenses/bsd-license.php New BSD License * @version Release: 1.0.0 * @since Class available since Release 0.1 */ class Net_UserAgent_Mobile_Error extends PEAR_Error {} // }}} /* * Local Variables: * mode: php * coding: iso-8859-1 * tab-width: 4 * c-basic-offset: 4 * c-hanging-comment-ender-p: nil * indent-tabs-mode: nil * End: */
apache-2.0
zdary/intellij-community
python/testData/formatter/multilineIfConditionComplex_after.py
151
a = b = c = 0 if (a and b and c or a and b or a or a and b or a and b and c or a and b or a): pass
apache-2.0
aki77/homebrew-cask
Casks/dbeaver-enterprise.rb
549
cask :v1 => 'dbeaver-enterprise' do version '3.4.2' if Hardware::CPU.is_32_bit? sha256 '2f5db0d7341ae96ccda9d0307c3609fe294effcbd4ac97202f13237c3715a8e4' url "http://dbeaver.jkiss.org/files/dbeaver-#{version}-ee-macosx.cocoa.x86.zip" else sha256 '3bf71701d6a75d15044df61d3274fe0603334559031ec2614b7492e694bf7c6c' url "http://dbeaver.jkiss.org/files/dbeaver-#{version}-ee-macosx.cocoa.x86_64.zip" end name 'DBeaver Enterprise Edition' homepage 'http://dbeaver.jkiss.org/' license :oss app 'dbeaver/dbeaver.app' end
bsd-2-clause
MIPS/external-chromium_org
chrome/browser/themes/theme_syncable_service.cc
13037
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/themes/theme_syncable_service.h" #include "base/strings/stringprintf.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_system.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/themes/theme_service.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/extensions/manifest_url_handler.h" #include "chrome/common/extensions/sync_helper.h" #include "sync/protocol/sync.pb.h" #include "sync/protocol/theme_specifics.pb.h" using std::string; namespace { bool IsTheme(const extensions::Extension* extension) { return extension->is_theme(); } // TODO(akalin): Remove this. bool IsSystemThemeDistinctFromDefaultTheme() { #if defined(TOOLKIT_GTK) return true; #else return false; #endif } } // namespace const char ThemeSyncableService::kCurrentThemeClientTag[] = "current_theme"; const char ThemeSyncableService::kCurrentThemeNodeTitle[] = "Current Theme"; ThemeSyncableService::ThemeSyncableService(Profile* profile, ThemeService* theme_service) : profile_(profile), theme_service_(theme_service), use_system_theme_by_default_(false) { DCHECK(profile_); DCHECK(theme_service_); } ThemeSyncableService::~ThemeSyncableService() { } void ThemeSyncableService::OnThemeChange() { if (sync_processor_.get()) { sync_pb::ThemeSpecifics current_specifics; if (!GetThemeSpecificsFromCurrentTheme(&current_specifics)) return; // Current theme is unsyncable. ProcessNewTheme(syncer::SyncChange::ACTION_UPDATE, current_specifics); use_system_theme_by_default_ = current_specifics.use_system_theme_by_default(); } } syncer::SyncMergeResult ThemeSyncableService::MergeDataAndStartSyncing( syncer::ModelType type, const syncer::SyncDataList& initial_sync_data, scoped_ptr<syncer::SyncChangeProcessor> sync_processor, scoped_ptr<syncer::SyncErrorFactory> error_handler) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(!sync_processor_.get()); DCHECK(sync_processor.get()); DCHECK(error_handler.get()); syncer::SyncMergeResult merge_result(type); sync_processor_ = sync_processor.Pass(); sync_error_handler_ = error_handler.Pass(); if (initial_sync_data.size() > 1) { sync_error_handler_->CreateAndUploadError( FROM_HERE, base::StringPrintf("Received %d theme specifics.", static_cast<int>(initial_sync_data.size()))); } sync_pb::ThemeSpecifics current_specifics; if (!GetThemeSpecificsFromCurrentTheme(&current_specifics)) { // Current theme is unsyncable - don't overwrite from sync data, and don't // save the unsyncable theme to sync data. return merge_result; } // Find the last SyncData that has theme data and set the current theme from // it. for (syncer::SyncDataList::const_reverse_iterator sync_data = initial_sync_data.rbegin(); sync_data != initial_sync_data.rend(); ++sync_data) { if (sync_data->GetSpecifics().has_theme()) { MaybeSetTheme(current_specifics, *sync_data); return merge_result; } } // No theme specifics are found. Create one according to current theme. merge_result.set_error(ProcessNewTheme( syncer::SyncChange::ACTION_ADD, current_specifics)); return merge_result; } void ThemeSyncableService::StopSyncing(syncer::ModelType type) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK_EQ(type, syncer::THEMES); sync_processor_.reset(); sync_error_handler_.reset(); } syncer::SyncDataList ThemeSyncableService::GetAllSyncData( syncer::ModelType type) const { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK_EQ(type, syncer::THEMES); syncer::SyncDataList list; sync_pb::EntitySpecifics entity_specifics; if (GetThemeSpecificsFromCurrentTheme(entity_specifics.mutable_theme())) { list.push_back(syncer::SyncData::CreateLocalData(kCurrentThemeClientTag, kCurrentThemeNodeTitle, entity_specifics)); } return list; } syncer::SyncError ThemeSyncableService::ProcessSyncChanges( const tracked_objects::Location& from_here, const syncer::SyncChangeList& change_list) { DCHECK(thread_checker_.CalledOnValidThread()); if (!sync_processor_.get()) { return syncer::SyncError(FROM_HERE, syncer::SyncError::DATATYPE_ERROR, "Theme syncable service is not started.", syncer::THEMES); } // TODO(akalin): Normally, we should only have a single change and // it should be an update. However, the syncapi may occasionally // generates multiple changes. When we fix syncapi to not do that, // we can remove the extra logic below. See: // http://code.google.com/p/chromium/issues/detail?id=41696 . if (change_list.size() != 1) { string err_msg = base::StringPrintf("Received %d theme changes: ", static_cast<int>(change_list.size())); for (size_t i = 0; i < change_list.size(); ++i) { base::StringAppendF(&err_msg, "[%s] ", change_list[i].ToString().c_str()); } sync_error_handler_->CreateAndUploadError(FROM_HERE, err_msg); } else if (change_list.begin()->change_type() != syncer::SyncChange::ACTION_ADD && change_list.begin()->change_type() != syncer::SyncChange::ACTION_UPDATE) { sync_error_handler_->CreateAndUploadError( FROM_HERE, "Invalid theme change: " + change_list.begin()->ToString()); } sync_pb::ThemeSpecifics current_specifics; if (!GetThemeSpecificsFromCurrentTheme(&current_specifics)) { // Current theme is unsyncable, so don't overwrite it. return syncer::SyncError(); } // Set current theme from the theme specifics of the last change of type // |ACTION_ADD| or |ACTION_UPDATE|. for (syncer::SyncChangeList::const_reverse_iterator theme_change = change_list.rbegin(); theme_change != change_list.rend(); ++theme_change) { if (theme_change->sync_data().GetSpecifics().has_theme() && (theme_change->change_type() == syncer::SyncChange::ACTION_ADD || theme_change->change_type() == syncer::SyncChange::ACTION_UPDATE)) { MaybeSetTheme(current_specifics, theme_change->sync_data()); return syncer::SyncError(); } } return syncer::SyncError(FROM_HERE, syncer::SyncError::DATATYPE_ERROR, "Didn't find valid theme specifics", syncer::THEMES); } void ThemeSyncableService::MaybeSetTheme( const sync_pb::ThemeSpecifics& current_specs, const syncer::SyncData& sync_data) { const sync_pb::ThemeSpecifics& sync_theme = sync_data.GetSpecifics().theme(); use_system_theme_by_default_ = sync_theme.use_system_theme_by_default(); DVLOG(1) << "Set current theme from specifics: " << sync_data.ToString(); if (!AreThemeSpecificsEqual(current_specs, sync_theme, IsSystemThemeDistinctFromDefaultTheme())) { SetCurrentThemeFromThemeSpecifics(sync_theme); } else { DVLOG(1) << "Skip setting theme because specs are equal"; } } void ThemeSyncableService::SetCurrentThemeFromThemeSpecifics( const sync_pb::ThemeSpecifics& theme_specifics) { if (theme_specifics.use_custom_theme()) { // TODO(akalin): Figure out what to do about third-party themes // (i.e., those not on either Google gallery). string id(theme_specifics.custom_theme_id()); GURL update_url(theme_specifics.custom_theme_update_url()); DVLOG(1) << "Applying theme " << id << " with update_url " << update_url; ExtensionServiceInterface* extensions_service = extensions::ExtensionSystem::Get(profile_)->extension_service(); CHECK(extensions_service); const extensions::Extension* extension = extensions_service->GetExtensionById(id, true); if (extension) { if (!extension->is_theme()) { DVLOG(1) << "Extension " << id << " is not a theme; aborting"; return; } if (!extensions_service->IsExtensionEnabled(id)) { DVLOG(1) << "Theme " << id << " is not enabled; aborting"; return; } // An enabled theme extension with the given id was found, so // just set the current theme to it. theme_service_->SetTheme(extension); } else { // No extension with this id exists -- we must install it; we do // so by adding it as a pending extension and then triggering an // auto-update cycle. const bool kInstallSilently = true; if (!extensions_service->pending_extension_manager()->AddFromSync( id, update_url, &IsTheme, kInstallSilently)) { LOG(WARNING) << "Could not add pending extension for " << id; return; } extensions_service->CheckForUpdatesSoon(); } } else if (theme_specifics.use_system_theme_by_default()) { DVLOG(1) << "Switch to use native theme"; theme_service_->SetNativeTheme(); } else { DVLOG(1) << "Switch to use default theme"; theme_service_->UseDefaultTheme(); } } bool ThemeSyncableService::GetThemeSpecificsFromCurrentTheme( sync_pb::ThemeSpecifics* theme_specifics) const { const extensions::Extension* current_theme = theme_service_->UsingDefaultTheme() ? NULL : extensions::ExtensionSystem::Get(profile_)->extension_service()-> GetExtensionById(theme_service_->GetThemeID(), false); if (current_theme && !extensions::sync_helper::IsSyncable(current_theme)) { DVLOG(1) << "Ignoring extension from external source: " << current_theme->location(); return false; } bool use_custom_theme = (current_theme != NULL); theme_specifics->set_use_custom_theme(use_custom_theme); if (IsSystemThemeDistinctFromDefaultTheme()) { // On platform where system theme is different from default theme, set // use_system_theme_by_default to true if system theme is used, false // if default system theme is used. Otherwise restore it to value in sync. if (theme_service_->UsingNativeTheme()) { theme_specifics->set_use_system_theme_by_default(true); } else if (theme_service_->UsingDefaultTheme()) { theme_specifics->set_use_system_theme_by_default(false); } else { theme_specifics->set_use_system_theme_by_default( use_system_theme_by_default_); } } else { // Restore use_system_theme_by_default when platform doesn't distinguish // between default theme and system theme. theme_specifics->set_use_system_theme_by_default( use_system_theme_by_default_); } if (use_custom_theme) { DCHECK(current_theme); DCHECK(current_theme->is_theme()); theme_specifics->set_custom_theme_name(current_theme->name()); theme_specifics->set_custom_theme_id(current_theme->id()); theme_specifics->set_custom_theme_update_url( extensions::ManifestURL::GetUpdateURL(current_theme).spec()); } else { DCHECK(!current_theme); theme_specifics->clear_custom_theme_name(); theme_specifics->clear_custom_theme_id(); theme_specifics->clear_custom_theme_update_url(); } return true; } /* static */ bool ThemeSyncableService::AreThemeSpecificsEqual( const sync_pb::ThemeSpecifics& a, const sync_pb::ThemeSpecifics& b, bool is_system_theme_distinct_from_default_theme) { if (a.use_custom_theme() != b.use_custom_theme()) { return false; } if (a.use_custom_theme()) { // We're using a custom theme, so simply compare IDs since those // are guaranteed unique. return a.custom_theme_id() == b.custom_theme_id(); } else if (is_system_theme_distinct_from_default_theme) { // We're not using a custom theme, but we care about system // vs. default. return a.use_system_theme_by_default() == b.use_system_theme_by_default(); } else { // We're not using a custom theme, and we don't care about system // vs. default. return true; } } syncer::SyncError ThemeSyncableService::ProcessNewTheme( syncer::SyncChange::SyncChangeType change_type, const sync_pb::ThemeSpecifics& theme_specifics) { syncer::SyncChangeList changes; sync_pb::EntitySpecifics entity_specifics; entity_specifics.mutable_theme()->CopyFrom(theme_specifics); changes.push_back( syncer::SyncChange(FROM_HERE, change_type, syncer::SyncData::CreateLocalData( kCurrentThemeClientTag, kCurrentThemeNodeTitle, entity_specifics))); DVLOG(1) << "Update theme specifics from current theme: " << changes.back().ToString(); return sync_processor_->ProcessSyncChanges(FROM_HERE, changes); }
bsd-3-clause
briancoutinho0905/2dsampling
src/arch/power/linux/linux.hh
8519
/* * Copyright (c) 2003-2005 The Regents of The University of Michigan * Copyright (c) 2009 The University of Edinburgh * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Timothy M. Jones */ #ifndef __ARCH_POWER_LINUX_LINUX_HH__ #define __ARCH_POWER_LINUX_LINUX_HH__ #include "kern/linux/linux.hh" /* * This works for a 2.6.15 kernel. */ class PowerLinux : public Linux { public: typedef int32_t time_t; typedef struct { uint64_t st_dev; uint32_t __pad1; uint32_t st_ino; uint32_t st_mode; uint32_t st_nlink; uint32_t st_uid; uint32_t st_gid; uint64_t st_rdev; uint32_t __pad2; uint32_t st_size; uint32_t st_blksize; uint32_t st_blocks; uint32_t st_atimeX; uint32_t st_atime_nsec; uint32_t st_mtimeX; uint32_t st_mtime_nsec; uint32_t st_ctimeX; uint32_t st_ctime_nsec; uint32_t __unused4; uint32_t __unused5; } tgt_stat; typedef struct { uint64_t st_dev; uint64_t st_ino; uint32_t st_mode; uint32_t st_nlink; uint32_t st_uid; uint32_t st_gid; uint64_t st_rdev; uint64_t __pad2; uint64_t st_size; uint32_t st_blksize; uint32_t __blksize_pad; uint64_t st_blocks; uint32_t st_atimeX; uint32_t st_atime_nsec; uint32_t st_mtimeX; uint32_t st_mtime_nsec; uint32_t st_ctimeX; uint32_t st_ctime_nsec; uint32_t __unused4; uint32_t __unused5; } tgt_stat64; /// For times(). struct tms { int32_t tms_utime; //!< user time int32_t tms_stime; //!< system time int32_t tms_cutime; //!< user time of children int32_t tms_cstime; //!< system time of children }; static const int TGT_SIGHUP = 0x000001; static const int TGT_SIGINT = 0x000002; static const int TGT_SIGQUIT = 0x000003; static const int TGT_SIGILL = 0x000004; static const int TGT_SIGTRAP = 0x000005; static const int TGT_SIGABRT = 0x000006; static const int TGT_SIGIOT = 0x000006; static const int TGT_SIGBUS = 0x000007; static const int TGT_SIGFPE = 0x000008; static const int TGT_SIGKILL = 0x000009; static const int TGT_SIGUSR1 = 0x00000a; static const int TGT_SIGSEGV = 0x00000b; static const int TGT_SIGUSR2 = 0x00000c; static const int TGT_SIGPIPE = 0x00000d; static const int TGT_SIGALRM = 0x00000e; static const int TGT_SIGTERM = 0x00000f; static const int TGT_SIGSTKFLT = 0x000010; static const int TGT_SIGCHLD = 0x000011; static const int TGT_SIGCONT = 0x000012; static const int TGT_SIGSTOP = 0x000013; static const int TGT_SIGTSTP = 0x000014; static const int TGT_SIGTTIN = 0x000015; static const int TGT_SIGTTOU = 0x000016; static const int TGT_SIGURG = 0x000017; static const int TGT_SIGXCPU = 0x000018; static const int TGT_SIGXFSZ = 0x000019; static const int TGT_SIGVTALRM = 0x00001a; static const int TGT_SIGPROF = 0x00001b; static const int TGT_SIGWINCH = 0x00001c; static const int TGT_SIGIO = 0x00001d; static const int TGT_SIGPOLL = 0x00001d; static const int TGT_SIGPWR = 0x00001e; static const int TGT_SIGSYS = 0x00001f; static const int TGT_SIGUNUSED = 0x00001f; /// This table maps the target open() flags to the corresponding /// host open() flags. static SyscallFlagTransTable openFlagTable[]; /// Number of entries in openFlagTable[]. static const int NUM_OPEN_FLAGS; //@{ /// open(2) flag values. static const int TGT_O_RDONLY = 000000000; //!< O_RDONLY static const int TGT_O_WRONLY = 000000001; //!< O_WRONLY static const int TGT_O_RDWR = 000000002; //!< O_RDWR static const int TGT_O_CREAT = 000000100; //!< O_CREAT static const int TGT_O_EXCL = 000000200; //!< O_EXCL static const int TGT_O_NOCTTY = 000000400; //!< O_NOCTTY static const int TGT_O_TRUNC = 000001000; //!< O_TRUNC static const int TGT_O_APPEND = 000002000; //!< O_APPEND static const int TGT_O_NONBLOCK = 000004000; //!< O_NONBLOCK static const int TGT_O_DSYNC = 000010000; //!< O_DSYNC static const int TGT_FASYNC = 000020000; //!< FASYNC static const int TGT_O_DIRECT = 000400000; //!< O_DIRECT static const int TGT_O_LARGEFILE = 000200000; //!< O_LARGEFILE static const int TGT_O_DIRECTORY = 000040000; //!< O_DIRECTORY static const int TGT_O_NOFOLLOW = 000100000; //!< O_NOFOLLOW static const int TGT_O_NOATIME = 001000000; //!< O_NOATIME static const int TGT_O_CLOEXEC = 002000000; //!< O_CLOEXEC static const int TGT_O_SYNC = 004010000; //!< O_SYNC static const int TGT_O_PATH = 010000000; //!< O_PATH //@} static const unsigned TGT_MAP_SHARED = 0x00001; static const unsigned TGT_MAP_PRIVATE = 0x00002; static const unsigned TGT_MAP_ANON = 0x00020; static const unsigned TGT_MAP_DENYWRITE = 0x00800; static const unsigned TGT_MAP_EXECUTABLE = 0x01000; static const unsigned TGT_MAP_FILE = 0x00000; static const unsigned TGT_MAP_GROWSDOWN = 0x00100; static const unsigned TGT_MAP_HUGETLB = 0x40000; static const unsigned TGT_MAP_LOCKED = 0x00080; static const unsigned TGT_MAP_NONBLOCK = 0x10000; static const unsigned TGT_MAP_NORESERVE = 0x00040; static const unsigned TGT_MAP_POPULATE = 0x08000; static const unsigned TGT_MAP_STACK = 0x20000; static const unsigned TGT_MAP_ANONYMOUS = 0x00020; static const unsigned TGT_MAP_FIXED = 0x00010; static const unsigned NUM_MMAP_FLAGS; //@{ /// ioctl() command codes. static const unsigned TGT_TIOCGETP = 0x40067408; static const unsigned TGT_TIOCSETP = 0x80067409; static const unsigned TGT_TIOCSETN = 0x8006740a; static const unsigned TGT_TIOCSETC = 0x80067411; static const unsigned TGT_TIOCGETC = 0x40067412; static const unsigned TGT_FIONREAD = 0x4004667f; static const unsigned TGT_TCGETS = 0x402c7413; static const unsigned TGT_TCGETA = 0x40127417; static const unsigned TGT_TCSETAW = 0x80147419; // 2.6.15 kernel //@} static bool isTtyReq(unsigned req) { switch (req) { case TGT_TIOCGETP: case TGT_TIOCSETP: case TGT_TIOCSETN: case TGT_TIOCSETC: case TGT_TIOCGETC: case TGT_TCGETS: case TGT_TCGETA: case TGT_TCSETAW: return true; default: return false; } } }; #endif // __ARCH_POWER_LINUX_LINUX_HH__
bsd-3-clause
CEBD/SuperiorStormShelters
src/packages/Orchard.Module.Contrib.Taxonomies.1.4/Content/Modules/Contrib.Taxonomies/Models/TaxonomyMenuPartRecord.cs
630
using Orchard.ContentManagement.Records; namespace Contrib.Taxonomies.Models { /// <summary> /// Contains the properties for the Taxonomy Menu Widget /// </summary> public class TaxonomyMenuPartRecord : ContentPartRecord { public virtual TaxonomyPartRecord TaxonomyPartRecord { get; set; } public virtual TermPartRecord TermPartRecord { get; set; } public virtual bool DisplayTopMenuItem { get; set; } public virtual int LevelsToDisplay { get; set; } public virtual bool DisplayContentCount { get; set; } public virtual bool HideEmptyTerms { get; set; } } }
bsd-3-clause
Priya91/corefx-1
src/System.ComponentModel.Annotations/tests/ValidatorTests.cs
39357
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using Xunit; namespace System.ComponentModel.DataAnnotations { public class ValidatorTests { public static readonly ValidationContext s_estValidationContext = new ValidationContext(new object()); #region TryValidateObject [Fact] public static void TryValidateObjectThrowsIf_ValidationContext_is_null() { Assert.Throws<ArgumentNullException>( () => Validator.TryValidateObject(new object(), validationContext: null, validationResults: null)); Assert.Throws<ArgumentNullException>( () => Validator.TryValidateObject(new object(), validationContext: null, validationResults: null, validateAllProperties: false)); } [Fact] public static void TryValidateObjectThrowsIf_instance_is_null() { Assert.Throws<ArgumentNullException>( () => Validator.TryValidateObject(null, s_estValidationContext, validationResults: null)); Assert.Throws<ArgumentNullException>( () => Validator.TryValidateObject(null, s_estValidationContext, validationResults: null, validateAllProperties: false)); } // TryValidateObjectThrowsIf_instance_does_not_match_ValidationContext_ObjectInstance [Fact] public static void TestTryValidateObjectThrowsIfInstanceNotMatch() { Assert.Throws<ArgumentException>( () => Validator.TryValidateObject(new object(), s_estValidationContext, validationResults: null)); Assert.Throws<ArgumentException>( () => Validator.TryValidateObject(new object(), s_estValidationContext, validationResults: null, validateAllProperties: true)); } [Fact] public static void TryValidateObject_returns_true_if_no_errors() { var objectToBeValidated = "ToBeValidated"; var validationContext = new ValidationContext(objectToBeValidated); Assert.True( Validator.TryValidateObject(objectToBeValidated, validationContext, validationResults: null)); Assert.True( Validator.TryValidateObject(objectToBeValidated, validationContext, validationResults: null, validateAllProperties: true)); } [Fact] public static void TryValidateObject_returns_false_if_errors() { var objectToBeValidated = new ToBeValidated() { PropertyToBeTested = "Invalid Value", PropertyWithRequiredAttribute = "Valid Value" }; var validationContext = new ValidationContext(objectToBeValidated); Assert.False( Validator.TryValidateObject(objectToBeValidated, validationContext, null, true)); var validationResults = new List<ValidationResult>(); Assert.False( Validator.TryValidateObject(objectToBeValidated, validationContext, validationResults, true)); Assert.Equal(1, validationResults.Count); Assert.Equal("ValidValueStringPropertyAttribute.IsValid failed for value Invalid Value", validationResults[0].ErrorMessage); } // TryValidateObject_returns_true_if_validateAllProperties_is_false_and_Required_test_passes_even_if_there_are_other_errors() [Fact] public static void TestTryValidateObjectSuccessEvenWithOtherErrors() { var objectToBeValidated = new ToBeValidated() { PropertyWithRequiredAttribute = "Invalid Value" }; var validationContext = new ValidationContext(objectToBeValidated); Assert.True( Validator.TryValidateObject(objectToBeValidated, validationContext, null, false)); var validationResults = new List<ValidationResult>(); Assert.True( Validator.TryValidateObject(objectToBeValidated, validationContext, validationResults, false)); Assert.Equal(0, validationResults.Count); } [Fact] public static void TryValidateObject_returns_false_if_validateAllProperties_is_true_and_Required_test_fails() { var objectToBeValidated = new ToBeValidated() { PropertyWithRequiredAttribute = null }; var validationContext = new ValidationContext(objectToBeValidated); Assert.False( Validator.TryValidateObject(objectToBeValidated, validationContext, null, true)); var validationResults = new List<ValidationResult>(); Assert.False( Validator.TryValidateObject(objectToBeValidated, validationContext, validationResults, true)); Assert.Equal(1, validationResults.Count); // cannot check error message - not defined on ret builds } [Fact] public static void TryValidateObject_returns_true_if_validateAllProperties_is_true_and_all_attributes_are_valid() { var objectToBeValidated = new ToBeValidated() { PropertyWithRequiredAttribute = "Valid Value" }; var validationContext = new ValidationContext(objectToBeValidated); Assert.True( Validator.TryValidateObject(objectToBeValidated, validationContext, null, true)); var validationResults = new List<ValidationResult>(); Assert.True( Validator.TryValidateObject(objectToBeValidated, validationContext, validationResults, true)); Assert.Equal(0, validationResults.Count); } [Fact] public static void TryValidateObject_returns_false_if_all_properties_are_valid_but_class_is_invalid() { var objectToBeValidated = new InvalidToBeValidated() { PropertyWithRequiredAttribute = "Valid Value" }; var validationContext = new ValidationContext(objectToBeValidated); Assert.False( Validator.TryValidateObject(objectToBeValidated, validationContext, null, true)); var validationResults = new List<ValidationResult>(); Assert.False( Validator.TryValidateObject(objectToBeValidated, validationContext, validationResults, true)); Assert.Equal(1, validationResults.Count); Assert.Equal("ValidClassAttribute.IsValid failed for class of type " + typeof(InvalidToBeValidated).FullName, validationResults[0].ErrorMessage); } #endregion TryValidateObject #region ValidateObject [Fact] public static void ValidateObjectThrowsIf_ValidationContext_is_null() { Assert.Throws<ArgumentNullException>( () => Validator.ValidateObject(new object(), validationContext: null)); Assert.Throws<ArgumentNullException>( () => Validator.ValidateObject(new object(), validationContext: null, validateAllProperties: false)); } [Fact] public static void ValidateObjectThrowsIf_instance_is_null() { Assert.Throws<ArgumentNullException>( () => Validator.ValidateObject(null, s_estValidationContext)); Assert.Throws<ArgumentNullException>( () => Validator.ValidateObject(null, s_estValidationContext, false)); } [Fact] public static void ValidateObjectThrowsIf_instance_does_not_match_ValidationContext_ObjectInstance() { Assert.Throws<ArgumentException>( () => Validator.ValidateObject(new object(), s_estValidationContext)); Assert.Throws<ArgumentException>( () => Validator.ValidateObject(new object(), s_estValidationContext, true)); } [Fact] public static void ValidateObject_succeeds_if_no_errors() { var objectToBeValidated = "ToBeValidated"; var validationContext = new ValidationContext(objectToBeValidated); AssertEx.DoesNotThrow( () => Validator.ValidateObject(objectToBeValidated, validationContext)); AssertEx.DoesNotThrow( () => Validator.ValidateObject(objectToBeValidated, validationContext, true)); } [Fact] public static void ValidateObject_throws_ValidationException_if_errors() { var objectToBeValidated = new ToBeValidated() { PropertyToBeTested = "Invalid Value", PropertyWithRequiredAttribute = "Valid Value" }; var validationContext = new ValidationContext(objectToBeValidated); var exception = Assert.Throws<ValidationException>( () => Validator.ValidateObject(objectToBeValidated, validationContext, true)); AssertEx.IsType<ValidValueStringPropertyAttribute>(exception.ValidationAttribute); Assert.Equal("ValidValueStringPropertyAttribute.IsValid failed for value Invalid Value", exception.ValidationResult.ErrorMessage); Assert.Equal("Invalid Value", exception.Value); } // ValidateObject_returns_true_if_validateAllProperties_is_false_and_Required_test_passes_even_if_there_are_other_errors [Fact] public static void TestValidateObjectNotThrowIfvalidateAllPropertiesFalse() { var objectToBeValidated = new ToBeValidated() { PropertyWithRequiredAttribute = "Invalid Value" }; var validationContext = new ValidationContext(objectToBeValidated); AssertEx.DoesNotThrow( () => Validator.ValidateObject(objectToBeValidated, validationContext, false)); } // ValidateObject_throws_ValidationException_if_validateAllProperties_is_true_and_Required_test_fails [Fact] public static void TestValidateObjectThrowsIfRequiredTestFails() { var objectToBeValidated = new ToBeValidated() { PropertyWithRequiredAttribute = null }; var validationContext = new ValidationContext(objectToBeValidated); var exception = Assert.Throws<ValidationException>( () => Validator.ValidateObject(objectToBeValidated, validationContext, true)); AssertEx.IsType<RequiredAttribute>(exception.ValidationAttribute); // cannot check error message - not defined on ret builds Assert.Null(exception.Value); } [Fact] public static void ValidateObject_succeeds_if_validateAllProperties_is_true_and_all_attributes_are_valid() { var objectToBeValidated = new ToBeValidated() { PropertyWithRequiredAttribute = "Valid Value" }; var validationContext = new ValidationContext(objectToBeValidated); AssertEx.DoesNotThrow( () => Validator.ValidateObject(objectToBeValidated, validationContext, true)); } [Fact] public static void ValidateObject_throws_ValidationException_if_all_properties_are_valid_but_class_is_invalid() { var objectToBeValidated = new InvalidToBeValidated() { PropertyWithRequiredAttribute = "Valid Value" }; var validationContext = new ValidationContext(objectToBeValidated); var exception = Assert.Throws<ValidationException>( () => Validator.ValidateObject(objectToBeValidated, validationContext, true)); AssertEx.IsType<ValidClassAttribute>(exception.ValidationAttribute); Assert.Equal( "ValidClassAttribute.IsValid failed for class of type " + typeof(InvalidToBeValidated).FullName, exception.ValidationResult.ErrorMessage); Assert.Equal(objectToBeValidated, exception.Value); } #endregion ValidateObject #region TryValidateProperty [Fact] public static void TryValidatePropertyThrowsIf_ValidationContext_is_null() { Assert.Throws<ArgumentNullException>( () => Validator.TryValidateProperty(new object(), validationContext: null, validationResults: null)); } [Fact] public static void TryValidatePropertyThrowsIf_value_is_null() { Assert.Throws<ArgumentNullException>( () => Validator.TryValidateProperty(null, s_estValidationContext, validationResults: null)); } // TryValidatePropertyThrowsIf_ValidationContext_MemberName_is_null_or_empty() [Fact] public static void TestTryValidatePropertyThrowsIfNullOrEmptyValidationContextMemberName() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = null; Assert.Throws<ArgumentNullException>( () => Validator.TryValidateProperty(null, validationContext, null)); validationContext.MemberName = string.Empty; Assert.Throws<ArgumentNullException>( () => Validator.TryValidateProperty(null, validationContext, null)); } // TryValidatePropertyThrowsIf_ValidationContext_MemberName_does_not_exist_on_object() [Fact] public static void TryValidatePropertyThrowsIf_ValidationContext_MemberName_does_not_exist_on_object() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "NonExist"; Assert.Throws<ArgumentException>( () => Validator.TryValidateProperty(null, validationContext, null)); } // TryValidatePropertyThrowsIf_ValidationContext_MemberName_is_not_public() [Fact] public static void TryValidatePropertyThrowsIf_ValidationContext_MemberName_is_not_public() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "InternalProperty"; Assert.Throws<ArgumentException>( () => Validator.TryValidateProperty(null, validationContext, null)); validationContext.MemberName = "ProtectedProperty"; Assert.Throws<ArgumentException>( () => Validator.TryValidateProperty(null, validationContext, null)); validationContext.MemberName = "PrivateProperty"; Assert.Throws<ArgumentException>( () => Validator.TryValidateProperty(null, validationContext, null)); } // TryValidatePropertyThrowsIf_ValidationContext_MemberName_is_for_a_public_indexer() [Fact] public static void TryValidatePropertyThrowsIf_ValidationContext_MemberName_is_for_a_public_indexer() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "Item"; Assert.Throws<ArgumentException>( () => Validator.TryValidateProperty(null, validationContext, validationResults: null)); } // TryValidatePropertyThrowsIf_value_passed_is_of_wrong_type_to_be_assigned_to_property() [Fact] public static void TryValidatePropertyThrowsIf_value_passed_is_of_wrong_type_to_be_assigned_to_property() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "NoAttributesProperty"; Assert.Throws<ArgumentException>( () => Validator.TryValidateProperty(123, validationContext, validationResults: null)); } [Fact] public static void TryValidatePropertyThrowsIf_null_passed_to_non_nullable_property() { var validationContext = new ValidationContext(new ToBeValidated()); // cannot assign null to a non-value-type property validationContext.MemberName = "EnumProperty"; Assert.Throws<ArgumentException>( () => Validator.TryValidateProperty(null, validationContext, validationResults: null)); // cannot assign null to a non-nullable property validationContext.MemberName = "NonNullableProperty"; Assert.Throws<ArgumentException>( () => Validator.TryValidateProperty(null, validationContext, validationResults: null)); } [Fact] public static void TryValidateProperty_returns_true_if_null_passed_to_nullable_property() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "NullableProperty"; Assert.True(Validator.TryValidateProperty(null, validationContext, validationResults: null)); } [Fact] public static void TryValidateProperty_returns_true_if_no_attributes_to_validate() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "NoAttributesProperty"; Assert.True( Validator.TryValidateProperty("Any Value", validationContext, validationResults: null)); } [Fact] public static void TryValidateProperty_returns_false_if_errors() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "PropertyToBeTested"; Assert.False( Validator.TryValidateProperty("Invalid Value", validationContext, null)); var validationResults = new List<ValidationResult>(); Assert.False( Validator.TryValidateProperty("Invalid Value", validationContext, validationResults)); Assert.Equal(1, validationResults.Count); Assert.Equal("ValidValueStringPropertyAttribute.IsValid failed for value Invalid Value", validationResults[0].ErrorMessage); } [Fact] public static void TryValidateProperty_returns_false_if_Required_attribute_test_fails() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "PropertyWithRequiredAttribute"; Assert.False( Validator.TryValidateProperty(null, validationContext, null)); var validationResults = new List<ValidationResult>(); Assert.False( Validator.TryValidateProperty(null, validationContext, validationResults)); Assert.Equal(1, validationResults.Count); // cannot check error message - not defined on ret builds } [Fact] public static void TryValidateProperty_returns_true_if_all_attributes_are_valid() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "PropertyWithRequiredAttribute"; Assert.True( Validator.TryValidateProperty("Valid Value", validationContext, null)); var validationResults = new List<ValidationResult>(); Assert.True( Validator.TryValidateProperty("Valid Value", validationContext, validationResults)); Assert.Equal(0, validationResults.Count); } #endregion TryValidateProperty #region ValidateProperty [Fact] public static void ValidatePropertyThrowsIf_ValidationContext_is_null() { Assert.Throws<ArgumentNullException>( () => Validator.ValidateProperty(new object(), validationContext: null)); } [Fact] public static void ValidatePropertyThrowsIf_value_is_null() { Assert.Throws<ArgumentNullException>( () => Validator.ValidateProperty(null, s_estValidationContext)); } [Fact] public static void ValidatePropertyThrowsIf_ValidationContext_MemberName_is_null_or_empty() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = null; Assert.Throws<ArgumentNullException>( () => Validator.ValidateProperty(null, validationContext)); validationContext.MemberName = string.Empty; Assert.Throws<ArgumentNullException>( () => Validator.ValidateProperty(null, validationContext)); } [Fact] public static void ValidatePropertyThrowsIf_ValidationContext_MemberName_does_not_exist_on_object() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "NonExist"; Assert.Throws<ArgumentException>( () => Validator.ValidateProperty(null, validationContext)); } [Fact] public static void ValidatePropertyThrowsIf_ValidationContext_MemberName_is_not_public() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "InternalProperty"; Assert.Throws<ArgumentException>( () => Validator.ValidateProperty(null, validationContext)); validationContext.MemberName = "ProtectedProperty"; Assert.Throws<ArgumentException>( () => Validator.ValidateProperty(null, validationContext)); validationContext.MemberName = "PrivateProperty"; Assert.Throws<ArgumentException>( () => Validator.ValidateProperty(null, validationContext)); } [Fact] public static void ValidatePropertyThrowsIf_ValidationContext_MemberName_is_for_a_public_indexer() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "Item"; Assert.Throws<ArgumentException>( () => Validator.ValidateProperty(null, validationContext)); } [Fact] public static void ValidatePropertyThrowsIf_value_passed_is_of_wrong_type_to_be_assigned_to_property() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "NoAttributesProperty"; Assert.Throws<ArgumentException>( () => Validator.ValidateProperty(123, validationContext)); } [Fact] public static void ValidatePropertyThrowsIf_null_passed_to_non_nullable_property() { var validationContext = new ValidationContext(new ToBeValidated()); // cannot assign null to a non-value-type property validationContext.MemberName = "EnumProperty"; Assert.Throws<ArgumentException>( () => Validator.ValidateProperty(null, validationContext)); // cannot assign null to a non-nullable property validationContext.MemberName = "NonNullableProperty"; Assert.Throws<ArgumentException>( () => Validator.ValidateProperty(null, validationContext)); } [Fact] public static void ValidateProperty_succeeds_if_null_passed_to_nullable_property() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "NullableProperty"; AssertEx.DoesNotThrow(() => Validator.ValidateProperty(null, validationContext)); } [Fact] public static void ValidateProperty_succeeds_if_no_attributes_to_validate() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "NoAttributesProperty"; AssertEx.DoesNotThrow( () => Validator.ValidateProperty("Any Value", validationContext)); } [Fact] public static void ValidateProperty_throws_ValidationException_if_errors() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "PropertyToBeTested"; var exception = Assert.Throws<ValidationException>( () => Validator.ValidateProperty("Invalid Value", validationContext)); AssertEx.IsType<ValidValueStringPropertyAttribute>(exception.ValidationAttribute); Assert.Equal("ValidValueStringPropertyAttribute.IsValid failed for value Invalid Value", exception.ValidationResult.ErrorMessage); Assert.Equal("Invalid Value", exception.Value); } [Fact] public static void ValidateProperty_throws_ValidationException_if_Required_attribute_test_fails() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "PropertyWithRequiredAttribute"; var exception = Assert.Throws<ValidationException>( () => Validator.ValidateProperty(null, validationContext)); AssertEx.IsType<RequiredAttribute>(exception.ValidationAttribute); // cannot check error message - not defined on ret builds Assert.Null(exception.Value); } [Fact] public static void ValidateProperty_succeeds_if_all_attributes_are_valid() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "PropertyWithRequiredAttribute"; AssertEx.DoesNotThrow( () => Validator.ValidateProperty("Valid Value", validationContext)); } #endregion ValidateProperty #region TryValidateValue [Fact] public static void TryValidateValueThrowsIf_ValidationContext_is_null() { Assert.Throws<ArgumentNullException>( () => Validator.TryValidateValue(new object(), validationContext: null, validationResults: null, validationAttributes: Enumerable.Empty<ValidationAttribute>())); } [Fact] public static void TryValidateValueThrowsIf_ValidationAttributeEnumerable_is_null() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = null; Assert.Throws<ArgumentNullException>( () => Validator.TryValidateValue(new object(), validationContext, validationResults: null, validationAttributes: null)); } [Fact] public static void TryValidateValue_returns_true_if_no_attributes_to_validate_regardless_of_value() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "NoAttributesProperty"; Assert.True(Validator.TryValidateValue(null, validationContext, validationResults: null, validationAttributes: Enumerable.Empty<ValidationAttribute>())); Assert.True(Validator.TryValidateValue(new object(), validationContext, validationResults: null, validationAttributes: Enumerable.Empty<ValidationAttribute>())); } [Fact] public static void TryValidateValue_returns_false_if_Property_has_RequiredAttribute_and_value_is_null() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "PropertyWithRequiredAttribute"; var attributesToValidate = new ValidationAttribute[] { new RequiredAttribute(), new ValidValueStringPropertyAttribute() }; Assert.False(Validator.TryValidateValue(null, validationContext, null, attributesToValidate)); var validationResults = new List<ValidationResult>(); Assert.False(Validator.TryValidateValue(null, validationContext, validationResults, attributesToValidate)); Assert.Equal(1, validationResults.Count); // cannot check error message - not defined on ret builds } [Fact] public static void TryValidateValue_returns_false_if_Property_has_RequiredAttribute_and_value_is_invalid() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "PropertyWithRequiredAttribute"; var attributesToValidate = new ValidationAttribute[] { new RequiredAttribute(), new ValidValueStringPropertyAttribute() }; Assert.False(Validator.TryValidateValue("Invalid Value", validationContext, null, attributesToValidate)); var validationResults = new List<ValidationResult>(); Assert.False(Validator.TryValidateValue("Invalid Value", validationContext, validationResults, attributesToValidate)); Assert.Equal(1, validationResults.Count); Assert.Equal("ValidValueStringPropertyAttribute.IsValid failed for value Invalid Value", validationResults[0].ErrorMessage); } [Fact] public static void TryValidateValue_returns_true_if_Property_has_RequiredAttribute_and_value_is_valid() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "PropertyWithRequiredAttribute"; var attributesToValidate = new ValidationAttribute[] { new RequiredAttribute(), new ValidValueStringPropertyAttribute() }; Assert.True(Validator.TryValidateValue("Valid Value", validationContext, null, attributesToValidate)); var validationResults = new List<ValidationResult>(); Assert.True(Validator.TryValidateValue("Valid Value", validationContext, validationResults, attributesToValidate)); Assert.Equal(0, validationResults.Count); } [Fact] public static void TryValidateValue_returns_false_if_Property_has_no_RequiredAttribute_and_value_is_invalid() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "PropertyWithRequiredAttribute"; var attributesToValidate = new ValidationAttribute[] { new ValidValueStringPropertyAttribute() }; Assert.False(Validator.TryValidateValue("Invalid Value", validationContext, null, attributesToValidate)); var validationResults = new List<ValidationResult>(); Assert.False(Validator.TryValidateValue("Invalid Value", validationContext, validationResults, attributesToValidate)); Assert.Equal(1, validationResults.Count); Assert.Equal("ValidValueStringPropertyAttribute.IsValid failed for value Invalid Value", validationResults[0].ErrorMessage); } [Fact] public static void TryValidateValue_returns_true_if_Property_has_no_RequiredAttribute_and_value_is_valid() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "PropertyToBeTested"; var attributesToValidate = new ValidationAttribute[] { new ValidValueStringPropertyAttribute() }; Assert.True(Validator.TryValidateValue("Valid Value", validationContext, null, attributesToValidate)); var validationResults = new List<ValidationResult>(); Assert.True(Validator.TryValidateValue("Valid Value", validationContext, validationResults, attributesToValidate)); Assert.Equal(0, validationResults.Count); } #endregion TryValidateValue #region ValidateValue [Fact] public static void ValidateValueThrowsIf_ValidationContext_is_null() { Assert.Throws<ArgumentNullException>( () => Validator.ValidateValue(new object(), validationContext: null, validationAttributes: Enumerable.Empty<ValidationAttribute>())); } [Fact] public static void ValidateValueThrowsIf_ValidationAttributeEnumerable_is_null() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = null; Assert.Throws<ArgumentNullException>( () => Validator.ValidateValue(new object(), validationContext, validationAttributes: null)); } [Fact] public static void ValidateValue_succeeds_if_no_attributes_to_validate_regardless_of_value() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "NoAttributesProperty"; AssertEx.DoesNotThrow(() => Validator.ValidateValue(null, validationContext, Enumerable.Empty<ValidationAttribute>())); AssertEx.DoesNotThrow(() => Validator.ValidateValue(new object(), validationContext, Enumerable.Empty<ValidationAttribute>())); } // ValidateValue_throws_ValidationException_if_Property_has_RequiredAttribute_and_value_is_null() [Fact] public static void TestValidateValueThrowsIfNullRequiredAttribute() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "PropertyWithRequiredAttribute"; var attributesToValidate = new ValidationAttribute[] { new RequiredAttribute(), new ValidValueStringPropertyAttribute() }; var exception = Assert.Throws<ValidationException>( () => Validator.ValidateValue(null, validationContext, attributesToValidate)); AssertEx.IsType<RequiredAttribute>(exception.ValidationAttribute); // cannot check error message - not defined on ret builds Assert.Null(exception.Value); } // ValidateValue_throws_ValidationException_if_Property_has_RequiredAttribute_and_value_is_invalid() [Fact] public static void TestValidateValueThrowsIfRequiredAttributeInvalid() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "PropertyWithRequiredAttribute"; var attributesToValidate = new ValidationAttribute[] { new RequiredAttribute(), new ValidValueStringPropertyAttribute() }; var exception = Assert.Throws<ValidationException>( () => Validator.ValidateValue("Invalid Value", validationContext, attributesToValidate)); AssertEx.IsType<ValidValueStringPropertyAttribute>(exception.ValidationAttribute); Assert.Equal("ValidValueStringPropertyAttribute.IsValid failed for value Invalid Value", exception.ValidationResult.ErrorMessage); Assert.Equal("Invalid Value", exception.Value); } [Fact] public static void ValidateValue_succeeds_if_Property_has_RequiredAttribute_and_value_is_valid() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "PropertyWithRequiredAttribute"; var attributesToValidate = new ValidationAttribute[] { new RequiredAttribute(), new ValidValueStringPropertyAttribute() }; AssertEx.DoesNotThrow(() => Validator.ValidateValue("Valid Value", validationContext, attributesToValidate)); } // ValidateValue_throws_ValidationException_if_Property_has_no_RequiredAttribute_and_value_is_invalid() [Fact] public static void TestValidateValueThrowsIfNoRequiredAttribute() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "PropertyWithRequiredAttribute"; var attributesToValidate = new ValidationAttribute[] { new ValidValueStringPropertyAttribute() }; var exception = Assert.Throws<ValidationException>( () => Validator.ValidateValue("Invalid Value", validationContext, attributesToValidate)); AssertEx.IsType<ValidValueStringPropertyAttribute>(exception.ValidationAttribute); Assert.Equal("ValidValueStringPropertyAttribute.IsValid failed for value Invalid Value", exception.ValidationResult.ErrorMessage); Assert.Equal("Invalid Value", exception.Value); } [Fact] public static void ValidateValue_succeeds_if_Property_has_no_RequiredAttribute_and_value_is_valid() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "PropertyToBeTested"; var attributesToValidate = new ValidationAttribute[] { new ValidValueStringPropertyAttribute() }; AssertEx.DoesNotThrow(() => Validator.ValidateValue("Valid Value", validationContext, attributesToValidate)); } #endregion ValidateValue [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] public class ValidValueStringPropertyAttribute : ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext _) { if (value == null) { return ValidationResult.Success; } var valueAsString = value as string; if ("Valid Value".Equals(valueAsString)) { return ValidationResult.Success; } return new ValidationResult("ValidValueStringPropertyAttribute.IsValid failed for value " + value); } } [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public class ValidClassAttribute : ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext _) { if (value == null) { return ValidationResult.Success; } if (value.GetType().Name.ToLowerInvariant().Contains("invalid")) { return new ValidationResult("ValidClassAttribute.IsValid failed for class of type " + value.GetType().FullName); } return ValidationResult.Success; } } [ValidClass] public class ToBeValidated { [ValidValueStringProperty] public string PropertyToBeTested { get; set; } public string NoAttributesProperty { get; set; } [Required] [ValidValueStringProperty] public string PropertyWithRequiredAttribute { get; set; } internal string InternalProperty { get; set; } protected string ProtectedProperty { get; set; } private string PrivateProperty { get; set; } public string this[int index] { get { return null; } set { } } public TestEnum EnumProperty { get; set; } public int NonNullableProperty { get; set; } public int? NullableProperty { get; set; } } public enum TestEnum { A = 0 } [ValidClass] public class InvalidToBeValidated { [ValidValueStringProperty] public string PropertyToBeTested { get; set; } public string NoAttributesProperty { get; set; } [Required] [ValidValueStringProperty] public string PropertyWithRequiredAttribute { get; set; } } } }
mit
thejonanshow/my-boxen
vendor/bundle/ruby/2.3.0/gems/puppet-3.8.7/lib/puppet/indirector/none.rb
197
require 'puppet/indirector/terminus' # A none terminus type, meant to always return nil class Puppet::Indirector::None < Puppet::Indirector::Terminus def find(request) return nil end end
mit
lucketta/got-quote-generator
node_modules/react-bootstrap/es/NavItem.js
2607
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import PropTypes from 'prop-types'; import SafeAnchor from './SafeAnchor'; import createChainedFunction from './utils/createChainedFunction'; var propTypes = { active: PropTypes.bool, disabled: PropTypes.bool, role: PropTypes.string, href: PropTypes.string, onClick: PropTypes.func, onSelect: PropTypes.func, eventKey: PropTypes.any }; var defaultProps = { active: false, disabled: false }; var NavItem = function (_React$Component) { _inherits(NavItem, _React$Component); function NavItem(props, context) { _classCallCheck(this, NavItem); var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context)); _this.handleClick = _this.handleClick.bind(_this); return _this; } NavItem.prototype.handleClick = function handleClick(e) { if (this.props.onSelect) { e.preventDefault(); if (!this.props.disabled) { this.props.onSelect(this.props.eventKey, e); } } }; NavItem.prototype.render = function render() { var _props = this.props, active = _props.active, disabled = _props.disabled, onClick = _props.onClick, className = _props.className, style = _props.style, props = _objectWithoutProperties(_props, ['active', 'disabled', 'onClick', 'className', 'style']); delete props.onSelect; delete props.eventKey; // These are injected down by `<Nav>` for building `<SubNav>`s. delete props.activeKey; delete props.activeHref; if (!props.role) { if (props.href === '#') { props.role = 'button'; } } else if (props.role === 'tab') { props['aria-selected'] = active; } return React.createElement( 'li', { role: 'presentation', className: classNames(className, { active: active, disabled: disabled }), style: style }, React.createElement(SafeAnchor, _extends({}, props, { disabled: disabled, onClick: createChainedFunction(onClick, this.handleClick) })) ); }; return NavItem; }(React.Component); NavItem.propTypes = propTypes; NavItem.defaultProps = defaultProps; export default NavItem;
mit
dapperAuteur/railscasts-episodes
episode-313/incoming-after/db/migrate/20111230231220_create_tickets.rb
194
class CreateTickets < ActiveRecord::Migration def change create_table :tickets do |t| t.string :subject t.string :from t.text :body t.timestamps end end end
mit
leontius/maven-framework-project
springmvc-beginners-guide/Appendix/code/webstore/src/main/java/com/packt/webstore/service/CartService.java
273
package com.packt.webstore.service; import com.packt.webstore.domain.Cart; public interface CartService { Cart create(Cart cart); Cart read(String cartId); void update(String cartId, Cart cart); void delete(String cartId); Cart validate(String cartId); }
mit
WitsSoftDev/Phonegap-Boilerplate
BoilerPlates/phonegap-2.9.1/lib/android/framework/src/org/apache/cordova/HttpHandler.java
2771
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.apache.cordova; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; public class HttpHandler { protected Boolean get(String url, String file) { HttpEntity entity = getHttpEntity(url); try { writeToDisk(entity, file); } catch (Exception e) { e.printStackTrace(); return false; } try { entity.consumeContent(); } catch (Exception e) { e.printStackTrace(); return false; } return true; } private HttpEntity getHttpEntity(String url) /** * get the http entity at a given url */ { HttpEntity entity = null; try { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url); HttpResponse response = httpclient.execute(httpget); entity = response.getEntity(); } catch (Exception e) { e.printStackTrace(); return null; } return entity; } private void writeToDisk(HttpEntity entity, String file) throws IllegalStateException, IOException /** * writes a HTTP entity to the specified filename and location on disk */ { //int i = 0; String FilePath = "/sdcard/" + file; InputStream in = entity.getContent(); byte buff[] = new byte[1024]; FileOutputStream out = new FileOutputStream(FilePath); do { int numread = in.read(buff); if (numread <= 0) break; out.write(buff, 0, numread); //i++; } while (true); out.flush(); out.close(); } }
mit
martinep/foam-extend-3.0
applications/utilities/postProcessing/graphics/newEnsightFoamReader/USERD_stop_part_building.H
149
// Not in use void USERD_stop_part_building(void) { #ifdef ENSIGHTDEBUG Info << "Entering: USERD_stop_part_building" << endl << flush; #endif }
gpl-2.0
gjerdery/providence
themes/default/views/editor/objects/access_html.php
1257
<?php /* ---------------------------------------------------------------------- * app/views/editor/objects/access_html.php : * ---------------------------------------------------------------------- * CollectiveAccess * Open-source collections management software * ---------------------------------------------------------------------- * * Software by Whirl-i-Gig (http://www.whirl-i-gig.com) * Copyright 2012 Whirl-i-Gig * * For more information visit http://www.CollectiveAccess.org * * This program is free software; you may redistribute it and/or modify it under * the terms of the provided license as published by Whirl-i-Gig * * CollectiveAccess is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTIES whatsoever, including any implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * This source code is free and modifiable under the terms of * GNU General Public License. (http://www.gnu.org/copyleft/gpl.html). See * the "license.txt" file for details, or visit the CollectiveAccess web site at * http://www.CollectiveAccess.org * * ---------------------------------------------------------------------- */ print caEditorACLEditor($this, $this->getVar('t_subject')); ?>
gpl-3.0
kalwar/openelisglobal-core
liquibase/OE2.9/testCatalogHT_LNSP/scripts/sampleTypeTest.py
1885
#!/usr/bin/env python # -*- coding: utf-8 -*- existing_types = [] def get_split_names( name ): split_name_list = name.split("/") for i in range(0, len(split_name_list)): split_name_list[i] = split_name_list[i].strip() return split_name_list type = [] test_names = [] descriptions = [] sample_type_file = open("sampleType.txt") name_file = open('testName.txt','r') existing_types_file = open("currentSampleTypes.txt") results = open("output/sampleTypeTestResults.txt", 'w') def esc_char(name): if "'" in name: return "$$" + name + "$$" else: return "'" + name + "'" for line in sample_type_file: type.append(line.strip()) sample_type_file.close() for line in name_file: test_names.append(line.strip()) name_file.close() for line in existing_types_file: if len(line) > 0: existing_types.append(line.strip()) existing_types_file.close() for row in range(0, len(test_names)): if len(test_names[row]) > 1: description = test_names[row] + "(" + type[row] + ")" test_select = " (select id from test where description = " + esc_char(description) + " ) " sample_select = " (select id from type_of_sample where description = '" + type[row]+ "') " if description not in descriptions: results.write("DELETE from clinlims.sampletype_test where test_id = " + test_select + " and sample_type_id =" + sample_select + ";\n" ) results.write("INSERT INTO clinlims.sampletype_test (id, test_id , sample_type_id) VALUES \n") results.write("\t(nextval( 'sample_type_test_seq' ) ," + test_select + " , " + sample_select + " );\n") descriptions.append(description) print "Done check sampleTypeTestResults.txt for results"
mpl-2.0
marcoslarsen/pentaho-kettle
engine/src/test/java/org/pentaho/di/job/entries/columnsexist/JobEntryColumnsExistTest.java
6137
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2018 by Hitachi Vantara : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.pentaho.di.job.entries.columnsexist; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import org.pentaho.di.core.KettleEnvironment; import org.pentaho.di.core.Result; import org.pentaho.di.core.database.Database; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.logging.LogLevel; import org.pentaho.di.job.Job; import org.pentaho.di.job.JobMeta; import org.pentaho.di.job.entry.JobEntryCopy; import org.pentaho.di.junit.rules.RestorePDIEngineEnvironment; import static junit.framework.Assert.assertTrue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.mockito.Mockito.when; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.any; import static org.mockito.Mockito.verify; /** * Unit tests for column exist job entry. * * @author Tim Ryzhov * @since 21-03-2017 * */ public class JobEntryColumnsExistTest { @ClassRule public static RestorePDIEngineEnvironment env = new RestorePDIEngineEnvironment(); private static final String TABLENAME = "TABLE"; private static final String SCHEMANAME = "SCHEMA"; private static final String[] COLUMNS = new String[]{"COLUMN1", "COLUMN2"}; private JobEntryColumnsExist jobEntry; private Database db; @BeforeClass public static void setUpBeforeClass() throws KettleException { KettleEnvironment.init( false ); } @AfterClass public static void tearDown() { KettleEnvironment.reset(); } @Before public void setUp() { Job parentJob = new Job( null, new JobMeta() ); jobEntry = spy( new JobEntryColumnsExist( "" ) ); parentJob.getJobMeta().addJobEntry( new JobEntryCopy( jobEntry ) ); parentJob.setStopped( false ); jobEntry.setParentJob( parentJob ); parentJob.setLogLevel( LogLevel.NOTHING ); DatabaseMeta dbMeta = mock( DatabaseMeta.class ); jobEntry.setDatabase( dbMeta ); db = spy( new Database( jobEntry, dbMeta ) ); jobEntry.setParentJob( parentJob ); jobEntry.setTablename( TABLENAME ); jobEntry.setArguments( COLUMNS ); jobEntry.setSchemaname( SCHEMANAME ); } @Test public void jobFail_tableNameIsEmpty() throws KettleException { jobEntry.setTablename( null ); final Result result = jobEntry.execute( new Result(), 0 ); assertEquals( "Should be error", 1, result.getNrErrors() ); assertFalse( "Result should be false", result.getResult() ); } @Test public void jobFail_columnsArrayIsEmpty() throws KettleException { jobEntry.setArguments( null ); final Result result = jobEntry.execute( new Result(), 0 ); assertEquals( "Should be error", 1, result.getNrErrors() ); assertFalse( "Result should be false", result.getResult() ); } @Test public void jobFail_connectionIsNull() throws KettleException { jobEntry.setDatabase( null ); final Result result = jobEntry.execute( new Result(), 0 ); assertEquals( "Should be error", 1, result.getNrErrors() ); assertFalse( "Result should be false", result.getResult() ); } @Test public void jobFail_tableNotExist() throws KettleException { when( jobEntry.getNewDatabaseFromMeta() ).thenReturn( db ); doNothing().when( db ).connect( anyString(), any() ); doReturn( false ).when( db ).checkTableExists( anyString(), anyString() ); final Result result = jobEntry.execute( new Result(), 0 ); assertEquals( "Should be error", 1, result.getNrErrors() ); assertFalse( "Result should be false", result.getResult() ); verify( db, atLeastOnce() ).disconnect(); } @Test public void jobFail_columnNotExist() throws KettleException { doReturn( db ).when( jobEntry ).getNewDatabaseFromMeta(); doNothing().when( db ).connect( anyString(), anyString() ); doReturn( true ).when( db ).checkTableExists( anyString(), anyString() ); doReturn( false ).when( db ).checkColumnExists( anyString(), anyString(), anyString() ); final Result result = jobEntry.execute( new Result(), 0 ); assertEquals( "Should be some errors", 1, result.getNrErrors() ); assertFalse( "Result should be false", result.getResult() ); verify( db, atLeastOnce() ).disconnect(); } @Test public void jobSuccess() throws KettleException { doReturn( db ).when( jobEntry ).getNewDatabaseFromMeta(); doNothing().when( db ).connect( anyString(), anyString() ); doReturn( true ).when( db ).checkColumnExists( anyString(), anyString(), anyString() ); doReturn( true ).when( db ).checkTableExists( anyString(), anyString() ); final Result result = jobEntry.execute( new Result(), 0 ); assertEquals( "Should be no error", 0, result.getNrErrors() ); assertTrue( "Result should be true", result.getResult() ); assertEquals( "Lines written", COLUMNS.length, result.getNrLinesWritten() ); verify( db, atLeastOnce() ).disconnect(); } }
apache-2.0
ariccy/fabric
examples/chaincode/go/chaincode_example04/chaincode_example04.go
4465
/* Copyright IBM Corp. 2016 All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "errors" "fmt" "strconv" "github.com/hyperledger/fabric/core/chaincode/shim" ) // This chaincode is a test for chaincode invoking another chaincode - invokes chaincode_example02 // SimpleChaincode example simple Chaincode implementation type SimpleChaincode struct { } func (t *SimpleChaincode) getChaincodeToCall(stub *shim.ChaincodeStub) (string, error) { //This is the hashcode for github.com/hyperledger/fabric/core/example/chaincode/chaincode_example02 //if the example is modifed this hashcode will change!! chainCodeToCall := "a5389f7dfb9efae379900a41db1503fea2199fe400272b61ac5fe7bd0c6b97cf10ce3aa8dd00cd7626ce02f18accc7e5f2059dae6eb0786838042958352b89fb" //with SHA3 return chainCodeToCall, nil } // Init takes two arguements, a string and int. These are stored in the key/value pair in the state func (t *SimpleChaincode) Init(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) { var event string // Indicates whether event has happened. Initially 0 var eventVal int // State of event var err error if len(args) != 2 { return nil, errors.New("Incorrect number of arguments. Expecting 2") } // Initialize the chaincode event = args[0] eventVal, err = strconv.Atoi(args[1]) if err != nil { return nil, errors.New("Expecting integer value for event status") } fmt.Printf("eventVal = %d\n", eventVal) err = stub.PutState(event, []byte(strconv.Itoa(eventVal))) if err != nil { return nil, err } return nil, nil } // Invoke invokes another chaincode - chaincode_example02, upon receipt of an event and changes event state func (t *SimpleChaincode) Invoke(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) { var event string // Event entity var eventVal int // State of event var err error if len(args) != 2 { return nil, errors.New("Incorrect number of arguments. Expecting 2") } event = args[0] eventVal, err = strconv.Atoi(args[1]) if err != nil { return nil, errors.New("Expected integer value for event state change") } if eventVal != 1 { fmt.Printf("Unexpected event. Doing nothing\n") return nil, nil } // Get the chaincode to call from the ledger chainCodeToCall, err := t.getChaincodeToCall(stub) if err != nil { return nil, err } f := "invoke" invokeArgs := []string{"a", "b", "10"} response, err := stub.InvokeChaincode(chainCodeToCall, f, invokeArgs) if err != nil { errStr := fmt.Sprintf("Failed to invoke chaincode. Got error: %s", err.Error()) fmt.Printf(errStr) return nil, errors.New(errStr) } fmt.Printf("Invoke chaincode successful. Got response %s", string(response)) // Write the event state back to the ledger err = stub.PutState(event, []byte(strconv.Itoa(eventVal))) if err != nil { return nil, err } return nil, nil } // Query callback representing the query of a chaincode func (t *SimpleChaincode) Query(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) { if function != "query" { return nil, errors.New("Invalid query function name. Expecting \"query\"") } var event string // Event entity var err error if len(args) != 1 { return nil, errors.New("Incorrect number of arguments. Expecting entity to query") } event = args[0] // Get the state from the ledger eventValbytes, err := stub.GetState(event) if err != nil { jsonResp := "{\"Error\":\"Failed to get state for " + event + "\"}" return nil, errors.New(jsonResp) } if eventValbytes == nil { jsonResp := "{\"Error\":\"Nil value for " + event + "\"}" return nil, errors.New(jsonResp) } jsonResp := "{\"Name\":\"" + event + "\",\"Amount\":\"" + string(eventValbytes) + "\"}" fmt.Printf("Query Response:%s\n", jsonResp) return []byte(jsonResp), nil } func main() { err := shim.Start(new(SimpleChaincode)) if err != nil { fmt.Printf("Error starting Simple chaincode: %s", err) } }
apache-2.0
Tesora/tesora-horizon
horizon/static/framework/util/q/q.module.spec.js
795
/* * 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. */ (function () { 'use strict'; describe('horizon.framework.util.q module', function () { it('should have been defined', function () { expect(angular.module('horizon.framework.util.q')).toBeDefined(); }); }); })();
apache-2.0
steveloughran/hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/io/erasurecode/rawcoder/TestDummyRawCoder.java
3098
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.io.erasurecode.rawcoder; import org.apache.hadoop.io.erasurecode.ECChunk; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.nio.ByteBuffer; /** * Test dummy raw coder. */ public class TestDummyRawCoder extends TestRawCoderBase { @Before public void setup() { encoderFactoryClass = DummyRawErasureCoderFactory.class; decoderFactoryClass = DummyRawErasureCoderFactory.class; setAllowDump(false); setChunkSize(baseChunkSize); } @Test public void testCoding_6x3_erasing_d0_d2() { prepare(null, 6, 3, new int[]{0, 2}, new int[0], false); testCodingDoMixed(); } @Test public void testCoding_6x3_erasing_d0_p0() { prepare(null, 6, 3, new int[]{0}, new int[]{0}, false); testCodingDoMixed(); } @Override protected void testCoding(boolean usingDirectBuffer) { this.usingDirectBuffer = usingDirectBuffer; prepareCoders(true); prepareBufferAllocator(true); setAllowChangeInputs(false); // Generate data and encode ECChunk[] dataChunks = prepareDataChunksForEncoding(); markChunks(dataChunks); ECChunk[] parityChunks = prepareParityChunksForEncoding(); try { encoder.encode(dataChunks, parityChunks); } catch (IOException e) { Assert.fail("Unexpected IOException: " + e.getMessage()); } compareAndVerify(parityChunks, getEmptyChunks(parityChunks.length)); // Decode restoreChunksFromMark(dataChunks); backupAndEraseChunks(dataChunks, parityChunks); ECChunk[] inputChunks = prepareInputChunksForDecoding( dataChunks, parityChunks); ensureOnlyLeastRequiredChunks(inputChunks); ECChunk[] recoveredChunks = prepareOutputChunksForDecoding(); try { decoder.decode(inputChunks, getErasedIndexesForDecoding(), recoveredChunks); } catch (IOException e) { Assert.fail("Unexpected IOException: " + e.getMessage()); } compareAndVerify(recoveredChunks, getEmptyChunks(recoveredChunks.length)); } private ECChunk[] getEmptyChunks(int num) { ECChunk[] chunks = new ECChunk[num]; for (int i = 0; i < chunks.length; i++) { chunks[i] = new ECChunk(ByteBuffer.wrap(getZeroChunkBytes())); } return chunks; } }
apache-2.0
jconley/homebrew-cask
Casks/near-lock.rb
301
cask 'near-lock' do version '4.0.0' sha256 'cb2c849b9b941b609a6f2c8101d8fa6990bfce0714b790567b16af824cf10c12' url 'https://nearlock.me/downloads/nearlock.dmg' appcast 'https://nearlock.me/downloads/nearlock.xml' name 'Near Lock' homepage 'https://nearlock.me/' app 'Near Lock.app' end
bsd-2-clause
MakMukhi/grpc
src/php/tests/qps/generated_code/Grpc/Testing/ProxyStat.php
924
<?php # Generated by the protocol buffer compiler. DO NOT EDIT! # source: src/proto/grpc/testing/proxy-service.proto namespace Grpc\Testing; use Google\Protobuf\Internal\GPBType; use Google\Protobuf\Internal\RepeatedField; use Google\Protobuf\Internal\GPBUtil; /** * Protobuf type <code>grpc.testing.ProxyStat</code> */ class ProxyStat extends \Google\Protobuf\Internal\Message { /** * <code>double latency = 1;</code> */ private $latency = 0.0; public function __construct() { \GPBMetadata\Src\Proto\Grpc\Testing\ProxyService::initOnce(); parent::__construct(); } /** * <code>double latency = 1;</code> */ public function getLatency() { return $this->latency; } /** * <code>double latency = 1;</code> */ public function setLatency($var) { GPBUtil::checkDouble($var); $this->latency = $var; } }
bsd-3-clause
poizan42/coreclr
src/pal/src/safecrt/wsplitpath_s.cpp
779
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*** *wsplitpath_s.c - break down path name into components * * *Purpose: * To provide support for accessing the individual components of an * arbitrary path name * *******************************************************************************/ #include <string.h> #include <errno.h> #include <limits.h> #include "internal_securecrt.h" #include "mbusafecrt_internal.h" #define _FUNC_PROLOGUE #define _FUNC_NAME _wsplitpath_s #define _CHAR char16_t #define _TCSNCPY_S wcsncpy_s #define _T(_Character) L##_Character #define _MBS_SUPPORT 0 #include "tsplitpath_s.inl"
mit
FallenAngel290487/slimtune
external/boost_1_44_0/boost/graph/named_function_params.hpp
21408
//======================================================================= // Copyright 1997, 1998, 1999, 2000 University of Notre Dame. // Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #ifndef BOOST_GRAPH_NAMED_FUNCTION_PARAMS_HPP #define BOOST_GRAPH_NAMED_FUNCTION_PARAMS_HPP #include <boost/graph/properties.hpp> #include <boost/ref.hpp> #include <boost/parameter/name.hpp> #include <boost/parameter/binding.hpp> #include <boost/type_traits/is_same.hpp> #include <boost/mpl/not.hpp> #include <boost/type_traits/add_reference.hpp> #include <boost/graph/named_function_params.hpp> #include <boost/property_map/property_map.hpp> #include <boost/property_map/shared_array_property_map.hpp> namespace boost { struct distance_compare_t { }; struct distance_combine_t { }; struct distance_inf_t { }; struct distance_zero_t { }; struct buffer_param_t { }; struct edge_copy_t { }; struct vertex_copy_t { }; struct vertex_isomorphism_t { }; struct vertex_invariant_t { }; struct vertex_invariant1_t { }; struct vertex_invariant2_t { }; struct edge_compare_t { }; struct vertex_max_invariant_t { }; struct orig_to_copy_t { }; struct root_vertex_t { }; struct polling_t { }; struct lookahead_t { }; struct in_parallel_t { }; struct attractive_force_t { }; struct repulsive_force_t { }; struct force_pairs_t { }; struct cooling_t { }; struct vertex_displacement_t { }; struct iterations_t { }; struct diameter_range_t { }; struct learning_constant_range_t { }; struct vertices_equivalent_t { }; struct edges_equivalent_t { }; #define BOOST_BGL_DECLARE_NAMED_PARAMS \ BOOST_BGL_ONE_PARAM_CREF(weight_map, edge_weight) \ BOOST_BGL_ONE_PARAM_CREF(weight_map2, edge_weight2) \ BOOST_BGL_ONE_PARAM_CREF(distance_map, vertex_distance) \ BOOST_BGL_ONE_PARAM_CREF(predecessor_map, vertex_predecessor) \ BOOST_BGL_ONE_PARAM_CREF(rank_map, vertex_rank) \ BOOST_BGL_ONE_PARAM_CREF(root_map, vertex_root) \ BOOST_BGL_ONE_PARAM_CREF(root_vertex, root_vertex) \ BOOST_BGL_ONE_PARAM_CREF(edge_centrality_map, edge_centrality) \ BOOST_BGL_ONE_PARAM_CREF(centrality_map, vertex_centrality) \ BOOST_BGL_ONE_PARAM_CREF(color_map, vertex_color) \ BOOST_BGL_ONE_PARAM_CREF(edge_color_map, edge_color) \ BOOST_BGL_ONE_PARAM_CREF(capacity_map, edge_capacity) \ BOOST_BGL_ONE_PARAM_CREF(residual_capacity_map, edge_residual_capacity) \ BOOST_BGL_ONE_PARAM_CREF(reverse_edge_map, edge_reverse) \ BOOST_BGL_ONE_PARAM_CREF(discover_time_map, vertex_discover_time) \ BOOST_BGL_ONE_PARAM_CREF(lowpoint_map, vertex_lowpoint) \ BOOST_BGL_ONE_PARAM_CREF(vertex_index_map, vertex_index) \ BOOST_BGL_ONE_PARAM_CREF(vertex_index1_map, vertex_index1) \ BOOST_BGL_ONE_PARAM_CREF(vertex_index2_map, vertex_index2) \ BOOST_BGL_ONE_PARAM_CREF(visitor, graph_visitor) \ BOOST_BGL_ONE_PARAM_CREF(distance_compare, distance_compare) \ BOOST_BGL_ONE_PARAM_CREF(distance_combine, distance_combine) \ BOOST_BGL_ONE_PARAM_CREF(distance_inf, distance_inf) \ BOOST_BGL_ONE_PARAM_CREF(distance_zero, distance_zero) \ BOOST_BGL_ONE_PARAM_CREF(edge_copy, edge_copy) \ BOOST_BGL_ONE_PARAM_CREF(vertex_copy, vertex_copy) \ BOOST_BGL_ONE_PARAM_REF(buffer, buffer_param) \ BOOST_BGL_ONE_PARAM_CREF(orig_to_copy, orig_to_copy) \ BOOST_BGL_ONE_PARAM_CREF(isomorphism_map, vertex_isomorphism) \ BOOST_BGL_ONE_PARAM_CREF(vertex_invariant, vertex_invariant) \ BOOST_BGL_ONE_PARAM_CREF(vertex_invariant1, vertex_invariant1) \ BOOST_BGL_ONE_PARAM_CREF(vertex_invariant2, vertex_invariant2) \ BOOST_BGL_ONE_PARAM_CREF(vertex_max_invariant, vertex_max_invariant) \ BOOST_BGL_ONE_PARAM_CREF(polling, polling) \ BOOST_BGL_ONE_PARAM_CREF(lookahead, lookahead) \ BOOST_BGL_ONE_PARAM_CREF(in_parallel, in_parallel) \ BOOST_BGL_ONE_PARAM_CREF(displacement_map, vertex_displacement) \ BOOST_BGL_ONE_PARAM_CREF(attractive_force, attractive_force) \ BOOST_BGL_ONE_PARAM_CREF(repulsive_force, repulsive_force) \ BOOST_BGL_ONE_PARAM_CREF(force_pairs, force_pairs) \ BOOST_BGL_ONE_PARAM_CREF(cooling, cooling) \ BOOST_BGL_ONE_PARAM_CREF(iterations, iterations) \ BOOST_BGL_ONE_PARAM_CREF(diameter_range, diameter_range) \ BOOST_BGL_ONE_PARAM_CREF(learning_constant_range, learning_constant_range) \ BOOST_BGL_ONE_PARAM_CREF(vertices_equivalent, vertices_equivalent) \ BOOST_BGL_ONE_PARAM_CREF(edges_equivalent, edges_equivalent) template <typename T, typename Tag, typename Base = no_property> struct bgl_named_params : public Base { typedef bgl_named_params self; typedef Base next_type; typedef Tag tag_type; typedef T value_type; bgl_named_params(T v = T()) : m_value(v) { } bgl_named_params(T v, const Base& b) : Base(b), m_value(v) { } T m_value; #define BOOST_BGL_ONE_PARAM_REF(name, key) \ template <typename PType> \ bgl_named_params<boost::reference_wrapper<PType>, BOOST_PP_CAT(key, _t), self> \ name(PType& p) const { \ typedef bgl_named_params<boost::reference_wrapper<PType>, BOOST_PP_CAT(key, _t), self> Params; \ return Params(boost::ref(p), *this); \ } \ #define BOOST_BGL_ONE_PARAM_CREF(name, key) \ template <typename PType> \ bgl_named_params<PType, BOOST_PP_CAT(key, _t), self> \ name(const PType& p) const { \ typedef bgl_named_params<PType, BOOST_PP_CAT(key, _t), self> Params; \ return Params(p, *this); \ } \ BOOST_BGL_DECLARE_NAMED_PARAMS #undef BOOST_BGL_ONE_PARAM_REF #undef BOOST_BGL_ONE_PARAM_CREF // Duplicate template <typename PType> bgl_named_params<PType, vertex_color_t, self> vertex_color_map(const PType& p) const {return this->color_map(p);} }; #define BOOST_BGL_ONE_PARAM_REF(name, key) \ template <typename PType> \ bgl_named_params<boost::reference_wrapper<PType>, BOOST_PP_CAT(key, _t)> \ name(PType& p) { \ typedef bgl_named_params<boost::reference_wrapper<PType>, BOOST_PP_CAT(key, _t)> Params; \ return Params(boost::ref(p)); \ } \ #define BOOST_BGL_ONE_PARAM_CREF(name, key) \ template <typename PType> \ bgl_named_params<PType, BOOST_PP_CAT(key, _t)> \ name(const PType& p) { \ typedef bgl_named_params<PType, BOOST_PP_CAT(key, _t)> Params; \ return Params(p); \ } \ BOOST_BGL_DECLARE_NAMED_PARAMS #undef BOOST_BGL_ONE_PARAM_REF #undef BOOST_BGL_ONE_PARAM_CREF // Duplicate template <typename PType> bgl_named_params<PType, vertex_color_t> vertex_color_map(const PType& p) {return color_map(p);} namespace detail { struct unused_tag_type {}; } typedef bgl_named_params<char, detail::unused_tag_type> no_named_parameters; //=========================================================================== // Functions for extracting parameters from bgl_named_params template <class Tag1, class Tag2, class T1, class Base> inline typename property_value< bgl_named_params<T1,Tag1,Base>, Tag2>::type get_param(const bgl_named_params<T1,Tag1,Base>& p, Tag2 tag2) { enum { match = detail::same_property<Tag1,Tag2>::value }; typedef typename property_value< bgl_named_params<T1,Tag1,Base>, Tag2>::type T2; T2* t2 = 0; typedef detail::property_value_dispatch<match> Dispatcher; return Dispatcher::const_get_value(p, t2, tag2); } namespace detail { // MSVC++ workaround template <class Param> struct choose_param_helper { template <class Default> struct result { typedef Param type; }; template <typename Default> static const Param& apply(const Param& p, const Default&) { return p; } }; template <> struct choose_param_helper<error_property_not_found> { template <class Default> struct result { typedef Default type; }; template <typename Default> static const Default& apply(const error_property_not_found&, const Default& d) { return d; } }; } // namespace detail template <class P, class Default> const typename detail::choose_param_helper<P>::template result<Default>::type& choose_param(const P& param, const Default& d) { return detail::choose_param_helper<P>::apply(param, d); } template <typename T> inline bool is_default_param(const T&) { return false; } inline bool is_default_param(const detail::error_property_not_found&) { return true; } namespace detail { struct choose_parameter { template <class P, class Graph, class Tag> struct bind_ { typedef const P& const_result_type; typedef const P& result_type; typedef P type; }; template <class P, class Graph, class Tag> static typename bind_<P, Graph, Tag>::const_result_type const_apply(const P& p, const Graph&, Tag&) { return p; } template <class P, class Graph, class Tag> static typename bind_<P, Graph, Tag>::result_type apply(const P& p, Graph&, Tag&) { return p; } }; struct choose_default_param { template <class P, class Graph, class Tag> struct bind_ { typedef typename property_map<Graph, Tag>::type result_type; typedef typename property_map<Graph, Tag>::const_type const_result_type; typedef typename property_map<Graph, Tag>::const_type type; }; template <class P, class Graph, class Tag> static typename bind_<P, Graph, Tag>::const_result_type const_apply(const P&, const Graph& g, Tag tag) { return get(tag, g); } template <class P, class Graph, class Tag> static typename bind_<P, Graph, Tag>::result_type apply(const P&, Graph& g, Tag tag) { return get(tag, g); } }; template <class Param> struct choose_property_map { typedef choose_parameter type; }; template <> struct choose_property_map<detail::error_property_not_found> { typedef choose_default_param type; }; template <class Param, class Graph, class Tag> struct choose_pmap_helper { typedef typename choose_property_map<Param>::type Selector; typedef typename Selector:: template bind_<Param, Graph, Tag> Bind; typedef Bind type; typedef typename Bind::result_type result_type; typedef typename Bind::const_result_type const_result_type; typedef typename Bind::type result; }; // used in the max-flow algorithms template <class Graph, class P, class T, class R> struct edge_capacity_value { typedef bgl_named_params<P, T, R> Params; typedef typename property_value< Params, edge_capacity_t>::type Param; typedef typename detail::choose_pmap_helper<Param, Graph, edge_capacity_t>::result CapacityEdgeMap; typedef typename property_traits<CapacityEdgeMap>::value_type type; }; } // namespace detail // Use this function instead of choose_param() when you want // to avoid requiring get(tag, g) when it is not used. template <typename Param, typename Graph, typename PropertyTag> typename detail::choose_pmap_helper<Param,Graph,PropertyTag>::const_result_type choose_const_pmap(const Param& p, const Graph& g, PropertyTag tag) { typedef typename detail::choose_pmap_helper<Param,Graph,PropertyTag>::Selector Choice; return Choice::const_apply(p, g, tag); } template <typename Param, typename Graph, typename PropertyTag> typename detail::choose_pmap_helper<Param,Graph,PropertyTag>::result_type choose_pmap(const Param& p, Graph& g, PropertyTag tag) { typedef typename detail::choose_pmap_helper<Param,Graph,PropertyTag>::Selector Choice; return Choice::apply(p, g, tag); } // Declare all new tags namespace graph { namespace keywords { #define BOOST_BGL_ONE_PARAM_REF(name, key) BOOST_PARAMETER_NAME(name) #define BOOST_BGL_ONE_PARAM_CREF(name, key) BOOST_PARAMETER_NAME(name) BOOST_BGL_DECLARE_NAMED_PARAMS #undef BOOST_BGL_ONE_PARAM_REF #undef BOOST_BGL_ONE_PARAM_CREF } } namespace detail { template <typename Tag> struct convert_one_keyword {}; #define BOOST_BGL_ONE_PARAM_REF(name, key) \ template <> \ struct convert_one_keyword<BOOST_PP_CAT(key, _t)> { \ typedef boost::graph::keywords::tag::name type; \ }; #define BOOST_BGL_ONE_PARAM_CREF(name, key) BOOST_BGL_ONE_PARAM_REF(name, key) BOOST_BGL_DECLARE_NAMED_PARAMS #undef BOOST_BGL_ONE_PARAM_REF #undef BOOST_BGL_ONE_PARAM_CREF template <typename T> struct convert_bgl_params_to_boost_parameter { typedef typename convert_one_keyword<typename T::tag_type>::type new_kw; typedef boost::parameter::aux::tagged_argument<new_kw, const typename T::value_type> tagged_arg_type; typedef convert_bgl_params_to_boost_parameter<typename T::next_type> rest_conv; typedef boost::parameter::aux::arg_list<tagged_arg_type, typename rest_conv::type> type; static type conv(const T& x) { return type(tagged_arg_type(x.m_value), rest_conv::conv(x)); } }; template <typename P, typename R> struct convert_bgl_params_to_boost_parameter<bgl_named_params<P, int, R> > { typedef convert_bgl_params_to_boost_parameter<R> rest_conv; typedef typename rest_conv::type type; static type conv(const bgl_named_params<P, int, R>& x) { return rest_conv::conv(x); } }; template <> struct convert_bgl_params_to_boost_parameter<boost::no_property> { typedef boost::parameter::aux::empty_arg_list type; static type conv(const boost::no_property&) {return type();} }; template <> struct convert_bgl_params_to_boost_parameter<boost::no_named_parameters> { typedef boost::parameter::aux::empty_arg_list type; static type conv(const boost::no_property&) {return type();} }; struct bgl_parameter_not_found_type {}; template <typename ArgPack, typename KeywordType> struct parameter_exists : boost::mpl::not_<boost::is_same<typename boost::parameter::binding<ArgPack, KeywordType, bgl_parameter_not_found_type>::type, bgl_parameter_not_found_type> > {}; } #define BOOST_GRAPH_DECLARE_CONVERTED_PARAMETERS(old_type, old_var) \ typedef typename boost::detail::convert_bgl_params_to_boost_parameter<old_type>::type arg_pack_type; \ arg_pack_type arg_pack = boost::detail::convert_bgl_params_to_boost_parameter<old_type>::conv(old_var); namespace detail { template <typename ArgType, typename Prop, typename Graph, bool Exists> struct override_const_property_t { typedef ArgType result_type; result_type operator()(const Graph&, const typename boost::add_reference<ArgType>::type a) const {return a;} }; template <typename ArgType, typename Prop, typename Graph> struct override_const_property_t<ArgType, Prop, Graph, false> { typedef typename boost::property_map<Graph, Prop>::const_type result_type; result_type operator()(const Graph& g, const ArgType&) const {return get(Prop(), g);} }; template <typename ArgPack, typename Tag, typename Prop, typename Graph> struct override_const_property_result { typedef typename override_const_property_t< typename boost::parameter::value_type<ArgPack, Tag, int>::type, Prop, Graph, boost::detail::parameter_exists<ArgPack, Tag>::value >::result_type type; }; template <typename ArgPack, typename Tag, typename Prop, typename Graph> typename override_const_property_result<ArgPack, Tag, Prop, Graph>::type override_const_property(const ArgPack& ap, const boost::parameter::keyword<Tag>& t, const Graph& g, Prop) { return override_const_property_t< typename boost::parameter::value_type<ArgPack, Tag, int>::type, Prop, Graph, boost::detail::parameter_exists<ArgPack, Tag>::value >()(g, ap[t | 0]); } template <typename ArgType, typename Prop, typename Graph, bool Exists> struct override_property_t { typedef ArgType result_type; result_type operator()(const Graph& g, const typename boost::add_reference<ArgType>::type a) const {return a;} }; template <typename ArgType, typename Prop, typename Graph> struct override_property_t<ArgType, Prop, Graph, false> { typedef typename boost::property_map<Graph, Prop>::type result_type; result_type operator()(const Graph& g, const ArgType& a) const {return get(Prop(), g);} }; template <typename ArgPack, typename Tag, typename Prop, typename Graph> struct override_property_result { typedef typename override_property_t< typename boost::parameter::value_type<ArgPack, Tag, int>::type, Prop, Graph, boost::detail::parameter_exists<ArgPack, Tag>::value >::result_type type; }; template <typename ArgPack, typename Tag, typename Prop, typename Graph> typename override_property_result<ArgPack, Tag, Prop, Graph>::type override_property(const ArgPack& ap, const boost::parameter::keyword<Tag>& t, const Graph& g, Prop prop) { return override_property_t< typename boost::parameter::value_type<ArgPack, Tag, int>::type, Prop, Graph, boost::detail::parameter_exists<ArgPack, Tag>::value >()(g, ap[t | 0]); } } namespace detail { template <bool Exists, typename Graph, typename ArgPack, typename Value, typename PM> struct map_maker_helper { typedef PM map_type; static PM make_map(const Graph&, Value, const PM& pm, const ArgPack&) { return pm; } }; template <typename Graph, typename ArgPack, typename Value, typename PM> struct map_maker_helper<false, Graph, ArgPack, Value, PM> { typedef typename boost::remove_const< typename override_const_property_t< typename boost::parameter::value_type< ArgPack, boost::graph::keywords::tag::vertex_index_map, int>::type, boost::vertex_index_t, Graph, boost::detail::parameter_exists< ArgPack, boost::graph::keywords::tag::vertex_index_map>::value >::result_type>::type vi_map_type; typedef boost::shared_array_property_map<Value, vi_map_type> map_type; static map_type make_map(const Graph& g, Value v, const PM&, const ArgPack& ap) { return make_shared_array_property_map( num_vertices(g), v, override_const_property( ap, boost::graph::keywords::_vertex_index_map, g, vertex_index)); } }; template <typename Graph, typename ArgPack, typename MapTag, typename ValueType> struct map_maker { BOOST_STATIC_CONSTANT( bool, has_map = (parameter_exists<ArgPack, MapTag> ::value)); typedef map_maker_helper<has_map, Graph, ArgPack, ValueType, typename boost::remove_const< typename boost::parameter::value_type< ArgPack, MapTag, int >::type >::type> helper; typedef typename helper::map_type map_type; static map_type make_map(const Graph& g, const ArgPack& ap, ValueType default_value) { return helper::make_map(g, default_value, ap[::boost::parameter::keyword<MapTag>::instance | 0], ap); } }; template <typename MapTag, typename ValueType = void> class make_property_map_from_arg_pack_gen { ValueType default_value; public: make_property_map_from_arg_pack_gen(ValueType default_value) : default_value(default_value) {} template <typename Graph, typename ArgPack> typename map_maker<Graph, ArgPack, MapTag, ValueType>::map_type operator()(const Graph& g, const ArgPack& ap) const { return map_maker<Graph, ArgPack, MapTag, ValueType>::make_map(g, ap, default_value); } }; template <typename MapTag> class make_property_map_from_arg_pack_gen<MapTag, void> { public: template <typename ValueType, typename Graph, typename ArgPack> typename map_maker<Graph, ArgPack, MapTag, ValueType>::map_type operator()(const Graph& g, const ArgPack& ap, ValueType default_value) const { return map_maker<Graph, ArgPack, MapTag, ValueType>::make_map(g, ap, default_value); } }; static const make_property_map_from_arg_pack_gen< boost::graph::keywords::tag::color_map, default_color_type> make_color_map_from_arg_pack(white_color); } } // namespace boost #undef BOOST_BGL_DECLARE_NAMED_PARAMS #endif // BOOST_GRAPH_NAMED_FUNCTION_PARAMS_HPP
mit
neilgaietto/Umbraco-CMS
src/Umbraco.Web/Models/ContentEditing/PropertyTypeBasic.cs
1595
using System; using System.ComponentModel.DataAnnotations; using System.Runtime.Serialization; namespace Umbraco.Web.Models.ContentEditing { [DataContract(Name = "propertyType")] public class PropertyTypeBasic { /// <summary> /// Gets a value indicating whether the property type is inherited through /// content types composition. /// </summary> /// <remarks>Inherited is true when the property is defined by a content type /// higher in the composition, and not by the content type currently being /// edited.</remarks> [DataMember(Name = "inherited")] public bool Inherited { get; set; } // needed - so we can handle alias renames [DataMember(Name = "id")] public int Id { get; set; } [Required] [RegularExpression(@"^([a-zA-Z]\w.*)$", ErrorMessage = "Invalid alias")] [DataMember(Name = "alias")] public string Alias { get; set; } [DataMember(Name = "description")] public string Description { get; set; } [DataMember(Name = "validation")] public PropertyTypeValidation Validation { get; set; } [DataMember(Name = "label")] [Required] public string Label { get; set; } [DataMember(Name = "sortOrder")] public int SortOrder { get; set; } [DataMember(Name = "dataTypeId")] [Required] public int DataTypeId { get; set; } //SD: Is this really needed ? [DataMember(Name = "groupId")] public int GroupId { get; set; } } }
mit
squashjedi/basecamp
vendor/symfony/http-foundation/Tests/CookieTest.php
6907
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\HttpFoundation\Tests; use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\Cookie; /** * CookieTest. * * @author John Kary <[email protected]> * @author Hugo Hamon <[email protected]> * * @group time-sensitive */ class CookieTest extends TestCase { public function invalidNames() { return array( array(''), array(',MyName'), array(';MyName'), array(' MyName'), array("\tMyName"), array("\rMyName"), array("\nMyName"), array("\013MyName"), array("\014MyName"), ); } /** * @dataProvider invalidNames * @expectedException \InvalidArgumentException */ public function testInstantiationThrowsExceptionIfCookieNameContainsInvalidCharacters($name) { new Cookie($name); } /** * @expectedException \InvalidArgumentException */ public function testInvalidExpiration() { new Cookie('MyCookie', 'foo', 'bar'); } public function testNegativeExpirationIsNotPossible() { $cookie = new Cookie('foo', 'bar', -100); $this->assertSame(0, $cookie->getExpiresTime()); } public function testGetValue() { $value = 'MyValue'; $cookie = new Cookie('MyCookie', $value); $this->assertSame($value, $cookie->getValue(), '->getValue() returns the proper value'); } public function testGetPath() { $cookie = new Cookie('foo', 'bar'); $this->assertSame('/', $cookie->getPath(), '->getPath() returns / as the default path'); } public function testGetExpiresTime() { $cookie = new Cookie('foo', 'bar'); $this->assertEquals(0, $cookie->getExpiresTime(), '->getExpiresTime() returns the default expire date'); $cookie = new Cookie('foo', 'bar', $expire = time() + 3600); $this->assertEquals($expire, $cookie->getExpiresTime(), '->getExpiresTime() returns the expire date'); } public function testGetExpiresTimeIsCastToInt() { $cookie = new Cookie('foo', 'bar', 3600.9); $this->assertSame(3600, $cookie->getExpiresTime(), '->getExpiresTime() returns the expire date as an integer'); } public function testConstructorWithDateTime() { $expire = new \DateTime(); $cookie = new Cookie('foo', 'bar', $expire); $this->assertEquals($expire->format('U'), $cookie->getExpiresTime(), '->getExpiresTime() returns the expire date'); } /** * @requires PHP 5.5 */ public function testConstructorWithDateTimeImmutable() { $expire = new \DateTimeImmutable(); $cookie = new Cookie('foo', 'bar', $expire); $this->assertEquals($expire->format('U'), $cookie->getExpiresTime(), '->getExpiresTime() returns the expire date'); } public function testGetExpiresTimeWithStringValue() { $value = '+1 day'; $cookie = new Cookie('foo', 'bar', $value); $expire = strtotime($value); $this->assertEquals($expire, $cookie->getExpiresTime(), '->getExpiresTime() returns the expire date', 1); } public function testGetDomain() { $cookie = new Cookie('foo', 'bar', 0, '/', '.myfoodomain.com'); $this->assertEquals('.myfoodomain.com', $cookie->getDomain(), '->getDomain() returns the domain name on which the cookie is valid'); } public function testIsSecure() { $cookie = new Cookie('foo', 'bar', 0, '/', '.myfoodomain.com', true); $this->assertTrue($cookie->isSecure(), '->isSecure() returns whether the cookie is transmitted over HTTPS'); } public function testIsHttpOnly() { $cookie = new Cookie('foo', 'bar', 0, '/', '.myfoodomain.com', false, true); $this->assertTrue($cookie->isHttpOnly(), '->isHttpOnly() returns whether the cookie is only transmitted over HTTP'); } public function testCookieIsNotCleared() { $cookie = new Cookie('foo', 'bar', time() + 3600 * 24); $this->assertFalse($cookie->isCleared(), '->isCleared() returns false if the cookie did not expire yet'); } public function testCookieIsCleared() { $cookie = new Cookie('foo', 'bar', time() - 20); $this->assertTrue($cookie->isCleared(), '->isCleared() returns true if the cookie has expired'); } public function testToString() { $cookie = new Cookie('foo', 'bar', $expire = strtotime('Fri, 20-May-2011 15:25:52 GMT'), '/', '.myfoodomain.com', true); $this->assertEquals('foo=bar; expires=Fri, 20-May-2011 15:25:52 GMT; max-age='.($expire - time()).'; path=/; domain=.myfoodomain.com; secure; httponly', (string) $cookie, '->__toString() returns string representation of the cookie'); $cookie = new Cookie('foo', null, 1, '/admin/', '.myfoodomain.com'); $this->assertEquals('foo=deleted; expires='.gmdate('D, d-M-Y H:i:s T', $expire = time() - 31536001).'; max-age='.($expire - time()).'; path=/admin/; domain=.myfoodomain.com; httponly', (string) $cookie, '->__toString() returns string representation of a cleared cookie if value is NULL'); $cookie = new Cookie('foo', 'bar', 0, '/', ''); $this->assertEquals('foo=bar; path=/; httponly', (string) $cookie); } public function testRawCookie() { $cookie = new Cookie('foo', 'b a r', 0, '/', null, false, false); $this->assertFalse($cookie->isRaw()); $this->assertEquals('foo=b+a+r; path=/', (string) $cookie); $cookie = new Cookie('foo', 'b+a+r', 0, '/', null, false, false, true); $this->assertTrue($cookie->isRaw()); $this->assertEquals('foo=b+a+r; path=/', (string) $cookie); } public function testGetMaxAge() { $cookie = new Cookie('foo', 'bar'); $this->assertEquals(0, $cookie->getMaxAge()); $cookie = new Cookie('foo', 'bar', $expire = time() + 100); $this->assertEquals($expire - time(), $cookie->getMaxAge()); $cookie = new Cookie('foo', 'bar', $expire = time() - 100); $this->assertEquals($expire - time(), $cookie->getMaxAge()); } public function testFromString() { $cookie = Cookie::fromString('foo=bar; expires=Fri, 20-May-2011 15:25:52 GMT; path=/; domain=.myfoodomain.com; secure; httponly'); $this->assertEquals(new Cookie('foo', 'bar', strtotime('Fri, 20-May-2011 15:25:52 GMT'), '/', '.myfoodomain.com', true, true, true), $cookie); $cookie = Cookie::fromString('foo=bar', true); $this->assertEquals(new Cookie('foo', 'bar'), $cookie); } }
mit
ckjeldgaard/hmdk
sites/all/modules/custom/firebase/google-api-php-client/vendor/google/apiclient-services/src/Google/Service/Spanner/LogConfig.php
1578
<?php /* * Copyright 2016 Google Inc. * * 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. */ class Google_Service_Spanner_LogConfig extends Google_Model { protected $cloudAuditType = 'Google_Service_Spanner_CloudAuditOptions'; protected $cloudAuditDataType = ''; protected $counterType = 'Google_Service_Spanner_CounterOptions'; protected $counterDataType = ''; protected $dataAccessType = 'Google_Service_Spanner_DataAccessOptions'; protected $dataAccessDataType = ''; public function setCloudAudit(Google_Service_Spanner_CloudAuditOptions $cloudAudit) { $this->cloudAudit = $cloudAudit; } public function getCloudAudit() { return $this->cloudAudit; } public function setCounter(Google_Service_Spanner_CounterOptions $counter) { $this->counter = $counter; } public function getCounter() { return $this->counter; } public function setDataAccess(Google_Service_Spanner_DataAccessOptions $dataAccess) { $this->dataAccess = $dataAccess; } public function getDataAccess() { return $this->dataAccess; } }
gpl-2.0
ernandesferreira/microcampcaxias
wp-content/themes/Revera/FT/colors.php
148
<?php return array ( 'color1' => '#adadb0', 'color2' => '#5a5b5c', 'color3' => '#9de8ff', 'color4' => '#f4fcff', 'color5' => '#d18a50', );
gpl-2.0
SunguckLee/MariaDB-PageCompression
storage/tokudb/ft-index/src/tests/openlimit17-locktree.cc
6566
/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */ // vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4: #ident "$Id$" /* COPYING CONDITIONS NOTICE: This program is free software; you can redistribute it and/or modify it under the terms of version 2 of the GNU General Public License as published by the Free Software Foundation, and provided that the following conditions are met: * Redistributions of source code must retain this COPYING CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the PATENT MARKING NOTICE (below), and the PATENT RIGHTS GRANT (below). * Redistributions in binary form must reproduce this COPYING CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the PATENT MARKING NOTICE (below), and the PATENT RIGHTS GRANT (below) in the documentation and/or other materials provided with the distribution. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. COPYRIGHT NOTICE: TokuFT, Tokutek Fractal Tree Indexing Library. Copyright (C) 2007-2013 Tokutek, Inc. DISCLAIMER: This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. UNIVERSITY PATENT NOTICE: The technology is licensed by the Massachusetts Institute of Technology, Rutgers State University of New Jersey, and the Research Foundation of State University of New York at Stony Brook under United States of America Serial No. 11/760379 and to the patents and/or patent applications resulting from it. PATENT MARKING NOTICE: This software is covered by US Patent No. 8,185,551. This software is covered by US Patent No. 8,489,638. PATENT RIGHTS GRANT: "THIS IMPLEMENTATION" means the copyrightable works distributed by Tokutek as part of the Fractal Tree project. "PATENT CLAIMS" means the claims of patents that are owned or licensable by Tokutek, both currently or in the future; and that in the absence of this license would be infringed by THIS IMPLEMENTATION or by using or running THIS IMPLEMENTATION. "PATENT CHALLENGE" shall mean a challenge to the validity, patentability, enforceability and/or non-infringement of any of the PATENT CLAIMS or otherwise opposing any of the PATENT CLAIMS. Tokutek hereby grants to you, for the term and geographical scope of the PATENT CLAIMS, a non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, transfer, and otherwise run, modify, and propagate the contents of THIS IMPLEMENTATION, where such license applies only to the PATENT CLAIMS. This grant does not include claims that would be infringed only as a consequence of further modifications of THIS IMPLEMENTATION. If you or your agent or licensee institute or order or agree to the institution of patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that THIS IMPLEMENTATION constitutes direct or contributory patent infringement, or inducement of patent infringement, then any rights granted to you under this License shall terminate as of the date such litigation is filed. If you or your agent or exclusive licensee institute or order or agree to the institution of a PATENT CHALLENGE, then Tokutek may terminate any rights granted to you under this License. */ #ident "Copyright (c) 2007-2013 Tokutek Inc. All rights reserved." #ident "The technology is licensed by the Massachusetts Institute of Technology, Rutgers State University of New Jersey, and the Research Foundation of State University of New York at Stony Brook under United States of America Serial No. 11/760379 and to the patents and/or patent applications resulting from it." #include "test.h" #include <sys/resource.h> // create 200 databases and close them. set the open file limit to 100 and try to open all of them. // eventually, the locktree can not clone fractal tree, and the db open fails. int test_main (int argc __attribute__((__unused__)), char *const argv[] __attribute__((__unused__))) { int r; const int N = 200; toku_os_recursive_delete(TOKU_TEST_FILENAME); r = toku_os_mkdir(TOKU_TEST_FILENAME, S_IRWXU+S_IRWXG+S_IRWXO); assert(r == 0); DB_ENV *env; r = db_env_create(&env, 0); assert(r == 0); r = env->open(env, TOKU_TEST_FILENAME, DB_INIT_MPOOL|DB_CREATE|DB_THREAD |DB_INIT_LOCK|DB_INIT_LOG|DB_INIT_TXN|DB_PRIVATE, S_IRWXU+S_IRWXG+S_IRWXO); assert(r == 0); DB **dbs = new DB *[N]; for (int i = 0; i < N; i++) { dbs[i] = NULL; } for (int i = 0; i < N; i++) { r = db_create(&dbs[i], env, 0); assert(r == 0); char dbname[32]; sprintf(dbname, "%d.test", i); r = dbs[i]->open(dbs[i], NULL, dbname, NULL, DB_BTREE, DB_AUTO_COMMIT+DB_CREATE, S_IRWXU+S_IRWXG+S_IRWXO); assert(r == 0); } for (int i = 0; i < N; i++) { if (dbs[i]) { r = dbs[i]->close(dbs[i], 0); assert(r == 0); } } struct rlimit nofile_limit = { N/2, N/2 }; r = setrlimit(RLIMIT_NOFILE, &nofile_limit); // assert(r == 0); // valgrind does not like this if (r != 0) { printf("warning: set nofile limit to %d failed %d %s\n", N, errno, strerror(errno)); } for (int i = 0; i < N; i++) { dbs[i] = NULL; } bool emfile_happened = false; // should happen since there are less than N unused file descriptors for (int i = 0; i < N; i++) { r = db_create(&dbs[i], env, 0); assert(r == 0); char dbname[32]; sprintf(dbname, "%d.test", i); r = dbs[i]->open(dbs[i], NULL, dbname, NULL, DB_BTREE, DB_AUTO_COMMIT, S_IRWXU+S_IRWXG+S_IRWXO); if (r == EMFILE) { emfile_happened = true; break; } } assert(emfile_happened); for (int i = 0; i < N; i++) { if (dbs[i]) { r = dbs[i]->close(dbs[i], 0); assert(r == 0); } } r = env->close(env, 0); assert(r == 0); delete [] dbs; return 0; }
gpl-2.0
tonyjbutler/moodle
course/format/classes/output/local/content/section/cmlist.php
4703
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Contains the default activity list from a section. * * @package core_courseformat * @copyright 2020 Ferran Recio <[email protected]> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ namespace core_courseformat\output\local\content\section; use core_courseformat\base as course_format; use section_info; use renderable; use templatable; use moodle_url; use stdClass; /** * Base class to render a section activity list. * * @package core_courseformat * @copyright 2020 Ferran Recio <[email protected]> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class cmlist implements renderable, templatable { /** @var course_format the course format class */ protected $format; /** @var section_format the course section class */ protected $section; /** @var array optional display options */ protected $displayoptions; /** @var string the item output class name */ protected $itemclass; /** @var optional move here output class */ protected $movehereclass; /** * Constructor. * * @param course_format $format the course format * @param section_info $section the section info * @param array $displayoptions optional extra display options */ public function __construct(course_format $format, section_info $section, array $displayoptions = []) { $this->format = $format; $this->section = $section; $this->displayoptions = $displayoptions; // Get the necessary classes. $this->itemclass = $format->get_output_classname('content\\section\\cmitem'); } /** * Export this data so it can be used as the context for a mustache template. * * @param renderer_base $output typically, the renderer that's calling this function * @return array data context for a mustache template */ public function export_for_template(\renderer_base $output): stdClass { global $USER; $format = $this->format; $section = $this->section; $course = $format->get_course(); $modinfo = $format->get_modinfo(); $user = $USER; $data = new stdClass(); $data->cms = []; // By default, non-ajax controls are disabled but in some places like the frontpage // it is necessary to display them. This is a temporal solution while JS is still // optional for course editing. $showmovehere = ismoving($course->id); if ($showmovehere) { $data->hascms = true; $data->showmovehere = true; $data->strmovefull = strip_tags(get_string("movefull", "", "'$user->activitycopyname'")); $data->movetosectionurl = new moodle_url('/course/mod.php', ['movetosection' => $section->id, 'sesskey' => sesskey()]); $data->movingstr = strip_tags(get_string('activityclipboard', '', $user->activitycopyname)); $data->cancelcopyurl = new moodle_url('/course/mod.php', ['cancelcopy' => 'true', 'sesskey' => sesskey()]); } if (empty($modinfo->sections[$section->section])) { return $data; } foreach ($modinfo->sections[$section->section] as $modnumber) { $mod = $modinfo->cms[$modnumber]; // If the old non-ajax move is necessary, we do not print the selected cm. if ($showmovehere && $USER->activitycopy == $mod->id) { continue; } if ($mod->is_visible_on_course_page()) { $item = new $this->itemclass($format, $section, $mod, $this->displayoptions); $data->cms[] = (object)[ 'cmitem' => $item->export_for_template($output), 'moveurl' => new moodle_url('/course/mod.php', array('moveto' => $modnumber, 'sesskey' => sesskey())), ]; } } if (!empty($data->cms)) { $data->hascms = true; } return $data; } }
gpl-3.0
scharron/chardet
chardet/langbulgarianmodel.py
13035
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is Mozilla Communicator client code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 1998 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA # 02110-1301 USA ######################### END LICENSE BLOCK ######################### from . import constants # 255: Control characters that usually does not exist in any text # 254: Carriage/Return # 253: symbol (punctuation) that does not belong to word # 252: 0 - 9 # Character Mapping Table: # this table is modified base on win1251BulgarianCharToOrderMap, so # only number <64 is sure valid Latin5_BulgarianCharToOrderMap = ( \ 255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10 253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20 252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30 253, 77, 90, 99,100, 72,109,107,101, 79,185, 81,102, 76, 94, 82, # 40 110,186,108, 91, 74,119, 84, 96,111,187,115,253,253,253,253,253, # 50 253, 65, 69, 70, 66, 63, 68,112,103, 92,194,104, 95, 86, 87, 71, # 60 116,195, 85, 93, 97,113,196,197,198,199,200,253,253,253,253,253, # 70 194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209, # 80 210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225, # 90 81,226,227,228,229,230,105,231,232,233,234,235,236, 45,237,238, # a0 31, 32, 35, 43, 37, 44, 55, 47, 40, 59, 33, 46, 38, 36, 41, 30, # b0 39, 28, 34, 51, 48, 49, 53, 50, 54, 57, 61,239, 67,240, 60, 56, # c0 1, 18, 9, 20, 11, 3, 23, 15, 2, 26, 12, 10, 14, 6, 4, 13, # d0 7, 8, 5, 19, 29, 25, 22, 21, 27, 24, 17, 75, 52,241, 42, 16, # e0 62,242,243,244, 58,245, 98,246,247,248,249,250,251, 91,252,253, # f0 ) win1251BulgarianCharToOrderMap = ( \ 255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10 253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20 252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30 253, 77, 90, 99,100, 72,109,107,101, 79,185, 81,102, 76, 94, 82, # 40 110,186,108, 91, 74,119, 84, 96,111,187,115,253,253,253,253,253, # 50 253, 65, 69, 70, 66, 63, 68,112,103, 92,194,104, 95, 86, 87, 71, # 60 116,195, 85, 93, 97,113,196,197,198,199,200,253,253,253,253,253, # 70 206,207,208,209,210,211,212,213,120,214,215,216,217,218,219,220, # 80 221, 78, 64, 83,121, 98,117,105,222,223,224,225,226,227,228,229, # 90 88,230,231,232,233,122, 89,106,234,235,236,237,238, 45,239,240, # a0 73, 80,118,114,241,242,243,244,245, 62, 58,246,247,248,249,250, # b0 31, 32, 35, 43, 37, 44, 55, 47, 40, 59, 33, 46, 38, 36, 41, 30, # c0 39, 28, 34, 51, 48, 49, 53, 50, 54, 57, 61,251, 67,252, 60, 56, # d0 1, 18, 9, 20, 11, 3, 23, 15, 2, 26, 12, 10, 14, 6, 4, 13, # e0 7, 8, 5, 19, 29, 25, 22, 21, 27, 24, 17, 75, 52,253, 42, 16, # f0 ) # Model Table: # total sequences: 100% # first 512 sequences: 96.9392% # first 1024 sequences:3.0618% # rest sequences: 0.2992% # negative sequences: 0.0020% BulgarianLangModel = ( \ 0,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,3,3,2,3,3,3,3,3, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,3,3,3,2,2,3,2,2,1,2,2, 3,1,3,3,2,3,3,3,3,3,3,3,3,3,3,3,3,0,3,3,3,3,3,3,3,3,3,3,0,3,0,1, 0,0,0,0,0,0,0,0,0,0,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,2,3,3,3,3,3,3,3,3,0,3,1,0, 0,1,0,0,0,0,0,0,0,0,1,1,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1, 3,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,1,3,2,3,3,3,3,3,3,3,3,0,3,0,0, 0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,2,3,3,2,3,3,3,3,3,3,3,3,3,3,3,3,1,3,2,3,3,3,3,3,3,3,3,0,3,0,0, 0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,2,3,2,2,1,3,3,3,3,2,2,2,1,1,2,0,1,0,1,0,0, 0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,1, 3,3,3,3,3,3,3,2,3,2,2,3,3,1,1,2,3,3,2,3,3,3,3,2,1,2,0,2,0,3,0,0, 0,0,0,0,0,0,0,1,0,0,2,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,1, 3,3,3,3,3,3,3,1,3,3,3,3,3,2,3,2,3,3,3,3,3,2,3,3,1,3,0,3,0,2,0,0, 0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1, 3,3,3,3,3,3,3,3,1,3,3,2,3,3,3,1,3,3,2,3,2,2,2,0,0,2,0,2,0,2,0,0, 0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,1, 3,3,3,3,3,3,3,3,3,0,3,3,3,2,2,3,3,3,1,2,2,3,2,1,1,2,0,2,0,0,0,0, 1,0,0,0,0,0,0,0,0,0,2,0,0,1,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1, 3,3,3,3,3,3,3,2,3,3,1,2,3,2,2,2,3,3,3,3,3,2,2,3,1,2,0,2,1,2,0,0, 0,0,0,0,0,0,0,0,0,0,3,0,0,1,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,1, 3,3,3,3,3,1,3,3,3,3,3,2,3,3,3,2,3,3,2,3,2,2,2,3,1,2,0,1,0,1,0,0, 0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1, 3,3,3,3,3,3,3,3,3,3,3,1,1,1,2,2,1,3,1,3,2,2,3,0,0,1,0,1,0,1,0,0, 0,0,0,1,0,0,0,0,1,0,2,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1, 3,3,3,3,3,2,2,3,2,2,3,1,2,1,1,1,2,3,1,3,1,2,2,0,1,1,1,1,0,1,0,0, 0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1, 3,3,3,3,3,1,3,2,2,3,3,1,2,3,1,1,3,3,3,3,1,2,2,1,1,1,0,2,0,2,0,1, 0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,1,2,2,3,3,3,2,2,1,1,2,0,2,0,1,0,0, 0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1, 3,0,1,2,1,3,3,2,3,3,3,3,3,2,3,2,1,0,3,1,2,1,2,1,2,3,2,1,0,1,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,1,1,2,3,3,3,3,3,3,3,3,3,3,3,3,0,0,3,1,3,3,2,3,3,2,2,2,0,1,0,0, 0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,3,3,3,3,0,3,3,3,3,3,2,1,1,2,1,3,3,0,3,1,1,1,1,3,2,0,1,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1, 3,3,2,2,2,3,3,3,3,3,3,3,3,3,3,3,1,1,3,1,3,3,2,3,2,2,2,3,0,2,0,0, 0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,2,3,3,2,2,3,2,1,1,1,1,1,3,1,3,1,1,0,0,0,1,0,0,0,1,0,0, 0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,2,3,2,0,3,2,0,3,0,2,0,0,2,1,3,1,0,0,1,0,0,0,1,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1, 3,3,3,3,2,1,1,1,1,2,1,1,2,1,1,1,2,2,1,2,1,1,1,0,1,1,0,1,0,1,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1, 3,3,3,3,2,1,3,1,1,2,1,3,2,1,1,0,1,2,3,2,1,1,1,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,3,3,3,3,2,2,1,0,1,0,0,1,0,0,0,2,1,0,3,0,0,1,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1, 3,3,3,2,3,2,3,3,1,3,2,1,1,1,2,1,1,2,1,3,0,1,0,0,0,1,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,1,1,2,2,3,3,2,3,2,2,2,3,1,2,2,1,1,2,1,1,2,2,0,1,1,0,1,0,2,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,2,1,3,1,0,2,2,1,3,2,1,0,0,2,0,2,0,1,0,0,0,0,0,0,0,1,0,0, 0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1, 3,3,3,3,3,3,1,2,0,2,3,1,2,3,2,0,1,3,1,2,1,1,1,0,0,1,0,0,2,2,2,3, 2,2,2,2,1,2,1,1,2,2,1,1,2,0,1,1,1,0,0,1,1,0,0,1,1,0,0,0,1,1,0,1, 3,3,3,3,3,2,1,2,2,1,2,0,2,0,1,0,1,2,1,2,1,1,0,0,0,1,0,1,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,1, 3,3,2,3,3,1,1,3,1,0,3,2,1,0,0,0,1,2,0,2,0,1,0,0,0,1,0,1,2,1,2,2, 1,1,1,1,1,1,1,2,2,2,1,1,1,1,1,1,1,0,1,2,1,1,1,0,0,0,0,0,1,1,0,0, 3,1,0,1,0,2,3,2,2,2,3,2,2,2,2,2,1,0,2,1,2,1,1,1,0,1,2,1,2,2,2,1, 1,1,2,2,2,2,1,2,1,1,0,1,2,1,2,2,2,1,1,1,0,1,1,1,1,2,0,1,0,0,0,0, 2,3,2,3,3,0,0,2,1,0,2,1,0,0,0,0,2,3,0,2,0,0,0,0,0,1,0,0,2,0,1,2, 2,1,2,1,2,2,1,1,1,2,1,1,1,0,1,2,2,1,1,1,1,1,0,1,1,1,0,0,1,2,0,0, 3,3,2,2,3,0,2,3,1,1,2,0,0,0,1,0,0,2,0,2,0,0,0,1,0,1,0,1,2,0,2,2, 1,1,1,1,2,1,0,1,2,2,2,1,1,1,1,1,1,1,0,1,1,1,0,0,0,0,0,0,1,1,0,0, 2,3,2,3,3,0,0,3,0,1,1,0,1,0,0,0,2,2,1,2,0,0,0,0,0,0,0,0,2,0,1,2, 2,2,1,1,1,1,1,2,2,2,1,0,2,0,1,0,1,0,0,1,0,1,0,0,1,0,0,0,0,1,0,0, 3,3,3,3,2,2,2,2,2,0,2,1,1,1,1,2,1,2,1,1,0,2,0,1,0,1,0,0,2,0,1,2, 1,1,1,1,1,1,1,2,2,1,1,0,2,0,1,0,2,0,0,1,1,1,0,0,2,0,0,0,1,1,0,0, 2,3,3,3,3,1,0,0,0,0,0,0,0,0,0,0,2,0,0,1,1,0,0,0,0,0,0,1,2,0,1,2, 2,2,2,1,1,2,1,1,2,2,2,1,2,0,1,1,1,1,1,1,0,1,1,1,1,0,0,1,1,1,0,0, 2,3,3,3,3,0,2,2,0,2,1,0,0,0,1,1,1,2,0,2,0,0,0,3,0,0,0,0,2,0,2,2, 1,1,1,2,1,2,1,1,2,2,2,1,2,0,1,1,1,0,1,1,1,1,0,2,1,0,0,0,1,1,0,0, 2,3,3,3,3,0,2,1,0,0,2,0,0,0,0,0,1,2,0,2,0,0,0,0,0,0,0,0,2,0,1,2, 1,1,1,2,1,1,1,1,2,2,2,0,1,0,1,1,1,0,0,1,1,1,0,0,1,0,0,0,0,1,0,0, 3,3,2,2,3,0,1,0,1,0,0,0,0,0,0,0,1,1,0,3,0,0,0,0,0,0,0,0,1,0,2,2, 1,1,1,1,1,2,1,1,2,2,1,2,2,1,0,1,1,1,1,1,0,1,0,0,1,0,0,0,1,1,0,0, 3,1,0,1,0,2,2,2,2,3,2,1,1,1,2,3,0,0,1,0,2,1,1,0,1,1,1,1,2,1,1,1, 1,2,2,1,2,1,2,2,1,1,0,1,2,1,2,2,1,1,1,0,0,1,1,1,2,1,0,1,0,0,0,0, 2,1,0,1,0,3,1,2,2,2,2,1,2,2,1,1,1,0,2,1,2,2,1,1,2,1,1,0,2,1,1,1, 1,2,2,2,2,2,2,2,1,2,0,1,1,0,2,1,1,1,1,1,0,0,1,1,1,1,0,1,0,0,0,0, 2,1,1,1,1,2,2,2,2,1,2,2,2,1,2,2,1,1,2,1,2,3,2,2,1,1,1,1,0,1,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,2,2,3,2,0,1,2,0,1,2,1,1,0,1,0,1,2,1,2,0,0,0,1,1,0,0,0,1,0,0,2, 1,1,0,0,1,1,0,1,1,1,1,0,2,0,1,1,1,0,0,1,1,0,0,0,0,1,0,0,0,1,0,0, 2,0,0,0,0,1,2,2,2,2,2,2,2,1,2,1,1,1,1,1,1,1,0,1,1,1,1,1,2,1,1,1, 1,2,2,2,2,1,1,2,1,2,1,1,1,0,2,1,2,1,1,1,0,2,1,1,1,1,0,1,0,0,0,0, 3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0, 1,1,0,1,0,1,1,1,1,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,2,2,3,2,0,0,0,0,1,0,0,0,0,0,0,1,1,0,2,0,0,0,0,0,0,0,0,1,0,1,2, 1,1,1,1,1,1,0,0,2,2,2,2,2,0,1,1,0,1,1,1,1,1,0,0,1,0,0,0,1,1,0,1, 2,3,1,2,1,0,1,1,0,2,2,2,0,0,1,0,0,1,1,1,1,0,0,0,0,0,0,0,1,0,1,2, 1,1,1,1,2,1,1,1,1,1,1,1,1,0,1,1,0,1,0,1,0,1,0,0,1,0,0,0,0,1,0,0, 2,2,2,2,2,0,0,2,0,0,2,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,2,0,2,2, 1,1,1,1,1,0,0,1,2,1,1,0,1,0,1,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0, 1,2,2,2,2,0,0,2,0,1,1,0,0,0,1,0,0,2,0,2,0,0,0,0,0,0,0,0,0,0,1,1, 0,0,0,1,1,1,1,1,1,1,1,1,1,0,1,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0, 1,2,2,3,2,0,0,1,0,0,1,0,0,0,0,0,0,1,0,2,0,0,0,1,0,0,0,0,0,0,0,2, 1,1,0,0,1,0,0,0,1,1,0,0,1,0,1,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0, 2,1,2,2,2,1,2,1,2,2,1,1,2,1,1,1,0,1,1,1,1,2,0,1,0,1,1,1,1,0,1,1, 1,1,2,1,1,1,1,1,1,0,0,1,2,1,1,1,1,1,1,0,0,1,1,1,0,0,0,0,0,0,0,0, 1,0,0,1,3,1,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,2,2,2,1,0,0,1,0,2,0,0,0,0,0,1,1,1,0,1,0,0,0,0,0,0,0,0,2,0,0,1, 0,2,0,1,0,0,1,1,2,0,1,0,1,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0, 1,2,2,2,2,0,1,1,0,2,1,0,1,1,1,0,0,1,0,2,0,1,0,0,0,0,0,0,0,0,0,1, 0,1,0,0,1,0,0,0,1,1,0,0,1,0,0,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0, 2,2,2,2,2,0,0,1,0,0,0,1,0,1,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,1, 0,1,0,1,1,1,0,0,1,1,1,0,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0, 2,0,1,0,0,1,2,1,1,1,1,1,1,2,2,1,0,0,1,0,1,0,0,0,0,1,1,1,1,0,0,0, 1,1,2,1,1,1,1,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,2,1,2,1,0,0,1,0,0,0,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,1, 0,0,0,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,0,0,1,2,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0, 0,1,1,0,1,1,1,0,0,1,0,0,1,0,1,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0, 1,0,1,0,0,1,1,1,1,1,1,1,1,1,1,1,0,0,1,0,2,0,0,2,0,1,0,0,1,0,0,1, 1,1,0,0,1,1,0,1,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0, 1,1,1,1,1,1,1,2,0,0,0,0,0,0,2,1,0,1,1,0,0,1,1,1,0,1,0,0,0,0,0,0, 2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,1,0,1,1,1,1,1,0,1,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1, ) Latin5BulgarianModel = { \ 'charToOrderMap': Latin5_BulgarianCharToOrderMap, 'precedenceMatrix': BulgarianLangModel, 'mTypicalPositiveRatio': 0.969392, 'keepEnglishLetter': False, 'charsetName': "ISO-8859-5" } Win1251BulgarianModel = { \ 'charToOrderMap': win1251BulgarianCharToOrderMap, 'precedenceMatrix': BulgarianLangModel, 'mTypicalPositiveRatio': 0.969392, 'keepEnglishLetter': False, 'charsetName': "windows-1251" }
lgpl-2.1
sacjaya/carbon-analytics-common
components/data-bridge/org.wso2.carbon.databridge.core/src/main/java/org/wso2/carbon/databridge/core/exception/DataBridgeException.java
1474
/** * * Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.carbon.databridge.core.exception; public class DataBridgeException extends Exception { private String errorMessage; public DataBridgeException() { } public DataBridgeException(String message) { super(message); errorMessage = message; } public DataBridgeException(String message, Throwable cause) { super(message, cause); errorMessage = message; } public DataBridgeException(Throwable cause) { super(cause); } public String getErrorMessage() { return errorMessage; } }
apache-2.0
mosaic-cloud/mosaic-distribution-dependencies
dependencies/mozilla-js/1.8.5/js/src/jit-test/tests/closures/setname-1.js
281
actual = ''; expected = '4,4,4,4,4,'; function f() { var k = 0; function g() { for (var i = 0; i < 5; ++i) { k = i; } } function h() { for (var i = 0; i < 5; ++i) { appendToActual(k); } } g(); h(); } f(); assertEq(actual, expected)
apache-2.0
froschdesign/zf1
tests/Zend/Http/TestAsset/InvalidDevice.php
1010
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to [email protected] so we can send you a copy immediately. * * @category Zend * @package Zend_Http_UserAgent * @subpackage UnitTests * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ /** * @category Zend * @package Zend_Http_UserAgent * @subpackage UnitTests * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Http_TestAsset_InvalidDevice { }
bsd-3-clause
Pluto-tv/chromium-crosswalk
tools/telemetry/telemetry/internal/platform/power_monitor/cros_power_monitor_unittest.py
7993
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import unittest from telemetry.internal.platform.power_monitor import cros_power_monitor class CrosPowerMonitorMonitorTest(unittest.TestCase): initial_power = ('''line_power_connected 0 battery_present 1 battery_percent 70.20 battery_charge 2.83 battery_charge_full 4.03 battery_charge_full_design 4.03 battery_current 1.08 battery_energy 31.83 battery_energy_rate 12.78 battery_voltage 11.82 battery_discharging 1''') final_power = ('''line_power_connected 0 battery_present 1 battery_percent 70.20 battery_charge 2.83 battery_charge_full 4.03 battery_charge_full_design 4.03 battery_current 1.08 battery_energy 31.83 battery_energy_rate 12.80 battery_voltage 12.24 battery_discharging 1''') incomplete_final_power = ('''line_power_connected 0 battery_present 1 battery_percent 70.20 battery_charge 2.83 battery_charge_full 4.03 battery_charge_full_design 4.03 battery_energy_rate 12.80 battery_discharging 1''') expected_power = { 'energy_consumption_mwh': 2558.0, 'power_samples_mw': [12780.0, 12800.0], 'component_utilization': { 'battery': { 'charge_full': 4.03, 'charge_full_design': 4.03, 'charge_now': 2.83, 'current_now': 1.08, 'energy': 31.83, 'energy_rate': 12.80, 'voltage_now': 12.24 } } } expected_incomplete_power = { 'energy_consumption_mwh': 2558.0, 'power_samples_mw': [12780.0, 12800.0], 'component_utilization': { 'battery': { 'charge_full': 4.03, 'charge_full_design': 4.03, 'charge_now': 2.83, 'energy_rate': 12.80, } } } expected_cpu = { 'whole_package': { 'frequency_percent': { 1700000000: 3.29254111574526, 1600000000: 0.0, 1500000000: 0.0, 1400000000: 0.15926805099535601, 1300000000: 0.47124116307273645, 1200000000: 0.818756100807525, 1100000000: 1.099381692400982, 1000000000: 2.5942528544384302, 900000000: 5.68661122326737, 800000000: 3.850545467654628, 700000000: 2.409691872245393, 600000000: 1.4693702487650486, 500000000: 2.4623575553879373, 400000000: 2.672038150383057, 300000000: 3.415770495015825, 200000000: 69.59817400982045 }, 'cstate_residency_percent': { 'C0': 83.67623835616438535, 'C1': 0.2698609589041096, 'C2': 0.2780191780821918, 'C3': 15.77588150684931505 } }, 'cpu0': { 'frequency_percent': { 1700000000: 4.113700564971752, 1600000000: 0.0, 1500000000: 0.0, 1400000000: 0.1765536723163842, 1300000000: 0.4943502824858757, 1200000000: 0.7944915254237288, 1100000000: 1.2226341807909604, 1000000000: 3.0632062146892656, 900000000: 5.680614406779661, 800000000: 3.6679025423728815, 700000000: 2.379060734463277, 600000000: 1.4124293785310735, 500000000: 2.599752824858757, 400000000: 3.0102401129943503, 300000000: 3.650247175141243, 200000000: 67.73481638418079 }, 'cstate_residency_percent': { 'C0': 76.76226164383562, 'C1': 0.3189164383561644, 'C2': 0.4544301369863014, 'C3': 22.4643917808219178 } }, 'cpu1': { 'frequency_percent': { 1700000000: 2.4713816665187682, 1600000000: 0.0, 1500000000: 0.0, 1400000000: 0.1419824296743278, 1300000000: 0.44813204365959713, 1200000000: 0.8430206761913214, 1100000000: 0.9761292040110037, 1000000000: 2.1252994941875945, 900000000: 5.69260803975508, 800000000: 4.033188392936374, 700000000: 2.4403230100275093, 600000000: 1.526311118999024, 500000000: 2.3249622859171177, 400000000: 2.3338361877717633, 300000000: 3.1812938148904073, 200000000: 71.46153163546012 }, 'cstate_residency_percent': { 'C0': 90.5902150684931507, 'C1': 0.2208054794520548, 'C2': 0.1016082191780822, 'C3': 9.0873712328767123 } } } def _assertPowerEqual(self, results, expected): battery = results['component_utilization']['battery'] expected_battery = expected['component_utilization']['battery'] self.assertItemsEqual(battery.keys(), expected_battery.keys()) for value in battery: self.assertAlmostEqual(battery[value], expected_battery[value]) self.assertAlmostEqual(results['energy_consumption_mwh'], expected['energy_consumption_mwh']) self.assertAlmostEqual(results['power_samples_mw'][0], expected['power_samples_mw'][0]) self.assertAlmostEqual(results['power_samples_mw'][1], expected['power_samples_mw'][1]) def testParsePower(self): results = cros_power_monitor.CrosPowerMonitor.ParsePower( self.initial_power, self.final_power, 0.2) self._assertPowerEqual(results, self.expected_power) def testParseIncompletePowerState(self): """Test the case where dump_power_status only outputs partial fields. CrosPowerMonitor hard-coded expected fields from dump_power_status, this test ensures it parses successfully when expected fields does not exist. It's mainly for backward compatibility. """ results = cros_power_monitor.CrosPowerMonitor.ParsePower( self.initial_power, self.incomplete_final_power, 0.2) self._assertPowerEqual(results, self.expected_incomplete_power) def testSplitSample(self): sample = self.initial_power + '\n1408739546\n' power, time = cros_power_monitor.CrosPowerMonitor.SplitSample(sample) self.assertEqual(power, self.initial_power) self.assertEqual(time, 1408739546) def testCombineResults(self): result = cros_power_monitor.CrosPowerMonitor.CombineResults( self.expected_cpu, self.expected_power) comp_util = result['component_utilization'] # Test power values. self.assertEqual(result['energy_consumption_mwh'], self.expected_power['energy_consumption_mwh']) self.assertEqual(result['power_samples_mw'], self.expected_power['power_samples_mw']) self.assertEqual(comp_util['battery'], self.expected_power['component_utilization']['battery']) # Test frequency values. self.assertDictEqual( comp_util['whole_package']['frequency_percent'], self.expected_cpu['whole_package']['frequency_percent']) self.assertDictEqual( comp_util['cpu0']['frequency_percent'], self.expected_cpu['cpu0']['frequency_percent']) self.assertDictEqual( comp_util['cpu1']['frequency_percent'], self.expected_cpu['cpu1']['frequency_percent']) # Test c-state residency values. self.assertDictEqual( comp_util['whole_package']['cstate_residency_percent'], self.expected_cpu['whole_package']['cstate_residency_percent']) self.assertDictEqual( comp_util['cpu0']['cstate_residency_percent'], self.expected_cpu['cpu0']['cstate_residency_percent']) self.assertDictEqual( comp_util['cpu1']['cstate_residency_percent'], self.expected_cpu['cpu1']['cstate_residency_percent']) def testCanMonitorPower(self): # TODO(tmandel): Add a test here where the device cannot monitor power. initial_status = cros_power_monitor.CrosPowerMonitor.ParsePowerStatus( self.initial_power) final_status = cros_power_monitor.CrosPowerMonitor.ParsePowerStatus( self.final_power) self.assertTrue(cros_power_monitor.CrosPowerMonitor.IsOnBatteryPower( initial_status, 'peppy')) self.assertTrue(cros_power_monitor.CrosPowerMonitor.IsOnBatteryPower( final_status, 'butterfly'))
bsd-3-clause
JAOSP/aosp_platform_external_chromium_org
chrome/browser/task_manager/worker_resource_provider.cc
10810
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/task_manager/worker_resource_provider.h" #include <vector> #include "base/basictypes.h" #include "base/strings/string16.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/devtools/devtools_window.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/task_manager/resource_provider.h" #include "chrome/browser/task_manager/task_manager.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/child_process_data.h" #include "content/public/browser/devtools_agent_host.h" #include "content/public/browser/worker_service.h" #include "content/public/common/process_type.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/image/image_skia.h" using content::BrowserThread; using content::DevToolsAgentHost; using content::WorkerService; namespace task_manager { // Objects of this class are created on the IO thread and then passed to the UI // thread where they are passed to the task manager. All methods must be called // only on the UI thread. Destructor may be called on any thread. class SharedWorkerResource : public Resource { public: SharedWorkerResource(const GURL& url, const string16& name, int process_id, int routing_id, base::ProcessHandle process_handle); virtual ~SharedWorkerResource(); bool Matches(int process_id, int routing_id) const; void UpdateProcessHandle(base::ProcessHandle handle); base::ProcessHandle handle() const { return handle_; } int process_id() const { return process_id_; } private: // Resource methods: virtual string16 GetTitle() const OVERRIDE; virtual string16 GetProfileName() const OVERRIDE; virtual gfx::ImageSkia GetIcon() const OVERRIDE; virtual base::ProcessHandle GetProcess() const OVERRIDE; virtual int GetUniqueChildProcessId() const OVERRIDE; virtual Type GetType() const OVERRIDE; virtual bool CanInspect() const OVERRIDE; virtual void Inspect() const OVERRIDE; virtual bool SupportNetworkUsage() const OVERRIDE; virtual void SetSupportNetworkUsage() OVERRIDE; int process_id_; int routing_id_; string16 title_; base::ProcessHandle handle_; static gfx::ImageSkia* default_icon_; DISALLOW_COPY_AND_ASSIGN(SharedWorkerResource); }; gfx::ImageSkia* SharedWorkerResource::default_icon_ = NULL; SharedWorkerResource::SharedWorkerResource( const GURL& url, const string16& name, int process_id, int routing_id, base::ProcessHandle process_handle) : process_id_(process_id), routing_id_(routing_id), handle_(process_handle) { title_ = UTF8ToUTF16(url.spec()); if (!name.empty()) title_ += ASCIIToUTF16(" (") + name + ASCIIToUTF16(")"); } SharedWorkerResource::~SharedWorkerResource() { } bool SharedWorkerResource::Matches(int process_id, int routing_id) const { return process_id_ == process_id && routing_id_ == routing_id; } void SharedWorkerResource::UpdateProcessHandle(base::ProcessHandle handle) { handle_ = handle; } string16 SharedWorkerResource::GetTitle() const { return l10n_util::GetStringFUTF16(IDS_TASK_MANAGER_WORKER_PREFIX, title_); } string16 SharedWorkerResource::GetProfileName() const { return string16(); } gfx::ImageSkia SharedWorkerResource::GetIcon() const { if (!default_icon_) { ResourceBundle& rb = ResourceBundle::GetSharedInstance(); default_icon_ = rb.GetImageSkiaNamed(IDR_PLUGINS_FAVICON); // TODO(jabdelmalek): use different icon for web workers. } return *default_icon_; } base::ProcessHandle SharedWorkerResource::GetProcess() const { return handle_; } int SharedWorkerResource::GetUniqueChildProcessId() const { return process_id_; } Resource::Type SharedWorkerResource::GetType() const { return WORKER; } bool SharedWorkerResource::CanInspect() const { return true; } void SharedWorkerResource::Inspect() const { // TODO(yurys): would be better to get profile from one of the tabs connected // to the worker. Profile* profile = ProfileManager::GetLastUsedProfile(); if (!profile) return; scoped_refptr<DevToolsAgentHost> agent_host( DevToolsAgentHost::GetForWorker(process_id_, routing_id_)); DevToolsWindow::OpenDevToolsWindowForWorker(profile, agent_host.get()); } bool SharedWorkerResource::SupportNetworkUsage() const { return false; } void SharedWorkerResource::SetSupportNetworkUsage() { } // This class is needed to ensure that all resources in WorkerResourceList are // deleted if corresponding task is posted to but not executed on the UI // thread. class WorkerResourceProvider::WorkerResourceListHolder { public: WorkerResourceListHolder() { } ~WorkerResourceListHolder() { STLDeleteElements(&resources_); } WorkerResourceList* resources() { return &resources_; } private: WorkerResourceList resources_; }; WorkerResourceProvider:: WorkerResourceProvider(TaskManager* task_manager) : updating_(false), task_manager_(task_manager) { } WorkerResourceProvider::~WorkerResourceProvider() { DeleteAllResources(); } Resource* WorkerResourceProvider::GetResource( int origin_pid, int render_process_host_id, int routing_id) { return NULL; } void WorkerResourceProvider::StartUpdating() { DCHECK(!updating_); updating_ = true; // Get existing workers. BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind( &WorkerResourceProvider::StartObservingWorkers, this)); BrowserChildProcessObserver::Add(this); } void WorkerResourceProvider::StopUpdating() { DCHECK(updating_); updating_ = false; launching_workers_.clear(); DeleteAllResources(); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind( &WorkerResourceProvider::StopObservingWorkers, this)); BrowserChildProcessObserver::Remove(this); } void WorkerResourceProvider::BrowserChildProcessHostConnected( const content::ChildProcessData& data) { DCHECK(updating_); if (data.process_type != content::PROCESS_TYPE_WORKER) return; ProcessIdToWorkerResources::iterator it(launching_workers_.find(data.id)); if (it == launching_workers_.end()) return; WorkerResourceList& resources = it->second; for (WorkerResourceList::iterator r = resources.begin(); r != resources.end(); ++r) { (*r)->UpdateProcessHandle(data.handle); task_manager_->AddResource(*r); } launching_workers_.erase(it); } void WorkerResourceProvider::BrowserChildProcessHostDisconnected( const content::ChildProcessData& data) { DCHECK(updating_); if (data.process_type != content::PROCESS_TYPE_WORKER) return; // Worker process may be destroyed before WorkerMsg_TerminateWorkerContex // message is handled and WorkerDestroyed is fired. In this case we won't // get WorkerDestroyed notification and have to clear resources for such // workers here when the worker process has been destroyed. for (WorkerResourceList::iterator it = resources_.begin(); it != resources_.end();) { if ((*it)->process_id() == data.id) { task_manager_->RemoveResource(*it); delete *it; it = resources_.erase(it); } else { ++it; } } DCHECK(!ContainsKey(launching_workers_, data.id)); } void WorkerResourceProvider::WorkerCreated( const GURL& url, const string16& name, int process_id, int route_id) { SharedWorkerResource* resource = new SharedWorkerResource( url, name, process_id, route_id, base::kNullProcessHandle); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&WorkerResourceProvider::NotifyWorkerCreated, this, base::Owned(new WorkerResourceHolder(resource)))); } void WorkerResourceProvider::WorkerDestroyed(int process_id, int route_id) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind( &WorkerResourceProvider::NotifyWorkerDestroyed, this, process_id, route_id)); } void WorkerResourceProvider::NotifyWorkerCreated( WorkerResourceHolder* resource_holder) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (!updating_) return; AddResource(resource_holder->release()); } void WorkerResourceProvider::NotifyWorkerDestroyed( int process_id, int routing_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (!updating_) return; for (WorkerResourceList::iterator it = resources_.begin(); it !=resources_.end(); ++it) { if ((*it)->Matches(process_id, routing_id)) { task_manager_->RemoveResource(*it); delete *it; resources_.erase(it); return; } } } void WorkerResourceProvider::StartObservingWorkers() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); scoped_ptr<WorkerResourceListHolder> holder(new WorkerResourceListHolder); std::vector<WorkerService::WorkerInfo> worker_info = WorkerService::GetInstance()->GetWorkers(); for (size_t i = 0; i < worker_info.size(); ++i) { holder->resources()->push_back(new SharedWorkerResource( worker_info[i].url, worker_info[i].name, worker_info[i].process_id, worker_info[i].route_id, worker_info[i].handle)); } BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind( &WorkerResourceProvider::AddWorkerResourceList, this, base::Owned(holder.release()))); WorkerService::GetInstance()->AddObserver(this); } void WorkerResourceProvider::StopObservingWorkers() { WorkerService::GetInstance()->RemoveObserver(this); } void WorkerResourceProvider::AddWorkerResourceList( WorkerResourceListHolder* resource_list_holder) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (!updating_) return; WorkerResourceList* resources = resource_list_holder->resources(); for (WorkerResourceList::iterator it = resources->begin(); it !=resources->end(); ++it) { AddResource(*it); } resources->clear(); } void WorkerResourceProvider::AddResource(SharedWorkerResource* resource) { DCHECK(updating_); resources_.push_back(resource); if (resource->handle() == base::kNullProcessHandle) { int process_id = resource->process_id(); launching_workers_[process_id].push_back(resource); } else { task_manager_->AddResource(resource); } } void WorkerResourceProvider::DeleteAllResources() { STLDeleteElements(&resources_); } } // namespace task_manager
bsd-3-clause
lijoantony/django-oscar
runtests.py
2644
#!/usr/bin/env python """ Custom test runner If args or options, we run the testsuite as quickly as possible. If args but no options, we default to using the spec plugin and aborting on first error/failure. If options, we ignore defaults and pass options onto pytest. Examples: Run all tests (as fast as possible) $ ./runtests.py Run all unit tests (using spec output) $ ./runtests.py tests/unit Run all checkout unit tests (using spec output) $ ./runtests.py tests/unit/checkout Re-run failing tests (requires pytest-cache) $ ./runtests.py ... --lf Drop into pdb when a test fails $ ./runtests.py ... --pdb """ import os import multiprocessing import sys import logging import warnings import pytest from django.utils.six.moves import map # No logging logging.disable(logging.CRITICAL) if __name__ == '__main__': args = sys.argv[1:] verbosity = 1 if not args: # If run with no args, try and run the testsuite as fast as possible. # That means across all cores and with no high-falutin' plugins. try: cpu_count = int(multiprocessing.cpu_count()) except ValueError: cpu_count = 1 args = [ '--capture=no', '--nomigrations', '-n=%d' % cpu_count, 'tests' ] else: # Some args/options specified. Check to see if any options have # been specified. If they have, then don't set any has_options = any(map(lambda x: x.startswith('--'), args)) if not has_options: # Default options: # --exitfirst Abort on first error/failure # --capture=no Don't capture STDOUT args.extend(['--capture=no', '--nomigrations', '--exitfirst']) else: args = [arg for arg in args if not arg.startswith('-')] with warnings.catch_warnings(): # The warnings module in default configuration will never cause tests # to fail, as it never raises an exception. We alter that behaviour by # turning DeprecationWarnings into exceptions, but exclude warnings # triggered by third-party libs. Note: The context manager is not # thread safe. Behaviour with multiple threads is undefined. warnings.filterwarnings('error', category=DeprecationWarning) warnings.filterwarnings('error', category=RuntimeWarning) libs = r'(sorl\.thumbnail.*|bs4.*|webtest.*)' warnings.filterwarnings( 'ignore', r'.*', DeprecationWarning, libs) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tests.settings') result_code = pytest.main(args) sys.exit(result_code)
bsd-3-clause
varunajmera0/webseries
assets/sdk_google/vendor/google/auth/tests/Subscriber/ScopedAccessTokenSubscriberTest.php
8334
<?php /* * Copyright 2015 Google Inc. * * 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. */ namespace Google\Auth\Tests; use Google\Auth\Subscriber\ScopedAccessTokenSubscriber; use GuzzleHttp\Client; use GuzzleHttp\Event\BeforeEvent; use GuzzleHttp\Transaction; class ScopedAccessTokenSubscriberTest extends BaseTest { const TEST_SCOPE = 'https://www.googleapis.com/auth/cloud-taskqueue'; private $mockCacheItem; private $mockCache; private $mockRequest; protected function setUp() { $this->onlyGuzzle5(); $this->mockCacheItem = $this ->getMockBuilder('Psr\Cache\CacheItemInterface') ->getMock(); $this->mockCache = $this ->getMockBuilder('Psr\Cache\CacheItemPoolInterface') ->getMock(); $this->mockRequest = $this ->getMockBuilder('GuzzleHttp\Psr7\Request') ->disableOriginalConstructor() ->getMock(); } /** * @expectedException InvalidArgumentException */ public function testRequiresScopeAsAStringOrArray() { $fakeAuthFunc = function ($unused_scopes) { return '1/abcdef1234567890'; }; new ScopedAccessTokenSubscriber($fakeAuthFunc, new \stdClass(), array()); } public function testSubscribesToEvents() { $fakeAuthFunc = function ($unused_scopes) { return '1/abcdef1234567890'; }; $s = new ScopedAccessTokenSubscriber($fakeAuthFunc, self::TEST_SCOPE, array()); $this->assertArrayHasKey('before', $s->getEvents()); } public function testAddsTheTokenAsAnAuthorizationHeader() { $fakeAuthFunc = function ($unused_scopes) { return '1/abcdef1234567890'; }; $s = new ScopedAccessTokenSubscriber($fakeAuthFunc, self::TEST_SCOPE, array()); $client = new Client(); $request = $client->createRequest('GET', 'http://testing.org', ['auth' => 'scoped']); $before = new BeforeEvent(new Transaction($client, $request)); $s->onBefore($before); $this->assertSame( 'Bearer 1/abcdef1234567890', $request->getHeader('Authorization') ); } public function testUsesCachedAuthToken() { $cachedValue = '2/abcdef1234567890'; $fakeAuthFunc = function ($unused_scopes) { return ''; }; $this->mockCacheItem ->expects($this->once()) ->method('get') ->will($this->returnValue($cachedValue)); $this->mockCache ->expects($this->once()) ->method('getItem') ->with($this->getValidKeyName(self::TEST_SCOPE)) ->will($this->returnValue($this->mockCacheItem)); // Run the test $s = new ScopedAccessTokenSubscriber($fakeAuthFunc, self::TEST_SCOPE, array(), $this->mockCache); $client = new Client(); $request = $client->createRequest('GET', 'http://testing.org', ['auth' => 'scoped']); $before = new BeforeEvent(new Transaction($client, $request)); $s->onBefore($before); $this->assertSame( 'Bearer 2/abcdef1234567890', $request->getHeader('Authorization') ); } public function testGetsCachedAuthTokenUsingCachePrefix() { $prefix = 'test_prefix-'; $cachedValue = '2/abcdef1234567890'; $fakeAuthFunc = function ($unused_scopes) { return ''; }; $this->mockCacheItem ->expects($this->once()) ->method('get') ->will($this->returnValue($cachedValue)); $this->mockCache ->expects($this->once()) ->method('getItem') ->with($prefix . $this->getValidKeyName(self::TEST_SCOPE)) ->will($this->returnValue($this->mockCacheItem)); // Run the test $s = new ScopedAccessTokenSubscriber($fakeAuthFunc, self::TEST_SCOPE, ['prefix' => $prefix], $this->mockCache); $client = new Client(); $request = $client->createRequest('GET', 'http://testing.org', ['auth' => 'scoped']); $before = new BeforeEvent(new Transaction($client, $request)); $s->onBefore($before); $this->assertSame( 'Bearer 2/abcdef1234567890', $request->getHeader('Authorization') ); } public function testShouldSaveValueInCache() { $token = '2/abcdef1234567890'; $fakeAuthFunc = function ($unused_scopes) { return '2/abcdef1234567890'; }; $this->mockCacheItem ->expects($this->once()) ->method('get') ->will($this->returnValue(false)); $this->mockCacheItem ->expects($this->once()) ->method('set') ->with($this->equalTo($token)) ->will($this->returnValue(false)); $this->mockCache ->expects($this->exactly(2)) ->method('getItem') ->with($this->getValidKeyName(self::TEST_SCOPE)) ->will($this->returnValue($this->mockCacheItem)); $s = new ScopedAccessTokenSubscriber($fakeAuthFunc, self::TEST_SCOPE, array(), $this->mockCache); $client = new Client(); $request = $client->createRequest('GET', 'http://testing.org', ['auth' => 'scoped']); $before = new BeforeEvent(new Transaction($client, $request)); $s->onBefore($before); $this->assertSame( 'Bearer 2/abcdef1234567890', $request->getHeader('Authorization') ); } public function testShouldSaveValueInCacheWithCacheOptions() { $token = '2/abcdef1234567890'; $prefix = 'test_prefix-'; $lifetime = '70707'; $fakeAuthFunc = function ($unused_scopes) { return '2/abcdef1234567890'; }; $this->mockCacheItem ->expects($this->once()) ->method('get') ->will($this->returnValue(false)); $this->mockCacheItem ->expects($this->once()) ->method('set') ->with($this->equalTo($token)); $this->mockCacheItem ->expects($this->once()) ->method('expiresAfter') ->with($this->equalTo($lifetime)); $this->mockCache ->expects($this->exactly(2)) ->method('getItem') ->with($prefix . $this->getValidKeyName(self::TEST_SCOPE)) ->will($this->returnValue($this->mockCacheItem)); // Run the test $s = new ScopedAccessTokenSubscriber($fakeAuthFunc, self::TEST_SCOPE, ['prefix' => $prefix, 'lifetime' => $lifetime], $this->mockCache); $client = new Client(); $request = $client->createRequest('GET', 'http://testing.org', ['auth' => 'scoped']); $before = new BeforeEvent(new Transaction($client, $request)); $s->onBefore($before); $this->assertSame( 'Bearer 2/abcdef1234567890', $request->getHeader('Authorization') ); } public function testOnlyTouchesWhenAuthConfigScoped() { $fakeAuthFunc = function ($unused_scopes) { return '1/abcdef1234567890'; }; $s = new ScopedAccessTokenSubscriber($fakeAuthFunc, self::TEST_SCOPE, array()); $client = new Client(); $request = $client->createRequest('GET', 'http://testing.org', ['auth' => 'notscoped']); $before = new BeforeEvent(new Transaction($client, $request)); $s->onBefore($before); $this->assertSame('', $request->getHeader('Authorization')); } }
mit
PanJ/SimplerCityGlide
node_modules/pipetteur/node_modules/onecolor/lib/plugins/namedColors.js
4325
module.exports = function namedColors(color) { color.namedColors = { aliceblue: 'f0f8ff', antiquewhite: 'faebd7', aqua: '0ff', aquamarine: '7fffd4', azure: 'f0ffff', beige: 'f5f5dc', bisque: 'ffe4c4', black: '000', blanchedalmond: 'ffebcd', blue: '00f', blueviolet: '8a2be2', brown: 'a52a2a', burlywood: 'deb887', cadetblue: '5f9ea0', chartreuse: '7fff00', chocolate: 'd2691e', coral: 'ff7f50', cornflowerblue: '6495ed', cornsilk: 'fff8dc', crimson: 'dc143c', cyan: '0ff', darkblue: '00008b', darkcyan: '008b8b', darkgoldenrod: 'b8860b', darkgray: 'a9a9a9', darkgrey: 'a9a9a9', darkgreen: '006400', darkkhaki: 'bdb76b', darkmagenta: '8b008b', darkolivegreen: '556b2f', darkorange: 'ff8c00', darkorchid: '9932cc', darkred: '8b0000', darksalmon: 'e9967a', darkseagreen: '8fbc8f', darkslateblue: '483d8b', darkslategray: '2f4f4f', darkslategrey: '2f4f4f', darkturquoise: '00ced1', darkviolet: '9400d3', deeppink: 'ff1493', deepskyblue: '00bfff', dimgray: '696969', dimgrey: '696969', dodgerblue: '1e90ff', firebrick: 'b22222', floralwhite: 'fffaf0', forestgreen: '228b22', fuchsia: 'f0f', gainsboro: 'dcdcdc', ghostwhite: 'f8f8ff', gold: 'ffd700', goldenrod: 'daa520', gray: '808080', grey: '808080', green: '008000', greenyellow: 'adff2f', honeydew: 'f0fff0', hotpink: 'ff69b4', indianred: 'cd5c5c', indigo: '4b0082', ivory: 'fffff0', khaki: 'f0e68c', lavender: 'e6e6fa', lavenderblush: 'fff0f5', lawngreen: '7cfc00', lemonchiffon: 'fffacd', lightblue: 'add8e6', lightcoral: 'f08080', lightcyan: 'e0ffff', lightgoldenrodyellow: 'fafad2', lightgray: 'd3d3d3', lightgrey: 'd3d3d3', lightgreen: '90ee90', lightpink: 'ffb6c1', lightsalmon: 'ffa07a', lightseagreen: '20b2aa', lightskyblue: '87cefa', lightslategray: '789', lightslategrey: '789', lightsteelblue: 'b0c4de', lightyellow: 'ffffe0', lime: '0f0', limegreen: '32cd32', linen: 'faf0e6', magenta: 'f0f', maroon: '800000', mediumaquamarine: '66cdaa', mediumblue: '0000cd', mediumorchid: 'ba55d3', mediumpurple: '9370d8', mediumseagreen: '3cb371', mediumslateblue: '7b68ee', mediumspringgreen: '00fa9a', mediumturquoise: '48d1cc', mediumvioletred: 'c71585', midnightblue: '191970', mintcream: 'f5fffa', mistyrose: 'ffe4e1', moccasin: 'ffe4b5', navajowhite: 'ffdead', navy: '000080', oldlace: 'fdf5e6', olive: '808000', olivedrab: '6b8e23', orange: 'ffa500', orangered: 'ff4500', orchid: 'da70d6', palegoldenrod: 'eee8aa', palegreen: '98fb98', paleturquoise: 'afeeee', palevioletred: 'd87093', papayawhip: 'ffefd5', peachpuff: 'ffdab9', peru: 'cd853f', pink: 'ffc0cb', plum: 'dda0dd', powderblue: 'b0e0e6', purple: '800080', rebeccapurple: '639', red: 'f00', rosybrown: 'bc8f8f', royalblue: '4169e1', saddlebrown: '8b4513', salmon: 'fa8072', sandybrown: 'f4a460', seagreen: '2e8b57', seashell: 'fff5ee', sienna: 'a0522d', silver: 'c0c0c0', skyblue: '87ceeb', slateblue: '6a5acd', slategray: '708090', slategrey: '708090', snow: 'fffafa', springgreen: '00ff7f', steelblue: '4682b4', tan: 'd2b48c', teal: '008080', thistle: 'd8bfd8', tomato: 'ff6347', turquoise: '40e0d0', violet: 'ee82ee', wheat: 'f5deb3', white: 'fff', whitesmoke: 'f5f5f5', yellow: 'ff0', yellowgreen: '9acd32' }; };
mit
JunaidPaul/numeric
tools/Crypto-JS v2.4.0/crypto-sha1-hmac-pbkdf2-rabbit/crypto-sha1-hmac-pbkdf2-rabbit.js
6356
/* * Crypto-JS v2.4.0 * http://code.google.com/p/crypto-js/ * Copyright (c) 2011, Jeff Mott. All rights reserved. * http://code.google.com/p/crypto-js/wiki/License */ if(typeof Crypto=="undefined"||!Crypto.util)(function(){var i=window.Crypto={},j=i.util={rotl:function(b,c){return b<<c|b>>>32-c},rotr:function(b,c){return b<<32-c|b>>>c},endian:function(b){if(b.constructor==Number)return j.rotl(b,8)&16711935|j.rotl(b,24)&4278255360;for(var c=0;c<b.length;c++)b[c]=j.endian(b[c]);return b},randomBytes:function(b){for(var c=[];b>0;b--)c.push(Math.floor(Math.random()*256));return c},bytesToWords:function(b){for(var c=[],e=0,g=0;e<b.length;e++,g+=8)c[g>>>5]|=b[e]<<24- g%32;return c},wordsToBytes:function(b){for(var c=[],e=0;e<b.length*32;e+=8)c.push(b[e>>>5]>>>24-e%32&255);return c},bytesToHex:function(b){for(var c=[],e=0;e<b.length;e++){c.push((b[e]>>>4).toString(16));c.push((b[e]&15).toString(16))}return c.join("")},hexToBytes:function(b){for(var c=[],e=0;e<b.length;e+=2)c.push(parseInt(b.substr(e,2),16));return c},bytesToBase64:function(b){if(typeof btoa=="function")return btoa(m.bytesToString(b));for(var c=[],e=0;e<b.length;e+=3)for(var g=b[e]<<16|b[e+1]<< 8|b[e+2],a=0;a<4;a++)e*8+a*6<=b.length*8?c.push("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(g>>>6*(3-a)&63)):c.push("=");return c.join("")},base64ToBytes:function(b){if(typeof atob=="function")return m.stringToBytes(atob(b));b=b.replace(/[^A-Z0-9+\/]/ig,"");for(var c=[],e=0,g=0;e<b.length;g=++e%4)g!=0&&c.push(("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(b.charAt(e-1))&Math.pow(2,-2*g+8)-1)<<g*2|"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(b.charAt(e))>>> 6-g*2);return c}};i=i.charenc={};i.UTF8={stringToBytes:function(b){return m.stringToBytes(unescape(encodeURIComponent(b)))},bytesToString:function(b){return decodeURIComponent(escape(m.bytesToString(b)))}};var m=i.Binary={stringToBytes:function(b){for(var c=[],e=0;e<b.length;e++)c.push(b.charCodeAt(e)&255);return c},bytesToString:function(b){for(var c=[],e=0;e<b.length;e++)c.push(String.fromCharCode(b[e]));return c.join("")}}})(); (function(){var i=Crypto,j=i.util,m=i.charenc,b=m.UTF8,c=m.Binary,e=i.SHA1=function(g,a){var d=j.wordsToBytes(e._sha1(g));return a&&a.asBytes?d:a&&a.asString?c.bytesToString(d):j.bytesToHex(d)};e._sha1=function(g){if(g.constructor==String)g=b.stringToBytes(g);var a=j.bytesToWords(g),d=g.length*8;g=[];var h=1732584193,f=-271733879,k=-1732584194,l=271733878,o=-1009589776;a[d>>5]|=128<<24-d%32;a[(d+64>>>9<<4)+15]=d;for(d=0;d<a.length;d+=16){for(var p=h,r=f,s=k,q=l,u=o,n=0;n<80;n++){if(n<16)g[n]=a[d+ n];else{var t=g[n-3]^g[n-8]^g[n-14]^g[n-16];g[n]=t<<1|t>>>31}t=(h<<5|h>>>27)+o+(g[n]>>>0)+(n<20?(f&k|~f&l)+1518500249:n<40?(f^k^l)+1859775393:n<60?(f&k|f&l|k&l)-1894007588:(f^k^l)-899497514);o=l;l=k;k=f<<30|f>>>2;f=h;h=t}h+=p;f+=r;k+=s;l+=q;o+=u}return[h,f,k,l,o]};e._blocksize=16;e._digestsize=20})(); (function(){var i=Crypto,j=i.util,m=i.charenc,b=m.UTF8,c=m.Binary;i.HMAC=function(e,g,a,d){if(g.constructor==String)g=b.stringToBytes(g);if(a.constructor==String)a=b.stringToBytes(a);if(a.length>e._blocksize*4)a=e(a,{asBytes:true});var h=a.slice(0);a=a.slice(0);for(var f=0;f<e._blocksize*4;f++){h[f]^=92;a[f]^=54}e=e(h.concat(e(a.concat(g),{asBytes:true})),{asBytes:true});return d&&d.asBytes?e:d&&d.asString?c.bytesToString(e):j.bytesToHex(e)}})(); (function(){var i=Crypto,j=i.util,m=i.charenc,b=m.UTF8,c=m.Binary;i.PBKDF2=function(e,g,a,d){function h(u,n){return i.HMAC(f,n,u,{asBytes:true})}if(e.constructor==String)e=b.stringToBytes(e);if(g.constructor==String)g=b.stringToBytes(g);for(var f=d&&d.hasher||i.SHA1,k=d&&d.iterations||1,l=[],o=1;l.length<a;){for(var p=h(e,g.concat(j.wordsToBytes([o]))),r=p,s=1;s<k;s++){r=h(e,r);for(var q=0;q<p.length;q++)p[q]^=r[q]}l=l.concat(p);o++}l.length=a;return d&&d.asBytes?l:d&&d.asString?c.bytesToString(l): j.bytesToHex(l)}})(); (function(){var i=Crypto,j=i.util,m=i.charenc.UTF8,b=[],c=[],e,g=i.Rabbit={encrypt:function(a,d){var h=m.stringToBytes(a),f=j.randomBytes(8),k=d.constructor==String?i.PBKDF2(d,f,32,{asBytes:true}):d;g._rabbit(h,k,j.bytesToWords(f));return j.bytesToBase64(f.concat(h))},decrypt:function(a,d){var h=j.base64ToBytes(a),f=h.splice(0,8),k=d.constructor==String?i.PBKDF2(d,f,32,{asBytes:true}):d;g._rabbit(h,k,j.bytesToWords(f));return m.bytesToString(h)},_rabbit:function(a,d,h){g._keysetup(d);h&&g._ivsetup(h); d=[];for(h=0;h<a.length;h++){if(h%16==0){g._nextstate();d[0]=b[0]^b[5]>>>16^b[3]<<16;d[1]=b[2]^b[7]>>>16^b[5]<<16;d[2]=b[4]^b[1]>>>16^b[7]<<16;d[3]=b[6]^b[3]>>>16^b[1]<<16;for(var f=0;f<4;f++)d[f]=(d[f]<<8|d[f]>>>24)&16711935|(d[f]<<24|d[f]>>>8)&4278255360;for(f=120;f>=0;f-=8)d[f/8]=d[f>>>5]>>>24-f%32&255}a[h]^=d[h%16]}},_keysetup:function(a){b[0]=a[0];b[2]=a[1];b[4]=a[2];b[6]=a[3];b[1]=a[3]<<16|a[2]>>>16;b[3]=a[0]<<16|a[3]>>>16;b[5]=a[1]<<16|a[0]>>>16;b[7]=a[2]<<16|a[1]>>>16;c[0]=j.rotl(a[2],16); c[2]=j.rotl(a[3],16);c[4]=j.rotl(a[0],16);c[6]=j.rotl(a[1],16);c[1]=a[0]&4294901760|a[1]&65535;c[3]=a[1]&4294901760|a[2]&65535;c[5]=a[2]&4294901760|a[3]&65535;c[7]=a[3]&4294901760|a[0]&65535;for(a=e=0;a<4;a++)g._nextstate();for(a=0;a<8;a++)c[a]^=b[a+4&7]},_ivsetup:function(a){var d=j.endian(a[0]);a=j.endian(a[1]);var h=d>>>16|a&4294901760,f=a<<16|d&65535;c[0]^=d;c[1]^=h;c[2]^=a;c[3]^=f;c[4]^=d;c[5]^=h;c[6]^=a;c[7]^=f;for(d=0;d<4;d++)g._nextstate()},_nextstate:function(){for(var a=[],d=0;d<8;d++)a[d]= c[d];c[0]=c[0]+1295307597+e>>>0;c[1]=c[1]+3545052371+(c[0]>>>0<a[0]>>>0?1:0)>>>0;c[2]=c[2]+886263092+(c[1]>>>0<a[1]>>>0?1:0)>>>0;c[3]=c[3]+1295307597+(c[2]>>>0<a[2]>>>0?1:0)>>>0;c[4]=c[4]+3545052371+(c[3]>>>0<a[3]>>>0?1:0)>>>0;c[5]=c[5]+886263092+(c[4]>>>0<a[4]>>>0?1:0)>>>0;c[6]=c[6]+1295307597+(c[5]>>>0<a[5]>>>0?1:0)>>>0;c[7]=c[7]+3545052371+(c[6]>>>0<a[6]>>>0?1:0)>>>0;e=c[7]>>>0<a[7]>>>0?1:0;a=[];for(d=0;d<8;d++){var h=b[d]+c[d]>>>0,f=h&65535,k=h>>>16;a[d]=((f*f>>>17)+f*k>>>15)+k*k^((h&4294901760)* h>>>0)+((h&65535)*h>>>0)>>>0}b[0]=a[0]+(a[7]<<16|a[7]>>>16)+(a[6]<<16|a[6]>>>16);b[1]=a[1]+(a[0]<<8|a[0]>>>24)+a[7];b[2]=a[2]+(a[1]<<16|a[1]>>>16)+(a[0]<<16|a[0]>>>16);b[3]=a[3]+(a[2]<<8|a[2]>>>24)+a[1];b[4]=a[4]+(a[3]<<16|a[3]>>>16)+(a[2]<<16|a[2]>>>16);b[5]=a[5]+(a[4]<<8|a[4]>>>24)+a[3];b[6]=a[6]+(a[5]<<16|a[5]>>>16)+(a[4]<<16|a[4]>>>16);b[7]=a[7]+(a[6]<<8|a[6]>>>24)+a[5]}}})();
mit
pitamar/Rocket.Chat
packages/rocketchat-livechat/messageTypes.js
963
RocketChat.MessageTypes.registerType({ id: 'livechat_video_call', system: true, message: 'New_videocall_request' }); RocketChat.actionLinks.register('createLivechatCall', function(message, params, instance) { if (Meteor.isClient) { instance.tabBar.open('video'); } }); RocketChat.actionLinks.register('denyLivechatCall', function(message/*, params*/) { if (Meteor.isServer) { const user = Meteor.user(); RocketChat.models.Messages.createWithTypeRoomIdMessageAndUser('command', message.rid, 'endCall', user); RocketChat.Notifications.notifyRoom(message.rid, 'deleteMessage', { _id: message._id }); const language = user.language || RocketChat.settings.get('language') || 'en'; RocketChat.Livechat.closeRoom({ user, room: RocketChat.models.Rooms.findOneById(message.rid), comment: TAPi18n.__('Videocall_declined', { lng: language }) }); Meteor.defer(() => { RocketChat.models.Messages.setHiddenById(message._id); }); } });
mit
Mustaavalkosta/toolchain_gcc-4.9
libstdc++-v3/testsuite/23_containers/array/tuple_interface/tuple_size.cc
1230
// { dg-options "-std=gnu++0x" } // // Copyright (C) 2011-2013 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. #include <array> #include <testsuite_hooks.h> void test01() { bool test __attribute__((unused)) = true; using namespace std; { const size_t len = 5; typedef array<int, len> array_type; VERIFY( tuple_size<array_type>::value == 5 ); } { const size_t len = 0; typedef array<float, len> array_type; VERIFY( tuple_size<array_type>::value == 0 ); } } int main() { test01(); return 0; }
gpl-2.0
stain/jdk8u
src/share/classes/sun/java2d/cmm/CMSManager.java
6971
/* * Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package sun.java2d.cmm; import java.awt.color.ColorSpace; import java.awt.color.ICC_Profile; import java.awt.color.CMMException; import java.awt.image.BufferedImage; import java.awt.image.Raster; import java.awt.image.WritableRaster; import java.security.AccessController; import java.security.PrivilegedAction; import sun.security.action.GetPropertyAction; import java.util.ServiceLoader; public class CMSManager { public static ColorSpace GRAYspace; // These two fields allow access public static ColorSpace LINEAR_RGBspace; // to java.awt.color.ColorSpace // private fields from other // packages. The fields are set // by java.awt.color.ColorSpace // and read by // java.awt.image.ColorModel. private static PCMM cmmImpl = null; public static synchronized PCMM getModule() { if (cmmImpl != null) { return cmmImpl; } CMMServiceProvider spi = AccessController.doPrivileged( new PrivilegedAction<CMMServiceProvider>() { public CMMServiceProvider run() { String cmmClass = System.getProperty( "sun.java2d.cmm", "sun.java2d.cmm.lcms.LcmsServiceProvider"); ServiceLoader<CMMServiceProvider> cmmLoader = ServiceLoader.loadInstalled(CMMServiceProvider.class); CMMServiceProvider spi = null; for (CMMServiceProvider cmm : cmmLoader) { spi = cmm; if (cmm.getClass().getName().equals(cmmClass)) { break; } } return spi; } }); cmmImpl = spi.getColorManagementModule(); if (cmmImpl == null) { throw new CMMException("Cannot initialize Color Management System."+ "No CM module found"); } GetPropertyAction gpa = new GetPropertyAction("sun.java2d.cmm.trace"); String cmmTrace = (String)AccessController.doPrivileged(gpa); if (cmmTrace != null) { cmmImpl = new CMMTracer(cmmImpl); } return cmmImpl; } static synchronized boolean canCreateModule() { return (cmmImpl == null); } /* CMM trace routines */ public static class CMMTracer implements PCMM { PCMM tcmm; String cName ; public CMMTracer(PCMM tcmm) { this.tcmm = tcmm; cName = tcmm.getClass().getName(); } public Profile loadProfile(byte[] data) { System.err.print(cName + ".loadProfile"); Profile p = tcmm.loadProfile(data); System.err.printf("(ID=%s)\n", p.toString()); return p; } public void freeProfile(Profile p) { System.err.printf(cName + ".freeProfile(ID=%s)\n", p.toString()); tcmm.freeProfile(p); } public int getProfileSize(Profile p) { System.err.print(cName + ".getProfileSize(ID=" + p + ")"); int size = tcmm.getProfileSize(p); System.err.println("=" + size); return size; } public void getProfileData(Profile p, byte[] data) { System.err.print(cName + ".getProfileData(ID=" + p + ") "); System.err.println("requested " + data.length + " byte(s)"); tcmm.getProfileData(p, data); } public int getTagSize(Profile p, int tagSignature) { System.err.printf(cName + ".getTagSize(ID=%x, TagSig=%s)", p, signatureToString(tagSignature)); int size = tcmm.getTagSize(p, tagSignature); System.err.println("=" + size); return size; } public void getTagData(Profile p, int tagSignature, byte[] data) { System.err.printf(cName + ".getTagData(ID=%x, TagSig=%s)", p, signatureToString(tagSignature)); System.err.println(" requested " + data.length + " byte(s)"); tcmm.getTagData(p, tagSignature, data); } public void setTagData(Profile p, int tagSignature, byte[] data) { System.err.print(cName + ".setTagData(ID=" + p + ", TagSig=" + tagSignature + ")"); System.err.println(" sending " + data.length + " byte(s)"); tcmm.setTagData(p, tagSignature, data); } /* methods for creating ColorTransforms */ public ColorTransform createTransform(ICC_Profile profile, int renderType, int transformType) { System.err.println(cName + ".createTransform(ICC_Profile,int,int)"); return tcmm.createTransform(profile, renderType, transformType); } public ColorTransform createTransform(ColorTransform[] transforms) { System.err.println(cName + ".createTransform(ColorTransform[])"); return tcmm.createTransform(transforms); } private static String signatureToString(int sig) { return String.format("%c%c%c%c", (char)(0xff & (sig >> 24)), (char)(0xff & (sig >> 16)), (char)(0xff & (sig >> 8)), (char)(0xff & (sig ))); } } }
gpl-2.0
bmacenbacher/multison
libraries/rokcommon/RokCommon/Service/Container/Loader/File/Ini.php
1393
<?php /* * This file is part of the symfony framework. * * (c) Fabien Potencier <[email protected]> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ /** * RokCommon_Service_Container_Loader_File_Ini loads parameters from INI files. * * @package symfony * @subpackage dependency_injection * @author Fabien Potencier <[email protected]> * @version SVN: $Id: Ini.php 10831 2013-05-29 19:32:17Z btowles $ */ class RokCommon_Service_Container_Loader_File_Ini extends RokCommon_Service_Container_Loader_File { public function doLoad($files) { $parameters = array(); foreach ($files as $file) { $path = $this->getAbsolutePath($file); if (!file_exists($path)) { throw new InvalidArgumentException(sprintf('The %s file does not exist.', $file)); } $result = parse_ini_file($path, true); if (false === $result || array() === $result) { throw new InvalidArgumentException(sprintf('The %s file is not valid.', $file)); } if (isset($result['parameters']) && is_array($result['parameters'])) { foreach ($result['parameters'] as $key => $value) { $parameters[strtolower($key)] = $value; } } } return array(array(), $parameters); } }
gpl-2.0
healthcommcore/lung_cancer_site
modules/mod_hd2login/helper.php
1126
<?php /** * @version $Id: helper.php 11668 2009-03-08 20:33:38Z willebil $ * @package Joomla * @copyright Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved. * @license GNU/GPL, see LICENSE.php * Joomla! is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. */ // no direct access defined('_JEXEC') or die('Restricted access'); class modLoginHelper { function getReturnURL($params, $type) { if($itemid = $params->get($type)) { $menu =& JSite::getMenu(); $item = $menu->getItem($itemid); $url = JRoute::_($item->link.'&Itemid='.$itemid, false); } else { // stay on the same page $uri = JFactory::getURI(); $url = $uri->toString(array('path', 'query', 'fragment')); } return base64_encode($url); } function getType() { $user = & JFactory::getUser(); return (!$user->get('guest')) ? 'logout' : 'login'; } }
gpl-2.0
Evilcome/GrubbyWorm-IOS
cocos2d/cocos/base/CCNS.cpp
5592
/**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2013-2014 Chukong Technologies http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "base/CCNS.h" #include <string> #include <vector> #include <string.h> #include <stdlib.h> using namespace std; NS_CC_BEGIN typedef std::vector<std::string> strArray; // string toolkit static inline void split(const std::string& src, const std::string& token, strArray& vect) { size_t nend = 0; size_t nbegin = 0; size_t tokenSize = token.size(); while(nend != std::string::npos) { nend = src.find(token, nbegin); if(nend == std::string::npos) vect.push_back(src.substr(nbegin, src.length()-nbegin)); else vect.push_back(src.substr(nbegin, nend-nbegin)); nbegin = nend + tokenSize; } } // first, judge whether the form of the string like this: {x,y} // if the form is right,the string will be split into the parameter strs; // or the parameter strs will be empty. // if the form is right return true,else return false. static bool splitWithForm(const std::string& content, strArray& strs) { bool bRet = false; do { CC_BREAK_IF(content.empty()); size_t nPosLeft = content.find('{'); size_t nPosRight = content.find('}'); // don't have '{' and '}' CC_BREAK_IF(nPosLeft == std::string::npos || nPosRight == std::string::npos); // '}' is before '{' CC_BREAK_IF(nPosLeft > nPosRight); const std::string pointStr = content.substr(nPosLeft + 1, nPosRight - nPosLeft - 1); // nothing between '{' and '}' CC_BREAK_IF(pointStr.length() == 0); size_t nPos1 = pointStr.find('{'); size_t nPos2 = pointStr.find('}'); // contain '{' or '}' CC_BREAK_IF(nPos1 != std::string::npos || nPos2 != std::string::npos); split(pointStr, ",", strs); if (strs.size() != 2 || strs[0].length() == 0 || strs[1].length() == 0) { strs.clear(); break; } bRet = true; } while (0); return bRet; } // implement the functions Rect RectFromString(const std::string& str) { Rect result = Rect::ZERO; do { CC_BREAK_IF(str.empty()); std::string content = str; // find the first '{' and the third '}' size_t nPosLeft = content.find('{'); size_t nPosRight = content.find('}'); for (int i = 1; i < 3; ++i) { if (nPosRight == std::string::npos) { break; } nPosRight = content.find('}', nPosRight + 1); } CC_BREAK_IF(nPosLeft == std::string::npos || nPosRight == std::string::npos); content = content.substr(nPosLeft + 1, nPosRight - nPosLeft - 1); size_t nPointEnd = content.find('}'); CC_BREAK_IF(nPointEnd == std::string::npos); nPointEnd = content.find(',', nPointEnd); CC_BREAK_IF(nPointEnd == std::string::npos); // get the point string and size string const std::string pointStr = content.substr(0, nPointEnd); const std::string sizeStr = content.substr(nPointEnd + 1, content.length() - nPointEnd); // split the string with ',' strArray pointInfo; CC_BREAK_IF(!splitWithForm(pointStr.c_str(), pointInfo)); strArray sizeInfo; CC_BREAK_IF(!splitWithForm(sizeStr.c_str(), sizeInfo)); float x = (float) atof(pointInfo[0].c_str()); float y = (float) atof(pointInfo[1].c_str()); float width = (float) atof(sizeInfo[0].c_str()); float height = (float) atof(sizeInfo[1].c_str()); result = Rect(x, y, width, height); } while (0); return result; } Vec2 PointFromString(const std::string& str) { Vec2 ret = Vec2::ZERO; do { strArray strs; CC_BREAK_IF(!splitWithForm(str, strs)); float x = (float) atof(strs[0].c_str()); float y = (float) atof(strs[1].c_str()); ret = Vec2(x, y); } while (0); return ret; } Size SizeFromString(const std::string& pszContent) { Size ret = Size::ZERO; do { strArray strs; CC_BREAK_IF(!splitWithForm(pszContent, strs)); float width = (float) atof(strs[0].c_str()); float height = (float) atof(strs[1].c_str()); ret = Size(width, height); } while (0); return ret; } NS_CC_END
gpl-3.0
lazzarello/bk-tb-remote
db/migrate/019_add_server_name_and_app.rb
285
class AddServerNameAndApp < ActiveRecord::Migration def self.up add_column :preferences, :server_name, :string add_column :preferences, :app_name, :string end def self.down remove_column :preferences, :app_name remove_column :preferences, :server_name end end
agpl-3.0
wangyum/tensorflow
tensorflow/contrib/layers/python/layers/embedding_ops.py
41512
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Embedding functions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from six.moves import xrange # pylint: disable=redefined-builtin from tensorflow.contrib.framework.python.framework import tensor_util as contrib_tensor_util from tensorflow.contrib.layers.python.ops import sparse_feature_cross_op from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import sparse_tensor from tensorflow.python.framework import tensor_shape from tensorflow.python.ops import array_ops from tensorflow.python.ops import clip_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import data_flow_ops from tensorflow.python.ops import embedding_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import resource_variable_ops from tensorflow.python.ops import sparse_ops from tensorflow.python.ops import variables from tensorflow.python.platform import tf_logging as logging __all__ = [ "safe_embedding_lookup_sparse", "scattered_embedding_lookup", "scattered_embedding_lookup_sparse", "embedding_lookup_unique", "embedding_lookup_sparse_with_distributed_aggregation" ] def safe_embedding_lookup_sparse(embedding_weights, sparse_ids, sparse_weights=None, combiner=None, default_id=None, name=None, partition_strategy="div", max_norm=None): """Lookup embedding results, accounting for invalid IDs and empty features. The partitioned embedding in `embedding_weights` must all be the same shape except for the first dimension. The first dimension is allowed to vary as the vocabulary size is not necessarily a multiple of `P`. `embedding_weights` may be a `PartitionedVariable` as returned by using `tf.get_variable()` with a partitioner. Invalid IDs (< 0) are pruned from input IDs and weights, as well as any IDs with non-positive weight. For an entry with no features, the embedding vector for `default_id` is returned, or the 0-vector if `default_id` is not supplied. The ids and weights may be multi-dimensional. Embeddings are always aggregated along the last dimension. Args: embedding_weights: A list of `P` float tensors or values representing partitioned embedding tensors. Alternatively, a `PartitionedVariable`, created by partitioning along dimension 0. The total unpartitioned shape should be `[e_0, e_1, ..., e_m]`, where `e_0` represents the vocab size and `e_1, ..., e_m` are the embedding dimensions. sparse_ids: `SparseTensor` of shape `[d_0, d_1, ..., d_n]` containing the ids. `d_0` is typically batch size. sparse_weights: `SparseTensor` of same shape as `sparse_ids`, containing float weights corresponding to `sparse_ids`, or `None` if all weights are be assumed to be 1.0. combiner: A string specifying how to combine embedding results for each entry. Currently "mean", "sqrtn" and "sum" are supported, with "mean" the default. default_id: The id to use for an entry with no features. name: A name for this operation (optional). partition_strategy: A string specifying the partitioning strategy. Currently `"div"` and `"mod"` are supported. Default is `"div"`. max_norm: If not None, all embeddings are l2-normalized to max_norm before combining. Returns: Dense tensor of shape `[d_0, d_1, ..., d_{n-1}, e_1, ..., e_m]`. Raises: ValueError: if `embedding_weights` is empty. """ if combiner is None: logging.warn("The default value of combiner will change from \"mean\" " "to \"sqrtn\" after 2016/11/01.") combiner = "mean" if embedding_weights is None: raise ValueError("Missing embedding_weights %s." % embedding_weights) if isinstance(embedding_weights, variables.PartitionedVariable): embedding_weights = list(embedding_weights) # get underlying Variables. if not isinstance(embedding_weights, list): embedding_weights = [embedding_weights] if len(embedding_weights) < 1: raise ValueError("Missing embedding_weights %s." % embedding_weights) dtype = sparse_weights.dtype if sparse_weights is not None else None if isinstance(embedding_weights, variables.PartitionedVariable): embedding_weights = list(embedding_weights) embedding_weights = [ ops.convert_to_tensor(w, dtype=dtype) for w in embedding_weights ] contrib_tensor_util.assert_same_float_dtype(embedding_weights + [sparse_weights]) with ops.name_scope(name, "embedding_lookup", embedding_weights + [sparse_ids, sparse_weights]) as scope: # Reshape higher-rank sparse ids and weights to linear segment ids. original_shape = sparse_ids.dense_shape original_rank_dim = sparse_ids.dense_shape.get_shape()[0] original_rank = ( array_ops.size(original_shape) if original_rank_dim.value is None else original_rank_dim.value) sparse_ids = sparse_ops.sparse_reshape(sparse_ids, [ math_ops.reduce_prod( array_ops.slice(original_shape, [0], [original_rank - 1])), array_ops.gather(original_shape, original_rank - 1)]) if sparse_weights is not None: sparse_weights = sparse_tensor.SparseTensor( sparse_ids.indices, sparse_weights.values, sparse_ids.dense_shape) # Prune invalid ids and weights. sparse_ids, sparse_weights = _prune_invalid_ids(sparse_ids, sparse_weights) # Fill in dummy values for empty features, if necessary. sparse_ids, is_row_empty = sparse_ops.sparse_fill_empty_rows(sparse_ids, default_id or 0) if sparse_weights is not None: sparse_weights, _ = sparse_ops.sparse_fill_empty_rows(sparse_weights, 1.0) result = embedding_ops.embedding_lookup_sparse( embedding_weights, sparse_ids, sparse_weights, combiner=combiner, partition_strategy=partition_strategy, name=None if default_id is None else scope, max_norm=max_norm) if default_id is None: # Broadcast is_row_empty to the same shape as embedding_lookup_result, # for use in Select. is_row_empty = array_ops.tile( array_ops.reshape(is_row_empty, [-1, 1]), array_ops.stack([1, array_ops.shape(result)[1]])) result = array_ops.where(is_row_empty, array_ops.zeros_like(result), result, name=scope) # Reshape back from linear ids back into higher-dimensional dense result. final_result = array_ops.reshape( result, array_ops.concat([ array_ops.slice( math_ops.cast(original_shape, dtypes.int32), [0], [original_rank - 1]), array_ops.slice(array_ops.shape(result), [1], [-1]) ], 0)) final_result.set_shape(tensor_shape.unknown_shape( (original_rank_dim - 1).value).concatenate(result.get_shape()[1:])) return final_result def _prune_invalid_ids(sparse_ids, sparse_weights): """Prune invalid IDs (< 0) from the input ids and weights.""" is_id_valid = math_ops.greater_equal(sparse_ids.values, 0) if sparse_weights is not None: is_id_valid = math_ops.logical_and( is_id_valid, math_ops.greater(sparse_weights.values, 0)) sparse_ids = sparse_ops.sparse_retain(sparse_ids, is_id_valid) if sparse_weights is not None: sparse_weights = sparse_ops.sparse_retain(sparse_weights, is_id_valid) return sparse_ids, sparse_weights def scattered_embedding_lookup(params, values, dimension, name=None, hash_key=None): """Looks up embeddings using parameter hashing for each value in `values`. The i-th embedding component of a value v in `values` is found by retrieving the weight whose index is a fingerprint of the pair (v,i). The concept is explored as "feature hashing" for model compression in this paper: http://arxiv.org/pdf/1504.04788.pdf Feature hashing has the pleasant effect of allowing us to compute an embedding without needing a pre-determined vocabulary, relieving some amount of process complexity. It also allows for us to maintain embeddings for possibly trillions of features with a fixed amount of memory. Note that this is superior to out-of-vocabulary shared "hash buckets" in that the embedding is extremely likely to be unique for each token as opposed to being shared across probably-colliding tokens. The price is that we must compute a hash once for each scalar in the token's embedding as opposed to once per token. If `params` is a list, it represents a partition of the embedding parameters. Each tensor in the list should have the same length, except for the first ones which may have an additional element. For instance 10 parameters can be partitioned in 4 tensors with length `[3, 3, 2, 2]`. Args: params: A `Tensor`, `list` of `Tensors`, or `PartitionedVariable`. Each tensor must be of rank 1 with fully-defined shape. values: `Tensor` of values to be embedded with shape `[d0, ..., dn]`. dimension: Embedding dimension. name: An optional name for this op. hash_key: Specify the hash_key that will be used by the `FingerprintCat64` function to combine the crosses fingerprints on SparseFeatureCrossOp (optional). Returns: A `Tensor` with shape `[d0, ..., dn, dimension]`. Raises: ValueError: if dimension is not positive or the partition size is invalid. """ if dimension is None: raise ValueError("You must specify dimension.") return _sampled_scattered_embedding_lookup( params, values, dimension=dimension, sampled_candidates=None, hash_key=hash_key, name=name) def _sampled_scattered_embedding_lookup( params, values, dimension=None, sampled_candidates=None, hash_key=None, name=None): """Looks up embeddings using parameter hashing for each value in `values`. This method looks up selected embedding dimensions if `sampled_candidates` is given, otherwise looks up all dimensions. The i-th embedding component of a value v in `values` is found by retrieving the weight whose index is a fingerprint of the pair (v,i). The concept is explored as "feature hashing" for model compression in this paper: http://arxiv.org/pdf/1504.04788.pdf Feature hashing has the pleasant effect of allowing us to compute an embedding without needing a pre-determined vocabulary, relieving some amount of process complexity. It also allows for us to maintain embeddings for possibly trillions of features with a fixed amount of memory. Note that this is superior to out-of-vocabulary shared "hash buckets" in that the embedding is extremely likely to be unique for each token as opposed to being shared across probably-colliding tokens. The price is that we must compute a hash once for each scalar in the token's embedding as opposed to once per token. If `params` is a list, it represents a partition of the embedding parameters. Each tensor in the list should have the same length, except for the first ones which may have an additional element. For instance 10 parameters can be partitioned in 4 tensors with length `[3, 3, 2, 2]`. Args: params: A `Tensor`, `list` of `Tensors`, or `PartitionedVariable`. Each tensor must be of rank 1 with fully-defined shape. values: `Tensor` of values to be embedded with shape `[d0, ..., dn]`. dimension: Embedding dimension. The user must specify either `dimension` or `sampled_candidates`. sampled_candidates: An optional `Tensor` of slice indices to keep along the final dimension with shape `[d0, ..., dn, N]`. If given, `dimension` is ignored. If `None`, looks up all candidates. hash_key: Specify the hash_key that will be used by the `FingerprintCat64` function to combine the crosses fingerprints on SparseFeatureCrossOp (optional). name: An optional name for this op. Returns: A `Tensor` with shape `[d0, ..., dn, dimension]`. If `sampled_candidates` is given, the output shape is `[d0, ..., dn, N]` Raises: ValueError: if dimension is not positive or the partition size is invalid. """ if isinstance(params, variables.PartitionedVariable): params = list(params) if not isinstance(params, list): params = [params] with ops.name_scope(name, "scattered_embedding_lookup", params + [dimension, values]): # Flatten the values values_shape = array_ops.shape(values) values = array_ops.reshape(values, [-1, 1]) if sampled_candidates is None: if dimension is None: raise ValueError( "You must specify either dimension or sampled_candidates.") if dimension <= 0: raise ValueError("Dimension must be >0. Given is %d" % dimension) sampled_candidates = array_ops.tile(array_ops.expand_dims( math_ops.range(0, dimension), 0), array_ops.shape(values)) else: dimension = array_ops.shape(sampled_candidates)[ math_ops.subtract(array_ops.rank(sampled_candidates), 1)] sampled_candidates_shape = array_ops.shape(sampled_candidates) dimension_tensor = array_ops.reshape(dimension, shape=[1,]) expected_shape = array_ops.concat([values_shape, dimension_tensor], 0) with ops.control_dependencies([control_flow_ops.Assert( math_ops.reduce_all(math_ops.equal(sampled_candidates_shape, expected_shape)), ["The shape of sampled_candidates: ", sampled_candidates_shape, " does not match the shape of values: ", values_shape])]): # Flatten sampled_candidates, same way as values are flattened. sampled_candidates = array_ops.reshape(sampled_candidates, [-1, dimension]) num_partitions = len(params) partition_sizes = [] for p in range(num_partitions): shape = params[p].get_shape() shape.assert_has_rank(1) shape.assert_is_fully_defined() partition_sizes.append(shape[0].value) num_params = sum(partition_sizes) # Total number of parameters. # Assert the size of each partition. for p in range(num_partitions): expected_size = (num_params - p - 1) // num_partitions + 1 if partition_sizes[p] != expected_size: raise ValueError("Tensor %d in params has size %d, expected %d." % (p, partition_sizes[p], expected_size)) # With two values v1 and v2 and 3 dimensions, we will cross # [[0, 1, 2], [0, 1, 2]] with [[v1], [v2]]. tensors_to_cross = [sampled_candidates, values] ids = sparse_feature_cross_op.sparse_feature_cross( tensors_to_cross, hashed_output=True, num_buckets=num_params, hash_key=hash_key) ids = sparse_ops.sparse_tensor_to_dense(ids) # No need to validate the indices since we have checked the params # dimensions and we know the largest id. result = embedding_ops.embedding_lookup( params, ids, partition_strategy="div") return array_ops.reshape(result, array_ops.concat([values_shape, [dimension]], 0)) def scattered_embedding_lookup_sparse(params, sparse_values, dimension, combiner=None, default_value=None, name=None, hash_key=None): """Looks up embeddings of a sparse feature using parameter hashing. See `tf.contrib.layers.scattered_embedding_lookup` for embedding with hashing. Args: params: A `Tensor`, `list` of `Tensors`, or `PartitionedVariable`. Each tensor must be of rank 1 with fully-defined shape. sparse_values: A 2-D `SparseTensor` containing the values to be embedded. Some rows may be empty. dimension: Embedding dimension combiner: A string specifying how to combine embedding results for each entry. Currently "mean", "sqrtn" and "sum" are supported, with "mean" the default. default_value: The value to use for an entry with no features. name: An optional name for this op. hash_key: Specify the hash_key that will be used by the `FingerprintCat64` function to combine the crosses fingerprints on SparseFeatureCrossOp (optional). Returns: Dense tensor with shape [N, dimension] with N the number of rows in sparse_values. Raises: TypeError: If sparse_values is not a SparseTensor. ValueError: If combiner is not one of {"mean", "sqrtn", "sum"}. """ if combiner is None: logging.warn("The default value of combiner will change from \"mean\" " "to \"sqrtn\" after 2016/11/01.") combiner = "mean" if isinstance(params, variables.PartitionedVariable): params = list(params) if not isinstance(params, list): params = [params] if not isinstance(sparse_values, sparse_tensor.SparseTensor): raise TypeError("sparse_values must be SparseTensor") with ops.name_scope(name, "scattered_embedding_lookup_sparse", params + [sparse_values]) as scope: # Fill in the empty rows. if default_value is None: # Random default values to reduce the risk of collision. if sparse_values.dtype == dtypes.string: default_value = "6ZxWzWOHxZ" else: default_value = 1288896567 sparse_values, _ = sparse_ops.sparse_fill_empty_rows( sparse_values, default_value) segment_ids = sparse_values.indices[:, 0] if segment_ids.dtype != dtypes.int32: segment_ids = math_ops.cast(segment_ids, dtypes.int32) values = sparse_values.values values, idx = array_ops.unique(values) embeddings = scattered_embedding_lookup( params, values, dimension, hash_key=hash_key) if combiner == "sum": embeddings = math_ops.sparse_segment_sum(embeddings, idx, segment_ids, name=scope) elif combiner == "mean": embeddings = math_ops.sparse_segment_mean(embeddings, idx, segment_ids, name=scope) elif combiner == "sqrtn": embeddings = math_ops.sparse_segment_sqrt_n(embeddings, idx, segment_ids, name=scope) else: raise ValueError("Combiner must be one of 'mean', 'sqrtn' or 'sum'.") return embeddings def embedding_lookup_unique(params, ids, name=None): """Version of embedding_lookup that avoids duplicate lookups. This can save communication in the case of repeated ids. Same interface as embedding_lookup. Except it supports multi-dimensional `ids` which allows to not reshape input/output to fit gather. Args: params: A list of tensors with the same shape and type, or a `PartitionedVariable`. Shape `[index, d1, d2, ...]`. ids: A one-dimensional `Tensor` with type `int32` or `int64` containing the ids to be looked up in `params`. Shape `[ids1, ids2, ...]`. name: A name for this operation (optional). Returns: A `Tensor` with the same type as the tensors in `params` and dimension of `[ids1, ids2, d1, d2, ...]`. Raises: ValueError: If `params` is empty. """ with ops.name_scope(name, "EmbeddingLookupUnique", [params, ids]): ids = ops.convert_to_tensor(ids) shape = array_ops.shape(ids) ids_flat = array_ops.reshape( ids, math_ops.reduce_prod(shape, keep_dims=True)) unique_ids, idx = array_ops.unique(ids_flat) unique_embeddings = embedding_ops.embedding_lookup(params, unique_ids) embeds_flat = array_ops.gather(unique_embeddings, idx) embed_shape = array_ops.concat( [shape, array_ops.shape(unique_embeddings)[1:]], 0) embeds = array_ops.reshape(embeds_flat, embed_shape) embeds.set_shape(ids.get_shape().concatenate( unique_embeddings.get_shape()[1:])) return embeds def _sampled_scattered_embedding_lookup_sparse(params, sp_values, dimension=None, sampled_candidates=None, hash_key=None, with_sign_hash=False, name=None): """Looks up embeddings using parameter hashing for sparse values. This method looks up selected embedding dimensions if `sampled_candidates` is given, otherwise looks up all dimensions. The i-th embedding component of a value v in `values` is found by retrieving the weight whose index is a fingerprint of the pair (v,i). The concept is explored as "feature hashing" for model compression in this paper: http://arxiv.org/pdf/1504.04788.pdf This is logically equivalent to: * Transforming `sp_values` (which has shape `[d0, d1]`) into a one-hot `Tensor` of shape `[d0, N]`. * Multiplying with a `Tensor` `h` of shape `[N, dimension]`, where `h(i, j) = params[hash(i, j)]`. Args: params: A float `Tensor` with rank 1 and fully-defined shape. sp_values: A 2D `SparseTensor` to be embedded with shape `[d0, d1]`. dimension: An int `Tensor` of the final dimension. The user needs to provide either `dimension` or `sampled_candidates`. sampled_candidates: An optional `Tensor` of column indices to keep along the final dimension with shape `[d0, N]`. If given, `dimension` is ignored. If `None`, looks up all candidates. hash_key: Specify the hash_key that will be used by the `FingerprintCat64` function to combine the crosses fingerprints on SparseFeatureCrossOp (optional). with_sign_hash: A `bool` indicating whether `h(i, j)` should be multiplied by `+1` or `-1`, where the value selected is determined by hashing `(i, j)`. This is often necessary to remove bias resulting from hash collisions. name: An optional name for this op. Returns: A `Tensor` of shape `[d0, dimension]`. If `sampled_candidates` is given, the output shape is `[d0, N]`. Raises: TypeError: If sp_values is not `SparseTensor`. ValueError: If both `dimension` and `sampled_candidates` are `None`. """ if not isinstance(sp_values, sparse_tensor.SparseTensor): raise TypeError("sp_values must be SparseTensor") with ops.name_scope( name=name, default_name="sampled_scattered_embedding_lookup_sparse", values=[sp_values, params, dimension, sampled_candidates]) as name_scope: segment_ids = sp_values.indices[:, 0] if sampled_candidates is not None: # Tile sampled_candidates so there is one line corresponding to each # element in sp_values.values sampled_candidates = array_ops.gather(sampled_candidates, segment_ids) embeddings = _sampled_scattered_embedding_lookup( params, sp_values.values, dimension=dimension, sampled_candidates=sampled_candidates, hash_key=hash_key, name="values_lookup") if with_sign_hash: signs = _sampled_scattered_embedding_lookup( array_ops.constant([-1., 1.]), sp_values.values, dimension=dimension, sampled_candidates=sampled_candidates, hash_key=hash_key, name="signs_lookup") embeddings = math_ops.multiply(signs, embeddings, name="signs_hash") if segment_ids.dtype != dtypes.int32: segment_ids = math_ops.cast(segment_ids, dtypes.int32) num_segments = array_ops.shape(sp_values)[0] return math_ops.unsorted_segment_sum(embeddings, segment_ids, num_segments=num_segments, name=name_scope) def embedding_lookup_sparse_with_distributed_aggregation( params, sp_ids, sp_weights, partition_strategy="mod", name=None, combiner=None, max_norm=None): """Computes embeddings for the given ids and weights. Embeddings belonging to same param are aggregated on that device first. This op is intended to decrease data transmission and improve parallelism. See `tf.nn.embedding_lookup_sparse` for the functionality and example of this op. Args: params: A single tensor representing the complete embedding tensor, or a list of P tensors all of same shape except for the first dimension, representing sharded embedding tensors. Alternatively, a `PartitionedVariable`, created by partitioning along dimension 0. Each element must be appropriately sized for the given `partition_strategy`. sp_ids: N x M SparseTensor of int64 ids (typically from FeatureValueToId), where N is typically batch size and M is arbitrary. sp_weights: either a SparseTensor of float / double weights, or None to indicate all weights should be taken to be 1. If specified, sp_weights must have exactly the same shape and indices as sp_ids. partition_strategy: A string specifying the partitioning strategy, relevant if `len(params) > 1`. Currently `"div"` and `"mod"` are supported. Default is `"mod"`. See `tf.nn.embedding_lookup` for more details. name: Optional name for the op. combiner: A string specifying the reduction op. Currently "mean", "sqrtn" and "sum" are supported. "sum" computes the weighted sum of the embedding results for each row. "mean" is the weighted sum divided by the total weight. "sqrtn" is the weighted sum divided by the square root of the sum of the squares of the weights. max_norm: If not None, each embedding is normalized to have l2 norm equal to max_norm before combining. Returns: A dense tensor representing the combined embeddings for the sparse ids. For each row in the dense tensor represented by sp_ids, the op looks up the embeddings for all ids in that row, multiplies them by the corresponding weight, and combines these embeddings as specified. Raises: TypeError: If sp_ids is not a SparseTensor, or if sp_weights is neither None nor SparseTensor. ValueError: If combiner is not one of {"mean", "sqrtn", "sum"}. """ if combiner is None: logging.warn("The default value of combiner will change from \"mean\" " "to \"sqrtn\" after 2016/11/01.") combiner = "mean" if combiner not in ("mean", "sqrtn", "sum"): raise ValueError("combiner must be one of 'mean', 'sqrtn' or 'sum'") if isinstance(params, variables.PartitionedVariable): params = list(params) # Iterate to get the underlying Variables. if not isinstance(params, list): params = [params] if not isinstance(sp_ids, sparse_tensor.SparseTensor): raise TypeError("sp_ids must be SparseTensor") ignore_weights = sp_weights is None if not ignore_weights: if not isinstance(sp_weights, sparse_tensor.SparseTensor): raise TypeError("sp_weights must be either None or SparseTensor") sp_ids.values.get_shape().assert_is_compatible_with( sp_weights.values.get_shape()) sp_ids.indices.get_shape().assert_is_compatible_with( sp_weights.indices.get_shape()) sp_ids.dense_shape.get_shape().assert_is_compatible_with( sp_weights.dense_shape.get_shape()) # TODO(yleon): Add enhanced node assertions to verify that sp_ids and # sp_weights have equal indices and shapes. with ops.name_scope(name, "embedding_lookup_sparse", params + [sp_ids]) as name: segment_ids = sp_ids.indices[:, 0] if segment_ids.dtype != dtypes.int32: segment_ids = math_ops.cast(segment_ids, dtypes.int32) ids = sp_ids.values if ignore_weights: ids, idx = array_ops.unique(ids) else: idx = None weights = None if ignore_weights else sp_weights.values embeddings = _embedding_lookup_with_distributed_aggregation( params, ids, partition_strategy=partition_strategy, max_norm=max_norm, weights=weights, idx=idx, segment_ids=segment_ids) # Set weights to all one if ignore weights. if ignore_weights: weights = array_ops.fill([array_ops.shape(segment_ids)[0]], 1) if weights.dtype != embeddings.dtype: weights = math_ops.cast(weights, embeddings.dtype) # Reshape weights. ones = array_ops.fill( array_ops.expand_dims(array_ops.rank(embeddings) - 1, 0), 1) bcast_weights_shape = array_ops.concat([array_ops.shape(weights), ones], 0) orig_weights_shape = weights.get_shape() weights = array_ops.reshape(weights, bcast_weights_shape) if embeddings.get_shape().ndims is not None: weights.set_shape( orig_weights_shape.concatenate( [1 for _ in range(embeddings.get_shape().ndims - 1)])) if combiner == "mean": weight_sum = math_ops.segment_sum(weights, segment_ids) embeddings = math_ops.div(embeddings, weight_sum) elif combiner == "sqrtn": weights_squared = math_ops.pow(weights, 2) weight_sum = math_ops.segment_sum(weights_squared, segment_ids) weight_sum_sqrt = math_ops.sqrt(weight_sum) embeddings = math_ops.div(embeddings, weight_sum_sqrt) elif combiner != "sum": assert False, "Unrecognized combiner" return embeddings def _do_gather(params, ids, name=None): """Deals with doing gather differently for resource variables.""" if isinstance(params, resource_variable_ops.ResourceVariable): return params.sparse_read(ids, name=name) return array_ops.gather(params, ids, name=name) def _embedding_lookup_with_distributed_aggregation(params, ids, partition_strategy="mod", name=None, max_norm=None, weights=None, idx=None, segment_ids=None): """Lookup helper for embedding_lookup_sparse_with_distributed_aggregation.""" if params is None or params == []: # pylint: disable=g-explicit-bool-comparison raise ValueError("Need at least one param") if isinstance(params, variables.PartitionedVariable): params = list(params) # Iterate to get the underlying Variables. if not isinstance(params, list): params = [params] def maybe_normalize(x): if max_norm is not None: if x.get_shape().ndims is not None: ndims = x.get_shape().ndims else: ndims = array_ops.size(array_ops.shape(x)) return clip_ops.clip_by_norm(x, max_norm, axes=list(range(1, ndims))) return x with ops.name_scope(name, "embedding_lookup_with_distributed_aggregation", params + [ids]) as name: np = len(params) # Number of partitions # Preserve the resource variable status to avoid accidental dense reads. if not any( isinstance(p, resource_variable_ops.ResourceVariable) for p in params): params = ops.convert_n_to_tensor_or_indexed_slices(params, name="params") if np == 1: with ops.colocate_with(params[0]): ret = maybe_normalize(_do_gather(params[0], ids)) ignore_weights = weights is None if not ignore_weights: if weights.dtype != ret.dtype: weights = math_ops.cast(weights, ret.dtype) # Reshape to allow broadcast ones = array_ops.fill( array_ops.expand_dims(array_ops.rank(ret) - 1, 0), 1) bcast_weights_shape = array_ops.concat( [array_ops.shape(weights), ones], 0) orig_weights_shape = weights.get_shape() weights = array_ops.reshape(weights, bcast_weights_shape) # Set weights shape after reshape if ret.get_shape().ndims is not None: weights.set_shape( orig_weights_shape.concatenate( [1 for _ in range(ret.get_shape().ndims - 1)])) ret *= weights return math_ops.segment_sum(ret, segment_ids, name=name) else: return math_ops.sparse_segment_sum(ret, idx, segment_ids, name=name) else: ids = ops.convert_to_tensor(ids, name="ids") flat_ids = array_ops.reshape(ids, [-1]) original_indices = math_ops.range(array_ops.size(flat_ids)) # Create p_assignments and set new_ids depending on the strategy. if partition_strategy == "mod": p_assignments = flat_ids % np new_ids = flat_ids // np elif partition_strategy == "div": # Compute num_total_ids as the sum of dim-0 of params, then assign to # partitions based on a constant number of ids per partition. Optimize # if we already know the full shape statically. dim_0_size = params[0].get_shape()[0] for p in xrange(1, np): dim_0_size += params[p].get_shape()[0] if dim_0_size.value: num_total_ids = constant_op.constant(dim_0_size.value, flat_ids.dtype) else: dim_0_sizes = [] for p in xrange(np): if params[p].get_shape()[0].value is not None: dim_0_sizes.append(params[p].get_shape()[0].value) else: with ops.colocate_with(params[p]): dim_0_sizes.append(array_ops.shape(params[p])[0]) num_total_ids = math_ops.reduce_sum( math_ops.cast(array_ops.stack(dim_0_sizes), flat_ids.dtype)) ids_per_partition = num_total_ids // np extras = num_total_ids % np p_assignments = math_ops.maximum(flat_ids // (ids_per_partition + 1), ( flat_ids - extras) // ids_per_partition) # Emulate a conditional using a boolean indicator tensor is_in_first_extras_partitions = math_ops.cast(p_assignments < extras, flat_ids.dtype) new_ids = (is_in_first_extras_partitions * (flat_ids % (ids_per_partition + 1)) + (1 - is_in_first_extras_partitions) * ( (flat_ids - extras) % ids_per_partition)) else: raise ValueError("Unrecognized partition strategy: " + partition_strategy) # Cast partition assignments to int32 for use in dynamic_partition. # There really should not be more than 2^32 partitions. p_assignments = math_ops.cast(p_assignments, dtypes.int32) # Partition list of ids based on assignments into np separate lists gather_ids = data_flow_ops.dynamic_partition(new_ids, p_assignments, np) # Similarly, partition the original indices. pindices = data_flow_ops.dynamic_partition(original_indices, p_assignments, np) # Do np separate lookups, finding embeddings for plist[p] in params[p] partitioned_result = [] for p in xrange(np): with ops.colocate_with(params[p]): partitioned_result.append(_do_gather(params[p], gather_ids[p])) ignore_weights = weights is None if not ignore_weights: # Partition weights according to pindices. partitioned_weight = [] for p in xrange(np): partitioned_weight.append(array_ops.gather(weights, pindices[p])) # Reshape each partition result. element_shape = params[0].get_shape()[1:] for p in params[1:]: element_shape = element_shape.merge_with(p.get_shape()[1:]) if element_shape.is_fully_defined(): for p in xrange(np): with ops.colocate_with(params[p]): partitioned_result[p] = array_ops.reshape( partitioned_result[p], array_ops.concat([array_ops.shape(pindices[p]), element_shape], 0)) else: with ops.colocate_with(params[0]): params_shape = array_ops.shape(params[0]) for p in xrange(np): with ops.colocate_with(params[p]): partitioned_result[p] = array_ops.reshape( partitioned_result[p], array_ops.concat([ array_ops.shape(pindices[p]), array_ops.slice( params_shape, [1], [-1]) ], 0)) # Normalize each partition result. for p in xrange(np): with ops.colocate_with(params[p]): partitioned_result[p] = maybe_normalize(partitioned_result[p]) if not ignore_weights: # Multiply each partition result with partition weights. for p in xrange(np): with ops.colocate_with(params[p]): if partitioned_weight[p].dtype != partitioned_result[p].dtype: partitioned_weight[p] = math_ops.cast(partitioned_weight[p], partitioned_result[p].dtype) # Reshape partition weights. ones = array_ops.fill( array_ops.expand_dims( array_ops.rank(partitioned_result[p]) - 1, 0), 1) bcast_weights_shape = array_ops.concat( [array_ops.shape(partitioned_weight[p]), ones], 0) orig_weights_shape = partitioned_weight[p].get_shape() partitioned_weight[p] = array_ops.reshape(partitioned_weight[p], bcast_weights_shape) if partitioned_result[p].get_shape().ndims is not None: partitioned_weight[p].set_shape( orig_weights_shape.concatenate([ 1 for _ in range(partitioned_result[p].get_shape().ndims - 1) ])) partitioned_result[p] *= partitioned_weight[p] partitioned_segment_ids = [] for p in xrange(np): if not ignore_weights: # Partition segment_ids according to pindices. p_segment_ids = array_ops.gather(segment_ids, pindices[p]) # Number the p_segment_ids to meet segment_sum's requirements. Note # that unique_p_segment_ids contains unique segment ids of this # partiton and these ids' order is unchanged. unique_p_segment_ids, unique_p_segment_idx = array_ops.unique( p_segment_ids) partitioned_segment_ids.append(unique_p_segment_ids) # segment_sum this partition's result. with ops.colocate_with(params[p]): partitioned_result[p] = math_ops.segment_sum( partitioned_result[p], unique_p_segment_idx) else: # When ignore weights, we need to get indexs of elements in idx and # segment_ids. _, exclude_idx = array_ops.setdiff1d(idx, pindices[p]) all_idx = math_ops.range(array_ops.shape(idx)[0]) _, include_idx = array_ops.setdiff1d(all_idx, exclude_idx) # Gather segment_ids and idx according to indexs. p_segment_ids = array_ops.gather(segment_ids, include_idx) p_idx = array_ops.gather(idx, include_idx) # Number the p_segment_ids, same as ignore_weights case above. unique_p_segment_ids, unique_p_segment_idx = array_ops.unique( p_segment_ids) _, unique_p_idx_idx = array_ops.unique(p_idx) partitioned_segment_ids.append(unique_p_segment_ids) with ops.colocate_with(params[p]): partitioned_result[p] = math_ops.sparse_segment_sum( partitioned_result[p], unique_p_idx_idx, unique_p_segment_idx) # Concat each partition's segment_ids and result for final segment_sum. concat_segment_ids = array_ops.concat(partitioned_segment_ids, 0) concat_partitioned_result = array_ops.concat(partitioned_result, 0) return math_ops.unsorted_segment_sum( concat_partitioned_result, concat_segment_ids, math_ops.reduce_max(concat_segment_ids) + 1, name=name)
apache-2.0
omnifone/aws-sdk-java
aws-java-sdk-opsworks/src/main/java/com/amazonaws/services/opsworks/model/ShutdownEventConfiguration.java
8445
/* * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.amazonaws.services.opsworks.model; import java.io.Serializable; /** * <p> * The Shutdown event configuration. * </p> */ public class ShutdownEventConfiguration implements Serializable, Cloneable { /** * The time, in seconds, that AWS OpsWorks will wait after triggering a * Shutdown event before shutting down an instance. */ private Integer executionTimeout; /** * Whether to enable Elastic Load Balancing connection draining. For more * information, see <a * href="http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/TerminologyandKeyConcepts.html#conn-drain">Connection * Draining</a> */ private Boolean delayUntilElbConnectionsDrained; /** * The time, in seconds, that AWS OpsWorks will wait after triggering a * Shutdown event before shutting down an instance. * * @return The time, in seconds, that AWS OpsWorks will wait after triggering a * Shutdown event before shutting down an instance. */ public Integer getExecutionTimeout() { return executionTimeout; } /** * The time, in seconds, that AWS OpsWorks will wait after triggering a * Shutdown event before shutting down an instance. * * @param executionTimeout The time, in seconds, that AWS OpsWorks will wait after triggering a * Shutdown event before shutting down an instance. */ public void setExecutionTimeout(Integer executionTimeout) { this.executionTimeout = executionTimeout; } /** * The time, in seconds, that AWS OpsWorks will wait after triggering a * Shutdown event before shutting down an instance. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param executionTimeout The time, in seconds, that AWS OpsWorks will wait after triggering a * Shutdown event before shutting down an instance. * * @return A reference to this updated object so that method calls can be chained * together. */ public ShutdownEventConfiguration withExecutionTimeout(Integer executionTimeout) { this.executionTimeout = executionTimeout; return this; } /** * Whether to enable Elastic Load Balancing connection draining. For more * information, see <a * href="http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/TerminologyandKeyConcepts.html#conn-drain">Connection * Draining</a> * * @return Whether to enable Elastic Load Balancing connection draining. For more * information, see <a * href="http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/TerminologyandKeyConcepts.html#conn-drain">Connection * Draining</a> */ public Boolean isDelayUntilElbConnectionsDrained() { return delayUntilElbConnectionsDrained; } /** * Whether to enable Elastic Load Balancing connection draining. For more * information, see <a * href="http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/TerminologyandKeyConcepts.html#conn-drain">Connection * Draining</a> * * @param delayUntilElbConnectionsDrained Whether to enable Elastic Load Balancing connection draining. For more * information, see <a * href="http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/TerminologyandKeyConcepts.html#conn-drain">Connection * Draining</a> */ public void setDelayUntilElbConnectionsDrained(Boolean delayUntilElbConnectionsDrained) { this.delayUntilElbConnectionsDrained = delayUntilElbConnectionsDrained; } /** * Whether to enable Elastic Load Balancing connection draining. For more * information, see <a * href="http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/TerminologyandKeyConcepts.html#conn-drain">Connection * Draining</a> * <p> * Returns a reference to this object so that method calls can be chained together. * * @param delayUntilElbConnectionsDrained Whether to enable Elastic Load Balancing connection draining. For more * information, see <a * href="http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/TerminologyandKeyConcepts.html#conn-drain">Connection * Draining</a> * * @return A reference to this updated object so that method calls can be chained * together. */ public ShutdownEventConfiguration withDelayUntilElbConnectionsDrained(Boolean delayUntilElbConnectionsDrained) { this.delayUntilElbConnectionsDrained = delayUntilElbConnectionsDrained; return this; } /** * Whether to enable Elastic Load Balancing connection draining. For more * information, see <a * href="http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/TerminologyandKeyConcepts.html#conn-drain">Connection * Draining</a> * * @return Whether to enable Elastic Load Balancing connection draining. For more * information, see <a * href="http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/TerminologyandKeyConcepts.html#conn-drain">Connection * Draining</a> */ public Boolean getDelayUntilElbConnectionsDrained() { return delayUntilElbConnectionsDrained; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getExecutionTimeout() != null) sb.append("ExecutionTimeout: " + getExecutionTimeout() + ","); if (isDelayUntilElbConnectionsDrained() != null) sb.append("DelayUntilElbConnectionsDrained: " + isDelayUntilElbConnectionsDrained() ); sb.append("}"); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getExecutionTimeout() == null) ? 0 : getExecutionTimeout().hashCode()); hashCode = prime * hashCode + ((isDelayUntilElbConnectionsDrained() == null) ? 0 : isDelayUntilElbConnectionsDrained().hashCode()); return hashCode; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ShutdownEventConfiguration == false) return false; ShutdownEventConfiguration other = (ShutdownEventConfiguration)obj; if (other.getExecutionTimeout() == null ^ this.getExecutionTimeout() == null) return false; if (other.getExecutionTimeout() != null && other.getExecutionTimeout().equals(this.getExecutionTimeout()) == false) return false; if (other.isDelayUntilElbConnectionsDrained() == null ^ this.isDelayUntilElbConnectionsDrained() == null) return false; if (other.isDelayUntilElbConnectionsDrained() != null && other.isDelayUntilElbConnectionsDrained().equals(this.isDelayUntilElbConnectionsDrained()) == false) return false; return true; } @Override public ShutdownEventConfiguration clone() { try { return (ShutdownEventConfiguration) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException( "Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
apache-2.0
fasterthanlime/homebrew
Library/Formula/librem.rb
1031
require "formula" class Librem < Formula homepage "http://www.creytiv.com" url "http://www.creytiv.com/pub/rem-0.4.6.tar.gz" sha1 "9698b48aee5e720e56440f4c660d8bd4dbb7f8fa" bottle do cellar :any sha1 "e1089e53d13bd264d8a6b95cce0401c7ae5b6aed" => :mavericks sha1 "8da4a993fa287e444b649b045fdfb48718b733d5" => :mountain_lion sha1 "cb6ace233af76a21ef463f005d13121686ffebeb" => :lion end depends_on "libre" def install libre = Formula["libre"] system "make", "install", "PREFIX=#{prefix}", "LIBRE_MK=#{libre.opt_share}/re/re.mk", "LIBRE_INC=#{libre.opt_include}/re", "LIBRE_SO=#{libre.opt_lib}" end test do (testpath/'test.c').write <<-EOS.undent #include <re/re.h> #include <rem/rem.h> int main() { return (NULL != vidfmt_name(VID_FMT_YUV420P)) ? 0 : 1; } EOS system ENV.cc, "test.c", "-L#{opt_lib}", "-lrem", "-o", "test" system "./test" end end
bsd-2-clause
liukaijv/fis3
test/diff_fis3_smarty/product_code/hao123_fis3_smarty/common/widget/header/skinbox/skin-mod.js
7639
var $ = require("common:widget/ui/jquery/jquery.js"); var UT = require("common:widget/ui/ut/ut.js"); var Helper = require("common:widget/ui/helper/helper.js"); var WINDOW = $(window); var BODY = $(document.body); /* * 换肤插件 * loadTime: 1. "" - 默认值,即刻加载 2. 数字 - 延迟加载,毫秒数 * recommandSkin:设置推荐皮肤 * data: key为皮肤关键字; value是一个对象,必须包含"bgImgSrc"属性(皮肤图片URL); * 使用示例: var skin = new Skin({ recommandSkin: "music", data: { music: { bgImgSrc: "http://xxx.com/a.jpg" }, baozou: { bgImgSrc: "http://xxx.com/b.jpg" } } }); skin.init(); */ var Skin = function(userOption) { var defaultOptions = { loadTime: "", recommandSkin: "", mainWidth: 960, data: [] }; $.extend(this, defaultOptions, userOption); this.bgContainer = $("#skin-bgimage"); this.leftClickArea = $("#skin-clickarea-left"); this.rightClickArea = $("#skin-clickarea-right"); this.clickArea = $(".skin-clickarea"); this.modId = "skinbox"; }; Skin.prototype = { constructor: Skin, //设置皮肤,若skin为空字符串则关闭皮肤 setSkin: function(skin, bgImgSrc) { if (bgImgSrc) { var removedSkin = conf.skin.current; var skinItem = this._getSkinDataByKey(skin); var needClass = skinItem.type ? ("skin skin-type-dark skin-"+skin) : ("skin skin-"+skin); var bodyBg = BODY.css("background-color"); var htmlBg = $("html").css("background-color"); this.bgContainer.css({ "background-image": "url(" + bgImgSrc + ")" }); // 背景图片支持Y方向重复 if (skinItem.isRepeat === "1") { this.bgContainer.css({ "background-repeat": "repeat-y" }); } else { this.bgContainer.css({ "background-repeat": "no-repeat" }); } this._resetLogo(skinItem.type); $.cookie("lastSkin", null); $.store("lastSkin", skin+"|"+conf.skin.recommandSkin, {expires: 100}); conf.skin.current = skin; if(skinItem.color){ BODY.css({ "background-color": skinItem.color, "z-index": 0 }); }else if(bodyBg != htmlBg){ BODY.css({ "background-color": htmlBg, "z-index": 0 }); } BODY.removeClass("skin-"+removedSkin+" skin-type-dark").addClass(needClass); }else if (bgImgSrc === "" || bgImgSrc == "no") { this.emptySkin(); } }, //清空皮肤 emptySkin: function(){ var removedSkin = conf.skin.current; this.bgContainer.css({ "background-image": "" }); this._resetLogo(); $.cookie("lastSkin", null); $.store("lastSkin", "no|"+conf.skin.recommandSkin, {expires: 100}); conf.skin.current = "no"; BODY.removeClass("skin skin-type-dark skin-"+removedSkin).css("background-color", $("html").css("background-color")); }, //可点击区域的重置 setClickArea: function(skin, clickData){ var self = this; WINDOW.off("resize.skin"); self.clickArea.off("click.skin"); if(clickData && clickData.length>0 && clickData[0].landingpage){ self._clickAreaAjust(clickData[0]); WINDOW.on("resize.skin", $.proxy(self._clickAreaAjust, self, clickData[0])); self.clickArea.on("click.skin", function(){ window.open(self._updateLandingpage(clickData[0].landingpage)); UT.send({ modId: self.modId, ac: "b", position: "background", sort: skin }); }); }else{ self.clickArea.width(0); } }, _resetLogo: function(type){ $("#searchGroupLogos img").each(function(){ var dataSrc = $(this).attr("data-src"), realSrc = $(this).attr("src"), oldSrc = realSrc || dataSrc || ""; if(!type){ if(realSrc) { $(this).attr("src", oldSrc.replace(/\/dark\//, "/")); } else { $(this).attr("data-src", oldSrc.replace(/\/dark\//, "/")); } }else if(!/\/dark\//.test(oldSrc)){ var prefix = oldSrc.substring(0, oldSrc.lastIndexOf("/")); var suffix = oldSrc.substring(oldSrc.lastIndexOf("/")); if(realSrc) { $(this).attr("src", prefix+"/dark"+suffix); } else { $(this).attr("data-src", prefix+"/dark"+suffix); } } }); }, _getSkinDataByKey: function(skin){ var data = this.data; var skinData = {}; for(var i=0; i<data.length; i++){ if(skin == data[i].key){ skinData = data[i]; break; } } return skinData; }, _updateLandingpage: function(url){ var paramKey = conf.skin.passQueryParam || "uid", paramVal = Helper.getQuery(location.href)[paramKey]; if(paramVal){ url += (url.indexOf("?") != -1 ? "&" : "?") + paramKey + "=" + paramVal; } return url; }, //生成html容器,并定义该变量(分拆) /*_genHtml: function() { $("[alog-alias=p-1]").append("<div id='skin-bgimage'></div>"); this.bgContainer = $("#skin-bgimage"); },*/ //绑定事件 _bindEvent: function() { var self = this; //class为"ui-skin-close"的元素点击时将关闭 //BODY.on("click", ".skinbox-item-default", $.proxy(self.emptySkin, self)); //class为"ui-skin-item"的元素点击时将设置皮肤(取属性值"data-value") BODY.on("click", ".skinbox-item", function(){ if($(this).hasClass("skinbox-item-selected")){ return; } $(".skinbox-item-selected").removeClass("skinbox-item-selected"); $(this).addClass("skinbox-item-selected"); var skin = $(this).attr("data-value"); var skinData = self._getSkinDataByKey(skin); self.setSkin(skin, skinData.bgImgSrc); self.setClickArea(skin, skinData.clickArea); // 判断,当当前选中的皮肤和皮肤skinTrans上推荐的皮肤一致时,改变skinTrans上的icon if( skin === conf.skinTrans.defaultSkin ){ $( window ).trigger( "skinTrans.recommendedSelect" ); } UT.send({ modId: self.modId, ac: "b", position: "thumbnail", sort: skin }); }); }, // 提供外部换肤接口 _setTrigger: function() { var self = this; WINDOW.on("skin.change", function(e, arg1) { $(".skinbox-item-selected").removeClass("skinbox-item-selected"); BODY.find(".skinbox-item[data-value='" + arg1 + "']").addClass("skinbox-item-selected"); var skinData = self._getSkinDataByKey(arg1); self.setSkin(arg1, skinData.bgImgSrc); self.setClickArea(arg1, skinData.clickArea); }); }, //具体设置可点击区域的样式 _clickAreaAjust: function(data){ var divWidth = parseInt(data.width); var mainWidth = parseInt(this.mainWidth); var windowWidth = WINDOW.width(); var margin = (windowWidth - mainWidth)/2; if(windowWidth <= mainWidth){ margin = 0; divWidth = 0; }else if(divWidth > margin){ divWidth = margin; } var firstLeft = margin - divWidth; var secondLeft = firstLeft + mainWidth + divWidth; this.leftClickArea.css({left:firstLeft, width:divWidth, height:data.height}); this.rightClickArea.css({left:secondLeft, width:divWidth, height:data.height}); }, //第一次载入时机、策略(分拆) /*_firstLoad: function(){ var skinCookie = $.cookie("lastSkin"); var skin = this.recommandSkin ? this.recommandSkin : skinCookie; //如果skin不为空,则进行皮肤设置 if (skin) { var time = this.loadTime; var self = this; //即刻加载 if (time === "") { self.setSkin(skin); //延迟加载 }else{ setTimeout($.proxy(self.setSkin, self, skin), time); } } },*/ //插件初始化 init: function() { var that = this; that._bindEvent(); that._setTrigger(); } }; module.exports = Skin;
bsd-2-clause
rjeli/scikit-image
skimage/io/_plugins/freeimage_plugin.py
27618
import ctypes import numpy import sys import os import os.path from numpy.compat import asbytes, asstr def _generate_candidate_libs(): # look for likely library files in the following dirs: lib_dirs = [os.path.dirname(__file__), '/lib', '/usr/lib', '/usr/local/lib', '/opt/local/lib', os.path.join(sys.prefix, 'lib'), os.path.join(sys.prefix, 'DLLs') ] if 'HOME' in os.environ: lib_dirs.append(os.path.join(os.environ['HOME'], 'lib')) lib_dirs = [ld for ld in lib_dirs if os.path.exists(ld)] lib_names = ['libfreeimage', 'freeimage'] # should be lower-case! # Now attempt to find libraries of that name in the given directory # (case-insensitive and without regard for extension) lib_paths = [] for lib_dir in lib_dirs: for lib_name in lib_names: files = os.listdir(lib_dir) lib_paths += [os.path.join(lib_dir, lib) for lib in files if lib.lower().startswith(lib_name) and not os.path.splitext(lib)[1] in ('.py', '.pyc', '.ini')] lib_paths = [lp for lp in lib_paths if os.path.exists(lp)] return lib_dirs, lib_paths if sys.platform == 'win32': LOADER = ctypes.windll FUNCTYPE = ctypes.WINFUNCTYPE else: LOADER = ctypes.cdll FUNCTYPE = ctypes.CFUNCTYPE def handle_errors(): global FT_ERROR_STR if FT_ERROR_STR: tmp = FT_ERROR_STR FT_ERROR_STR = None raise RuntimeError(tmp) FT_ERROR_STR = None # This MUST happen in module scope, or the function pointer is garbage # collected, leading to a segfault when error_handler is called. @FUNCTYPE(None, ctypes.c_int, ctypes.c_char_p) def c_error_handler(fif, message): global FT_ERROR_STR FT_ERROR_STR = 'FreeImage error: %s' % message def load_freeimage(): freeimage = None errors = [] # First try a few bare library names that ctypes might be able to find # in the default locations for each platform. Win DLL names don't need the # extension, but other platforms do. bare_libs = ['FreeImage', 'libfreeimage.dylib', 'libfreeimage.so', 'libfreeimage.so.3'] lib_dirs, lib_paths = _generate_candidate_libs() lib_paths = bare_libs + lib_paths for lib in lib_paths: try: freeimage = LOADER.LoadLibrary(lib) break except Exception: if lib not in bare_libs: # Don't record errors when it couldn't load the library from # a bare name -- this fails often, and doesn't provide any # useful debugging information anyway, beyond "couldn't find # library..." # Get exception instance in Python 2.x/3.x compatible manner e_type, e_value, e_tb = sys.exc_info() del e_tb errors.append((lib, e_value)) if freeimage is None: if errors: # No freeimage library loaded, and load-errors reported for some # candidate libs err_txt = ['%s:\n%s' % (l, str(e)) for l, e in errors] raise RuntimeError('One or more FreeImage libraries were found, ' 'but could not be loaded due to the following ' 'errors:\n\n\n'.join(err_txt)) else: # No errors, because no potential libraries found at all! raise RuntimeError('Could not find a FreeImage library in any of:' '\n\n'.join(lib_dirs)) # FreeImage found freeimage.FreeImage_SetOutputMessage(c_error_handler) return freeimage _FI = load_freeimage() API = { # All we're doing here is telling ctypes that some of the FreeImage # functions return pointers instead of integers. (On 64-bit systems, # without this information the pointers get truncated and crashes result). # There's no need to list functions that return ints, or the types of the # parameters to these or other functions -- that's fine to do implicitly. # Note that the ctypes immediately converts the returned void_p back to a # python int again! This is really not helpful, because then passing it # back to another library call will cause truncation-to-32-bits on 64-bit # systems. Thanks, ctypes! So after these calls one must immediately # re-wrap the int as a c_void_p if it is to be passed back into FreeImage. 'FreeImage_AllocateT': (ctypes.c_void_p, None), 'FreeImage_FindFirstMetadata': (ctypes.c_void_p, None), 'FreeImage_GetBits': (ctypes.c_void_p, None), 'FreeImage_GetPalette': (ctypes.c_void_p, None), 'FreeImage_GetTagKey': (ctypes.c_char_p, None), 'FreeImage_GetTagValue': (ctypes.c_void_p, None), 'FreeImage_Load': (ctypes.c_void_p, None), 'FreeImage_LockPage': (ctypes.c_void_p, None), 'FreeImage_OpenMultiBitmap': (ctypes.c_void_p, None) } # Albert's ctypes pattern def register_api(lib, api): for f, (restype, argtypes) in api.items(): func = getattr(lib, f) func.restype = restype func.argtypes = argtypes register_api(_FI, API) class FiTypes(object): FIT_UNKNOWN = 0 FIT_BITMAP = 1 FIT_UINT16 = 2 FIT_INT16 = 3 FIT_UINT32 = 4 FIT_INT32 = 5 FIT_FLOAT = 6 FIT_DOUBLE = 7 FIT_COMPLEX = 8 FIT_RGB16 = 9 FIT_RGBA16 = 10 FIT_RGBF = 11 FIT_RGBAF = 12 dtypes = {FIT_BITMAP: numpy.uint8, FIT_UINT16: numpy.uint16, FIT_INT16: numpy.int16, FIT_UINT32: numpy.uint32, FIT_INT32: numpy.int32, FIT_FLOAT: numpy.float32, FIT_DOUBLE: numpy.float64, FIT_COMPLEX: numpy.complex128, FIT_RGB16: numpy.uint16, FIT_RGBA16: numpy.uint16, FIT_RGBF: numpy.float32, FIT_RGBAF: numpy.float32, } fi_types = {(numpy.dtype('uint8'), 1): FIT_BITMAP, (numpy.dtype('uint8'), 3): FIT_BITMAP, (numpy.dtype('uint8'), 4): FIT_BITMAP, (numpy.dtype('uint16'), 1): FIT_UINT16, (numpy.dtype('int16'), 1): FIT_INT16, (numpy.dtype('uint32'), 1): FIT_UINT32, (numpy.dtype('int32'), 1): FIT_INT32, (numpy.dtype('float32'), 1): FIT_FLOAT, (numpy.dtype('float64'), 1): FIT_DOUBLE, (numpy.dtype('complex128'), 1): FIT_COMPLEX, (numpy.dtype('uint16'), 3): FIT_RGB16, (numpy.dtype('uint16'), 4): FIT_RGBA16, (numpy.dtype('float32'), 3): FIT_RGBF, (numpy.dtype('float32'), 4): FIT_RGBAF, } extra_dims = {FIT_UINT16: [], FIT_INT16: [], FIT_UINT32: [], FIT_INT32: [], FIT_FLOAT: [], FIT_DOUBLE: [], FIT_COMPLEX: [], FIT_RGB16: [3], FIT_RGBA16: [4], FIT_RGBF: [3], FIT_RGBAF: [4], } @classmethod def get_type_and_shape(cls, bitmap): w = _FI.FreeImage_GetWidth(bitmap) handle_errors() h = _FI.FreeImage_GetHeight(bitmap) handle_errors() fi_type = _FI.FreeImage_GetImageType(bitmap) handle_errors() if not fi_type: raise ValueError('Unknown image pixel type') dtype = cls.dtypes[fi_type] if fi_type == cls.FIT_BITMAP: bpp = _FI.FreeImage_GetBPP(bitmap) handle_errors() if bpp == 8: extra_dims = [] elif bpp == 24: extra_dims = [3] elif bpp == 32: extra_dims = [4] else: raise ValueError('Cannot convert %d BPP bitmap' % bpp) else: extra_dims = cls.extra_dims[fi_type] return numpy.dtype(dtype), extra_dims + [w, h] class IoFlags(object): # loading: load the image header only (not supported by all plugins) FIF_LOAD_NOPIXELS = 0x8000 BMP_DEFAULT = 0 BMP_SAVE_RLE = 1 CUT_DEFAULT = 0 DDS_DEFAULT = 0 EXR_DEFAULT = 0 # save data as half with piz-based wavelet compression EXR_FLOAT = 0x0001 # save data as float instead of half (not recommended) EXR_NONE = 0x0002 # save with no compression EXR_ZIP = 0x0004 # save with zlib compression, in blocks of 16 scan lines EXR_PIZ = 0x0008 # save with piz-based wavelet compression EXR_PXR24 = 0x0010 # save with lossy 24-bit float compression # save with lossy 44% float compression (22% when combined with EXR_LC) EXR_B44 = 0x0020 # one luminance and two chroma channels rather than as RGB (lossy) EXR_LC = 0x0040 FAXG3_DEFAULT = 0 GIF_DEFAULT = 0 # Load as 256 color image with ununsed palette entries if 16 or 2 color GIF_LOAD256 = 1 # 'Play' the GIF generating each frame (as 32bpp) instead of raw frame data GIF_PLAYBACK = 2 HDR_DEFAULT = 0 ICO_DEFAULT = 0 # convert to 32bpp then add an alpha channel from the AND-mask when loading ICO_MAKEALPHA = 1 IFF_DEFAULT = 0 J2K_DEFAULT = 0 # save with a 16:1 rate JP2_DEFAULT = 0 # save with a 16:1 rate # loading (see JPEG_FAST) # saving (see JPEG_QUALITYGOOD|JPEG_SUBSAMPLING_420) JPEG_DEFAULT = 0 # load the file as fast as possible, sacrificing some quality JPEG_FAST = 0x0001 # load the file with the best quality, sacrificing some speed JPEG_ACCURATE = 0x0002 # load separated CMYK "as is" (use | to combine with other load flags) JPEG_CMYK = 0x0004 # load and rotate according to Exif 'Orientation' tag if available JPEG_EXIFROTATE = 0x0008 JPEG_QUALITYSUPERB = 0x80 # save with superb quality (100:1) JPEG_QUALITYGOOD = 0x0100 # save with good quality (75:1) JPEG_QUALITYNORMAL = 0x0200 # save with normal quality (50:1) JPEG_QUALITYAVERAGE = 0x0400 # save with average quality (25:1) JPEG_QUALITYBAD = 0x0800 # save with bad quality (10:1) # save as a progressive-JPEG (use | to combine with other save flags) JPEG_PROGRESSIVE = 0x2000 # save with high 4x1 chroma subsampling (4:1:1) JPEG_SUBSAMPLING_411 = 0x1000 # save with medium 2x2 medium chroma subsampling (4:2:0) - default value JPEG_SUBSAMPLING_420 = 0x4000 # save with low 2x1 chroma subsampling (4:2:2) JPEG_SUBSAMPLING_422 = 0x8000 JPEG_SUBSAMPLING_444 = 0x10000 # save with no chroma subsampling (4:4:4) # compute optimal Huffman coding tables (can reduce file size a few %) JPEG_OPTIMIZE = 0x20000 # on saving, JPEG_BASELINE = 0x40000 # save basic JPEG, without metadata or any markers KOALA_DEFAULT = 0 LBM_DEFAULT = 0 MNG_DEFAULT = 0 PCD_DEFAULT = 0 PCD_BASE = 1 # load the bitmap sized 768 x 512 PCD_BASEDIV4 = 2 # load the bitmap sized 384 x 256 PCD_BASEDIV16 = 3 # load the bitmap sized 192 x 128 PCX_DEFAULT = 0 PFM_DEFAULT = 0 PICT_DEFAULT = 0 PNG_DEFAULT = 0 PNG_IGNOREGAMMA = 1 # loading: avoid gamma correction # save using ZLib level 1 compression flag (default value is 6) PNG_Z_BEST_SPEED = 0x0001 # save using ZLib level 6 compression flag (default recommended value) PNG_Z_DEFAULT_COMPRESSION = 0x0006 # save using ZLib level 9 compression flag (default value is 6) PNG_Z_BEST_COMPRESSION = 0x0009 PNG_Z_NO_COMPRESSION = 0x0100 # save without ZLib compression # save using Adam7 interlacing (use | to combine with other save flags) PNG_INTERLACED = 0x0200 PNM_DEFAULT = 0 PNM_SAVE_RAW = 0 # Writer saves in RAW format (i.e. P4, P5 or P6) PNM_SAVE_ASCII = 1 # Writer saves in ASCII format (i.e. P1, P2 or P3) PSD_DEFAULT = 0 PSD_CMYK = 1 # reads tags for separated CMYK (default converts to RGB) PSD_LAB = 2 # reads tags for CIELab (default is conversion to RGB) RAS_DEFAULT = 0 RAW_DEFAULT = 0 # load the file as linear RGB 48-bit # try to load embedded JPEG preview from Exif Data or default to RGB 24-bit RAW_PREVIEW = 1 RAW_DISPLAY = 2 # load the file as RGB 24-bit SGI_DEFAULT = 0 TARGA_DEFAULT = 0 TARGA_LOAD_RGB888 = 1 # Convert RGB555 and ARGB8888 -> RGB888. TARGA_SAVE_RLE = 2 # Save with RLE compression TIFF_DEFAULT = 0 # reads/stores tags for separated CMYK # (use | to combine with compression flags) TIFF_CMYK = 0x0001 TIFF_PACKBITS = 0x0100 # save using PACKBITS compression TIFF_DEFLATE = 0x0200 # save using DEFLATE (a.k.a. ZLIB) compression TIFF_ADOBE_DEFLATE = 0x0400 # save using ADOBE DEFLATE compression TIFF_NONE = 0x0800 # save without any compression TIFF_CCITTFAX3 = 0x1000 # save using CCITT Group 3 fax encoding TIFF_CCITTFAX4 = 0x2000 # save using CCITT Group 4 fax encoding TIFF_LZW = 0x4000 # save using LZW compression TIFF_JPEG = 0x8000 # save using JPEG compression TIFF_LOGLUV = 0x10000 # save using LogLuv compression WBMP_DEFAULT = 0 XBM_DEFAULT = 0 XPM_DEFAULT = 0 class MetadataModels(object): FIMD_COMMENTS = 0 FIMD_EXIF_MAIN = 1 FIMD_EXIF_EXIF = 2 FIMD_EXIF_GPS = 3 FIMD_EXIF_MAKERNOTE = 4 FIMD_EXIF_INTEROP = 5 FIMD_IPTC = 6 FIMD_XMP = 7 FIMD_GEOTIFF = 8 FIMD_ANIMATION = 9 class MetadataDatatype(object): FIDT_BYTE = 1 # 8-bit unsigned integer FIDT_ASCII = 2 # 8-bit bytes w/ last byte null FIDT_SHORT = 3 # 16-bit unsigned integer FIDT_LONG = 4 # 32-bit unsigned integer FIDT_RATIONAL = 5 # 64-bit unsigned fraction FIDT_SBYTE = 6 # 8-bit signed integer FIDT_UNDEFINED = 7 # 8-bit untyped data FIDT_SSHORT = 8 # 16-bit signed integer FIDT_SLONG = 9 # 32-bit signed integer FIDT_SRATIONAL = 10 # 64-bit signed fraction FIDT_FLOAT = 11 # 32-bit IEEE floating point FIDT_DOUBLE = 12 # 64-bit IEEE floating point FIDT_IFD = 13 # 32-bit unsigned integer (offset) FIDT_PALETTE = 14 # 32-bit RGBQUAD FIDT_LONG8 = 16 # 64-bit unsigned integer FIDT_SLONG8 = 17 # 64-bit signed integer FIDT_IFD8 = 18 # 64-bit unsigned integer (offset) dtypes = {FIDT_BYTE: numpy.uint8, FIDT_SHORT: numpy.uint16, FIDT_LONG: numpy.uint32, FIDT_RATIONAL: [('numerator', numpy.uint32), ('denominator', numpy.uint32)], FIDT_SBYTE: numpy.int8, FIDT_UNDEFINED: numpy.uint8, FIDT_SSHORT: numpy.int16, FIDT_SLONG: numpy.int32, FIDT_SRATIONAL: [('numerator', numpy.int32), ('denominator', numpy.int32)], FIDT_FLOAT: numpy.float32, FIDT_DOUBLE: numpy.float64, FIDT_IFD: numpy.uint32, FIDT_PALETTE: [('R', numpy.uint8), ('G', numpy.uint8), ('B', numpy.uint8), ('A', numpy.uint8)], FIDT_LONG8: numpy.uint64, FIDT_SLONG8: numpy.int64, FIDT_IFD8: numpy.uint64, } def _process_bitmap(filename, flags, process_func): filename = asbytes(filename) ftype = _FI.FreeImage_GetFileType(filename, 0) handle_errors() if ftype == -1: raise ValueError('Cannot determine type of file %s' % filename) bitmap = _FI.FreeImage_Load(ftype, filename, flags) handle_errors() bitmap = ctypes.c_void_p(bitmap) if not bitmap: raise ValueError('Could not load file %s' % filename) try: return process_func(bitmap) finally: _FI.FreeImage_Unload(bitmap) handle_errors() def read(filename, flags=0): """Read an image to a numpy array of shape (height, width) for greyscale images, or shape (height, width, nchannels) for RGB or RGBA images. The `flags` parameter should be one or more values from the IoFlags class defined in this module, or-ed together with | as appropriate. (See the source-code comments for more details.) """ return _process_bitmap(filename, flags, _array_from_bitmap) def read_metadata(filename): """Return a dict containing all image metadata. Returned dict maps (metadata_model, tag_name) keys to tag values, where metadata_model is a string name based on the FreeImage "metadata models" defined in the class MetadataModels. """ flags = IoFlags.FIF_LOAD_NOPIXELS return _process_bitmap(filename, flags, _read_metadata) def _process_multipage(filename, flags, process_func): filename = asbytes(filename) ftype = _FI.FreeImage_GetFileType(filename, 0) handle_errors() if ftype == -1: raise ValueError('Cannot determine type of file %s' % filename) create_new = False read_only = True keep_cache_in_memory = True multibitmap = _FI.FreeImage_OpenMultiBitmap( ftype, filename, create_new, read_only, keep_cache_in_memory, flags) handle_errors() multibitmap = ctypes.c_void_p(multibitmap) if not multibitmap: raise ValueError('Could not open %s as multi-page image.' % filename) try: pages = _FI.FreeImage_GetPageCount(multibitmap) handle_errors() out = [] for i in range(pages): bitmap = _FI.FreeImage_LockPage(multibitmap, i) handle_errors() bitmap = ctypes.c_void_p(bitmap) if not bitmap: raise ValueError('Could not open %s as a multi-page image.' % filename) try: out.append(process_func(bitmap)) finally: _FI.FreeImage_UnlockPage(multibitmap, bitmap, False) handle_errors() return out finally: _FI.FreeImage_CloseMultiBitmap(multibitmap, 0) handle_errors() def read_multipage(filename, flags=0): """Read a multipage image to a list of numpy arrays, where each array is of shape (height, width) for greyscale images, or shape (height, width, nchannels) for RGB or RGBA images. The `flags` parameter should be one or more values from the IoFlags class defined in this module, or-ed together with | as appropriate. (See the source-code comments for more details.) """ return _process_multipage(filename, flags, _array_from_bitmap) def read_multipage_metadata(filename): """Read a multipage image to a list of metadata dicts, one dict for each page. The dict format is as in read_metadata(). """ flags = IoFlags.FIF_LOAD_NOPIXELS return _process_multipage(filename, flags, _read_metadata) def _wrap_bitmap_bits_in_array(bitmap, shape, dtype): """Return an ndarray view on the data in a FreeImage bitmap. Only valid for as long as the bitmap is loaded (if single page) / locked in memory (if multipage). """ pitch = _FI.FreeImage_GetPitch(bitmap) handle_errors() height = shape[-1] byte_size = height * pitch itemsize = dtype.itemsize if len(shape) == 3: strides = (itemsize, shape[0] * itemsize, pitch) else: strides = (itemsize, pitch) bits = _FI.FreeImage_GetBits(bitmap) handle_errors() array = numpy.ndarray( shape, dtype=dtype, buffer=(ctypes.c_char * byte_size).from_address(bits), strides=strides) return array def _array_from_bitmap(bitmap): """Convert a FreeImage bitmap pointer to a numpy array. """ dtype, shape = FiTypes.get_type_and_shape(bitmap) array = _wrap_bitmap_bits_in_array(bitmap, shape, dtype) # swizzle the color components and flip the scanlines to go from # FreeImage's BGR[A] and upside-down internal memory format to something # more normal def n(arr): return arr[..., ::-1].T if len(shape) == 3 and _FI.FreeImage_IsLittleEndian() and \ dtype.type == numpy.uint8: b = n(array[0]) g = n(array[1]) r = n(array[2]) if shape[0] == 3: handle_errors() return numpy.dstack((r, g, b)) elif shape[0] == 4: a = n(array[3]) return numpy.dstack((r, g, b, a)) else: raise ValueError('Cannot handle images of shape %s' % shape) # We need to copy because array does *not* own its memory # after bitmap is freed. return n(array).copy() def _read_metadata(bitmap): metadata = {} models = [(name[5:], number) for name, number in MetadataModels.__dict__.items() if name.startswith('FIMD_')] tag = ctypes.c_void_p() for model_name, number in models: mdhandle = _FI.FreeImage_FindFirstMetadata(number, bitmap, ctypes.byref(tag)) handle_errors() mdhandle = ctypes.c_void_p(mdhandle) if mdhandle: more = True while more: tag_name = asstr(_FI.FreeImage_GetTagKey(tag)) tag_type = _FI.FreeImage_GetTagType(tag) byte_size = _FI.FreeImage_GetTagLength(tag) handle_errors() char_ptr = ctypes.c_char * byte_size tag_str = char_ptr.from_address(_FI.FreeImage_GetTagValue(tag)) handle_errors() if tag_type == MetadataDatatype.FIDT_ASCII: tag_val = asstr(tag_str.value) else: tag_val = numpy.fromstring( tag_str, dtype=MetadataDatatype.dtypes[tag_type]) if len(tag_val) == 1: tag_val = tag_val[0] metadata[(model_name, tag_name)] = tag_val more = _FI.FreeImage_FindNextMetadata(mdhandle, ctypes.byref(tag)) handle_errors() _FI.FreeImage_FindCloseMetadata(mdhandle) handle_errors() return metadata def write(array, filename, flags=0): """Write a (height, width) or (height, width, nchannels) array to a greyscale, RGB, or RGBA image, with file type deduced from the filename. The `flags` parameter should be one or more values from the IoFlags class defined in this module, or-ed together with | as appropriate. (See the source-code comments for more details.) """ array = numpy.asarray(array) filename = asbytes(filename) ftype = _FI.FreeImage_GetFIFFromFilename(filename) handle_errors() if ftype == -1: raise ValueError('Cannot determine type for %s' % filename) bitmap, fi_type = _array_to_bitmap(array) try: if fi_type == FiTypes.FIT_BITMAP: can_write = _FI.FreeImage_FIFSupportsExportBPP( ftype, _FI.FreeImage_GetBPP(bitmap)) handle_errors() else: can_write = _FI.FreeImage_FIFSupportsExportType(ftype, fi_type) handle_errors() if not can_write: raise TypeError('Cannot save image of this format ' 'to this file type') res = _FI.FreeImage_Save(ftype, bitmap, filename, flags) handle_errors() if not res: raise RuntimeError('Could not save image properly.') finally: _FI.FreeImage_Unload(bitmap) handle_errors() def write_multipage(arrays, filename, flags=0): """Write a list of (height, width) or (height, width, nchannels) arrays to a multipage greyscale, RGB, or RGBA image, with file type deduced from the filename. The `flags` parameter should be one or more values from the IoFlags class defined in this module, or-ed together with | as appropriate. (See the source-code comments for more details.) """ filename = asbytes(filename) ftype = _FI.FreeImage_GetFIFFromFilename(filename) if ftype == -1: raise ValueError('Cannot determine type of file %s' % filename) create_new = True read_only = False keep_cache_in_memory = True multibitmap = _FI.FreeImage_OpenMultiBitmap(ftype, filename, create_new, read_only, keep_cache_in_memory, 0) multibitmap = ctypes.c_void_p(multibitmap) if not multibitmap: raise ValueError('Could not open %s for writing multi-page image.' % filename) try: for array in arrays: array = numpy.asarray(array) bitmap, fi_type = _array_to_bitmap(array) _FI.FreeImage_AppendPage(multibitmap, bitmap) finally: _FI.FreeImage_CloseMultiBitmap(multibitmap, flags) # 4-byte quads of 0,v,v,v from 0,0,0,0 to 0,255,255,255 _GREY_PALETTE = numpy.arange(0, 0x01000000, 0x00010101, dtype=numpy.uint32) def _array_to_bitmap(array): """Allocate a FreeImage bitmap and copy a numpy array into it. """ shape = array.shape dtype = array.dtype r, c = shape[:2] if len(shape) == 2: n_channels = 1 w_shape = (c, r) elif len(shape) == 3: n_channels = shape[2] w_shape = (n_channels, c, r) else: n_channels = shape[0] try: fi_type = FiTypes.fi_types[(dtype, n_channels)] except KeyError: raise ValueError('Cannot write arrays of given type and shape.') itemsize = array.dtype.itemsize bpp = 8 * itemsize * n_channels bitmap = _FI.FreeImage_AllocateT(fi_type, c, r, bpp, 0, 0, 0) bitmap = ctypes.c_void_p(bitmap) if not bitmap: raise RuntimeError('Could not allocate image for storage') try: def n(arr): # normalise to freeimage's in-memory format return arr.T[..., ::-1] wrapped_array = _wrap_bitmap_bits_in_array(bitmap, w_shape, dtype) # swizzle the color components and flip the scanlines to go to # FreeImage's BGR[A] and upside-down internal memory format if len(shape) == 3 and _FI.FreeImage_IsLittleEndian(): r = array[:, :, 0] g = array[:, :, 1] b = array[:, :, 2] if dtype.type == numpy.uint8: wrapped_array[0] = n(b) wrapped_array[1] = n(g) wrapped_array[2] = n(r) elif dtype.type == numpy.uint16: wrapped_array[0] = n(r) wrapped_array[1] = n(g) wrapped_array[2] = n(b) if shape[2] == 4: a = array[:, :, 3] wrapped_array[3] = n(a) else: wrapped_array[:] = n(array) if len(shape) == 2 and dtype.type == numpy.uint8: palette = _FI.FreeImage_GetPalette(bitmap) palette = ctypes.c_void_p(palette) if not palette: raise RuntimeError('Could not get image palette') ctypes.memmove(palette, _GREY_PALETTE.ctypes.data, 1024) return bitmap, fi_type except: _FI.FreeImage_Unload(bitmap) raise def imread(filename): """ img = imread(filename) Reads an image from file `filename` Parameters ---------- filename : file name Returns ------- img : ndarray """ img = read(filename) return img def imsave(filename, img): ''' imsave(filename, img) Save image to disk Image type is inferred from filename Parameters ---------- filename : file name img : image to be saved as nd array ''' write(img, filename)
bsd-3-clause
jgcaaprom/android_external_chromium_org
chrome/browser/performance_monitor/process_metrics_history.cc
5086
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <limits> #include "base/logging.h" #include "base/metrics/histogram.h" #include "base/process/process_metrics.h" #include "chrome/browser/performance_monitor/process_metrics_history.h" #if defined(OS_MACOSX) #include "content/public/browser/browser_child_process_host.h" #endif #include "content/public/common/process_type.h" namespace performance_monitor { // If a process is consistently above this CPU utilization percentage over time, // we consider it as high and may take action. const float kHighCPUUtilizationThreshold = 90.0f; ProcessMetricsHistory::ProcessMetricsHistory() : process_handle_(0), process_type_(content::PROCESS_TYPE_UNKNOWN), last_update_sequence_(0) { ResetCounters(); } ProcessMetricsHistory::~ProcessMetricsHistory() {} void ProcessMetricsHistory::ResetCounters() { min_cpu_usage_ = std::numeric_limits<double>::max(); accumulated_cpu_usage_ = 0.0; accumulated_private_bytes_ = 0; accumulated_shared_bytes_ = 0; sample_count_ = 0; } void ProcessMetricsHistory::Initialize(base::ProcessHandle process_handle, int process_type, int initial_update_sequence) { DCHECK(process_handle_ == 0); process_handle_ = process_handle; process_type_ = process_type; last_update_sequence_ = initial_update_sequence; #if defined(OS_MACOSX) process_metrics_.reset(base::ProcessMetrics::CreateProcessMetrics( process_handle_, content::BrowserChildProcessHost::GetPortProvider())); #else process_metrics_.reset( base::ProcessMetrics::CreateProcessMetrics(process_handle_)); #endif } void ProcessMetricsHistory::SampleMetrics() { double cpu_usage = process_metrics_->GetPlatformIndependentCPUUsage(); min_cpu_usage_ = std::min(min_cpu_usage_, cpu_usage); accumulated_cpu_usage_ += cpu_usage; size_t private_bytes = 0; size_t shared_bytes = 0; if (!process_metrics_->GetMemoryBytes(&private_bytes, &shared_bytes)) LOG(WARNING) << "GetMemoryBytes returned NULL (platform-specific error)"; accumulated_private_bytes_ += private_bytes; accumulated_shared_bytes_ += shared_bytes; sample_count_++; } void ProcessMetricsHistory::EndOfCycle() { RunPerformanceTriggers(); ResetCounters(); } void ProcessMetricsHistory::RunPerformanceTriggers() { if (sample_count_ == 0) return; // We scale up to the equivalent of 64 CPU cores fully loaded. More than this // doesn't really matter, as we're already in a terrible place. const int kHistogramMin = 0; const int kHistogramMax = 6400; const int kHistogramBucketCount = 50; const double average_cpu_usage = accumulated_cpu_usage_ / sample_count_; // The histogram macros don't support variables as histogram names, // hence the macro duplication for each process type. switch (process_type_) { case content::PROCESS_TYPE_BROWSER: UMA_HISTOGRAM_CUSTOM_COUNTS( "PerformanceMonitor.AverageCPU.BrowserProcess", average_cpu_usage, kHistogramMin, kHistogramMax, kHistogramBucketCount); // If CPU usage has consistently been above our threshold, // we *may* have an issue. if (min_cpu_usage_ > kHighCPUUtilizationThreshold) { UMA_HISTOGRAM_BOOLEAN("PerformanceMonitor.HighCPU.BrowserProcess", true); } break; case content::PROCESS_TYPE_RENDERER: UMA_HISTOGRAM_CUSTOM_COUNTS( "PerformanceMonitor.AverageCPU.RendererProcess", average_cpu_usage, kHistogramMin, kHistogramMax, kHistogramBucketCount); if (min_cpu_usage_ > kHighCPUUtilizationThreshold) { UMA_HISTOGRAM_BOOLEAN("PerformanceMonitor.HighCPU.RendererProcess", true); } break; case content::PROCESS_TYPE_PLUGIN: UMA_HISTOGRAM_CUSTOM_COUNTS( "PerformanceMonitor.AverageCPU.PluginProcess", average_cpu_usage, kHistogramMin, kHistogramMax, kHistogramBucketCount); if (min_cpu_usage_ > kHighCPUUtilizationThreshold) UMA_HISTOGRAM_BOOLEAN("PerformanceMonitor.HighCPU.PluginProcess", true); break; case content::PROCESS_TYPE_GPU: UMA_HISTOGRAM_CUSTOM_COUNTS( "PerformanceMonitor.AverageCPU.GPUProcess", average_cpu_usage, kHistogramMin, kHistogramMax, kHistogramBucketCount); if (min_cpu_usage_ > kHighCPUUtilizationThreshold) UMA_HISTOGRAM_BOOLEAN("PerformanceMonitor.HighCPU.GPUProcess", true); break; case content::PROCESS_TYPE_PPAPI_PLUGIN: UMA_HISTOGRAM_CUSTOM_COUNTS( "PerformanceMonitor.AverageCPU.PPAPIProcess", average_cpu_usage, kHistogramMin, kHistogramMax, kHistogramBucketCount); if (min_cpu_usage_ > kHighCPUUtilizationThreshold) UMA_HISTOGRAM_BOOLEAN("PerformanceMonitor.HighCPU.PPAPIProcess", true); break; default: break; } } } // namespace performance_monitor
bsd-3-clause
li8/Poker-Planner
node_modules/gzippo/test/fixtures/test.js
15
alert("hello");
mit
mcliment/DefinitelyTyped
types/vue-nice-dates/index.d.ts
827
// Type definitions for vue-nice-dates 2.0 // Project: https://github.com/zhangchizi/vue-nice-dates#readme // Definitions by: zhangchizi <https://github.com/zhangchizi> // wanghuan <https://github.com/huanlala> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // Minimum TypeScript Version: 3.5 export { Calendar } from './Calendar'; export { DatePicker } from './DatePicker'; export { DatePickerCalendar } from './DatePickerCalendar'; export { DateRangePicker } from './DateRangePicker'; export { DateRangePickerCalendar } from './DateRangePickerCalendar'; export { Popover } from './Popover'; export const START_DATE: string; export const END_DATE: string; export const GRID_DAY: string; export const GRID_MONTH: string; export const GRID_YEAR: string; export as namespace vueNiceDates;
mit
ccschneidr/babel
packages/babel-generator/test/fixtures/compact/while/expected.js
16
while(true)x();
mit
thomasmckay/katello
app/assets/javascripts/katello/widgets/subpanel_new.js
271
$(document).ready(function(){ var form_id = $('#new_subpanel'), form_submit_id = form_id.find('.subpanel_create'), url_after_submit = form_submit_id.data('url_after_submit'); KT.panel.registerSubPanelSubmit(form_id, form_submit_id, url_after_submit); });
gpl-2.0
YehudaItkin/virt-test
virttest/libvirt_xml/devices/video.py
1908
""" video device support class(es) http://libvirt.org/formatdomain.html#elementsVideo """ from virttest.libvirt_xml import accessors from virttest.libvirt_xml.devices import base class Video(base.TypedDeviceBase): __slots__ = ('model_type', 'model_ram', 'model_vram', 'model_heads', 'primary', 'acceleration', 'address') def __init__(self, type_name, virsh_instance=base.base.virsh): accessors.XMLAttribute('model_type', self, parent_xpath='/', tag_name='model', attribute='type') accessors.XMLAttribute('model_ram', self, parent_xpath='/', tag_name='model', attribute='ram') accessors.XMLAttribute('model_vram', self, parent_xpath='/', tag_name='model', attribute='vram') accessors.XMLAttribute('model_heads', self, parent_xpath='/', tag_name='model', attribute='heads') accessors.XMLAttribute('primary', self, parent_xpath='/', tag_name='model', attribute='primary') accessors.XMLElementDict('acceleration', self, parent_xpath='/model', tag_name='acceleration') accessors.XMLElementDict('address', self, parent_xpath='/', tag_name='address') super(Video, self).__init__(device_tag='video', type_name=type_name, virsh_instance=virsh_instance)
gpl-2.0
rajuniit/chotrobazaar
lib/Zend/Service/ShortUrl/AbstractShortener.php
2533
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to [email protected] so we can send you a copy immediately. * * @category Zend * @package Zend_Service_ShortUrl * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: $ */ /** * @see Zend_Service_Abstract */ #require_once 'Zend/Service/Abstract.php'; /** * @see Zend_Service_ShortUrl_Shortener */ #require_once 'Zend/Service/ShortUrl/Shortener.php'; /** * @category Zend * @package Zend_Service_ShortUrl * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ abstract class Zend_Service_ShortUrl_AbstractShortener extends Zend_Service_Abstract implements Zend_Service_ShortUrl_Shortener { /** * Base URI of the service * * @var string */ protected $_baseUri = null; /** * Checks whether URL to be shortened is valid * * @param string $url * @throws Zend_Service_ShortUrl_Exception When URL is not valid */ protected function _validateUri($url) { #require_once 'Zend/Uri.php'; if (!Zend_Uri::check($url)) { #require_once 'Zend/Service/ShortUrl/Exception.php'; throw new Zend_Service_ShortUrl_Exception(sprintf( 'The url "%s" is not valid and cannot be shortened', $url )); } } /** * Verifies that the URL has been shortened by this service * * @throws Zend_Service_ShortUrl_Exception If the URL hasn't been shortened by this service * @param string $shortenedUrl */ protected function _verifyBaseUri($shortenedUrl) { if (strpos($shortenedUrl, $this->_baseUri) !== 0) { #require_once 'Zend/Service/ShortUrl/Exception.php'; throw new Zend_Service_ShortUrl_Exception(sprintf( 'The url "%s" is not valid for this service and the target cannot be resolved', $shortenedUrl )); } } }
gpl-2.0
yclas/yclas
oc/vendor/oauth2/vendor/league/oauth2-client/src/Tool/ProviderRedirectTrait.php
3174
<?php namespace League\OAuth2\Client\Tool; use GuzzleHttp\Exception\BadResponseException; use GuzzleHttp\Psr7\Uri; use InvalidArgumentException; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; trait ProviderRedirectTrait { /** * Maximum number of times to follow provider initiated redirects * * @var integer */ protected $redirectLimit = 2; /** * Retrieves a response for a given request and retrieves subsequent * responses, with authorization headers, if a redirect is detected. * * @param RequestInterface $request * @return ResponseInterface * @throws BadResponseException */ protected function followRequestRedirects(RequestInterface $request) { $response = null; $attempts = 0; while ($attempts < $this->redirectLimit) { $attempts++; $response = $this->getHttpClient()->send($request, [ 'allow_redirects' => false ]); if ($this->isRedirect($response)) { $redirectUrl = new Uri($response->getHeader('Location')[0]); $request = $request->withUri($redirectUrl); } else { break; } } return $response; } /** * Returns the HTTP client instance. * * @return GuzzleHttp\ClientInterface */ abstract public function getHttpClient(); /** * Retrieves current redirect limit. * * @return integer */ public function getRedirectLimit() { return $this->redirectLimit; } /** * Determines if a given response is a redirect. * * @param ResponseInterface $response * * @return boolean */ protected function isRedirect(ResponseInterface $response) { $statusCode = $response->getStatusCode(); return $statusCode > 300 && $statusCode < 400 && $response->hasHeader('Location'); } /** * Sends a request instance and returns a response instance. * * WARNING: This method does not attempt to catch exceptions caused by HTTP * errors! It is recommended to wrap this method in a try/catch block. * * @param RequestInterface $request * @return ResponseInterface */ public function getResponse(RequestInterface $request) { try { $response = $this->followRequestRedirects($request); } catch (BadResponseException $e) { $response = $e->getResponse(); } return $response; } /** * Updates the redirect limit. * * @param integer $limit * @return League\OAuth2\Client\Provider\AbstractProvider * @throws InvalidArgumentException */ public function setRedirectLimit($limit) { if (!is_int($limit)) { throw new InvalidArgumentException('redirectLimit must be an integer.'); } if ($limit < 1) { throw new InvalidArgumentException('redirectLimit must be greater than or equal to one.'); } $this->redirectLimit = $limit; return $this; } }
gpl-3.0
wrgeorge1983/librenms
vendor/amenadiel/jpgraph/src/plot/MileStone.php
3518
<?php namespace Amenadiel\JpGraph\Plot; //=================================================== // CLASS MileStone // Responsible for formatting individual milestones //=================================================== class MileStone extends GanttPlotObject { public $mark; //--------------- // CONSTRUCTOR public function __construct($aVPos, $aLabel, $aDate, $aCaption = "") { GanttPlotObject::__construct(); $this->caption->Set($aCaption); $this->caption->Align("left", "center"); $this->caption->SetFont(FF_FONT1, FS_BOLD); $this->title->Set($aLabel); $this->title->SetColor("darkred"); $this->mark = new PlotMark(); $this->mark->SetWidth(10); $this->mark->SetType(MARK_DIAMOND); $this->mark->SetColor("darkred"); $this->mark->SetFillColor("darkred"); $this->iVPos = $aVPos; $this->iStart = $aDate; } //--------------- // PUBLIC METHODS public function GetAbsHeight($aImg) { return max($this->title->GetHeight($aImg), $this->mark->GetWidth()); } public function Stroke($aImg, $aScale) { // Put the mark in the middle at the middle of the day $d = $aScale->NormalizeDate($this->iStart) + SECPERDAY / 2; $x = $aScale->TranslateDate($d); $y = $aScale->TranslateVertPos($this->iVPos) - ($aScale->GetVertSpacing() / 2); $this->StrokeActInfo($aImg, $aScale, $y); // CSIM for title if (!empty($this->title->csimtarget)) { $yt = round($y - $this->title->GetHeight($aImg) / 2); $yb = round($y + $this->title->GetHeight($aImg) / 2); $colwidth = $this->title->GetColWidth($aImg); $colstarts = array(); $aScale->actinfo->GetColStart($aImg, $colstarts, true); $n = min(count($colwidth), count($this->title->csimtarget)); for ($i = 0; $i < $n; ++$i) { $title_xt = $colstarts[$i]; $title_xb = $title_xt + $colwidth[$i]; $coords = "$title_xt,$yt,$title_xb,$yt,$title_xb,$yb,$title_xt,$yb"; if (!empty($this->title->csimtarget[$i])) { $this->csimarea .= "<area shape=\"poly\" coords=\"$coords\" href=\"" . $this->title->csimtarget[$i] . "\""; if (!empty($this->title->csimwintarget[$i])) { $this->csimarea .= "target=\"" . $this->title->csimwintarget[$i] . "\""; } if (!empty($this->title->csimalt[$i])) { $tmp = $this->title->csimalt[$i]; $this->csimarea .= " title=\"$tmp\" alt=\"$tmp\" "; } $this->csimarea .= " />\n"; } } } if ($d < $aScale->iStartDate || $d > $aScale->iEndDate) { return; } // Remember the coordinates for any constrains linking to // this milestone $w = $this->mark->GetWidth() / 2; $this->SetConstrainPos($x, round($y - $w), $x, round($y + $w)); // Setup CSIM if ($this->csimtarget != '') { $this->mark->SetCSIMTarget($this->csimtarget); $this->mark->SetCSIMAlt($this->csimalt); } $this->mark->Stroke($aImg, $x, $y); $this->caption->Stroke($aImg, $x + $this->mark->width / 2 + $this->iCaptionMargin, $y); $this->csimarea .= $this->mark->GetCSIMAreas(); } }
gpl-3.0
mglukhikh/intellij-community
java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/impl/PsiTypeParameterListStubImpl.java
1301
/* * Copyright 2000-2016 JetBrains s.r.o. * * 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 com.intellij.psi.impl.java.stubs.impl; import com.intellij.psi.PsiTypeParameterList; import com.intellij.psi.impl.java.stubs.JavaStubElementTypes; import com.intellij.psi.impl.java.stubs.PsiTypeParameterListStub; import com.intellij.psi.stubs.StubBase; import com.intellij.psi.stubs.StubElement; /** * @author max */ public class PsiTypeParameterListStubImpl extends StubBase<PsiTypeParameterList> implements PsiTypeParameterListStub{ public PsiTypeParameterListStubImpl(final StubElement parent) { super(parent, JavaStubElementTypes.TYPE_PARAMETER_LIST); } @SuppressWarnings({"HardCodedStringLiteral"}) public String toString() { return "PsiTypeParameterListStub"; } }
apache-2.0
Maxwe11/roslyn
src/EditorFeatures/Test/Extensions/ITextSnapshotExtensionsTests.cs
7723
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Roslyn.Test.EditorUtilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Extensions { public class ITextSnapshotExtensionsTests { [Fact] public void GetLeadingWhitespaceOfLineAtPosition_EmptyLineReturnsEmptyString() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition(string.Empty, 0); Assert.Equal(string.Empty, leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_WhitespaceLineReturnsWhitespace1() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition(" ", 0); Assert.Equal(" ", leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_WhitespaceLineReturnsWhitespace2() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition(" \t ", 0); Assert.Equal(" \t ", leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_WhitespaceLineReturnsWhitespace3() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("\t\t", 0); Assert.Equal("\t\t", leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_TextLine() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Foo", 0); Assert.Equal(string.Empty, leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_TextLineStartingWithWhitespace1() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition(" Foo", 0); Assert.Equal(" ", leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_TextLineStartingWithWhitespace2() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition(" \t Foo", 0); Assert.Equal(" \t ", leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_TextLineStartingWithWhitespace3() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("\t\tFoo", 0); Assert.Equal("\t\t", leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_EmptySecondLineReturnsEmptyString() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Foo\r\n", 5); Assert.Equal(string.Empty, leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_WhitespaceSecondLineReturnsWhitespace1() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Foo\r\n ", 5); Assert.Equal(" ", leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_WhitespaceSecondLineReturnsWhitespace2() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Foo\r\n \t ", 5); Assert.Equal(" \t ", leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_WhitespaceSecondLineReturnsWhitespace3() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Foo\r\n\t\t", 5); Assert.Equal("\t\t", leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_TextSecondLine() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Foo\r\nFoo", 5); Assert.Equal(string.Empty, leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_TextSecondLineStartingWithWhitespace1() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Foo\r\n Foo", 5); Assert.Equal(" ", leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_TextSecondLineStartingWithWhitespace2() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Foo\r\n \t Foo", 5); Assert.Equal(" \t ", leadingWhitespace); } [Fact] public void GetLeadingWhitespaceOfLineAtPosition_TextSecondLineStartingWithWhitespace3() { var leadingWhitespace = GetLeadingWhitespaceOfLineAtPosition("Foo\r\n\t\tFoo", 5); Assert.Equal("\t\t", leadingWhitespace); } [Fact] public void GetSpanTest() { // each line of sample code contains 4 characters followed by a newline var snapshot = GetSampleCodeSnapshot(); var span = snapshot.GetSpan(0, 2, 1, 1); // column 0, index 2 = (0 * 5) + 2 = 2 Assert.Equal(span.Start, 2); // column 1, index 1 = (1 * 5) + 1 = 6 Assert.Equal(span.End, 6); } [Fact] public void TryGetPositionTest() { // each line of sample code contains 4 characters followed by a newline var snapshot = GetSampleCodeSnapshot(); var point = new SnapshotPoint(); // valid line, valid column Assert.True(snapshot.TryGetPosition(3, 2, out point)); Assert.Equal(17, point.Position); // valid line, invalid column Assert.False(snapshot.TryGetPosition(1, 8, out point)); Assert.False(snapshot.TryGetPosition(3, -2, out point)); // invalid line, valid column Assert.False(snapshot.TryGetPosition(18, 1, out point)); Assert.False(snapshot.TryGetPosition(-1, 1, out point)); } [Fact] public void GetPointTest() { var snapshot = GetSampleCodeSnapshot(); Assert.Equal(new SnapshotPoint(snapshot, 15), snapshot.GetPoint(3, 0)); } [Fact] public void GetLineAndColumnTest() { var snapshot = GetSampleCodeSnapshot(); int line; int col; snapshot.GetLineAndColumn(16, out line, out col); Assert.Equal(3, line); Assert.Equal(1, col); } private string GetLeadingWhitespaceOfLineAtPosition(string code, int position) { var snapshot = EditorFactory.CreateBuffer(TestExportProvider.ExportProviderWithCSharpAndVisualBasic, code).CurrentSnapshot; return snapshot.GetLeadingWhitespaceOfLineAtPosition(position); } private ITextSnapshot GetSampleCodeSnapshot() { // to make verification simpler, each line of code is 4 characters and will be joined to other lines // with a single newline character making the formula to calculate the offset from a given line and // column thus: // position = row * 5 + column var lines = new string[] { "foo1", "bar1", "foo2", "bar2", "foo3", "bar3", }; var code = string.Join("\n", lines); var snapshot = EditorFactory.CreateBuffer(TestExportProvider.ExportProviderWithCSharpAndVisualBasic, code).CurrentSnapshot; return snapshot; } } }
apache-2.0
doug-fish/horizon
openstack_dashboard/dashboards/admin/defaults/tests.py
5796
# Copyright 2013 Kylin, Inc. # # 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. from django.core.urlresolvers import reverse from django import http from mox3.mox import IsA # noqa from openstack_dashboard import api from openstack_dashboard.test import helpers as test from openstack_dashboard.usage import quotas INDEX_URL = reverse('horizon:admin:defaults:index') class ServicesViewTests(test.BaseAdminViewTests): def test_index(self): self._test_index(neutron_enabled=True) def test_index_with_neutron_disabled(self): self._test_index(neutron_enabled=False) def test_index_with_neutron_sg_disabled(self): self._test_index(neutron_enabled=True, neutron_sg_enabled=False) def _test_index(self, neutron_enabled=True, neutron_sg_enabled=True): # Neutron does not have an API for getting default system # quotas. When not using Neutron, the floating ips quotas # should be in the list. self.mox.StubOutWithMock(api.nova, 'default_quota_get') self.mox.StubOutWithMock(api.cinder, 'default_quota_get') self.mox.StubOutWithMock(api.base, 'is_service_enabled') if neutron_enabled: self.mox.StubOutWithMock(api.neutron, 'is_extension_supported') api.base.is_service_enabled(IsA(http.HttpRequest), 'volume') \ .AndReturn(True) api.base.is_service_enabled(IsA(http.HttpRequest), 'network') \ .MultipleTimes().AndReturn(neutron_enabled) api.nova.default_quota_get(IsA(http.HttpRequest), self.tenant.id).AndReturn(self.quotas.nova) api.cinder.default_quota_get(IsA(http.HttpRequest), self.tenant.id) \ .AndReturn(self.cinder_quotas.first()) if neutron_enabled: api.neutron.is_extension_supported( IsA(http.HttpRequest), 'security-group').AndReturn(neutron_sg_enabled) self.mox.ReplayAll() res = self.client.get(INDEX_URL) self.assertTemplateUsed(res, 'admin/defaults/index.html') quotas_tab = res.context['tab_group'].get_tab('quotas') expected_tabs = ['<Quota: (injected_file_content_bytes, 1)>', '<Quota: (metadata_items, 1)>', '<Quota: (injected_files, 1)>', '<Quota: (gigabytes, 1000)>', '<Quota: (ram, 10000)>', '<Quota: (instances, 10)>', '<Quota: (snapshots, 1)>', '<Quota: (volumes, 1)>', '<Quota: (cores, 10)>', '<Quota: (floating_ips, 1)>', '<Quota: (fixed_ips, 10)>', '<Quota: (security_groups, 10)>', '<Quota: (security_group_rules, 20)>'] if neutron_enabled: expected_tabs.remove('<Quota: (floating_ips, 1)>') expected_tabs.remove('<Quota: (fixed_ips, 10)>') if neutron_sg_enabled: expected_tabs.remove('<Quota: (security_groups, 10)>') expected_tabs.remove('<Quota: (security_group_rules, 20)>') self.assertQuerysetEqual(quotas_tab._tables['quotas'].data, expected_tabs, ordered=False) class UpdateDefaultQuotasTests(test.BaseAdminViewTests): def _get_quota_info(self, quota): quota_data = {} for field in (quotas.QUOTA_FIELDS + quotas.MISSING_QUOTA_FIELDS): if field != 'fixed_ips': limit = quota.get(field).limit or 10 quota_data[field] = int(limit) return quota_data @test.create_stubs({api.nova: ('default_quota_update', ), api.cinder: ('default_quota_update', ), quotas: ('get_default_quota_data', 'get_disabled_quotas')}) def test_update_default_quotas(self): quota = self.quotas.first() # init quotas.get_disabled_quotas(IsA(http.HttpRequest)) \ .AndReturn(self.disabled_quotas.first()) quotas.get_default_quota_data(IsA(http.HttpRequest)).AndReturn(quota) # update some fields quota[0].limit = 123 quota[1].limit = -1 updated_quota = self._get_quota_info(quota) # handle nova_fields = quotas.NOVA_QUOTA_FIELDS + quotas.MISSING_QUOTA_FIELDS nova_updated_quota = dict([(key, updated_quota[key]) for key in nova_fields if key != 'fixed_ips']) api.nova.default_quota_update(IsA(http.HttpRequest), **nova_updated_quota) cinder_updated_quota = dict([(key, updated_quota[key]) for key in quotas.CINDER_QUOTA_FIELDS]) api.cinder.default_quota_update(IsA(http.HttpRequest), **cinder_updated_quota) self.mox.ReplayAll() url = reverse('horizon:admin:defaults:update_defaults') res = self.client.post(url, updated_quota) self.assertNoFormErrors(res) self.assertRedirectsNoFollow(res, INDEX_URL)
apache-2.0
bradtopol/kubernetes
staging/src/k8s.io/client-go/informers/extensions/v1beta1/podsecuritypolicy.go
3619
/* Copyright 2018 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. */ // This file was automatically generated by informer-gen package v1beta1 import ( time "time" extensions_v1beta1 "k8s.io/api/extensions/v1beta1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" watch "k8s.io/apimachinery/pkg/watch" internalinterfaces "k8s.io/client-go/informers/internalinterfaces" kubernetes "k8s.io/client-go/kubernetes" v1beta1 "k8s.io/client-go/listers/extensions/v1beta1" cache "k8s.io/client-go/tools/cache" ) // PodSecurityPolicyInformer provides access to a shared informer and lister for // PodSecurityPolicies. type PodSecurityPolicyInformer interface { Informer() cache.SharedIndexInformer Lister() v1beta1.PodSecurityPolicyLister } type podSecurityPolicyInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc } // NewPodSecurityPolicyInformer constructs a new informer for PodSecurityPolicy type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. func NewPodSecurityPolicyInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewFilteredPodSecurityPolicyInformer(client, resyncPeriod, indexers, nil) } // NewFilteredPodSecurityPolicyInformer constructs a new informer for PodSecurityPolicy type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. func NewFilteredPodSecurityPolicyInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { return cache.NewSharedIndexInformer( &cache.ListWatch{ ListFunc: func(options v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { tweakListOptions(&options) } return client.ExtensionsV1beta1().PodSecurityPolicies().List(options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } return client.ExtensionsV1beta1().PodSecurityPolicies().Watch(options) }, }, &extensions_v1beta1.PodSecurityPolicy{}, resyncPeriod, indexers, ) } func (f *podSecurityPolicyInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { return NewFilteredPodSecurityPolicyInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) } func (f *podSecurityPolicyInformer) Informer() cache.SharedIndexInformer { return f.factory.InformerFor(&extensions_v1beta1.PodSecurityPolicy{}, f.defaultInformer) } func (f *podSecurityPolicyInformer) Lister() v1beta1.PodSecurityPolicyLister { return v1beta1.NewPodSecurityPolicyLister(f.Informer().GetIndexer()) }
apache-2.0
strapdata/cassandra
src/java/org/apache/cassandra/tools/nodetool/Snapshot.java
4584
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.tools.nodetool; import static com.google.common.collect.Iterables.toArray; import static org.apache.commons.lang3.StringUtils.join; import io.airlift.command.Arguments; import io.airlift.command.Command; import io.airlift.command.Option; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.cassandra.tools.NodeProbe; import org.apache.cassandra.tools.NodeTool.NodeToolCmd; @Command(name = "snapshot", description = "Take a snapshot of specified keyspaces or a snapshot of the specified table") public class Snapshot extends NodeToolCmd { @Arguments(usage = "[<keyspaces...>]", description = "List of keyspaces. By default, all keyspaces") private List<String> keyspaces = new ArrayList<>(); @Option(title = "table", name = {"-cf", "--column-family", "--table"}, description = "The table name (you must specify one and only one keyspace for using this option)") private String table = null; @Option(title = "tag", name = {"-t", "--tag"}, description = "The name of the snapshot") private String snapshotName = Long.toString(System.currentTimeMillis()); @Option(title = "ktlist", name = { "-kt", "--kt-list", "-kc", "--kc.list" }, description = "The list of Keyspace.table to take snapshot.(you must not specify only keyspace)") private String ktList = null; @Option(title = "skip-flush", name = {"-sf", "--skip-flush"}, description = "Do not flush memtables before snapshotting (snapshot will not contain unflushed data)") private boolean skipFlush = false; @Override public void execute(NodeProbe probe) { try { StringBuilder sb = new StringBuilder(); sb.append("Requested creating snapshot(s) for "); Map<String, String> options = new HashMap<String,String>(); options.put("skipFlush", Boolean.toString(skipFlush)); // Create a separate path for kclist to avoid breaking of already existing scripts if (null != ktList && !ktList.isEmpty()) { ktList = ktList.replace(" ", ""); if (keyspaces.isEmpty() && null == table) sb.append("[").append(ktList).append("]"); else { throw new IOException( "When specifying the Keyspace columfamily list for a snapshot, you should not specify columnfamily"); } if (!snapshotName.isEmpty()) sb.append(" with snapshot name [").append(snapshotName).append("]"); sb.append(" and options ").append(options.toString()); System.out.println(sb.toString()); probe.takeMultipleTableSnapshot(snapshotName, options, ktList.split(",")); System.out.println("Snapshot directory: " + snapshotName); } else { if (keyspaces.isEmpty()) sb.append("[all keyspaces]"); else sb.append("[").append(join(keyspaces, ", ")).append("]"); if (!snapshotName.isEmpty()) sb.append(" with snapshot name [").append(snapshotName).append("]"); sb.append(" and options ").append(options.toString()); System.out.println(sb.toString()); probe.takeSnapshot(snapshotName, table, options, toArray(keyspaces, String.class)); System.out.println("Snapshot directory: " + snapshotName); } } catch (IOException e) { throw new RuntimeException("Error during taking a snapshot", e); } } }
apache-2.0
programming086/omim
qt/update_dialog.hpp
1326
#pragma once #include "map/framework.hpp" #include <QtWidgets/QApplication> #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) #include <QtGui/QDialog> #else #include <QtWidgets/QDialog> #endif class QTreeWidget; class QTreeWidgetItem; class QLabel; class QPushButton; class Framework; namespace qt { class UpdateDialog : public QDialog { Q_OBJECT public: explicit UpdateDialog(QWidget * parent, Framework & framework); virtual ~UpdateDialog(); /// @name Called from downloader to notify GUI //@{ void OnCountryChanged(storage::TIndex const & index); void OnCountryDownloadProgress(storage::TIndex const & index, pair<int64_t, int64_t> const & progress); //@} void ShowModal(); private slots: void OnItemClick(QTreeWidgetItem * item, int column); void OnCloseClick(); private: void FillTree(); void UpdateRowWithCountryInfo(storage::TIndex const & index); QTreeWidgetItem * CreateTreeItem(storage::TIndex const & index, int value, QTreeWidgetItem * parent); int GetChildsCount(storage::TIndex const & index) const; private: inline storage::Storage & GetStorage() const { return m_framework.Storage(); } QTreeWidget * m_tree; Framework & m_framework; int m_observerSlotId; }; } // namespace qt
apache-2.0
mhart/relay
examples/todo/server.js
1419
import express from 'express'; import graphQLHTTP from 'express-graphql'; import path from 'path'; import webpack from 'webpack'; import WebpackDevServer from 'webpack-dev-server'; import {GraphQLTodoSchema} from './data/schema'; const APP_PORT = 3000; const GRAPHQL_PORT = 8080; // Expose a GraphQL endpoint var graphQLServer = express(); graphQLServer.use('/', graphQLHTTP({schema: GraphQLTodoSchema, pretty: true})); graphQLServer.listen(GRAPHQL_PORT, () => console.log( `GraphQL Server is now running on http://localhost:${GRAPHQL_PORT}` )); // Serve the Relay app var compiler = webpack({ entry: path.resolve(__dirname, 'js', 'app.js'), eslint: { configFile: '.eslintrc' }, module: { loaders: [ { test: /\.js$/, loader: 'babel', query: { stage: 0, plugins: ['./build/babelGraphQLPlugin'] } }, { test: /\.js$/, loader: 'eslint' } ] }, output: {filename: 'app.js', path: '/'} }); var app = new WebpackDevServer(compiler, { contentBase: '/public/', proxy: {'/graphql': `http://localhost:${GRAPHQL_PORT}`}, publicPath: '/js/', stats: {colors: true} }); // Serve static resources app.use('/', express.static('public')); app.use('/node_modules', express.static('node_modules')); app.listen(APP_PORT, () => { console.log(`Relay TodoMVC is now running on http://localhost:${APP_PORT}`); });
bsd-3-clause
markogresak/DefinitelyTyped
types/carbon__icons-react/es/direction--straight--right--filled/32.d.ts
68
export { DirectionStraightRightFilled32 as default } from "../../";
mit
sfshine/actor-platform
actor-server/actor-commons-base/src/main/scala/im/actor/server/commons/serialization/ActorSerializer.scala
2966
package im.actor.server.commons.serialization import akka.serialization._ import com.google.protobuf.{ GeneratedMessage ⇒ GGeneratedMessage, ByteString } import com.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap.{ Builder ⇒ MapBuilder } import com.trueaccord.scalapb.GeneratedMessage import scala.util.{ Failure, Success } object ActorSerializer { private val ARRAY_OF_BYTE_ARRAY = Array[Class[_]](classOf[Array[Byte]]) // FIXME: dynamically increase capacity private val map = new MapBuilder[Int, Class[_]].maximumWeightedCapacity(1024).build() private val reverseMap = new MapBuilder[Class[_], Int].maximumWeightedCapacity(1024).build() def clean(): Unit = { map.clear() reverseMap.clear() } def register(id: Int, clazz: Class[_]): Unit = { get(id) match { case None ⇒ get(clazz) match { case Some(regId) ⇒ throw new IllegalArgumentException(s"There is already a mapping for class: ${clazz}, id: ${regId}") case None ⇒ map.put(id, Class.forName(clazz.getName + '$')) reverseMap.put(clazz, id) } case Some(registered) ⇒ if (!get(clazz).exists(_ == id)) throw new IllegalArgumentException(s"There is already a mapping with id ${id}: ${map.get(id)}") } } def get(id: Int): Option[Class[_]] = Option(map.get(id)) def get(clazz: Class[_]) = Option(reverseMap.get(clazz)) def fromBinary(bytes: Array[Byte]): AnyRef = { val SerializedMessage(id, bodyBytes) = SerializedMessage.parseFrom(bytes) ActorSerializer.get(id) match { case Some(clazz) ⇒ val field = clazz.getField("MODULE$").get(null) clazz .getDeclaredMethod("validate", ARRAY_OF_BYTE_ARRAY: _*) .invoke(field, bodyBytes.toByteArray) match { case Success(msg) ⇒ msg.asInstanceOf[GeneratedMessage] case Failure(e) ⇒ throw e } case None ⇒ throw new IllegalArgumentException(s"Can't find mapping for id ${id}") } } def toBinary(o: AnyRef): Array[Byte] = { ActorSerializer.get(o.getClass) match { case Some(id) ⇒ o match { case m: GeneratedMessage ⇒ SerializedMessage(id, ByteString.copyFrom(m.toByteArray)).toByteArray case m: GGeneratedMessage ⇒ SerializedMessage(id, ByteString.copyFrom(m.toByteArray)).toByteArray case _ ⇒ throw new IllegalArgumentException(s"Can't serialize non-scalapb message [${o}]") } case None ⇒ throw new IllegalArgumentException(s"Can't find mapping for message [${o}]") } } } class ActorSerializer extends Serializer { override def identifier: Int = 3456 override def includeManifest: Boolean = false override def fromBinary(bytes: Array[Byte], manifest: Option[Class[_]]): AnyRef = ActorSerializer.fromBinary(bytes) override def toBinary(o: AnyRef): Array[Byte] = ActorSerializer.toBinary(o) }
mit
shimingsg/corefx
src/System.Net.Security/src/System/Net/Security/NegotiateStreamPal.Unix.cs
2094
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.ComponentModel; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security; using System.Security.Authentication; using System.Security.Authentication.ExtendedProtection; using System.Security.Claims; using System.Security.Principal; using System.Threading; using Microsoft.Win32.SafeHandles; namespace System.Net.Security { // // The class maintains the state of the authentication process and the security context. // It encapsulates security context and does the real work in authentication and // user data encryption with NEGO SSPI package. // internal static partial class NegotiateStreamPal { internal static IIdentity GetIdentity(NTAuthentication context) { string name = context.Spn; string protocol = context.ProtocolName; if (context.IsServer) { var safeContext = context.GetContext(out var status); if (status.ErrorCode != SecurityStatusPalErrorCode.OK) { throw new Win32Exception((int)status.ErrorCode); } name = GetUser(ref safeContext); } return new GenericIdentity(name, protocol); } internal static string QueryContextAssociatedName(SafeDeleteContext securityContext) { throw new PlatformNotSupportedException(SR.net_nego_server_not_supported); } internal static void ValidateImpersonationLevel(TokenImpersonationLevel impersonationLevel) { if (impersonationLevel != TokenImpersonationLevel.Identification) { throw new ArgumentOutOfRangeException(nameof(impersonationLevel), impersonationLevel.ToString(), SR.net_auth_supported_impl_levels); } } } }
mit
neo4jrb/neo4j_fat_free_crm
app/helpers/admin/settings_helper.rb
324
# Copyright (c) 2008-2013 Michael Dvorkin and contributors. # # Fat Free CRM is freely distributable under the terms of MIT license. # See MIT-LICENSE file or http://www.opensource.org/licenses/mit-license.php #------------------------------------------------------------------------------ module Admin::SettingsHelper end
mit
ViktorHofer/corefx
src/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionError.cs
7815
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel.Composition.Primitives; using System.Diagnostics; using System.Globalization; namespace System.ComponentModel.Composition { /// <summary> /// Represents an error that occurs during composition. /// </summary> [DebuggerTypeProxy(typeof(CompositionErrorDebuggerProxy))] public class CompositionError { private readonly CompositionErrorId _id; private readonly string _description; private readonly Exception _exception; private readonly ICompositionElement _element; /// <summary> /// Initializes a new instance of the <see cref="CompositionError"/> class /// with the specified error message. /// </summary> /// <param name="message"> /// A <see cref="string"/> containing a message that describes the /// <see cref="CompositionError"/>; or <see langword="null"/> to set the /// <see cref="Description"/> property to an empty string (""). /// </param> public CompositionError(string message) : this(CompositionErrorId.Unknown, message, (ICompositionElement)null, (Exception)null) { } /// <summary> /// Initializes a new instance of the <see cref="CompositionError"/> class /// with the specified error message and composition element that is the /// cause of the composition error. /// </summary> /// <param name="element"> /// The <see cref="ICompositionElement"/> that is the cause of the /// <see cref="CompositionError"/>; or <see langword="null"/> to set /// the <see cref="CompositionError.Element"/> property to /// <see langword="null"/>. /// </param> /// <param name="message"> /// A <see cref="string"/> containing a message that describes the /// <see cref="CompositionError"/>; or <see langword="null"/> to set the /// <see cref="Description"/> property to an empty string (""). /// </param> public CompositionError(string message, ICompositionElement element) : this(CompositionErrorId.Unknown, message, element, (Exception)null) { } /// <summary> /// Initializes a new instance of the <see cref="CompositionError"/> class /// with the specified error message and exception that is the cause of the /// composition error. /// </summary> /// <param name="message"> /// A <see cref="string"/> containing a message that describes the /// <see cref="CompositionError"/>; or <see langword="null"/> to set the /// <see cref="Description"/> property to an empty string (""). /// </param> /// <param name="exception"> /// The <see cref="Exception"/> that is the underlying cause of the /// <see cref="CompositionError"/>; or <see langword="null"/> to set /// the <see cref="CompositionError.Exception"/> property to <see langword="null"/>. /// </param> public CompositionError(string message, Exception exception) : this(CompositionErrorId.Unknown, message, (ICompositionElement)null, exception) { } /// <summary> /// Initializes a new instance of the <see cref="CompositionError"/> class /// with the specified error message, and composition element and exception that /// is the cause of the composition error. /// </summary> /// <param name="message"> /// A <see cref="string"/> containing a message that describes the /// <see cref="CompositionError"/>; or <see langword="null"/> to set the /// <see cref="Description"/> property to an empty string (""). /// </param> /// <param name="element"> /// The <see cref="ICompositionElement"/> that is the cause of the /// <see cref="CompositionError"/>; or <see langword="null"/> to set /// the <see cref="CompositionError.Element"/> property to /// <see langword="null"/>. /// </param> /// <param name="exception"> /// The <see cref="Exception"/> that is the underlying cause of the /// <see cref="CompositionError"/>; or <see langword="null"/> to set /// the <see cref="CompositionError.Exception"/> property to <see langword="null"/>. /// </param> public CompositionError(string message, ICompositionElement element, Exception exception) : this(CompositionErrorId.Unknown, message, element, exception) { } internal CompositionError(CompositionErrorId id, string description, ICompositionElement element, Exception exception) { _id = id; _description = description ?? string.Empty; _element = element; _exception = exception; } /// <summary> /// Gets the composition element that is the cause of the error. /// </summary> /// <value> /// The <see cref="ICompositionElement"/> that is the cause of the /// <see cref="CompositionError"/>. The default is <see langword="null"/>. /// </value> public ICompositionElement Element { get { return _element; } } /// <summary> /// Gets the message that describes the composition error. /// </summary> /// <value> /// A <see cref="string"/> containing a message that describes the /// <see cref="CompositionError"/>. /// </value> public string Description { get { return _description; } } /// <summary> /// Gets the exception that is the underlying cause of the composition error. /// </summary> /// <value> /// The <see cref="Exception"/> that is the underlying cause of the /// <see cref="CompositionError"/>. The default is <see langword="null"/>. /// </value> public Exception Exception { get { return _exception; } } internal CompositionErrorId Id { get { return _id; } } internal Exception InnerException { get { return Exception; } } /// <summary> /// Returns a string representation of the composition error. /// </summary> /// <returns> /// A <see cref="string"/> containing the <see cref="Description"/> property. /// </returns> public override string ToString() { return Description; } internal static CompositionError Create(CompositionErrorId id, string format, params object[] parameters) { return Create(id, (ICompositionElement)null, (Exception)null, format, parameters); } internal static CompositionError Create(CompositionErrorId id, ICompositionElement element, string format, params object[] parameters) { return Create(id, element, (Exception)null, format, parameters); } internal static CompositionError Create(CompositionErrorId id, ICompositionElement element, Exception exception, string format, params object[] parameters) { return new CompositionError(id, string.Format(CultureInfo.CurrentCulture, format, parameters), element, exception); } } }
mit
sufuf3/cdnjs
ajax/libs/collect.js/4.0.23/collect.js
67459
var collect = /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 4); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Values helper * * Retrieve values from [this.items] when it is an array, object or Collection * * @returns {*} * @param items */ function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } module.exports = function values(items) { var valuesArray = []; if (Array.isArray(items)) { valuesArray.push.apply(valuesArray, _toConsumableArray(items)); } else if (items.constructor.name === 'Collection') { valuesArray.push.apply(valuesArray, _toConsumableArray(items.all())); } else { Object.keys(items).forEach(function (prop) { return valuesArray.push(items[prop]); }); } return valuesArray; }; /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Get value of a nested property * * @param mainObject * @param key * @returns {*} */ module.exports = function nestedValue(mainObject, key) { try { return key.split('.').reduce(function (obj, property) { return obj[property]; }, mainObject); } catch (err) { return null; } }; /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Variadic helper function * * @param args * @returns {*} */ module.exports = function variadic(args) { if (Array.isArray(args[0])) { return args[0]; } return args; }; /***/ }), /* 3 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function average(key) { if (key === undefined) { return this.sum() / this.items.length; } return new this.constructor(this.items).pluck(key).sum() / this.items.length; }; /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function Collection(collection) { this.items = collection || []; } var SymbolIterator = __webpack_require__(5); if (typeof Symbol !== 'undefined') { Collection.prototype[Symbol.iterator] = SymbolIterator; } Collection.prototype.all = __webpack_require__(6); Collection.prototype.average = __webpack_require__(3); Collection.prototype.avg = __webpack_require__(3); Collection.prototype.chunk = __webpack_require__(7); Collection.prototype.collapse = __webpack_require__(8); Collection.prototype.combine = __webpack_require__(9); Collection.prototype.concat = __webpack_require__(10); Collection.prototype.contains = __webpack_require__(11); Collection.prototype.count = __webpack_require__(12); Collection.prototype.crossJoin = __webpack_require__(13); Collection.prototype.dd = __webpack_require__(14); Collection.prototype.diff = __webpack_require__(16); Collection.prototype.diffAssoc = __webpack_require__(17); Collection.prototype.diffKeys = __webpack_require__(18); Collection.prototype.dump = __webpack_require__(19); Collection.prototype.each = __webpack_require__(20); Collection.prototype.eachSpread = __webpack_require__(21); Collection.prototype.every = __webpack_require__(22); Collection.prototype.except = __webpack_require__(23); Collection.prototype.filter = __webpack_require__(24); Collection.prototype.first = __webpack_require__(25); Collection.prototype.firstWhere = __webpack_require__(26); Collection.prototype.flatMap = __webpack_require__(27); Collection.prototype.flatten = __webpack_require__(28); Collection.prototype.flip = __webpack_require__(29); Collection.prototype.forPage = __webpack_require__(30); Collection.prototype.forget = __webpack_require__(31); Collection.prototype.get = __webpack_require__(32); Collection.prototype.groupBy = __webpack_require__(33); Collection.prototype.has = __webpack_require__(34); Collection.prototype.implode = __webpack_require__(35); Collection.prototype.intersect = __webpack_require__(36); Collection.prototype.intersectByKeys = __webpack_require__(37); Collection.prototype.isEmpty = __webpack_require__(38); Collection.prototype.isNotEmpty = __webpack_require__(39); Collection.prototype.keyBy = __webpack_require__(40); Collection.prototype.keys = __webpack_require__(41); Collection.prototype.last = __webpack_require__(42); Collection.prototype.macro = __webpack_require__(43); Collection.prototype.map = __webpack_require__(44); Collection.prototype.mapSpread = __webpack_require__(45); Collection.prototype.mapToDictionary = __webpack_require__(46); Collection.prototype.mapInto = __webpack_require__(47); Collection.prototype.mapToGroups = __webpack_require__(48); Collection.prototype.mapWithKeys = __webpack_require__(49); Collection.prototype.max = __webpack_require__(50); Collection.prototype.median = __webpack_require__(51); Collection.prototype.merge = __webpack_require__(52); Collection.prototype.min = __webpack_require__(53); Collection.prototype.mode = __webpack_require__(54); Collection.prototype.nth = __webpack_require__(55); Collection.prototype.only = __webpack_require__(56); Collection.prototype.pad = __webpack_require__(57); Collection.prototype.partition = __webpack_require__(59); Collection.prototype.pipe = __webpack_require__(60); Collection.prototype.pluck = __webpack_require__(61); Collection.prototype.pop = __webpack_require__(62); Collection.prototype.prepend = __webpack_require__(63); Collection.prototype.pull = __webpack_require__(64); Collection.prototype.push = __webpack_require__(65); Collection.prototype.put = __webpack_require__(66); Collection.prototype.random = __webpack_require__(67); Collection.prototype.reduce = __webpack_require__(68); Collection.prototype.reject = __webpack_require__(69); Collection.prototype.reverse = __webpack_require__(70); Collection.prototype.search = __webpack_require__(71); Collection.prototype.shift = __webpack_require__(72); Collection.prototype.shuffle = __webpack_require__(73); Collection.prototype.slice = __webpack_require__(74); Collection.prototype.sort = __webpack_require__(75); Collection.prototype.sortBy = __webpack_require__(76); Collection.prototype.sortByDesc = __webpack_require__(77); Collection.prototype.splice = __webpack_require__(78); Collection.prototype.split = __webpack_require__(79); Collection.prototype.sum = __webpack_require__(80); Collection.prototype.take = __webpack_require__(81); Collection.prototype.tap = __webpack_require__(82); Collection.prototype.times = __webpack_require__(83); Collection.prototype.toArray = __webpack_require__(84); Collection.prototype.toJson = __webpack_require__(85); Collection.prototype.transform = __webpack_require__(86); Collection.prototype.unless = __webpack_require__(87); Collection.prototype.union = __webpack_require__(88); Collection.prototype.unique = __webpack_require__(89); Collection.prototype.unwrap = __webpack_require__(90); Collection.prototype.values = __webpack_require__(91); Collection.prototype.when = __webpack_require__(92); Collection.prototype.where = __webpack_require__(93); Collection.prototype.whereIn = __webpack_require__(94); Collection.prototype.whereNotIn = __webpack_require__(95); Collection.prototype.wrap = __webpack_require__(96); Collection.prototype.zip = __webpack_require__(97); var collect = function collect(collection) { return new Collection(collection); }; module.exports = collect; module.exports.default = collect; /***/ }), /* 5 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function SymbolIterator() { var _this = this; var index = -1; return { next: function next() { index += 1; return { value: _this.items[index], done: index >= _this.items.length }; } }; }; /***/ }), /* 6 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function all() { return this.items; }; /***/ }), /* 7 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; module.exports = function chunk(size) { var _this = this; var chunks = []; var index = 0; if (Array.isArray(this.items)) { do { var items = this.items.slice(index, index + size); var collection = new this.constructor(items); chunks.push(collection); index += size; } while (index < this.items.length); } else if (_typeof(this.items) === 'object') { var keys = Object.keys(this.items); var _loop = function _loop() { var keysOfChunk = keys.slice(index, index + size); var collection = new _this.constructor({}); keysOfChunk.forEach(function (key) { return collection.put(key, _this.items[key]); }); chunks.push(collection); index += size; }; do { _loop(); } while (index < keys.length); } else { chunks.push(new this.constructor([this.items])); } return new this.constructor(chunks); }; /***/ }), /* 8 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } module.exports = function collapse() { var _ref; return new this.constructor((_ref = []).concat.apply(_ref, _toConsumableArray(this.items))); }; /***/ }), /* 9 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; module.exports = function combine(array) { var _this = this; var values = array; if (values instanceof this.constructor) { values = array.all(); } var collection = {}; if (Array.isArray(this.items) && Array.isArray(values)) { this.items.forEach(function (key, iterator) { collection[key] = values[iterator]; }); } else if (_typeof(this.items) === 'object' && (typeof values === 'undefined' ? 'undefined' : _typeof(values)) === 'object') { Object.keys(this.items).forEach(function (key, index) { collection[_this.items[key]] = values[Object.keys(values)[index]]; }); } else if (Array.isArray(this.items)) { collection[this.items[0]] = values; } else if (typeof this.items === 'string' && Array.isArray(values)) { collection[this.items] = values[0]; } else if (typeof this.items === 'string') { collection[this.items] = values; } return new this.constructor(collection); }; /***/ }), /* 10 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; module.exports = function concat(collectionOrArrayOrObject) { var _this = this; var list = collectionOrArrayOrObject; if (collectionOrArrayOrObject instanceof this.constructor) { list = collectionOrArrayOrObject.all(); } else if ((typeof collectionOrArrayOrObject === 'undefined' ? 'undefined' : _typeof(collectionOrArrayOrObject)) === 'object') { list = []; Object.keys(collectionOrArrayOrObject).forEach(function (property) { list.push(collectionOrArrayOrObject[property]); }); } list.forEach(function (item) { if ((typeof item === 'undefined' ? 'undefined' : _typeof(item)) === 'object') { Object.keys(item).forEach(function (key) { return _this.items.push(item[key]); }); } else { _this.items.push(item); } }); return this; }; /***/ }), /* 11 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } var values = __webpack_require__(0); module.exports = function contains(key, value) { if (value !== undefined) { if (Array.isArray(this.items)) { return this.items.filter(function (items) { return items[key] !== undefined && items[key] === value; }).length > 0; } return this.items[key] !== undefined && this.items[key] === value; } if (typeof key === 'function') { return this.items.filter(function (item, index) { return key(item, index); }).length > 0; } if (Array.isArray(this.items)) { return this.items.indexOf(key) !== -1; } var keysAndValues = values(this.items); keysAndValues.push.apply(keysAndValues, _toConsumableArray(Object.keys(this.items))); return keysAndValues.indexOf(key) !== -1; }; /***/ }), /* 12 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function count() { if (Array.isArray(this.items)) { return this.items.length; } return Object.keys(this.items).length; }; /***/ }), /* 13 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function crossJoin() { function join(collection, constructor, args) { var current = args[0]; if (current instanceof constructor) { current = current.all(); } var rest = args.slice(1); var last = !rest.length; var result = []; for (var i = 0; i < current.length; i += 1) { var collectionCopy = collection.slice(); collectionCopy.push(current[i]); if (last) { result.push(collectionCopy); } else { result = result.concat(join(collectionCopy, constructor, rest)); } } return result; } for (var _len = arguments.length, values = Array(_len), _key = 0; _key < _len; _key++) { values[_key] = arguments[_key]; } return new this.constructor(join([], this.constructor, [].concat([this.items], values))); }; /***/ }), /* 14 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(process) { module.exports = function dd() { this.dump(); if (typeof process !== 'undefined') { process.exit(1); } }; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(15))) /***/ }), /* 15 */ /***/ (function(module, exports) { // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.prependListener = noop; process.prependOnceListener = noop; process.listeners = function (name) { return [] } process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; /***/ }), /* 16 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function diff(values) { var valuesToDiff = void 0; if (values instanceof this.constructor) { valuesToDiff = values.all(); } else { valuesToDiff = values; } var collection = this.items.filter(function (item) { return valuesToDiff.indexOf(item) === -1; }); return new this.constructor(collection); }; /***/ }), /* 17 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function diffAssoc(values) { var _this = this; var diffValues = values; if (values instanceof this.constructor) { diffValues = values.all(); } var collection = {}; Object.keys(this.items).forEach(function (key) { if (diffValues[key] === undefined || diffValues[key] !== _this.items[key]) { collection[key] = _this.items[key]; } }); return new this.constructor(collection); }; /***/ }), /* 18 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function diffKeys(object) { var objectToDiff = void 0; if (object instanceof this.constructor) { objectToDiff = object.all(); } else { objectToDiff = object; } var objectKeys = Object.keys(objectToDiff); var remainingKeys = Object.keys(this.items).filter(function (item) { return objectKeys.indexOf(item) === -1; }); return new this.constructor(this.items).only(remainingKeys); }; /***/ }), /* 19 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function dump() { // eslint-disable-next-line console.log(this); return this; }; /***/ }), /* 20 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function each(fn) { var _this = this; if (Array.isArray(this.items)) { this.items.forEach(fn); } else { Object.keys(this.items).forEach(function (key) { fn(_this.items[key], key, _this.items); }); } return this; }; /***/ }), /* 21 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } module.exports = function eachSpread(fn) { this.each(function (values, key) { fn.apply(undefined, _toConsumableArray(values).concat([key])); }); return this; }; /***/ }), /* 22 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var values = __webpack_require__(0); module.exports = function every(fn) { var items = values(this.items); return items.map(function (item, index) { return fn(item, index); }).indexOf(false) === -1; }; /***/ }), /* 23 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var variadic = __webpack_require__(2); module.exports = function except() { var _this = this; for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var properties = variadic(args); if (Array.isArray(this.items)) { var _collection = this.items.filter(function (item) { return properties.indexOf(item) === -1; }); return new this.constructor(_collection); } var collection = {}; Object.keys(this.items).forEach(function (property) { if (properties.indexOf(property) === -1) { collection[property] = _this.items[property]; } }); return new this.constructor(collection); }; /***/ }), /* 24 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; function falsyValue(item) { if (Array.isArray(item)) { if (item.length) { return false; } } else if (item !== undefined && item !== null && (typeof item === 'undefined' ? 'undefined' : _typeof(item)) === 'object') { if (Object.keys(item).length) { return false; } } else if (item) { return false; } return true; } function filterObject(func, items) { var result = {}; Object.keys(items).forEach(function (key) { if (func) { if (func(items[key], key)) { result[key] = items[key]; } } else if (!falsyValue(items[key])) { result[key] = items[key]; } }); return result; } function filterArray(func, items) { if (func) { return items.filter(func); } var result = []; for (var i = 0; i < items.length; i += 1) { var item = items[i]; if (!falsyValue(item)) { result.push(item); } } return result; } module.exports = function filter(fn) { var func = fn || false; var filteredItems = null; if (Array.isArray(this.items)) { filteredItems = filterArray(func, this.items); } else { filteredItems = filterObject(func, this.items); } return new this.constructor(filteredItems); }; /***/ }), /* 25 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function first(fn, defaultValue) { if (typeof fn === 'function') { for (var i = 0, length = this.items.length; i < length; i += 1) { var item = this.items[i]; if (fn(item)) { return item; } } if (typeof defaultValue === 'function') { return defaultValue(); } return defaultValue; } if (Array.isArray(this.items) && this.items.length || Object.keys(this.items).length) { if (Array.isArray(this.items)) { return this.items[0]; } var firstKey = Object.keys(this.items)[0]; return this.items[firstKey]; } if (typeof defaultValue === 'function') { return defaultValue(); } return defaultValue; }; /***/ }), /* 26 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function firstWhere(key, value) { return this.where(key, value).first() || null; }; /***/ }), /* 27 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function flatMap(fn) { var items = []; this.items.forEach(function (childObject, index) { var keys = Object.keys(childObject); var values = []; keys.forEach(function (prop) { values.push(childObject[prop]); }); var mapped = fn(values, index); var collection = {}; keys.forEach(function (key, i) { collection[key] = mapped[i]; }); items.push(collection); }); return new this.constructor(Object.assign.apply(Object, items)); }; /***/ }), /* 28 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; module.exports = function flatten(depth) { var flattenDepth = depth || Infinity; var fullyFlattened = false; var collection = []; var flat = function flat(items) { collection = []; if (Array.isArray(items)) { items.forEach(function (item) { if (typeof item === 'string') { collection.push(item); } else if (Array.isArray(item)) { collection = collection.concat(item); } else { Object.keys(item).forEach(function (property) { collection = collection.concat(item[property]); }); } }); } else { Object.keys(items).forEach(function (property) { if (typeof items[property] === 'string') { collection.push(items[property]); } else if (Array.isArray(items[property])) { collection = collection.concat(items[property]); } else { Object.keys(items).forEach(function (prop) { collection = collection.concat(items[prop]); }); } }); } fullyFlattened = collection.filter(function (item) { return (typeof item === 'undefined' ? 'undefined' : _typeof(item)) === 'object'; }); fullyFlattened = fullyFlattened.length === 0; flattenDepth -= 1; }; flat(this.items); while (!fullyFlattened && flattenDepth > 0) { flat(collection); } return new this.constructor(collection); }; /***/ }), /* 29 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function flip() { var _this = this; var collection = {}; if (Array.isArray(this.items)) { Object.keys(this.items).forEach(function (key) { collection[_this.items[key]] = Number(key); }); } else { Object.keys(this.items).forEach(function (key) { collection[_this.items[key]] = key; }); } return new this.constructor(collection); }; /***/ }), /* 30 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function forPage(page, chunk) { var _this = this; var collection = {}; if (Array.isArray(this.items)) { collection = this.items.slice(page * chunk - chunk, page * chunk); } else { Object.keys(this.items).slice(page * chunk - chunk, page * chunk).forEach(function (key) { collection[key] = _this.items[key]; }); } return new this.constructor(collection); }; /***/ }), /* 31 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function forget(key) { if (Array.isArray(this.items)) { this.items.splice(key, 1); } else { delete this.items[key]; } return this; }; /***/ }), /* 32 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function get(key) { var defaultValue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; if (this.items[key] !== undefined) { return this.items[key]; } if (typeof defaultValue === 'function') { return defaultValue(); } if (defaultValue !== null) { return defaultValue; } return null; }; /***/ }), /* 33 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function groupBy(key) { var _this = this; var collection = {}; this.items.forEach(function (item, index) { var resolvedKey = void 0; if (typeof key === 'function') { resolvedKey = key(item, index); } else { resolvedKey = item[key] || ''; } if (collection[resolvedKey] === undefined) { collection[resolvedKey] = new _this.constructor([]); } collection[resolvedKey].push(item); }); return new this.constructor(collection); }; /***/ }), /* 34 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var variadic = __webpack_require__(2); module.exports = function has() { var _this = this; for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var properties = variadic(args); return properties.filter(function (key) { return _this.items[key]; }).length === properties.length; }; /***/ }), /* 35 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function implode(key, glue) { if (glue === undefined) { return this.items.join(key); } return new this.constructor(this.items).pluck(key).all().join(glue); }; /***/ }), /* 36 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function intersect(values) { var intersectValues = values; if (values instanceof this.constructor) { intersectValues = values.all(); } var collection = this.items.filter(function (item) { return intersectValues.indexOf(item) !== -1; }); return new this.constructor(collection); }; /***/ }), /* 37 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function intersectByKeys(values) { var _this = this; var intersectKeys = Object.keys(values); if (values instanceof this.constructor) { intersectKeys = Object.keys(values.all()); } var collection = {}; Object.keys(this.items).forEach(function (key) { if (intersectKeys.indexOf(key) !== -1) { collection[key] = _this.items[key]; } }); return new this.constructor(collection); }; /***/ }), /* 38 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function isEmpty() { return !this.items.length; }; /***/ }), /* 39 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function isNotEmpty() { return !!this.items.length; }; /***/ }), /* 40 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function keyBy(key) { var collection = {}; if (typeof key === 'function') { this.items.forEach(function (item) { collection[key(item)] = item; }); } else { this.items.forEach(function (item) { collection[item[key] || ''] = item; }); } return new this.constructor(collection); }; /***/ }), /* 41 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function keys() { var collection = Object.keys(this.items); if (Array.isArray(this.items)) { collection = collection.map(Number); } return new this.constructor(collection); }; /***/ }), /* 42 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function last(fn, defaultValue) { var items = this.items; if (typeof fn === 'function') { items = this.filter(fn).all(); } if (Array.isArray(items) && !items.length || !Object.keys(items).length) { if (typeof defaultValue === 'function') { return defaultValue(); } return defaultValue; } if (Array.isArray(items)) { return items[items.length - 1]; } var keys = Object.keys(items); return items[keys[keys.length - 1]]; }; /***/ }), /* 43 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function macro(name, fn) { this.constructor.prototype[name] = fn; }; /***/ }), /* 44 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function map(fn) { var _this = this; if (Array.isArray(this.items)) { return new this.constructor(this.items.map(fn)); } var collection = {}; Object.keys(this.items).forEach(function (key) { collection[key] = fn(_this.items[key], key); }); return new this.constructor(collection); }; /***/ }), /* 45 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } module.exports = function mapSpread(fn) { return this.map(function (values, key) { return fn.apply(undefined, _toConsumableArray(values).concat([key])); }); }; /***/ }), /* 46 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); module.exports = function mapToDictionary(fn) { var collection = {}; this.items.forEach(function (item, k) { var _fn = fn(item, k), _fn2 = _slicedToArray(_fn, 2), key = _fn2[0], value = _fn2[1]; if (collection[key] === undefined) { collection[key] = [value]; } else { collection[key].push(value); } }); return new this.constructor(collection); }; /***/ }), /* 47 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function mapInto(ClassName) { return this.map(function (value, key) { return new ClassName(value, key); }); }; /***/ }), /* 48 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); module.exports = function mapToGroups(fn) { var collection = {}; this.items.forEach(function (item, key) { var _fn = fn(item, key), _fn2 = _slicedToArray(_fn, 2), keyed = _fn2[0], value = _fn2[1]; if (collection[keyed] === undefined) { collection[keyed] = [value]; } else { collection[keyed].push(value); } }); return new this.constructor(collection); }; /***/ }), /* 49 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); module.exports = function mapWithKeys(fn) { var _this = this; var collection = {}; if (Array.isArray(this.items)) { this.items.forEach(function (item) { var _fn = fn(item), _fn2 = _slicedToArray(_fn, 2), keyed = _fn2[0], value = _fn2[1]; collection[keyed] = value; }); } else { Object.keys(this.items).forEach(function (key) { var _fn3 = fn(_this.items[key]), _fn4 = _slicedToArray(_fn3, 2), keyed = _fn4[0], value = _fn4[1]; collection[keyed] = value; }); } return new this.constructor(collection); }; /***/ }), /* 50 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } module.exports = function max(key) { if (typeof key === 'string') { return Math.max.apply(Math, _toConsumableArray(this.pluck(key).all())); } return Math.max.apply(Math, _toConsumableArray(this.items)); }; /***/ }), /* 51 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function median(key) { var length = this.items.length; if (key === undefined) { if (length % 2 === 0) { return (this.items[length / 2 - 1] + this.items[length / 2]) / 2; } return this.items[Math.floor(length / 2)]; } if (length % 2 === 0) { return (this.items[length / 2 - 1][key] + this.items[length / 2][key]) / 2; } return this.items[Math.floor(length / 2)][key]; }; /***/ }), /* 52 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function merge(value) { var arrayOrObject = value; if (typeof arrayOrObject === 'string') { arrayOrObject = [arrayOrObject]; } if (Array.isArray(this.items) && Array.isArray(arrayOrObject)) { return new this.constructor(this.items.concat(arrayOrObject)); } var collection = JSON.parse(JSON.stringify(this.items)); Object.keys(arrayOrObject).forEach(function (key) { collection[key] = arrayOrObject[key]; }); return new this.constructor(collection); }; /***/ }), /* 53 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } module.exports = function min(key) { if (key !== undefined) { return Math.min.apply(Math, _toConsumableArray(this.pluck(key).all())); } return Math.min.apply(Math, _toConsumableArray(this.items)); }; /***/ }), /* 54 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function mode(key) { var values = []; var highestCount = 1; if (!this.items.length) { return null; } this.items.forEach(function (item) { var tempValues = values.filter(function (value) { if (key !== undefined) { return value.key === item[key]; } return value.key === item; }); if (!tempValues.length) { if (key !== undefined) { values.push({ key: item[key], count: 1 }); } else { values.push({ key: item, count: 1 }); } } else { tempValues[0].count += 1; var count = tempValues[0].count; if (count > highestCount) { highestCount = count; } } }); return values.filter(function (value) { return value.count === highestCount; }).map(function (value) { return value.key; }); }; /***/ }), /* 55 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var values = __webpack_require__(0); module.exports = function nth(n) { var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; var items = values(this.items); var collection = items.slice(offset).filter(function (item, index) { return index % n === 0; }); return new this.constructor(collection); }; /***/ }), /* 56 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var variadic = __webpack_require__(2); module.exports = function only() { var _this = this; for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var properties = variadic(args); if (Array.isArray(this.items)) { var _collection = this.items.filter(function (item) { return properties.indexOf(item) !== -1; }); return new this.constructor(_collection); } var collection = {}; Object.keys(this.items).forEach(function (prop) { if (properties.indexOf(prop) !== -1) { collection[prop] = _this.items[prop]; } }); return new this.constructor(collection); }; /***/ }), /* 57 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var clone = __webpack_require__(58); module.exports = function pad(size, value) { var abs = Math.abs(size); var count = this.count(); if (abs <= count) { return this; } var diff = abs - count; var items = clone(this.items); var isArray = Array.isArray(this.items); var prepend = size < 0; for (var iterator = 0; iterator < diff;) { if (!isArray) { if (items[iterator] !== undefined) { diff += 1; } else { items[iterator] = value; } } else if (prepend) { items.unshift(value); } else { items.push(value); } iterator += 1; } return new this.constructor(items); }; /***/ }), /* 58 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Clone helper * * Clone an array or object * * @param items * @returns {*} */ function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } module.exports = function clone(items) { var cloned = void 0; if (Array.isArray(items)) { var _cloned; cloned = []; (_cloned = cloned).push.apply(_cloned, _toConsumableArray(items)); } else { cloned = {}; Object.keys(items).forEach(function (prop) { cloned[prop] = items[prop]; }); } return cloned; }; /***/ }), /* 59 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function partition(fn) { var _this = this; var arrays = void 0; if (Array.isArray(this.items)) { arrays = [new this.constructor([]), new this.constructor([])]; this.items.forEach(function (item) { if (fn(item) === true) { arrays[0].push(item); } else { arrays[1].push(item); } }); } else { arrays = [new this.constructor({}), new this.constructor({})]; Object.keys(this.items).forEach(function (prop) { var value = _this.items[prop]; if (fn(value) === true) { arrays[0].put(prop, value); } else { arrays[1].put(prop, value); } }); } return new this.constructor(arrays); }; /***/ }), /* 60 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function pipe(fn) { return fn(this); }; /***/ }), /* 61 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var nestedValue = __webpack_require__(1); var buildKeyPathMap = function buildKeyPathMap(items) { var keyPaths = {}; items.forEach(function (item, index) { function buildKeyPath(val, keyPath) { if ((typeof val === 'undefined' ? 'undefined' : _typeof(val)) === 'object') { Object.keys(val).forEach(function (prop) { buildKeyPath(val[prop], keyPath + '.' + prop); }); } keyPaths[keyPath] = val; } buildKeyPath(item, index); }); return keyPaths; }; module.exports = function pluck(value, key) { if (value.indexOf('*') !== -1) { var keyPathMap = buildKeyPathMap(this.items); var keyMatches = []; if (key !== undefined) { var keyRegex = new RegExp('0.' + key, 'g'); var keyNumberOfLevels = ('0.' + key).split('.').length; Object.keys(keyPathMap).forEach(function (k) { var matchingKey = k.match(keyRegex); if (matchingKey) { var match = matchingKey[0]; if (match.split('.').length === keyNumberOfLevels) { keyMatches.push(keyPathMap[match]); } } }); } var valueMatches = []; var valueRegex = new RegExp('0.' + value, 'g'); var valueNumberOfLevels = ('0.' + value).split('.').length; Object.keys(keyPathMap).forEach(function (k) { var matchingValue = k.match(valueRegex); if (matchingValue) { var match = matchingValue[0]; if (match.split('.').length === valueNumberOfLevels) { valueMatches.push(keyPathMap[match]); } } }); if (key !== undefined) { var collection = {}; this.items.forEach(function (item, index) { collection[keyMatches[index] || ''] = valueMatches; }); return new this.constructor(collection); } return new this.constructor([valueMatches]); } if (key !== undefined) { var _collection = {}; this.items.forEach(function (item) { if (nestedValue(item, value) !== undefined) { _collection[item[key] || ''] = nestedValue(item, value); } else { _collection[item[key] || ''] = null; } }); return new this.constructor(_collection); } return this.map(function (item) { if (nestedValue(item, value) !== undefined) { return nestedValue(item, value); } return null; }); }; /***/ }), /* 62 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function pop() { if (Array.isArray(this.items)) { return this.items.pop(); } var keys = Object.keys(this.items); var key = keys[keys.length - 1]; var last = this.items[key]; delete this.items[key]; return last; }; /***/ }), /* 63 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function prepend(value, key) { if (key !== undefined) { return this.put(key, value); } this.items.unshift(value); return this; }; /***/ }), /* 64 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function pull(key, defaultValue) { var returnValue = this.items[key] || null; if (!returnValue && defaultValue !== undefined) { if (typeof defaultValue === 'function') { returnValue = defaultValue(); } else { returnValue = defaultValue; } } delete this.items[key]; return returnValue; }; /***/ }), /* 65 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function push() { var _items; (_items = this.items).push.apply(_items, arguments); return this; }; /***/ }), /* 66 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function put(key, value) { this.items[key] = value; return this; }; /***/ }), /* 67 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var values = __webpack_require__(0); module.exports = function random() { var length = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1; var items = values(this.items); var collection = new this.constructor(items).shuffle(); if (length === 1) { return collection.first(); } return collection.take(length); }; /***/ }), /* 68 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function reduce(fn, carry) { var _this = this; var reduceCarry = null; if (carry !== undefined) { reduceCarry = carry; } if (Array.isArray(this.items)) { this.items.forEach(function (item) { reduceCarry = fn(reduceCarry, item); }); } else { Object.keys(this.items).forEach(function (key) { reduceCarry = fn(reduceCarry, _this.items[key], key); }); } return reduceCarry; }; /***/ }), /* 69 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function reject(fn) { return new this.constructor(this.items.filter(function (item) { return !fn(item); })); }; /***/ }), /* 70 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function reverse() { var collection = [].concat(this.items).reverse(); return new this.constructor(collection); }; /***/ }), /* 71 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function search(valueOrFunction, strict) { var _this = this; var valueFn = valueOrFunction; if (typeof valueOrFunction === 'function') { valueFn = this.items.filter(function (value, key) { return valueOrFunction(value, key); })[0]; } var index = false; if (Array.isArray(this.items)) { var itemKey = this.items.filter(function (item) { if (strict === true) { return item === valueFn; } return item === Number(valueFn) || item === valueFn.toString(); })[0]; index = this.items.indexOf(itemKey); } else { return Object.keys(this.items).filter(function (prop) { if (strict === true) { return _this.items[prop] === valueFn; } return _this.items[prop] === Number(valueFn) || _this.items[prop] === valueFn.toString(); })[0] || false; } if (index === -1) { return false; } return index; }; /***/ }), /* 72 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function shift() { if (Array.isArray(this.items)) { return this.items.shift(); } var key = Object.keys(this.items)[0]; var value = this.items[key] || null; delete this.items[key]; return value; }; /***/ }), /* 73 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var values = __webpack_require__(0); module.exports = function shuffle() { var items = values(this.items); var j = void 0; var x = void 0; var i = void 0; for (i = items.length; i; i -= 1) { j = Math.floor(Math.random() * i); x = items[i - 1]; items[i - 1] = items[j]; items[j] = x; } this.items = items; return this; }; /***/ }), /* 74 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function slice(remove, limit) { var collection = this.items.slice(remove); if (limit !== undefined) { collection = collection.slice(0, limit); } return new this.constructor(collection); }; /***/ }), /* 75 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function sort(fn) { var collection = [].concat(this.items); if (fn === undefined) { if (this.every(function (item) { return typeof item === 'number'; })) { collection.sort(function (a, b) { return a - b; }); } else { collection.sort(); } } else { collection.sort(fn); } return new this.constructor(collection); }; /***/ }), /* 76 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function sortBy(valueOrFunction) { var collection = [].concat(this.items); if (typeof valueOrFunction === 'function') { collection.sort(function (a, b) { if (valueOrFunction(a) < valueOrFunction(b)) return -1; if (valueOrFunction(a) > valueOrFunction(b)) return 1; return 0; }); } else { collection.sort(function (a, b) { if (a[valueOrFunction] < b[valueOrFunction]) return -1; if (a[valueOrFunction] > b[valueOrFunction]) return 1; return 0; }); } return new this.constructor(collection); }; /***/ }), /* 77 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function sortByDesc(valueOrFunction) { return this.sortBy(valueOrFunction).reverse(); }; /***/ }), /* 78 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function splice(index, limit, replace) { var slicedCollection = this.slice(index, limit); this.items = this.diff(slicedCollection.all()).all(); if (Array.isArray(replace)) { for (var iterator = 0, length = replace.length; iterator < length; iterator += 1) { this.items.splice(index + iterator, 0, replace[iterator]); } } return slicedCollection; }; /***/ }), /* 79 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function split(numberOfGroups) { var itemsPerGroup = Math.round(this.items.length / numberOfGroups); var items = JSON.parse(JSON.stringify(this.items)); var collection = []; for (var iterator = 0; iterator < numberOfGroups; iterator += 1) { collection.push(new this.constructor(items.splice(0, itemsPerGroup))); } return new this.constructor(collection); }; /***/ }), /* 80 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function sum(key) { var total = 0; if (key === undefined) { for (var i = 0, length = this.items.length; i < length; i += 1) { total += this.items[i]; } } else if (typeof key === 'function') { for (var _i = 0, _length = this.items.length; _i < _length; _i += 1) { total += key(this.items[_i]); } } else { for (var _i2 = 0, _length2 = this.items.length; _i2 < _length2; _i2 += 1) { total += this.items[_i2][key]; } } return total; }; /***/ }), /* 81 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; module.exports = function take(length) { var _this = this; if (!Array.isArray(this.items) && _typeof(this.items) === 'object') { var keys = Object.keys(this.items); var slicedKeys = void 0; if (length < 0) { slicedKeys = keys.slice(length); } else { slicedKeys = keys.slice(0, length); } var collection = {}; keys.forEach(function (prop) { if (slicedKeys.indexOf(prop) !== -1) { collection[prop] = _this.items[prop]; } }); return new this.constructor(collection); } if (length < 0) { return new this.constructor(this.items.slice(length)); } return new this.constructor(this.items.slice(0, length)); }; /***/ }), /* 82 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function tap(fn) { fn(this); return this; }; /***/ }), /* 83 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function times(n, fn) { for (var iterator = 1; iterator <= n; iterator += 1) { this.items.push(fn(iterator)); } return this; }; /***/ }), /* 84 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function toArray() { var collectionInstance = this.constructor; function iterate(list, collection) { var childCollection = []; if (list instanceof collectionInstance) { list.items.forEach(function (i) { return iterate(i, childCollection); }); collection.push(childCollection); } else if (Array.isArray(list)) { list.forEach(function (i) { return iterate(i, childCollection); }); collection.push(childCollection); } else { collection.push(list); } } if (Array.isArray(this.items)) { var collection = []; this.items.forEach(function (items) { iterate(items, collection); }); return collection; } return this.values().all(); }; /***/ }), /* 85 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function toJson() { return JSON.stringify(this.toArray()); }; /***/ }), /* 86 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function transform(fn) { var _this = this; if (Array.isArray(this.items)) { this.items = this.items.map(fn); } else { var collection = {}; Object.keys(this.items).forEach(function (key) { collection[key] = fn(_this.items[key], key); }); this.items = collection; } return this; }; /***/ }), /* 87 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function when(value, fn, defaultFn) { if (!value) { fn(this); } else { defaultFn(this); } }; /***/ }), /* 88 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function union(object) { var _this = this; var collection = JSON.parse(JSON.stringify(this.items)); Object.keys(object).forEach(function (prop) { if (_this.items[prop] === undefined) { collection[prop] = object[prop]; } }); return new this.constructor(collection); }; /***/ }), /* 89 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function unique(key) { var collection = void 0; if (key === undefined) { collection = this.items.filter(function (element, index, self) { return self.indexOf(element) === index; }); } else { collection = []; var usedKeys = []; for (var iterator = 0, length = this.items.length; iterator < length; iterator += 1) { var uniqueKey = void 0; if (typeof key === 'function') { uniqueKey = key(this.items[iterator]); } else { uniqueKey = this.items[iterator][key]; } if (usedKeys.indexOf(uniqueKey) === -1) { collection.push(this.items[iterator]); usedKeys.push(uniqueKey); } } } return new this.constructor(collection); }; /***/ }), /* 90 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function unwrap(value) { if (value instanceof this.constructor) { return value.all(); } return value; }; /***/ }), /* 91 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function values() { var _this = this; var collection = []; Object.keys(this.items).forEach(function (property) { collection.push(_this.items[property]); }); return new this.constructor(collection); }; /***/ }), /* 92 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function when(value, fn, defaultFn) { if (value) { fn(this); } else { defaultFn(this); } }; /***/ }), /* 93 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var values = __webpack_require__(0); var nestedValue = __webpack_require__(1); module.exports = function where(key, operator, value) { var comparisonOperator = operator; var comparisonValue = value; if (value === undefined) { comparisonValue = operator; comparisonOperator = '==='; } var items = values(this.items); var collection = items.filter(function (item) { switch (comparisonOperator) { case '==': return nestedValue(item, key) === Number(comparisonValue) || nestedValue(item, key) === comparisonValue.toString(); default: case '===': return nestedValue(item, key) === comparisonValue; case '!=': case '<>': return nestedValue(item, key) !== Number(comparisonValue) && nestedValue(item, key) !== comparisonValue.toString(); case '!==': return nestedValue(item, key) !== comparisonValue; case '<': return nestedValue(item, key) < comparisonValue; case '<=': return nestedValue(item, key) <= comparisonValue; case '>': return nestedValue(item, key) > comparisonValue; case '>=': return nestedValue(item, key) >= comparisonValue; } }); return new this.constructor(collection); }; /***/ }), /* 94 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var extractValues = __webpack_require__(0); var nestedValue = __webpack_require__(1); module.exports = function whereIn(key, values) { var items = extractValues(values); var collection = this.items.filter(function (item) { return items.indexOf(nestedValue(item, key)) !== -1; }); return new this.constructor(collection); }; /***/ }), /* 95 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var extractValues = __webpack_require__(0); var nestedValue = __webpack_require__(1); module.exports = function whereNotIn(key, values) { var items = extractValues(values); var collection = this.items.filter(function (item) { return items.indexOf(nestedValue(item, key)) === -1; }); return new this.constructor(collection); }; /***/ }), /* 96 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; module.exports = function wrap(value) { if (value instanceof this.constructor) { return value; } if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object') { return new this.constructor(value); } return new this.constructor([value]); }; /***/ }), /* 97 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function zip(array) { var _this = this; var values = array; if (values instanceof this.constructor) { values = values.all(); } var collection = this.items.map(function (item, index) { return new _this.constructor([item, values[index]]); }); return new this.constructor(collection); }; /***/ }) /******/ ]);
mit
tejaswi2492/pmip6ns3.13new
src/uan/model/uan-prop-model.cc
7925
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2009 University of Washington * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Leonard Tracy <[email protected]> */ #include "uan-prop-model.h" #include "ns3/nstime.h" #include <complex> #include <vector> namespace ns3 { std::ostream & operator<< (std::ostream &os, UanPdp &pdp) { os << pdp.GetNTaps () << '|'; os << pdp.GetResolution ().GetSeconds () << '|'; UanPdp::Iterator it = pdp.m_taps.begin (); for (; it != pdp.m_taps.end (); it++) { os << (*it).GetAmp () << '|'; } return os; } std::istream & operator>> (std::istream &is, UanPdp &pdp) { uint32_t ntaps; double resolution; char c1; is >> ntaps >> c1; if (c1 != '|') { NS_FATAL_ERROR ("UanPdp data corrupted at # of taps"); return is; } is >> resolution >> c1; if (c1 != '|') { NS_FATAL_ERROR ("UanPdp data corrupted at resolution"); return is; } pdp.m_resolution = Seconds (resolution); std::complex<double> amp; pdp.m_taps = std::vector<Tap> (ntaps); for (uint32_t i = 0; i < ntaps; i++) { is >> amp >> c1; if (c1 != '|') { NS_FATAL_ERROR ("UanPdp data corrupted at tap " << i); return is; } pdp.m_taps[i] = Tap (Seconds (resolution * i), amp); } return is; } Tap::Tap () : m_amplitude (0.0), m_delay (Seconds (0)) { } Tap::Tap (Time delay, std::complex<double> amp) : m_amplitude (amp), m_delay (delay) { } std::complex<double> Tap::GetAmp (void) const { return m_amplitude; } Time Tap::GetDelay (void) const { return m_delay; } UanPdp::UanPdp () { } UanPdp::UanPdp (std::vector<Tap> taps, Time resolution) : m_taps (taps), m_resolution (resolution) { } UanPdp::UanPdp (std::vector<std::complex<double> > amps, Time resolution) : m_resolution (resolution) { m_taps.resize (amps.size ()); Time arrTime = Seconds (0); for (uint32_t index = 0; index < amps.size (); index++) { m_taps[index] = Tap (arrTime, amps[index]); arrTime = arrTime + m_resolution; } } UanPdp::UanPdp (std::vector<double> amps, Time resolution) : m_resolution (resolution) { m_taps.resize (amps.size ()); Time arrTime = Seconds (0); for (uint32_t index = 0; index < amps.size (); index++) { m_taps[index] = Tap (arrTime, amps[index]); arrTime = arrTime + m_resolution; } } UanPdp::~UanPdp () { m_taps.clear (); } void UanPdp::SetTap (std::complex<double> amp, uint32_t index) { if (m_taps.size () <= index) { m_taps.resize (index + 1); } Time delay = Seconds (index * m_resolution.GetSeconds ()); m_taps[index] = Tap (delay, amp); } const Tap & UanPdp::GetTap (uint32_t i) const { NS_ASSERT_MSG (i < GetNTaps (), "Call to UanPdp::GetTap with requested tap out of range"); return m_taps[i]; } void UanPdp::SetNTaps (uint32_t nTaps) { m_taps.resize (nTaps); } void UanPdp::SetResolution (Time resolution) { m_resolution = resolution; } UanPdp::Iterator UanPdp::GetBegin (void) const { return m_taps.begin (); } UanPdp::Iterator UanPdp::GetEnd (void) const { return m_taps.end (); } uint32_t UanPdp::GetNTaps (void) const { return m_taps.size (); } Time UanPdp::GetResolution (void) const { return m_resolution; } std::complex<double> UanPdp::SumTapsFromMaxC (Time delay, Time duration) const { if (m_resolution <= Seconds (0)) { NS_ASSERT_MSG (GetNTaps () == 1, "Attempted to sum taps over time interval in " "UanPdp with resolution 0 and multiple taps"); return m_taps[0].GetAmp (); } uint32_t numTaps = static_cast<uint32_t> (duration.GetSeconds () / m_resolution.GetSeconds () + 0.5); double maxAmp = -1; uint32_t maxTapIndex = 0; for (uint32_t i = 0; i < GetNTaps (); i++) { if (abs (m_taps[i].GetAmp ()) > maxAmp) { maxAmp = abs (m_taps[i].GetAmp ()); maxTapIndex = i; } } uint32_t start = maxTapIndex + static_cast<uint32_t> (delay.GetSeconds () / m_resolution.GetSeconds ()); uint32_t end = std::min (start + numTaps, GetNTaps ()); std::complex<double> sum = 0; for (uint32_t i = start; i < end; i++) { sum += m_taps[i].GetAmp (); } return sum; } double UanPdp::SumTapsFromMaxNc (Time delay, Time duration) const { if (m_resolution <= Seconds (0)) { NS_ASSERT_MSG (GetNTaps () == 1, "Attempted to sum taps over time interval in " "UanPdp with resolution 0 and multiple taps"); return abs (m_taps[0].GetAmp ()); } uint32_t numTaps = static_cast<uint32_t> (duration.GetSeconds () / m_resolution.GetSeconds () + 0.5); double maxAmp = -1; uint32_t maxTapIndex = 0; for (uint32_t i = 0; i < GetNTaps (); i++) { if (abs (m_taps[i].GetAmp ()) > maxAmp) { maxAmp = abs (m_taps[i].GetAmp ()); maxTapIndex = i; } } uint32_t start = maxTapIndex + static_cast<uint32_t> (delay.GetSeconds () / m_resolution.GetSeconds ()); uint32_t end = std::min (start + numTaps, GetNTaps ()); double sum = 0; for (uint32_t i = start; i < end; i++) { sum += abs (m_taps[i].GetAmp ()); } return sum; } double UanPdp::SumTapsNc (Time begin, Time end) const { if (m_resolution <= Seconds (0)) { NS_ASSERT_MSG (GetNTaps () == 1, "Attempted to sum taps over time interval in " "UanPdp with resolution 0 and multiple taps"); if (begin <= Seconds (0.0) && end >= Seconds (0.0)) { return abs (m_taps[0].GetAmp ()); } else { return 0.0; } } uint32_t stIndex = (uint32_t)(begin.GetSeconds () / m_resolution.GetSeconds () + 0.5); uint32_t endIndex = (uint32_t)(end.GetSeconds () / m_resolution.GetSeconds () + 0.5); endIndex = std::min (endIndex, GetNTaps ()); double sum = 0; for (uint32_t i = stIndex; i < endIndex; i++) { sum += abs (m_taps[i].GetAmp ()); } return sum; } std::complex<double> UanPdp::SumTapsC (Time begin, Time end) const { if (m_resolution <= Seconds (0)) { NS_ASSERT_MSG (GetNTaps () == 1, "Attempted to sum taps over time interval in " "UanPdp with resolution 0 and multiple taps"); if (begin <= Seconds (0.0) && end >= Seconds (0.0)) { return m_taps[0].GetAmp (); } else { return std::complex<double> (0.0); } } uint32_t stIndex = (uint32_t)(begin.GetSeconds () / m_resolution.GetSeconds () + 0.5); uint32_t endIndex = (uint32_t)(end.GetSeconds () / m_resolution.GetSeconds () + 0.5); endIndex = std::min (endIndex, GetNTaps ()); std::complex<double> sum = 0; for (uint32_t i = stIndex; i < endIndex; i++) { sum += m_taps[i].GetAmp (); } return sum; } UanPdp UanPdp::CreateImpulsePdp (void) { UanPdp pdp; pdp.SetResolution (Seconds (0)); pdp.SetTap (1.0,0); return pdp; } NS_OBJECT_ENSURE_REGISTERED (UanPropModel); TypeId UanPropModel::GetTypeId (void) { static TypeId tid = TypeId ("ns3::UanPropModel") .SetParent<Object> (); return tid; } void UanPropModel::Clear (void) { } void UanPropModel::DoDispose (void) { Clear (); Object::DoDispose (); } }
gpl-2.0
rajuniit/chotrobazaar
lib/Zend/Feed/Reader/Feed/Rss.php
21753
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to [email protected] so we can send you a copy immediately. * * @category Zend * @package Zend_Feed_Reader * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: Rss.php 23170 2010-10-19 18:29:24Z mabe $ */ /** * @see Zend_Feed_Reader_FeedAbstract */ #require_once 'Zend/Feed/Reader/FeedAbstract.php'; /** * @see Zend_feed_Reader_Extension_Atom_Feed */ #require_once 'Zend/Feed/Reader/Extension/Atom/Feed.php'; /** * @see Zend_Feed_Reader_Extension_DublinCore_Feed */ #require_once 'Zend/Feed/Reader/Extension/DublinCore/Feed.php'; /** * @see Zend_Date */ #require_once 'Zend/Date.php'; /** * @see Zend_Feed_Reader_Collection_Author */ #require_once 'Zend/Feed/Reader/Collection/Author.php'; /** * @category Zend * @package Zend_Feed_Reader * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Feed_Reader_Feed_Rss extends Zend_Feed_Reader_FeedAbstract { /** * Constructor * * @param DOMDocument $dom * @param string $type */ public function __construct(DomDocument $dom, $type = null) { parent::__construct($dom, $type); $dublinCoreClass = Zend_Feed_Reader::getPluginLoader()->getClassName('DublinCore_Feed'); $this->_extensions['DublinCore_Feed'] = new $dublinCoreClass($dom, $this->_data['type'], $this->_xpath); $atomClass = Zend_Feed_Reader::getPluginLoader()->getClassName('Atom_Feed'); $this->_extensions['Atom_Feed'] = new $atomClass($dom, $this->_data['type'], $this->_xpath); if ($this->getType() !== Zend_Feed_Reader::TYPE_RSS_10 && $this->getType() !== Zend_Feed_Reader::TYPE_RSS_090) { $xpathPrefix = '/rss/channel'; } else { $xpathPrefix = '/rdf:RDF/rss:channel'; } foreach ($this->_extensions as $extension) { $extension->setXpathPrefix($xpathPrefix); } } /** * Get a single author * * @param int $index * @return string|null */ public function getAuthor($index = 0) { $authors = $this->getAuthors(); if (isset($authors[$index])) { return $authors[$index]; } return null; } /** * Get an array with feed authors * * @return array */ public function getAuthors() { if (array_key_exists('authors', $this->_data)) { return $this->_data['authors']; } $authors = array(); $authors_dc = $this->getExtension('DublinCore')->getAuthors(); if (!empty($authors_dc)) { foreach ($authors_dc as $author) { $authors[] = array( 'name' => $author['name'] ); } } /** * Technically RSS doesn't specific author element use at the feed level * but it's supported on a "just in case" basis. */ if ($this->getType() !== Zend_Feed_Reader::TYPE_RSS_10 && $this->getType() !== Zend_Feed_Reader::TYPE_RSS_090) { $list = $this->_xpath->query('//author'); } else { $list = $this->_xpath->query('//rss:author'); } if ($list->length) { foreach ($list as $author) { $string = trim($author->nodeValue); $email = null; $name = null; $data = array(); // Pretty rough parsing - but it's a catchall if (preg_match("/^.*@[^ ]*/", $string, $matches)) { $data['email'] = trim($matches[0]); if (preg_match("/\((.*)\)$/", $string, $matches)) { $data['name'] = $matches[1]; } $authors[] = $data; } } } if (count($authors) == 0) { $authors = $this->getExtension('Atom')->getAuthors(); } else { $authors = new Zend_Feed_Reader_Collection_Author( Zend_Feed_Reader::arrayUnique($authors) ); } if (count($authors) == 0) { $authors = null; } $this->_data['authors'] = $authors; return $this->_data['authors']; } /** * Get the copyright entry * * @return string|null */ public function getCopyright() { if (array_key_exists('copyright', $this->_data)) { return $this->_data['copyright']; } $copyright = null; if ($this->getType() !== Zend_Feed_Reader::TYPE_RSS_10 && $this->getType() !== Zend_Feed_Reader::TYPE_RSS_090) { $copyright = $this->_xpath->evaluate('string(/rss/channel/copyright)'); } if (!$copyright && $this->getExtension('DublinCore') !== null) { $copyright = $this->getExtension('DublinCore')->getCopyright(); } if (empty($copyright)) { $copyright = $this->getExtension('Atom')->getCopyright(); } if (!$copyright) { $copyright = null; } $this->_data['copyright'] = $copyright; return $this->_data['copyright']; } /** * Get the feed creation date * * @return string|null */ public function getDateCreated() { return $this->getDateModified(); } /** * Get the feed modification date * * @return Zend_Date */ public function getDateModified() { if (array_key_exists('datemodified', $this->_data)) { return $this->_data['datemodified']; } $dateModified = null; $date = null; if ($this->getType() !== Zend_Feed_Reader::TYPE_RSS_10 && $this->getType() !== Zend_Feed_Reader::TYPE_RSS_090) { $dateModified = $this->_xpath->evaluate('string(/rss/channel/pubDate)'); if (!$dateModified) { $dateModified = $this->_xpath->evaluate('string(/rss/channel/lastBuildDate)'); } if ($dateModified) { $dateModifiedParsed = strtotime($dateModified); if ($dateModifiedParsed) { $date = new Zend_Date($dateModifiedParsed); } else { $dateStandards = array(Zend_Date::RSS, Zend_Date::RFC_822, Zend_Date::RFC_2822, Zend_Date::DATES); $date = new Zend_Date; foreach ($dateStandards as $standard) { try { $date->set($dateModified, $standard); break; } catch (Zend_Date_Exception $e) { if ($standard == Zend_Date::DATES) { #require_once 'Zend/Feed/Exception.php'; throw new Zend_Feed_Exception( 'Could not load date due to unrecognised' .' format (should follow RFC 822 or 2822):' . $e->getMessage(), 0, $e ); } } } } } } if (!$date) { $date = $this->getExtension('DublinCore')->getDate(); } if (!$date) { $date = $this->getExtension('Atom')->getDateModified(); } if (!$date) { $date = null; } $this->_data['datemodified'] = $date; return $this->_data['datemodified']; } /** * Get the feed lastBuild date * * @return Zend_Date */ public function getLastBuildDate() { if (array_key_exists('lastBuildDate', $this->_data)) { return $this->_data['lastBuildDate']; } $lastBuildDate = null; $date = null; if ($this->getType() !== Zend_Feed_Reader::TYPE_RSS_10 && $this->getType() !== Zend_Feed_Reader::TYPE_RSS_090) { $lastBuildDate = $this->_xpath->evaluate('string(/rss/channel/lastBuildDate)'); if ($lastBuildDate) { $lastBuildDateParsed = strtotime($lastBuildDate); if ($lastBuildDateParsed) { $date = new Zend_Date($lastBuildDateParsed); } else { $dateStandards = array(Zend_Date::RSS, Zend_Date::RFC_822, Zend_Date::RFC_2822, Zend_Date::DATES); $date = new Zend_Date; foreach ($dateStandards as $standard) { try { $date->set($lastBuildDate, $standard); break; } catch (Zend_Date_Exception $e) { if ($standard == Zend_Date::DATES) { #require_once 'Zend/Feed/Exception.php'; throw new Zend_Feed_Exception( 'Could not load date due to unrecognised' .' format (should follow RFC 822 or 2822):' . $e->getMessage(), 0, $e ); } } } } } } if (!$date) { $date = null; } $this->_data['lastBuildDate'] = $date; return $this->_data['lastBuildDate']; } /** * Get the feed description * * @return string|null */ public function getDescription() { if (array_key_exists('description', $this->_data)) { return $this->_data['description']; } $description = null; if ($this->getType() !== Zend_Feed_Reader::TYPE_RSS_10 && $this->getType() !== Zend_Feed_Reader::TYPE_RSS_090) { $description = $this->_xpath->evaluate('string(/rss/channel/description)'); } else { $description = $this->_xpath->evaluate('string(/rdf:RDF/rss:channel/rss:description)'); } if (!$description && $this->getExtension('DublinCore') !== null) { $description = $this->getExtension('DublinCore')->getDescription(); } if (empty($description)) { $description = $this->getExtension('Atom')->getDescription(); } if (!$description) { $description = null; } $this->_data['description'] = $description; return $this->_data['description']; } /** * Get the feed ID * * @return string|null */ public function getId() { if (array_key_exists('id', $this->_data)) { return $this->_data['id']; } $id = null; if ($this->getType() !== Zend_Feed_Reader::TYPE_RSS_10 && $this->getType() !== Zend_Feed_Reader::TYPE_RSS_090) { $id = $this->_xpath->evaluate('string(/rss/channel/guid)'); } if (!$id && $this->getExtension('DublinCore') !== null) { $id = $this->getExtension('DublinCore')->getId(); } if (empty($id)) { $id = $this->getExtension('Atom')->getId(); } if (!$id) { if ($this->getLink()) { $id = $this->getLink(); } elseif ($this->getTitle()) { $id = $this->getTitle(); } else { $id = null; } } $this->_data['id'] = $id; return $this->_data['id']; } /** * Get the feed image data * * @return array|null */ public function getImage() { if (array_key_exists('image', $this->_data)) { return $this->_data['image']; } if ($this->getType() !== Zend_Feed_Reader::TYPE_RSS_10 && $this->getType() !== Zend_Feed_Reader::TYPE_RSS_090) { $list = $this->_xpath->query('/rss/channel/image'); $prefix = '/rss/channel/image[1]'; } else { $list = $this->_xpath->query('/rdf:RDF/rss:channel/rss:image'); $prefix = '/rdf:RDF/rss:channel/rss:image[1]'; } if ($list->length > 0) { $image = array(); $value = $this->_xpath->evaluate('string(' . $prefix . '/url)'); if ($value) { $image['uri'] = $value; } $value = $this->_xpath->evaluate('string(' . $prefix . '/link)'); if ($value) { $image['link'] = $value; } $value = $this->_xpath->evaluate('string(' . $prefix . '/title)'); if ($value) { $image['title'] = $value; } $value = $this->_xpath->evaluate('string(' . $prefix . '/height)'); if ($value) { $image['height'] = $value; } $value = $this->_xpath->evaluate('string(' . $prefix . '/width)'); if ($value) { $image['width'] = $value; } $value = $this->_xpath->evaluate('string(' . $prefix . '/description)'); if ($value) { $image['description'] = $value; } } else { $image = null; } $this->_data['image'] = $image; return $this->_data['image']; } /** * Get the feed language * * @return string|null */ public function getLanguage() { if (array_key_exists('language', $this->_data)) { return $this->_data['language']; } $language = null; if ($this->getType() !== Zend_Feed_Reader::TYPE_RSS_10 && $this->getType() !== Zend_Feed_Reader::TYPE_RSS_090) { $language = $this->_xpath->evaluate('string(/rss/channel/language)'); } if (!$language && $this->getExtension('DublinCore') !== null) { $language = $this->getExtension('DublinCore')->getLanguage(); } if (empty($language)) { $language = $this->getExtension('Atom')->getLanguage(); } if (!$language) { $language = $this->_xpath->evaluate('string(//@xml:lang[1])'); } if (!$language) { $language = null; } $this->_data['language'] = $language; return $this->_data['language']; } /** * Get a link to the feed * * @return string|null */ public function getLink() { if (array_key_exists('link', $this->_data)) { return $this->_data['link']; } $link = null; if ($this->getType() !== Zend_Feed_Reader::TYPE_RSS_10 && $this->getType() !== Zend_Feed_Reader::TYPE_RSS_090) { $link = $this->_xpath->evaluate('string(/rss/channel/link)'); } else { $link = $this->_xpath->evaluate('string(/rdf:RDF/rss:channel/rss:link)'); } if (empty($link)) { $link = $this->getExtension('Atom')->getLink(); } if (!$link) { $link = null; } $this->_data['link'] = $link; return $this->_data['link']; } /** * Get a link to the feed XML * * @return string|null */ public function getFeedLink() { if (array_key_exists('feedlink', $this->_data)) { return $this->_data['feedlink']; } $link = null; $link = $this->getExtension('Atom')->getFeedLink(); if ($link === null || empty($link)) { $link = $this->getOriginalSourceUri(); } $this->_data['feedlink'] = $link; return $this->_data['feedlink']; } /** * Get the feed generator entry * * @return string|null */ public function getGenerator() { if (array_key_exists('generator', $this->_data)) { return $this->_data['generator']; } $generator = null; if ($this->getType() !== Zend_Feed_Reader::TYPE_RSS_10 && $this->getType() !== Zend_Feed_Reader::TYPE_RSS_090) { $generator = $this->_xpath->evaluate('string(/rss/channel/generator)'); } if (!$generator) { if ($this->getType() !== Zend_Feed_Reader::TYPE_RSS_10 && $this->getType() !== Zend_Feed_Reader::TYPE_RSS_090) { $generator = $this->_xpath->evaluate('string(/rss/channel/atom:generator)'); } else { $generator = $this->_xpath->evaluate('string(/rdf:RDF/rss:channel/atom:generator)'); } } if (empty($generator)) { $generator = $this->getExtension('Atom')->getGenerator(); } if (!$generator) { $generator = null; } $this->_data['generator'] = $generator; return $this->_data['generator']; } /** * Get the feed title * * @return string|null */ public function getTitle() { if (array_key_exists('title', $this->_data)) { return $this->_data['title']; } $title = null; if ($this->getType() !== Zend_Feed_Reader::TYPE_RSS_10 && $this->getType() !== Zend_Feed_Reader::TYPE_RSS_090) { $title = $this->_xpath->evaluate('string(/rss/channel/title)'); } else { $title = $this->_xpath->evaluate('string(/rdf:RDF/rss:channel/rss:title)'); } if (!$title && $this->getExtension('DublinCore') !== null) { $title = $this->getExtension('DublinCore')->getTitle(); } if (!$title) { $title = $this->getExtension('Atom')->getTitle(); } if (!$title) { $title = null; } $this->_data['title'] = $title; return $this->_data['title']; } /** * Get an array of any supported Pusubhubbub endpoints * * @return array|null */ public function getHubs() { if (array_key_exists('hubs', $this->_data)) { return $this->_data['hubs']; } $hubs = $this->getExtension('Atom')->getHubs(); if (empty($hubs)) { $hubs = null; } else { $hubs = array_unique($hubs); } $this->_data['hubs'] = $hubs; return $this->_data['hubs']; } /** * Get all categories * * @return Zend_Feed_Reader_Collection_Category */ public function getCategories() { if (array_key_exists('categories', $this->_data)) { return $this->_data['categories']; } if ($this->getType() !== Zend_Feed_Reader::TYPE_RSS_10 && $this->getType() !== Zend_Feed_Reader::TYPE_RSS_090) { $list = $this->_xpath->query('/rss/channel//category'); } else { $list = $this->_xpath->query('/rdf:RDF/rss:channel//rss:category'); } if ($list->length) { $categoryCollection = new Zend_Feed_Reader_Collection_Category; foreach ($list as $category) { $categoryCollection[] = array( 'term' => $category->nodeValue, 'scheme' => $category->getAttribute('domain'), 'label' => $category->nodeValue, ); } } else { $categoryCollection = $this->getExtension('DublinCore')->getCategories(); } if (count($categoryCollection) == 0) { $categoryCollection = $this->getExtension('Atom')->getCategories(); } $this->_data['categories'] = $categoryCollection; return $this->_data['categories']; } /** * Read all entries to the internal entries array * */ protected function _indexEntries() { $entries = array(); if ($this->getType() !== Zend_Feed_Reader::TYPE_RSS_10 && $this->getType() !== Zend_Feed_Reader::TYPE_RSS_090) { $entries = $this->_xpath->evaluate('//item'); } else { $entries = $this->_xpath->evaluate('//rss:item'); } foreach($entries as $index=>$entry) { $this->_entries[$index] = $entry; } } /** * Register the default namespaces for the current feed format * */ protected function _registerNamespaces() { switch ($this->_data['type']) { case Zend_Feed_Reader::TYPE_RSS_10: $this->_xpath->registerNamespace('rdf', Zend_Feed_Reader::NAMESPACE_RDF); $this->_xpath->registerNamespace('rss', Zend_Feed_Reader::NAMESPACE_RSS_10); break; case Zend_Feed_Reader::TYPE_RSS_090: $this->_xpath->registerNamespace('rdf', Zend_Feed_Reader::NAMESPACE_RDF); $this->_xpath->registerNamespace('rss', Zend_Feed_Reader::NAMESPACE_RSS_090); break; } } }
gpl-2.0
rukhshanda/moodle-anmc
lib/yuilib/3.7.3/build/model/model.js
33359
/* YUI 3.7.3 (build 5687) Copyright 2012 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('model', function (Y, NAME) { /** Attribute-based data model with APIs for getting, setting, validating, and syncing attribute values, as well as events for being notified of model changes. @module app @submodule model @since 3.4.0 **/ /** Attribute-based data model with APIs for getting, setting, validating, and syncing attribute values, as well as events for being notified of model changes. In most cases, you'll want to create your own subclass of `Y.Model` and customize it to meet your needs. In particular, the `sync()` and `validate()` methods are meant to be overridden by custom implementations. You may also want to override the `parse()` method to parse non-generic server responses. @class Model @constructor @extends Base @since 3.4.0 **/ var GlobalEnv = YUI.namespace('Env.Model'), Lang = Y.Lang, YArray = Y.Array, YObject = Y.Object, /** Fired when one or more attributes on this model are changed. @event change @param {Object} changed Hash of change information for each attribute that changed. Each item in the hash has the following properties: @param {Any} changed.newVal New value of the attribute. @param {Any} changed.prevVal Previous value of the attribute. @param {String|null} changed.src Source of the change event, if any. **/ EVT_CHANGE = 'change', /** Fired when an error occurs, such as when the model doesn't validate or when a sync layer response can't be parsed. @event error @param {Any} error Error message, object, or exception generated by the error. Calling `toString()` on this should result in a meaningful error message. @param {String} src Source of the error. May be one of the following (or any custom error source defined by a Model subclass): * `load`: An error loading the model from a sync layer. The sync layer's response (if any) will be provided as the `response` property on the event facade. * `parse`: An error parsing a JSON response. The response in question will be provided as the `response` property on the event facade. * `save`: An error saving the model to a sync layer. The sync layer's response (if any) will be provided as the `response` property on the event facade. * `validate`: The model failed to validate. The attributes being validated will be provided as the `attributes` property on the event facade. **/ EVT_ERROR = 'error', /** Fired after model attributes are loaded from a sync layer. @event load @param {Object} parsed The parsed version of the sync layer's response to the load request. @param {any} response The sync layer's raw, unparsed response to the load request. @since 3.5.0 **/ EVT_LOAD = 'load', /** Fired after model attributes are saved to a sync layer. @event save @param {Object} [parsed] The parsed version of the sync layer's response to the save request, if there was a response. @param {any} [response] The sync layer's raw, unparsed response to the save request, if there was one. @since 3.5.0 **/ EVT_SAVE = 'save'; function Model() { Model.superclass.constructor.apply(this, arguments); } Y.Model = Y.extend(Model, Y.Base, { // -- Public Properties ---------------------------------------------------- /** Hash of attributes that have changed since the last time this model was saved. @property changed @type Object @default {} **/ /** Name of the attribute to use as the unique id (or primary key) for this model. The default is `id`, but if your persistence layer uses a different name for the primary key (such as `_id` or `uid`), you can specify that here. The built-in `id` attribute will always be an alias for whatever attribute name you specify here, so getting and setting `id` will always behave the same as getting and setting your custom id attribute. @property idAttribute @type String @default `'id'` **/ idAttribute: 'id', /** Hash of attributes that were changed in the last `change` event. Each item in this hash is an object with the following properties: * `newVal`: The new value of the attribute after it changed. * `prevVal`: The old value of the attribute before it changed. * `src`: The source of the change, or `null` if no source was specified. @property lastChange @type Object @default {} **/ /** Array of `ModelList` instances that contain this model. When a model is in one or more lists, the model's events will bubble up to those lists. You can subscribe to a model event on a list to be notified when any model in the list fires that event. This property is updated automatically when this model is added to or removed from a `ModelList` instance. You shouldn't alter it manually. When working with models in a list, you should always add and remove models using the list's `add()` and `remove()` methods. @example Subscribing to model events on a list: // Assuming `list` is an existing Y.ModelList instance. list.on('*:change', function (e) { // This function will be called whenever any model in the list // fires a `change` event. // // `e.target` will refer to the model instance that fired the // event. }); @property lists @type ModelList[] @default `[]` **/ // -- Protected Properties ------------------------------------------------- /** This tells `Y.Base` that it should create ad-hoc attributes for config properties passed to Model's constructor. This makes it possible to instantiate a model and set a bunch of attributes without having to subclass `Y.Model` and declare all those attributes first. @property _allowAdHocAttrs @type Boolean @default true @protected @since 3.5.0 **/ _allowAdHocAttrs: true, /** Total hack to allow us to identify Model instances without using `instanceof`, which won't work when the instance was created in another window or YUI sandbox. @property _isYUIModel @type Boolean @default true @protected @since 3.5.0 **/ _isYUIModel: true, // -- Lifecycle Methods ---------------------------------------------------- initializer: function (config) { this.changed = {}; this.lastChange = {}; this.lists = []; }, // -- Public Methods ------------------------------------------------------- /** Destroys this model instance and removes it from its containing lists, if any. The _callback_, if one is provided, will be called after the model is destroyed. If `options.remove` is `true`, then this method delegates to the `sync()` method to delete the model from the persistence layer, which is an asynchronous action. In this case, the _callback_ (if provided) will be called after the sync layer indicates success or failure of the delete operation. @method destroy @param {Object} [options] Sync options. It's up to the custom sync implementation to determine what options it supports or requires, if any. @param {Boolean} [options.remove=false] If `true`, the model will be deleted via the sync layer in addition to the instance being destroyed. @param {callback} [callback] Called after the model has been destroyed (and deleted via the sync layer if `options.remove` is `true`). @param {Error|null} callback.err If an error occurred, this parameter will contain the error. Otherwise _err_ will be `null`. @chainable **/ destroy: function (options, callback) { var self = this; // Allow callback as only arg. if (typeof options === 'function') { callback = options; options = null; } self.onceAfter('destroy', function () { function finish(err) { if (!err) { YArray.each(self.lists.concat(), function (list) { list.remove(self, options); }); } callback && callback.apply(null, arguments); } if (options && (options.remove || options['delete'])) { self.sync('delete', options, finish); } else { finish(); } }); return Model.superclass.destroy.call(self); }, /** Returns a clientId string that's unique among all models on the current page (even models in other YUI instances). Uniqueness across pageviews is unlikely. @method generateClientId @return {String} Unique clientId. **/ generateClientId: function () { GlobalEnv.lastId || (GlobalEnv.lastId = 0); return this.constructor.NAME + '_' + (GlobalEnv.lastId += 1); }, /** Returns the value of the specified attribute. If the attribute's value is an object, _name_ may use dot notation to specify the path to a specific property within the object, and the value of that property will be returned. @example // Set the 'foo' attribute to an object. myModel.set('foo', { bar: { baz: 'quux' } }); // Get the value of 'foo'. myModel.get('foo'); // => {bar: {baz: 'quux'}} // Get the value of 'foo.bar.baz'. myModel.get('foo.bar.baz'); // => 'quux' @method get @param {String} name Attribute name or object property path. @return {Any} Attribute value, or `undefined` if the attribute doesn't exist. **/ // get() is defined by Y.Attribute. /** Returns an HTML-escaped version of the value of the specified string attribute. The value is escaped using `Y.Escape.html()`. @method getAsHTML @param {String} name Attribute name or object property path. @return {String} HTML-escaped attribute value. **/ getAsHTML: function (name) { var value = this.get(name); return Y.Escape.html(Lang.isValue(value) ? String(value) : ''); }, /** Returns a URL-encoded version of the value of the specified string attribute. The value is encoded using the native `encodeURIComponent()` function. @method getAsURL @param {String} name Attribute name or object property path. @return {String} URL-encoded attribute value. **/ getAsURL: function (name) { var value = this.get(name); return encodeURIComponent(Lang.isValue(value) ? String(value) : ''); }, /** Returns `true` if any attribute of this model has been changed since the model was last saved. New models (models for which `isNew()` returns `true`) are implicitly considered to be "modified" until the first time they're saved. @method isModified @return {Boolean} `true` if this model has changed since it was last saved, `false` otherwise. **/ isModified: function () { return this.isNew() || !YObject.isEmpty(this.changed); }, /** Returns `true` if this model is "new", meaning it hasn't been saved since it was created. Newness is determined by checking whether the model's `id` attribute has been set. An empty id is assumed to indicate a new model, whereas a non-empty id indicates a model that was either loaded or has been saved since it was created. @method isNew @return {Boolean} `true` if this model is new, `false` otherwise. **/ isNew: function () { return !Lang.isValue(this.get('id')); }, /** Loads this model from the server. This method delegates to the `sync()` method to perform the actual load operation, which is an asynchronous action. Specify a _callback_ function to be notified of success or failure. A successful load operation will fire a `load` event, while an unsuccessful load operation will fire an `error` event with the `src` value "load". If the load operation succeeds and one or more of the loaded attributes differ from this model's current attributes, a `change` event will be fired. @method load @param {Object} [options] Options to be passed to `sync()` and to `set()` when setting the loaded attributes. It's up to the custom sync implementation to determine what options it supports or requires, if any. @param {callback} [callback] Called when the sync operation finishes. @param {Error|null} callback.err If an error occurred, this parameter will contain the error. If the sync operation succeeded, _err_ will be `null`. @param {Any} callback.response The server's response. This value will be passed to the `parse()` method, which is expected to parse it and return an attribute hash. @chainable **/ load: function (options, callback) { var self = this; // Allow callback as only arg. if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); self.sync('read', options, function (err, response) { var facade = { options : options, response: response }, parsed; if (err) { facade.error = err; facade.src = 'load'; self.fire(EVT_ERROR, facade); } else { // Lazy publish. if (!self._loadEvent) { self._loadEvent = self.publish(EVT_LOAD, { preventable: false }); } parsed = facade.parsed = self._parse(response); self.setAttrs(parsed, options); self.changed = {}; self.fire(EVT_LOAD, facade); } callback && callback.apply(null, arguments); }); return self; }, /** Called to parse the _response_ when the model is loaded from the server. This method receives a server _response_ and is expected to return an attribute hash. The default implementation assumes that _response_ is either an attribute hash or a JSON string that can be parsed into an attribute hash. If _response_ is a JSON string and either `Y.JSON` or the native `JSON` object are available, it will be parsed automatically. If a parse error occurs, an `error` event will be fired and the model will not be updated. You may override this method to implement custom parsing logic if necessary. @method parse @param {Any} response Server response. @return {Object} Attribute hash. **/ parse: function (response) { if (typeof response === 'string') { try { return Y.JSON.parse(response); } catch (ex) { this.fire(EVT_ERROR, { error : ex, response: response, src : 'parse' }); return null; } } return response; }, /** Saves this model to the server. This method delegates to the `sync()` method to perform the actual save operation, which is an asynchronous action. Specify a _callback_ function to be notified of success or failure. A successful save operation will fire a `save` event, while an unsuccessful save operation will fire an `error` event with the `src` value "save". If the save operation succeeds and one or more of the attributes returned in the server's response differ from this model's current attributes, a `change` event will be fired. @method save @param {Object} [options] Options to be passed to `sync()` and to `set()` when setting synced attributes. It's up to the custom sync implementation to determine what options it supports or requires, if any. @param {Function} [callback] Called when the sync operation finishes. @param {Error|null} callback.err If an error occurred or validation failed, this parameter will contain the error. If the sync operation succeeded, _err_ will be `null`. @param {Any} callback.response The server's response. This value will be passed to the `parse()` method, which is expected to parse it and return an attribute hash. @chainable **/ save: function (options, callback) { var self = this; // Allow callback as only arg. if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); self._validate(self.toJSON(), function (err) { if (err) { callback && callback.call(null, err); return; } self.sync(self.isNew() ? 'create' : 'update', options, function (err, response) { var facade = { options : options, response: response }, parsed; if (err) { facade.error = err; facade.src = 'save'; self.fire(EVT_ERROR, facade); } else { // Lazy publish. if (!self._saveEvent) { self._saveEvent = self.publish(EVT_SAVE, { preventable: false }); } if (response) { parsed = facade.parsed = self._parse(response); self.setAttrs(parsed, options); } self.changed = {}; self.fire(EVT_SAVE, facade); } callback && callback.apply(null, arguments); }); }); return self; }, /** Sets the value of a single attribute. If model validation fails, the attribute will not be set and an `error` event will be fired. Use `setAttrs()` to set multiple attributes at once. @example model.set('foo', 'bar'); @method set @param {String} name Attribute name or object property path. @param {any} value Value to set. @param {Object} [options] Data to be mixed into the event facade of the `change` event(s) for these attributes. @param {Boolean} [options.silent=false] If `true`, no `change` event will be fired. @chainable **/ set: function (name, value, options) { var attributes = {}; attributes[name] = value; return this.setAttrs(attributes, options); }, /** Sets the values of multiple attributes at once. If model validation fails, the attributes will not be set and an `error` event will be fired. @example model.setAttrs({ foo: 'bar', baz: 'quux' }); @method setAttrs @param {Object} attributes Hash of attribute names and values to set. @param {Object} [options] Data to be mixed into the event facade of the `change` event(s) for these attributes. @param {Boolean} [options.silent=false] If `true`, no `change` event will be fired. @chainable **/ setAttrs: function (attributes, options) { var idAttribute = this.idAttribute, changed, e, key, lastChange, transaction; options || (options = {}); transaction = options._transaction = {}; // When a custom id attribute is in use, always keep the default `id` // attribute in sync. if (idAttribute !== 'id') { // So we don't modify someone else's object. attributes = Y.merge(attributes); if (YObject.owns(attributes, idAttribute)) { attributes.id = attributes[idAttribute]; } else if (YObject.owns(attributes, 'id')) { attributes[idAttribute] = attributes.id; } } for (key in attributes) { if (YObject.owns(attributes, key)) { this._setAttr(key, attributes[key], options); } } if (!YObject.isEmpty(transaction)) { changed = this.changed; lastChange = this.lastChange = {}; for (key in transaction) { if (YObject.owns(transaction, key)) { e = transaction[key]; changed[key] = e.newVal; lastChange[key] = { newVal : e.newVal, prevVal: e.prevVal, src : e.src || null }; } } if (!options.silent) { // Lazy publish for the change event. if (!this._changeEvent) { this._changeEvent = this.publish(EVT_CHANGE, { preventable: false }); } this.fire(EVT_CHANGE, Y.merge(options, {changed: lastChange})); } } return this; }, /** Override this method to provide a custom persistence implementation for this model. The default just calls the callback without actually doing anything. This method is called internally by `load()`, `save()`, and `destroy()`. @method sync @param {String} action Sync action to perform. May be one of the following: * `create`: Store a newly-created model for the first time. * `delete`: Delete an existing model. * `read` : Load an existing model. * `update`: Update an existing model. @param {Object} [options] Sync options. It's up to the custom sync implementation to determine what options it supports or requires, if any. @param {Function} [callback] Called when the sync operation finishes. @param {Error|null} callback.err If an error occurred, this parameter will contain the error. If the sync operation succeeded, _err_ will be falsy. @param {Any} [callback.response] The server's response. **/ sync: function (/* action, options, callback */) { var callback = YArray(arguments, 0, true).pop(); if (typeof callback === 'function') { callback(); } }, /** Returns a copy of this model's attributes that can be passed to `Y.JSON.stringify()` or used for other nefarious purposes. The `clientId` attribute is not included in the returned object. If you've specified a custom attribute name in the `idAttribute` property, the default `id` attribute will not be included in the returned object. Note: The ECMAScript 5 specification states that objects may implement a `toJSON` method to provide an alternate object representation to serialize when passed to `JSON.stringify(obj)`. This allows class instances to be serialized as if they were plain objects. This is why Model's `toJSON` returns an object, not a JSON string. See <http://es5.github.com/#x15.12.3> for details. @method toJSON @return {Object} Copy of this model's attributes. **/ toJSON: function () { var attrs = this.getAttrs(); delete attrs.clientId; delete attrs.destroyed; delete attrs.initialized; if (this.idAttribute !== 'id') { delete attrs.id; } return attrs; }, /** Reverts the last change to the model. If an _attrNames_ array is provided, then only the named attributes will be reverted (and only if they were modified in the previous change). If no _attrNames_ array is provided, then all changed attributes will be reverted to their previous values. Note that only one level of undo is available: from the current state to the previous state. If `undo()` is called when no previous state is available, it will simply do nothing. @method undo @param {Array} [attrNames] Array of specific attribute names to revert. If not specified, all attributes modified in the last change will be reverted. @param {Object} [options] Data to be mixed into the event facade of the change event(s) for these attributes. @param {Boolean} [options.silent=false] If `true`, no `change` event will be fired. @chainable **/ undo: function (attrNames, options) { var lastChange = this.lastChange, idAttribute = this.idAttribute, toUndo = {}, needUndo; attrNames || (attrNames = YObject.keys(lastChange)); YArray.each(attrNames, function (name) { if (YObject.owns(lastChange, name)) { // Don't generate a double change for custom id attributes. name = name === idAttribute ? 'id' : name; needUndo = true; toUndo[name] = lastChange[name].prevVal; } }); return needUndo ? this.setAttrs(toUndo, options) : this; }, /** Override this method to provide custom validation logic for this model. While attribute-specific validators can be used to validate individual attributes, this method gives you a hook to validate a hash of all attributes before the model is saved. This method is called automatically before `save()` takes any action. If validation fails, the `save()` call will be aborted. In your validation method, call the provided `callback` function with no arguments to indicate success. To indicate failure, pass a single argument, which may contain an error message, an array of error messages, or any other value. This value will be passed along to the `error` event. @example model.validate = function (attrs, callback) { if (attrs.pie !== true) { // No pie?! Invalid! callback('Must provide pie.'); return; } // Success! callback(); }; @method validate @param {Object} attrs Attribute hash containing all model attributes to be validated. @param {Function} callback Validation callback. Call this function when your validation logic finishes. To trigger a validation failure, pass any value as the first argument to the callback (ideally a meaningful validation error of some kind). @param {Any} [callback.err] Validation error. Don't provide this argument if validation succeeds. If validation fails, set this to an error message or some other meaningful value. It will be passed along to the resulting `error` event. **/ validate: function (attrs, callback) { callback && callback(); }, // -- Protected Methods ---------------------------------------------------- /** Duckpunches the `addAttr` method provided by `Y.Attribute` to keep the `id` attribute’s value and a custom id attribute’s (if provided) value in sync when adding the attributes to the model instance object. Marked as protected to hide it from Model's public API docs, even though this is a public method in Attribute. @method addAttr @param {String} name The name of the attribute. @param {Object} config An object with attribute configuration property/value pairs, specifying the configuration for the attribute. @param {Boolean} lazy (optional) Whether or not to add this attribute lazily (on the first call to get/set). @return {Object} A reference to the host object. @chainable @protected **/ addAttr: function (name, config, lazy) { var idAttribute = this.idAttribute, idAttrCfg, id; if (idAttribute && name === idAttribute) { idAttrCfg = this._isLazyAttr('id') || this._getAttrCfg('id'); id = config.value === config.defaultValue ? null : config.value; if (!Lang.isValue(id)) { // Hunt for the id value. id = idAttrCfg.value === idAttrCfg.defaultValue ? null : idAttrCfg.value; if (!Lang.isValue(id)) { // No id value provided on construction, check defaults. id = Lang.isValue(config.defaultValue) ? config.defaultValue : idAttrCfg.defaultValue; } } config.value = id; // Make sure `id` is in sync. if (idAttrCfg.value !== id) { idAttrCfg.value = id; if (this._isLazyAttr('id')) { this._state.add('id', 'lazy', idAttrCfg); } else { this._state.add('id', 'value', id); } } } return Model.superclass.addAttr.apply(this, arguments); }, /** Calls the public, overrideable `parse()` method and returns the result. Override this method to provide a custom pre-parsing implementation. This provides a hook for custom persistence implementations to "prep" a response before calling the `parse()` method. @method _parse @param {Any} response Server response. @return {Object} Attribute hash. @protected @see Model.parse() @since 3.7.0 **/ _parse: function (response) { return this.parse(response); }, /** Calls the public, overridable `validate()` method and fires an `error` event if validation fails. @method _validate @param {Object} attributes Attribute hash. @param {Function} callback Validation callback. @param {Any} [callback.err] Value on failure, non-value on success. @protected **/ _validate: function (attributes, callback) { var self = this; function handler(err) { if (Lang.isValue(err)) { // Validation failed. Fire an error. self.fire(EVT_ERROR, { attributes: attributes, error : err, src : 'validate' }); callback(err); return; } callback(); } if (self.validate.length === 1) { // Backcompat for 3.4.x-style synchronous validate() functions that // don't take a callback argument. handler(self.validate(attributes, handler)); } else { self.validate(attributes, handler); } }, // -- Protected Event Handlers --------------------------------------------- /** Duckpunches the `_defAttrChangeFn()` provided by `Y.Attribute` so we can have a single global notification when a change event occurs. @method _defAttrChangeFn @param {EventFacade} e @protected **/ _defAttrChangeFn: function (e) { var attrName = e.attrName; if (!this._setAttrVal(attrName, e.subAttrName, e.prevVal, e.newVal)) { // Prevent "after" listeners from being invoked since nothing changed. e.stopImmediatePropagation(); } else { e.newVal = this.get(attrName); if (e._transaction) { e._transaction[attrName] = e; } } } }, { NAME: 'model', ATTRS: { /** A client-only identifier for this model. Like the `id` attribute, `clientId` may be used to retrieve model instances from lists. Unlike the `id` attribute, `clientId` is automatically generated, and is only intended to be used on the client during the current pageview. @attribute clientId @type String @readOnly **/ clientId: { valueFn : 'generateClientId', readOnly: true }, /** A unique identifier for this model. Among other things, this id may be used to retrieve model instances from lists, so it should be unique. If the id is empty, this model instance is assumed to represent a new item that hasn't yet been saved. If you would prefer to use a custom attribute as this model's id instead of using the `id` attribute (for example, maybe you'd rather use `_id` or `uid` as the primary id), you may set the `idAttribute` property to the name of your custom id attribute. The `id` attribute will then act as an alias for your custom attribute. @attribute id @type String|Number|null @default `null` **/ id: {value: null} } }); }, '3.7.3', {"requires": ["base-build", "escape", "json-parse"]});
gpl-3.0
vlinhd11/vlinhd11-android-scripting
android/ScriptingLayerForAndroid/src/org/connectbot/util/EncodingPreference.java
1215
package org.connectbot.util; import android.content.Context; import android.preference.ListPreference; import android.util.AttributeSet; import java.nio.charset.Charset; import java.util.LinkedList; import java.util.List; import java.util.Map.Entry; public class EncodingPreference extends ListPreference { public EncodingPreference(Context context, AttributeSet attrs) { super(context, attrs); List<CharSequence> charsetIdsList = new LinkedList<CharSequence>(); List<CharSequence> charsetNamesList = new LinkedList<CharSequence>(); for (Entry<String, Charset> entry : Charset.availableCharsets().entrySet()) { Charset c = entry.getValue(); if (c.canEncode() && c.isRegistered()) { String key = entry.getKey(); if (key.startsWith("cp")) { // Custom CP437 charset changes charsetIdsList.add("CP437"); charsetNamesList.add("CP437"); } charsetIdsList.add(entry.getKey()); charsetNamesList.add(c.displayName()); } } this.setEntryValues(charsetIdsList.toArray(new CharSequence[charsetIdsList.size()])); this.setEntries(charsetNamesList.toArray(new CharSequence[charsetNamesList.size()])); } }
apache-2.0
sawyer2011/cobar
server/src/test/java/com/alibaba/cobar/queue/Queue.java
5131
/* * Copyright 1999-2012 Alibaba Group. * * 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 com.alibaba.cobar.queue; /** * @author xianmao.hexm */ public final class Queue<T> { private final static int MIN_SHRINK_SIZE = 1024; private T[] items; private int count = 0; private int start = 0, end = 0; private int suggestedSize, size = 0; public Queue(int suggestedSize) { this.size = this.suggestedSize = suggestedSize; items = newArray(this.size); } public Queue() { this(4); } public synchronized void clear() { count = start = end = 0; size = suggestedSize; items = newArray(size); } public synchronized boolean hasElements() { return (count != 0); } public synchronized int size() { return count; } public synchronized void prepend(T item) { if (count == size) { makeMoreRoom(); } if (start == 0) { start = size - 1; } else { start--; } this.items[start] = item; count++; if (count == 1) { notify(); } } public synchronized void append(T item) { append0(item, count == 0); } public synchronized void appendSilent(T item) { append0(item, false); } public synchronized void appendLoud(T item) { append0(item, true); } public synchronized T getNonBlocking() { if (count == 0) { return null; } // pull the object off, and clear our reference to it T retval = items[start]; items[start] = null; start = (start + 1) % size; count--; return retval; } public synchronized void waitForItem() { while (count == 0) { try { wait(); } catch (InterruptedException e) { } } } public synchronized T get(long maxwait) { if (count == 0) { try { wait(maxwait); } catch (InterruptedException e) { } if (count == 0) { return null; } } return get(); } public synchronized T get() { while (count == 0) { try { wait(); } catch (InterruptedException e) { } } // pull the object off, and clear our reference to it T retval = items[start]; items[start] = null; start = (start + 1) % size; count--; // if we are only filling 1/8th of the space, shrink by half if ((size > MIN_SHRINK_SIZE) && (size > suggestedSize) && (count < (size >> 3))) { shrink(); } return retval; } private void append0(T item, boolean notify) { if (count == size) { makeMoreRoom(); } this.items[end] = item; end = (end + 1) % size; count++; if (notify) { notify(); } } private void makeMoreRoom() { T[] items = newArray(size * 2); System.arraycopy(this.items, start, items, 0, size - start); System.arraycopy(this.items, 0, items, size - start, end); start = 0; end = size; size *= 2; this.items = items; } // shrink by half private void shrink() { T[] items = newArray(size / 2); if (start > end) { // the data wraps around System.arraycopy(this.items, start, items, 0, size - start); System.arraycopy(this.items, 0, items, size - start, end + 1); } else { // the data does not wrap around System.arraycopy(this.items, start, items, 0, end - start + 1); } size = size / 2; start = 0; end = count; this.items = items; } @SuppressWarnings("unchecked") private T[] newArray(int size) { return (T[]) new Object[size]; } @Override public String toString() { StringBuilder buf = new StringBuilder(); buf.append("[count=").append(count); buf.append(", size=").append(size); buf.append(", start=").append(start); buf.append(", end=").append(end); buf.append(", elements={"); for (int i = 0; i < count; i++) { int pos = (i + start) % size; if (i > 0) buf.append(", "); buf.append(items[pos]); } buf.append("}]"); return buf.toString(); } }
apache-2.0
khadim-raath/yazzoopa-scraper
application/libraries/paypal_adaptive_payments/vendor/paypal/sdk-core-php/lib/formatters/IPPFormatter.php
492
<?php /** * Interface for all classes that format objects to * and from a on-wire representation * * For every new payload format, write a new formatter * class that implements this interface * */ interface IPPFormatter { /** * * @param PPRequest $request The request to format * @param array $options Any formatter specific options * to be passed in */ public function toString($request, $options=array()); public function toObject($string, $options=array()); }
apache-2.0
sallyom/origin
vendor/github.com/openshift/client-go/config/clientset/versioned/typed/config/v1/operatorhub.go
6087
// Code generated by client-gen. DO NOT EDIT. package v1 import ( "context" "time" v1 "github.com/openshift/api/config/v1" scheme "github.com/openshift/client-go/config/clientset/versioned/scheme" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" rest "k8s.io/client-go/rest" ) // OperatorHubsGetter has a method to return a OperatorHubInterface. // A group's client should implement this interface. type OperatorHubsGetter interface { OperatorHubs() OperatorHubInterface } // OperatorHubInterface has methods to work with OperatorHub resources. type OperatorHubInterface interface { Create(ctx context.Context, operatorHub *v1.OperatorHub, opts metav1.CreateOptions) (*v1.OperatorHub, error) Update(ctx context.Context, operatorHub *v1.OperatorHub, opts metav1.UpdateOptions) (*v1.OperatorHub, error) UpdateStatus(ctx context.Context, operatorHub *v1.OperatorHub, opts metav1.UpdateOptions) (*v1.OperatorHub, error) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error Get(ctx context.Context, name string, opts metav1.GetOptions) (*v1.OperatorHub, error) List(ctx context.Context, opts metav1.ListOptions) (*v1.OperatorHubList, error) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.OperatorHub, err error) OperatorHubExpansion } // operatorHubs implements OperatorHubInterface type operatorHubs struct { client rest.Interface } // newOperatorHubs returns a OperatorHubs func newOperatorHubs(c *ConfigV1Client) *operatorHubs { return &operatorHubs{ client: c.RESTClient(), } } // Get takes name of the operatorHub, and returns the corresponding operatorHub object, and an error if there is any. func (c *operatorHubs) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.OperatorHub, err error) { result = &v1.OperatorHub{} err = c.client.Get(). Resource("operatorhubs"). Name(name). VersionedParams(&options, scheme.ParameterCodec). Do(ctx). Into(result) return } // List takes label and field selectors, and returns the list of OperatorHubs that match those selectors. func (c *operatorHubs) List(ctx context.Context, opts metav1.ListOptions) (result *v1.OperatorHubList, err error) { var timeout time.Duration if opts.TimeoutSeconds != nil { timeout = time.Duration(*opts.TimeoutSeconds) * time.Second } result = &v1.OperatorHubList{} err = c.client.Get(). Resource("operatorhubs"). VersionedParams(&opts, scheme.ParameterCodec). Timeout(timeout). Do(ctx). Into(result) return } // Watch returns a watch.Interface that watches the requested operatorHubs. func (c *operatorHubs) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) { var timeout time.Duration if opts.TimeoutSeconds != nil { timeout = time.Duration(*opts.TimeoutSeconds) * time.Second } opts.Watch = true return c.client.Get(). Resource("operatorhubs"). VersionedParams(&opts, scheme.ParameterCodec). Timeout(timeout). Watch(ctx) } // Create takes the representation of a operatorHub and creates it. Returns the server's representation of the operatorHub, and an error, if there is any. func (c *operatorHubs) Create(ctx context.Context, operatorHub *v1.OperatorHub, opts metav1.CreateOptions) (result *v1.OperatorHub, err error) { result = &v1.OperatorHub{} err = c.client.Post(). Resource("operatorhubs"). VersionedParams(&opts, scheme.ParameterCodec). Body(operatorHub). Do(ctx). Into(result) return } // Update takes the representation of a operatorHub and updates it. Returns the server's representation of the operatorHub, and an error, if there is any. func (c *operatorHubs) Update(ctx context.Context, operatorHub *v1.OperatorHub, opts metav1.UpdateOptions) (result *v1.OperatorHub, err error) { result = &v1.OperatorHub{} err = c.client.Put(). Resource("operatorhubs"). Name(operatorHub.Name). VersionedParams(&opts, scheme.ParameterCodec). Body(operatorHub). Do(ctx). Into(result) return } // UpdateStatus was generated because the type contains a Status member. // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). func (c *operatorHubs) UpdateStatus(ctx context.Context, operatorHub *v1.OperatorHub, opts metav1.UpdateOptions) (result *v1.OperatorHub, err error) { result = &v1.OperatorHub{} err = c.client.Put(). Resource("operatorhubs"). Name(operatorHub.Name). SubResource("status"). VersionedParams(&opts, scheme.ParameterCodec). Body(operatorHub). Do(ctx). Into(result) return } // Delete takes name of the operatorHub and deletes it. Returns an error if one occurs. func (c *operatorHubs) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error { return c.client.Delete(). Resource("operatorhubs"). Name(name). Body(&opts). Do(ctx). Error() } // DeleteCollection deletes a collection of objects. func (c *operatorHubs) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error { var timeout time.Duration if listOpts.TimeoutSeconds != nil { timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second } return c.client.Delete(). Resource("operatorhubs"). VersionedParams(&listOpts, scheme.ParameterCodec). Timeout(timeout). Body(&opts). Do(ctx). Error() } // Patch applies the patch and returns the patched operatorHub. func (c *operatorHubs) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.OperatorHub, err error) { result = &v1.OperatorHub{} err = c.client.Patch(pt). Resource("operatorhubs"). Name(name). SubResource(subresources...). VersionedParams(&opts, scheme.ParameterCodec). Body(data). Do(ctx). Into(result) return }
apache-2.0
aswanderley/phabricator
src/applications/differential/constants/DifferentialRevisionStatus.php
3585
<?php /** * NOTE: you probably want {@class:ArcanistDifferentialRevisionStatus}. * This class just contains a mapping for color within the Differential * application. */ final class DifferentialRevisionStatus extends Phobject { const COLOR_STATUS_DEFAULT = 'status'; const COLOR_STATUS_DARK = 'status-dark'; const COLOR_STATUS_GREEN = 'status-green'; const COLOR_STATUS_RED = 'status-red'; public static function getRevisionStatusColor($status) { $default = self::COLOR_STATUS_DEFAULT; $map = array( ArcanistDifferentialRevisionStatus::NEEDS_REVIEW => self::COLOR_STATUS_DEFAULT, ArcanistDifferentialRevisionStatus::NEEDS_REVISION => self::COLOR_STATUS_RED, ArcanistDifferentialRevisionStatus::CHANGES_PLANNED => self::COLOR_STATUS_RED, ArcanistDifferentialRevisionStatus::ACCEPTED => self::COLOR_STATUS_GREEN, ArcanistDifferentialRevisionStatus::CLOSED => self::COLOR_STATUS_DARK, ArcanistDifferentialRevisionStatus::ABANDONED => self::COLOR_STATUS_DARK, ArcanistDifferentialRevisionStatus::IN_PREPARATION => self::COLOR_STATUS_DARK, ); return idx($map, $status, $default); } public static function getRevisionStatusIcon($status) { $default = 'fa-square-o bluegrey'; $map = array( ArcanistDifferentialRevisionStatus::NEEDS_REVIEW => 'fa-square-o bluegrey', ArcanistDifferentialRevisionStatus::NEEDS_REVISION => 'fa-refresh red', ArcanistDifferentialRevisionStatus::CHANGES_PLANNED => 'fa-headphones red', ArcanistDifferentialRevisionStatus::ACCEPTED => 'fa-check green', ArcanistDifferentialRevisionStatus::CLOSED => 'fa-check-square-o', ArcanistDifferentialRevisionStatus::ABANDONED => 'fa-check-square-o', ArcanistDifferentialRevisionStatus::IN_PREPARATION => 'fa-question-circle blue', ); return idx($map, $status, $default); } public static function renderFullDescription($status) { $color = self::getRevisionStatusColor($status); $status_name = ArcanistDifferentialRevisionStatus::getNameForRevisionStatus($status); $img = id(new PHUIIconView()) ->setIconFont(self::getRevisionStatusIcon($status)); $tag = phutil_tag( 'span', array( 'class' => 'phui-header-status phui-header-'.$color, ), array( $img, $status_name, )); return $tag; } public static function getClosedStatuses() { $statuses = array( ArcanistDifferentialRevisionStatus::CLOSED, ArcanistDifferentialRevisionStatus::ABANDONED, ); if (PhabricatorEnv::getEnvConfig('differential.close-on-accept')) { $statuses[] = ArcanistDifferentialRevisionStatus::ACCEPTED; } return $statuses; } public static function getOpenStatuses() { return array_diff(self::getAllStatuses(), self::getClosedStatuses()); } public static function getAllStatuses() { return array( ArcanistDifferentialRevisionStatus::NEEDS_REVIEW, ArcanistDifferentialRevisionStatus::NEEDS_REVISION, ArcanistDifferentialRevisionStatus::CHANGES_PLANNED, ArcanistDifferentialRevisionStatus::ACCEPTED, ArcanistDifferentialRevisionStatus::CLOSED, ArcanistDifferentialRevisionStatus::ABANDONED, ArcanistDifferentialRevisionStatus::IN_PREPARATION, ); } public static function isClosedStatus($status) { return in_array($status, self::getClosedStatuses()); } }
apache-2.0
ShinichiU/OpenPNE3_with_webInstaller
lib/vendor/symfony/lib/task/generator/sfGenerateProjectTask.class.php
5752
<?php /* * This file is part of the symfony package. * (c) 2004-2006 Fabien Potencier <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ require_once(dirname(__FILE__).'/sfGeneratorBaseTask.class.php'); /** * Generates a new project. * * @package symfony * @subpackage task * @author Fabien Potencier <[email protected]> * @version SVN: $Id: sfGenerateProjectTask.class.php 27211 2010-01-26 20:23:26Z FabianLange $ */ class sfGenerateProjectTask extends sfGeneratorBaseTask { /** * @see sfTask */ protected function doRun(sfCommandManager $commandManager, $options) { $this->process($commandManager, $options); return $this->execute($commandManager->getArgumentValues(), $commandManager->getOptionValues()); } /** * @see sfTask */ protected function configure() { $this->addArguments(array( new sfCommandArgument('name', sfCommandArgument::REQUIRED, 'The project name'), new sfCommandArgument('author', sfCommandArgument::OPTIONAL, 'The project author', 'Your name here'), )); $this->addOptions(array( new sfCommandOption('orm', null, sfCommandOption::PARAMETER_REQUIRED, 'The ORM to use by default', 'Doctrine'), new sfCommandOption('installer', null, sfCommandOption::PARAMETER_REQUIRED, 'An installer script to execute', null), )); $this->namespace = 'generate'; $this->name = 'project'; $this->briefDescription = 'Generates a new project'; $this->detailedDescription = <<<EOF The [generate:project|INFO] task creates the basic directory structure for a new project in the current directory: [./symfony generate:project blog|INFO] If the current directory already contains a symfony project, it throws a [sfCommandException|COMMENT]. By default, the task configures Doctrine as the ORM. If you want to use Propel, use the [--orm|COMMENT] option: [./symfony generate:project blog --orm=Propel|INFO] If you don't want to use an ORM, pass [none|COMMENT] to [--orm|COMMENT] option: [./symfony generate:project blog --orm=none|INFO] You can also pass the [--installer|COMMENT] option to further customize the project: [./symfony generate:project blog --installer=./installer.php|INFO] You can optionally include a second [author|COMMENT] argument to specify what name to use as author when symfony generates new classes: [./symfony generate:project blog "Jack Doe"|INFO] EOF; } /** * @see sfTask */ protected function execute($arguments = array(), $options = array()) { if (file_exists('symfony')) { throw new sfCommandException(sprintf('A symfony project already exists in this directory (%s).', getcwd())); } if (!in_array(strtolower($options['orm']), array('propel', 'doctrine', 'none'))) { throw new InvalidArgumentException(sprintf('Invalid ORM name "%s".', $options['orm'])); } if ($options['installer'] && $this->commandApplication && !file_exists($options['installer'])) { throw new InvalidArgumentException(sprintf('The installer "%s" does not exist.', $options['installer'])); } // clean orm option $options['orm'] = ucfirst(strtolower($options['orm'])); $this->arguments = $arguments; $this->options = $options; // create basic project structure $this->installDir(dirname(__FILE__).'/skeleton/project'); // update ProjectConfiguration class (use a relative path when the symfony core is nested within the project) $symfonyCoreAutoload = 0 === strpos(sfConfig::get('sf_symfony_lib_dir'), sfConfig::get('sf_root_dir')) ? sprintf('dirname(__FILE__).\'/..%s/autoload/sfCoreAutoload.class.php\'', str_replace(sfConfig::get('sf_root_dir'), '', sfConfig::get('sf_symfony_lib_dir'))) : var_export(sfConfig::get('sf_symfony_lib_dir').'/autoload/sfCoreAutoload.class.php', true); $this->replaceTokens(array(sfConfig::get('sf_config_dir')), array('SYMFONY_CORE_AUTOLOAD' => $symfonyCoreAutoload)); $this->tokens = array( 'ORM' => $this->options['orm'], 'PROJECT_NAME' => $this->arguments['name'], 'AUTHOR_NAME' => $this->arguments['author'], 'PROJECT_DIR' => sfConfig::get('sf_root_dir'), ); $this->replaceTokens(); // execute the choosen ORM installer script if (in_array($options['orm'], array('Doctrine', 'Propel'))) { include dirname(__FILE__).'/../../plugins/sf'.$options['orm'].'Plugin/config/installer.php'; } // execute a custom installer if ($options['installer'] && $this->commandApplication) { if ($this->canRunInstaller($options['installer'])) { $this->reloadTasks(); include $options['installer']; } } // fix permission for common directories $fixPerms = new sfProjectPermissionsTask($this->dispatcher, $this->formatter); $fixPerms->setCommandApplication($this->commandApplication); $fixPerms->setConfiguration($this->configuration); $fixPerms->run(); $this->replaceTokens(); } protected function canRunInstaller($installer) { if (preg_match('#^(https?|ftps?)://#', $installer)) { if (ini_get('allow_url_fopen') === false) { $this->logSection('generate', sprintf('Cannot run remote installer "%s" because "allow_url_fopen" is off', $installer)); } if (ini_get('allow_url_include') === false) { $this->logSection('generate', sprintf('Cannot run remote installer "%s" because "allow_url_include" is off', $installer)); } return ini_get('allow_url_fopen') && ini_get('allow_url_include'); } return true; } }
apache-2.0
bottompawn/RakNet
Source/LogCommandParser.cpp
7824
/* * Copyright (c) 2014, Oculus VR, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "NativeFeatureIncludes.h" #if _RAKNET_SUPPORT_LogCommandParser==1 #include "LogCommandParser.h" #include "TransportInterface.h" #include <memory.h> #include <stdio.h> #include <string.h> #include <stdarg.h> #include "LinuxStrings.h" #ifdef _MSC_VER #pragma warning( push ) #endif using namespace RakNet; STATIC_FACTORY_DEFINITIONS(LogCommandParser,LogCommandParser); LogCommandParser::LogCommandParser() { RegisterCommand(CommandParserInterface::VARIABLE_NUMBER_OF_PARAMETERS,"Subscribe","[<ChannelName>] - Subscribes to a named channel, or all channels"); RegisterCommand(CommandParserInterface::VARIABLE_NUMBER_OF_PARAMETERS,"Unsubscribe","[<ChannelName>] - Unsubscribes from a named channel, or all channels"); memset(channelNames,0,sizeof(channelNames)); } LogCommandParser::~LogCommandParser() { } bool LogCommandParser::OnCommand(const char *command, unsigned numParameters, char **parameterList, TransportInterface *transport, const SystemAddress &systemAddress, const char *originalString) { (void) originalString; if (strcmp(command, "Subscribe")==0) { unsigned channelIndex; if (numParameters==0) { Subscribe(systemAddress, 0); transport->Send(systemAddress, "Subscribed to all channels.\r\n"); } else if (numParameters==1) { if ((channelIndex=Subscribe(systemAddress, parameterList[0]))!=(unsigned)-1) { transport->Send(systemAddress, "You are now subscribed to channel %s.\r\n", channelNames[channelIndex]); } else { transport->Send(systemAddress, "Cannot find channel %s.\r\n", parameterList[0]); PrintChannels(systemAddress, transport); } } else { transport->Send(systemAddress, "Subscribe takes either 0 or 1 parameters.\r\n"); } } else if (strcmp(command, "Unsubscribe")==0) { unsigned channelIndex; if (numParameters==0) { Unsubscribe(systemAddress, 0); transport->Send(systemAddress, "Unsubscribed from all channels.\r\n"); } else if (numParameters==1) { if ((channelIndex=Unsubscribe(systemAddress, parameterList[0]))!=(unsigned)-1) { transport->Send(systemAddress, "You are now unsubscribed from channel %s.\r\n", channelNames[channelIndex]); } else { transport->Send(systemAddress, "Cannot find channel %s.\r\n", parameterList[0]); PrintChannels(systemAddress, transport); } } else { transport->Send(systemAddress, "Unsubscribe takes either 0 or 1 parameters.\r\n"); } } return true; } const char *LogCommandParser::GetName(void) const { return "Logger"; } void LogCommandParser::SendHelp(TransportInterface *transport, const SystemAddress &systemAddress) { transport->Send(systemAddress, "The logger will accept user log data via the Log(...) function.\r\n"); transport->Send(systemAddress, "Each log is associated with a named channel.\r\n"); transport->Send(systemAddress, "You can subscribe to or unsubscribe from named channels.\r\n"); PrintChannels(systemAddress, transport); } void LogCommandParser::AddChannel(const char *channelName) { unsigned channelIndex=0; channelIndex = GetChannelIndexFromName(channelName); // Each channel can only be added once. RakAssert(channelIndex==(unsigned)-1); unsigned i; for (i=0; i < 32; i++) { if (channelNames[i]==0) { // Assuming a persistent static string. channelNames[i]=channelName; return; } } // No more available channels - max 32 with this implementation where I save subscribed channels with bit operations RakAssert(0); } void LogCommandParser::WriteLog(const char *channelName, const char *format, ...) { if (channelName==0 || format==0) return; unsigned channelIndex; channelIndex = GetChannelIndexFromName(channelName); if (channelIndex==(unsigned)-1) { AddChannel(channelName); } char text[REMOTE_MAX_TEXT_INPUT]; va_list ap; va_start(ap, format); _vsnprintf(text, REMOTE_MAX_TEXT_INPUT, format, ap); va_end(ap); text[REMOTE_MAX_TEXT_INPUT-1]=0; // Make sure that text ends in \r\n int textLen; textLen=(int)strlen(text); if (textLen==0) return; if (text[textLen-1]=='\n') { text[textLen-1]=0; } if (textLen < REMOTE_MAX_TEXT_INPUT-4) strcat(text, "\r\n"); else { text[textLen-3]='\r'; text[textLen-2]='\n'; text[textLen-1]=0; } // For each user that subscribes to this channel, send to them. unsigned i; for (i=0; i < remoteUsers.Size(); i++) { if (remoteUsers[i].channels & (1 << channelIndex)) { trans->Send(remoteUsers[i].systemAddress, text); } } } void LogCommandParser::PrintChannels(const SystemAddress &systemAddress, TransportInterface *transport) const { unsigned i; bool anyChannels=false; transport->Send(systemAddress, "CHANNELS:\r\n"); for (i=0; i < 32; i++) { if (channelNames[i]) { transport->Send(systemAddress, "%i. %s\r\n", i+1,channelNames[i]); anyChannels=true; } } if (anyChannels==false) transport->Send(systemAddress, "None.\r\n"); } void LogCommandParser::OnNewIncomingConnection(const SystemAddress &systemAddress, TransportInterface *transport) { (void) systemAddress; (void) transport; } void LogCommandParser::OnConnectionLost(const SystemAddress &systemAddress, TransportInterface *transport) { (void) transport; Unsubscribe(systemAddress, 0); } unsigned LogCommandParser::Unsubscribe(const SystemAddress &systemAddress, const char *channelName) { unsigned i; for (i=0; i < remoteUsers.Size(); i++) { if (remoteUsers[i].systemAddress==systemAddress) { if (channelName==0) { // Unsubscribe from all and delete this user. remoteUsers[i]=remoteUsers[remoteUsers.Size()-1]; remoteUsers.RemoveFromEnd(); return 0; } else { unsigned channelIndex; channelIndex = GetChannelIndexFromName(channelName); if (channelIndex!=(unsigned)-1) { remoteUsers[i].channels&=0xFFFF ^ (1<<channelIndex); // Unset this bit } return channelIndex; } } } return (unsigned)-1; } unsigned LogCommandParser::Subscribe(const SystemAddress &systemAddress, const char *channelName) { unsigned i; unsigned channelIndex=(unsigned)-1; if (channelName) { channelIndex = GetChannelIndexFromName(channelName); if (channelIndex==(unsigned)-1) return channelIndex; } for (i=0; i < remoteUsers.Size(); i++) { if (remoteUsers[i].systemAddress==systemAddress) { if (channelName) remoteUsers[i].channels|=1<<channelIndex; // Set this bit for an existing user else remoteUsers[i].channels=0xFFFF; return channelIndex; } } // Make a new user SystemAddressAndChannel newUser; newUser.systemAddress = systemAddress; if (channelName) newUser.channels=1<<channelIndex; else newUser.channels=0xFFFF; remoteUsers.Insert(newUser, _FILE_AND_LINE_); return channelIndex; } unsigned LogCommandParser::GetChannelIndexFromName(const char *channelName) { unsigned i; for (i=0; i < 32; i++) { if (channelNames[i]==0) return (unsigned) -1; if (_stricmp(channelNames[i], channelName)==0) return i; } return (unsigned)-1; } void LogCommandParser::OnTransportChange(TransportInterface *transport) { // I don't want users to have to pass TransportInterface *transport to Log. trans=transport; } #ifdef _MSC_VER #pragma warning( pop ) #endif #endif // _RAKNET_SUPPORT_*
bsd-2-clause
shonjir/homebrew-cask
Casks/kotori.rb
616
cask 'kotori' do version '0.24' sha256 '02b2cf71d5ff4138a768781c920232ab905d852e20b3db0e178c3d611f640636' url "https://github.com/Watson1978/kotori/releases/download/v#{version}/kotori_#{version}.dmg" appcast 'https://github.com/Watson1978/kotori/releases.atom', checkpoint: '32edd1fe702bc3121a92ce4cdad6152e25c4064e9494d9eeb47a89450e9f2cad' name 'kotori' name '小鳥' homepage 'https://github.com/Watson1978/kotori' app 'kotori.app' zap delete: '~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/jp.cat-soft.kotori.sfl' end
bsd-2-clause
anirudhSK/chromium
remoting/webapp/identity.js
4846
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileoverview * Wrapper class for Chrome's identity API. */ 'use strict'; /** @suppress {duplicate} */ var remoting = remoting || {}; /** * TODO(jamiewalch): Remove remoting.OAuth2 from this type annotation when * the Apps v2 work is complete. * * @type {remoting.Identity|remoting.OAuth2} */ remoting.identity = null; /** * @param {function(function():void):void} consentCallback Callback invoked if * user consent is required. The callback is passed a continuation function * which must be called from an interactive event handler (e.g. "click"). * @constructor */ remoting.Identity = function(consentCallback) { /** @private */ this.consentCallback_ = consentCallback; /** @type {?string} @private */ this.email_ = null; /** @type {Array.<remoting.Identity.Callbacks>} */ this.pendingCallbacks_ = []; }; /** * Call a function with an access token. * * TODO(jamiewalch): Currently, this results in a new GAIA token being minted * each time the function is called. Implement caching functionality unless * getAuthToken starts doing so itself. * * @param {function(string):void} onOk Function to invoke with access token if * an access token was successfully retrieved. * @param {function(remoting.Error):void} onError Function to invoke with an * error code on failure. * @return {void} Nothing. */ remoting.Identity.prototype.callWithToken = function(onOk, onError) { this.pendingCallbacks_.push(new remoting.Identity.Callbacks(onOk, onError)); if (this.pendingCallbacks_.length == 1) { chrome.identity.getAuthToken( { 'interactive': false }, this.onAuthComplete_.bind(this, false)); } }; /** * Get the user's email address. * * @param {function(string):void} onOk Callback invoked when the email * address is available. * @param {function(remoting.Error):void} onError Callback invoked if an * error occurs. * @return {void} Nothing. */ remoting.Identity.prototype.getEmail = function(onOk, onError) { /** @type {remoting.Identity} */ var that = this; /** @param {string} email */ var onResponse = function(email) { that.email_ = email; onOk(email); }; this.callWithToken( remoting.OAuth2Api.getEmail.bind(null, onResponse, onError), onError); }; /** * Get the user's email address, or null if no successful call to getEmail * has been made. * * @return {?string} The cached email address, if available. */ remoting.Identity.prototype.getCachedEmail = function() { return this.email_; }; /** * Callback for the getAuthToken API. * * @param {boolean} interactive The value of the "interactive" parameter to * getAuthToken. * @param {?string} token The auth token, or null if the request failed. * @private */ remoting.Identity.prototype.onAuthComplete_ = function(interactive, token) { // Pass the token to the callback(s) if it was retrieved successfully. if (token) { while (this.pendingCallbacks_.length > 0) { var callback = /** @type {remoting.Identity.Callbacks} */ this.pendingCallbacks_.shift(); callback.onOk(token); } return; } // If not, pass an error back to the callback(s) if we've already prompted the // user for permission. // TODO(jamiewalch): Figure out what to do with the error in this case. if (interactive) { console.error(chrome.runtime.lastError); while (this.pendingCallbacks_.length > 0) { var callback = /** @type {remoting.Identity.Callbacks} */ this.pendingCallbacks_.shift(); callback.onError(remoting.Error.UNEXPECTED); } return; } // If there's no token, but we haven't yet prompted for permission, do so // now. The consent callback is responsible for continuing the auth flow. this.consentCallback_(this.onAuthContinue_.bind(this)); }; /** * Called in response to the user signing in to the web-app. * * @private */ remoting.Identity.prototype.onAuthContinue_ = function() { chrome.identity.getAuthToken( { 'interactive': true }, this.onAuthComplete_.bind(this, true)); }; /** * Internal representation for pair of callWithToken callbacks. * * @param {function(string):void} onOk * @param {function(remoting.Error):void} onError * @constructor * @private */ remoting.Identity.Callbacks = function(onOk, onError) { /** @type {function(string):void} */ this.onOk = onOk; /** @type {function(remoting.Error):void} */ this.onError = onError; }; /** * Returns whether the web app has authenticated with the Google services. * * @return {boolean} */ remoting.Identity.prototype.isAuthenticated = function() { return remoting.identity.email_ != null; };
bsd-3-clause
itinance/Sylius
src/Sylius/Component/Promotion/spec/Model/PromotionRuleSpec.php
1607
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace spec\Sylius\Component\Promotion\Model; use PhpSpec\ObjectBehavior; use Sylius\Component\Promotion\Model\PromotionInterface; use Sylius\Component\Promotion\Model\PromotionRuleInterface; final class PromotionRuleSpec extends ObjectBehavior { function it_is_a_promotion_rule(): void { $this->shouldImplement(PromotionRuleInterface::class); } function it_does_not_have_id_by_default(): void { $this->getId()->shouldReturn(null); } function it_does_not_have_type_by_default(): void { $this->getType()->shouldReturn(null); } function its_type_is_mutable(): void { $this->setType('type'); $this->getType()->shouldReturn('type'); } function it_initializes_array_for_configuration_by_default(): void { $this->getConfiguration()->shouldReturn([]); } function its_configuration_is_mutable(): void { $this->setConfiguration(['value' => 500]); $this->getConfiguration()->shouldReturn(['value' => 500]); } function it_does_not_have_a_promotion_by_default(): void { $this->getPromotion()->shouldReturn(null); } function its_promotion_by_is_mutable(PromotionInterface $promotion): void { $this->setPromotion($promotion); $this->getPromotion()->shouldReturn($promotion); } }
mit
redmunds/cdnjs
ajax/libs/lazysizes/3.0.0-rc4/plugins/static-gecko-picture/ls.static-gecko-picture.min.js
1007
/*! lazysizes - v3.0.0-rc4 */ !function(a){var b=navigator.userAgent;a.HTMLPictureElement&&/ecko/.test(b)&&b.match(/rv\:(\d+)/)&&RegExp.$1<41&&addEventListener("resize",function(){var b,c=document.createElement("source"),d=function(a){var b,d,e=a.parentNode;"PICTURE"===e.nodeName.toUpperCase()?(b=c.cloneNode(),e.insertBefore(b,e.firstElementChild),setTimeout(function(){e.removeChild(b)})):(!a._pfLastSize||a.offsetWidth>a._pfLastSize)&&(a._pfLastSize=a.offsetWidth,d=a.sizes,a.sizes+=",100vw",setTimeout(function(){a.sizes=d}))},e=function(){var a,b=document.querySelectorAll("picture > img, img[srcset][sizes]");for(a=0;a<b.length;a++)d(b[a])},f=function(){clearTimeout(b),b=setTimeout(e,99)},g=a.matchMedia&&matchMedia("(orientation: landscape)"),h=function(){f(),g&&g.addListener&&g.addListener(f)};return c.srcset="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==",/^[c|i]|d$/.test(document.readyState||"")?h():document.addEventListener("DOMContentLoaded",h),f}())}(window);
mit
isaacl/openjdk-jdk
test/javax/sound/midi/Gervill/SoftTuning/Load9.java
2566
/* * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* @test @summary Test SoftTuning load method */ import javax.sound.midi.MidiUnavailableException; import javax.sound.midi.Patch; import javax.sound.sampled.*; import com.sun.media.sound.*; public class Load9 { private static void assertEquals(Object a, Object b) throws Exception { if(!a.equals(b)) throw new RuntimeException("assertEquals fails!"); } private static void assertTrue(boolean value) throws Exception { if(!value) throw new RuntimeException("assertTrue fails!"); } public static void main(String[] args) throws Exception { // http://www.midi.org/about-midi/tuning-scale.shtml // 0x09 scale/octave tuning 2-byte form (Non Real-Time/REAL-TIME) SoftTuning tuning = new SoftTuning(); int[] msg = {0xf0,0x7f,0x7f,0x08,0x09,0x03,0x7f,0x7f, 5,10,15,20,25,30,35,40,45,50,51,52, 5,10,15,20,25,30,35,40,45,50,51,52, 0xf7}; int[] oct = {5,10,15,20,25,30,35,40,45,50,51,52,5,10,15,20,25,30,35,40,45,50,51,52}; byte[] bmsg = new byte[msg.length]; for (int i = 0; i < bmsg.length; i++) bmsg[i] = (byte)msg[i]; tuning.load(bmsg); double[] tunings = tuning.getTuning(); for (int i = 0; i < tunings.length; i++) { double c = (oct[(i%12)*2]*128 + oct[(i%12)*2+1] -8192)*(100.0/8192.0); assertTrue(Math.abs(tunings[i]-(i*100 + (c))) < 0.00001); } } }
gpl-2.0
alexsco74/drupal-trade
sites/all/modules/contrib/panels/plugins/style_bases/pane/pane_plain_box/pane-plain-box.tpl.php
409
<?php /** * @file * * Display the box for rounded corners. * * - $pane: The pane being rendered * - $display: The display being rendered * - $content: An object containing the content and title * - $output: The result of theme('panels_pane') * - $classes: The classes that must be applied to the top divs. */ ?> <div class="<?php print $classes ?>"> <?php print $output; ?> </div>
gpl-2.0
dvh11er/mage-cheatcode
magento/lib/Zend/Validate/Barcode/Sscc.php
1427
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to [email protected] so we can send you a copy immediately. * * @category Zend * @package Zend_Validate * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ /** * @see Zend_Validate_Barcode_AdapterAbstract */ #require_once 'Zend/Validate/Barcode/AdapterAbstract.php'; /** * @category Zend * @package Zend_Validate * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Validate_Barcode_Sscc extends Zend_Validate_Barcode_AdapterAbstract { /** * Allowed barcode lengths * @var integer */ protected $_length = 18; /** * Allowed barcode characters * @var string */ protected $_characters = '0123456789'; /** * Checksum function * @var string */ protected $_checksum = '_gtin'; }
gpl-2.0
lucval/dmm-ns-3.17
src/lte/test/lte-test-earfcn.cc
5044
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2011 Centre Tecnologic de Telecomunicacions de Catalunya (CTTC) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Nicola Baldo <[email protected]> */ #include "ns3/test.h" #include "ns3/log.h" #include "ns3/lte-spectrum-value-helper.h" NS_LOG_COMPONENT_DEFINE ("LteTestEarfcn"); namespace ns3 { class LteEarfcnTestCase : public TestCase { public: LteEarfcnTestCase (const char* str, uint16_t earfcn, double f); virtual ~LteEarfcnTestCase (); protected: uint16_t m_earfcn; double m_f; private: virtual void DoRun (void); }; LteEarfcnTestCase::LteEarfcnTestCase (const char* str, uint16_t earfcn, double f) : TestCase (str), m_earfcn (earfcn), m_f (f) { NS_LOG_FUNCTION (this << str << earfcn << f); } LteEarfcnTestCase::~LteEarfcnTestCase () { } void LteEarfcnTestCase::DoRun (void) { double f = LteSpectrumValueHelper::GetCarrierFrequency (m_earfcn); NS_TEST_ASSERT_MSG_EQ_TOL (f, m_f, 0.0000001, "wrong frequency"); } class LteEarfcnDlTestCase : public LteEarfcnTestCase { public: LteEarfcnDlTestCase (const char* str, uint16_t earfcn, double f); private: virtual void DoRun (void); }; LteEarfcnDlTestCase::LteEarfcnDlTestCase (const char* str, uint16_t earfcn, double f) : LteEarfcnTestCase (str, earfcn, f) { } void LteEarfcnDlTestCase::DoRun (void) { // LogLevel logLevel = (LogLevel)(LOG_PREFIX_FUNC | LOG_PREFIX_TIME | LOG_LEVEL_ALL); // LogComponentEnable ("LteSpectrumValueHelper", logLevel); // LogComponentEnable ("LteTestEarfcn", logLevel); double f = LteSpectrumValueHelper::GetDownlinkCarrierFrequency (m_earfcn); NS_TEST_ASSERT_MSG_EQ_TOL (f, m_f, 0.0000001, "wrong frequency"); } class LteEarfcnUlTestCase : public LteEarfcnTestCase { public: LteEarfcnUlTestCase (const char* str, uint16_t earfcn, double f); private: virtual void DoRun (void); }; LteEarfcnUlTestCase::LteEarfcnUlTestCase (const char* str, uint16_t earfcn, double f) : LteEarfcnTestCase (str, earfcn, f) { } void LteEarfcnUlTestCase::DoRun (void) { double f = LteSpectrumValueHelper::GetUplinkCarrierFrequency (m_earfcn); NS_TEST_ASSERT_MSG_EQ_TOL (f, m_f, 0.0000001, "wrong frequency"); } /** * Test the calculation of carrier frequency based on EARFCN */ class LteEarfcnTestSuite : public TestSuite { public: LteEarfcnTestSuite (); }; static LteEarfcnTestSuite g_lteEarfcnTestSuite; LteEarfcnTestSuite::LteEarfcnTestSuite () : TestSuite ("lte-earfcn", UNIT) { NS_LOG_FUNCTION (this); AddTestCase (new LteEarfcnDlTestCase ("DL EARFCN=500", 500, 2160e6), TestCase::QUICK); AddTestCase (new LteEarfcnDlTestCase ("DL EARFCN=1000", 1000, 1970e6), TestCase::QUICK); AddTestCase (new LteEarfcnDlTestCase ("DL EARFCN=1301", 1301, 1815.1e6), TestCase::QUICK); AddTestCase (new LteEarfcnDlTestCase ("DL EARFCN=7000", 7000, 0.0), TestCase::QUICK); AddTestCase (new LteEarfcnDlTestCase ("DL EARFCN=20000", 20000, 0.0), TestCase::QUICK); AddTestCase (new LteEarfcnDlTestCase ("DL EARFCN=50000", 50000, 0.0), TestCase::QUICK); AddTestCase (new LteEarfcnUlTestCase ("UL EARFCN=18100", 18100, 1930e6), TestCase::QUICK); AddTestCase (new LteEarfcnUlTestCase ("UL EARFCN=19000", 19000, 1890e6), TestCase::QUICK); AddTestCase (new LteEarfcnUlTestCase ("UL EARFCN=19400", 19400, 1730e6), TestCase::QUICK); AddTestCase (new LteEarfcnUlTestCase ("UL EARFCN=10", 10, 0.0), TestCase::QUICK); AddTestCase (new LteEarfcnUlTestCase ("UL EARFCN=1000", 1000, 0.0), TestCase::QUICK); AddTestCase (new LteEarfcnUlTestCase ("UL EARFCN=50000", 50000, 0.0), TestCase::QUICK); AddTestCase (new LteEarfcnTestCase ("EARFCN=500", 500, 2160e6), TestCase::QUICK); AddTestCase (new LteEarfcnTestCase ("EARFCN=1000", 1000, 1970e6), TestCase::QUICK); AddTestCase (new LteEarfcnTestCase ("EARFCN=1301", 1301, 1815.1e6), TestCase::QUICK); AddTestCase (new LteEarfcnTestCase ("EARFCN=8000", 8000, 0.0), TestCase::QUICK); AddTestCase (new LteEarfcnTestCase ("EARFCN=50000", 50000, 0.0), TestCase::QUICK); AddTestCase (new LteEarfcnTestCase ("EARFCN=18100", 18100, 1930e6), TestCase::QUICK); AddTestCase (new LteEarfcnTestCase ("EARFCN=19000", 19000, 1890e6), TestCase::QUICK); AddTestCase (new LteEarfcnTestCase ("EARFCN=19400", 19400, 1730e6), TestCase::QUICK); AddTestCase (new LteEarfcnTestCase ("EARFCN=50000", 50000, 0.0), TestCase::QUICK); } } // namespace ns3
gpl-2.0
medbenali/CyberScan
scapy/layers/gprs.py
533
## This file is part of Scapy ## See http://www.secdev.org/projects/scapy for more informations ## Copyright (C) Philippe Biondi <[email protected]> ## This program is published under a GPLv2 license """ GPRS (General Packet Radio Service) for mobile data communication. """ from scapy.fields import * from scapy.packet import * from scapy.layers.inet import IP class GPRS(Packet): name = "GPRSdummy" fields_desc = [ StrStopField("dummy","","\x65\x00\x00",1) ] bind_layers( GPRS, IP, )
gpl-3.0
gamchantoi/AgroSHop-UTUAWARDS
themes/Backend/ExtJs/backend/performance/view/tabs/settings/main.js
4420
/** * Shopware 5 * Copyright (c) shopware AG * * According to our dual licensing model, this program can be used either * under the terms of the GNU Affero General Public License, version 3, * or under a proprietary license. * * The texts of the GNU Affero General Public License with an additional * permission and of our proprietary license can be found at and * in the LICENSE file you have received along with this program. * * 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. * * "Shopware" is a registered trademark of shopware AG. * The licensing of the program under the AGPLv3 does not imply a * trademark license. Therefore any rights, title and interest in * our trademarks remain entirely with us. * * @category Shopware * @package Order * @subpackage View * @version $Id$ * @author shopware AG */ //{namespace name=backend/performance/main} //{block name="backend/performance/view/tabs/settings/main"} Ext.define('Shopware.apps.Performance.view.tabs.settings.Main', { /** * Define that the additional information is an Ext.panel.Panel extension * @string */ extend:'Ext.panel.Panel', /** * List of short aliases for class names. Most useful for defining xtypes for widgets. * @string */ alias:'widget.performance-tabs-settings-main', // Title of the panel shown in the tab title: '{s name=tabs/settings/title}Settings{/s}', // Define the layout of the panel to be a border layut layout: 'border', /** * The initComponent template method is an important initialization step for a Component. * It is intended to be implemented by each subclass of Ext.Component to provide any needed constructor logic. * The initComponent method of the class being created is called first, * with each initComponent method up the hierarchy to Ext.Component being called thereafter. * This makes it easy to implement and, if needed, override the constructor logic of the Component at any step in the hierarchy. * The initComponent method must contain a call to callParent in order to ensure that the parent class' initComponent method is also called. * * @return void */ initComponent:function () { var me = this; me.items = me.createItems(); me.dockedItems = [{ xtype: 'toolbar', dock: 'bottom', ui: 'shopware-ui', cls: 'shopware-toolbar', items: me.getButtons() }]; me.callParent(arguments); }, /* * Helper method which creates the items of the panel * @return Array */ createItems: function() { var me = this; me.panel = Ext.create('Ext.form.Panel', { region: 'center', trackResetOnLoad: true, autoScroll: true, items: [ { xtype: 'performance-tabs-settings-home' },{ xtype: 'performance-tabs-settings-seo' },{ xtype: 'performance-tabs-settings-http-cache' },{ xtype: 'performance-tabs-settings-theme-cache' },{ xtype: 'performance-tabs-settings-search' },{ xtype: 'performance-tabs-settings-topseller' },{ xtype: 'performance-tabs-settings-various' },{ xtype: 'performance-tabs-settings-customers' },{ xtype: 'performance-tabs-settings-categories' },{ xtype: 'performance-tabs-settings-filter' }] }); me.navigation = Ext.create('Shopware.apps.Performance.view.tabs.settings.Navigation', { region: 'west', bodyStyle: 'background: #ffffff;' }); return [ me.navigation, me.panel ]; }, /** * @return Array */ getButtons: function() { var me = this; return ['->', { text: '{s name=settings/buttons/save}Save{/s}', action: 'save-settings', cls: 'primary' }]; } }); //{/block}
agpl-3.0
cleitoncsg/0mqL
zeromq-3.2.1/src/thread.hpp
2299
/* Copyright (c) 2010-2011 250bpm s.r.o. Copyright (c) 2007-2011 iMatix Corporation Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file This file is part of 0MQ. 0MQ is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. 0MQ 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef __ZMQ_THREAD_HPP_INCLUDED__ #define __ZMQ_THREAD_HPP_INCLUDED__ #include "platform.hpp" #ifdef ZMQ_HAVE_WINDOWS #include "windows.hpp" #else #include <pthread.h> #endif namespace zmq { typedef void (thread_fn) (void*); // Class encapsulating OS thread. Thread initiation/termination is done // using special functions rather than in constructor/destructor so that // thread isn't created during object construction by accident, causing // newly created thread to access half-initialised object. Same applies // to the destruction process: Thread should be terminated before object // destruction begins, otherwise it can access half-destructed object. class thread_t { public: inline thread_t () { } // Creates OS thread. 'tfn' is main thread function. It'll be passed // 'arg' as an argument. void start (thread_fn *tfn_, void *arg_); // Waits for thread termination. void stop (); // These are internal members. They should be private, however then // they would not be accessible from the main C routine of the thread. thread_fn *tfn; void *arg; private: #ifdef ZMQ_HAVE_WINDOWS HANDLE descriptor; #else pthread_t descriptor; #endif thread_t (const thread_t&); const thread_t &operator = (const thread_t&); }; } #endif
lgpl-3.0
baslr/ArangoDB
3rdParty/boost/1.62.0/libs/multi_index/example/rearrange.cpp
6683
/* Boost.MultiIndex example of use of rearrange facilities. * * Copyright 2003-2015 Joaquin M Lopez Munoz. * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) * * See http://www.boost.org/libs/multi_index for library home page. */ #if !defined(NDEBUG) #define BOOST_MULTI_INDEX_ENABLE_INVARIANT_CHECKING #define BOOST_MULTI_INDEX_ENABLE_SAFE_MODE #endif #include <boost/config.hpp> #include <boost/detail/iterator.hpp> #include <boost/multi_index_container.hpp> #include <boost/multi_index/random_access_index.hpp> #include <boost/random/binomial_distribution.hpp> #include <boost/random/uniform_real.hpp> #include <boost/random/mersenne_twister.hpp> #include <algorithm> #include <iostream> #include <iterator> #include <vector> #if !defined(BOOST_NO_CXX11_HDR_RANDOM) #include <random> #endif using boost::multi_index_container; using namespace boost::multi_index; /* We model a card deck with a random access array containing * card numbers (from 0 to 51), supplemented with an additional * index which retains the start ordering. */ class deck { BOOST_STATIC_CONSTANT(std::size_t,num_cards=52); typedef multi_index_container< int, indexed_by< random_access<>, /* base index */ random_access<> /* "start" index */ > > container_type; container_type cont; public: deck() { cont.reserve(num_cards); get<1>(cont).reserve(num_cards); for(std::size_t i=0;i<num_cards;++i)cont.push_back(i); } typedef container_type::iterator iterator; typedef container_type::size_type size_type; iterator begin()const{return cont.begin();} iterator end()const{return cont.end();} size_type size()const{return cont.size();} template<typename InputIterator> void rearrange(InputIterator it) { cont.rearrange(it); } void reset() { /* simply rearrange the base index like the start index */ cont.rearrange(get<1>(cont).begin()); } std::size_t position(int i)const { /* The position of a card in the deck is calculated by locating * the card through the start index (which is ordered), projecting * to the base index and diffing with the begin position. * Resulting complexity: constant. */ return project<0>(cont,get<1>(cont).begin()+i)-cont.begin(); } std::size_t rising_sequences()const { /* Iterate through all cards and increment the sequence count * when the current position is left to the previous. * Resulting complexity: O(n), n=num_cards. */ std::size_t s=1; std::size_t last_pos=0; for(std::size_t i=0;i<num_cards;++i){ std::size_t pos=position(i); if(pos<last_pos)++s; last_pos=pos; } return s; } }; /* A vector of reference_wrappers to deck elements can be used * as a view to the deck container. * We use a special implicit_reference_wrapper having implicit * ctor from its base type, as this simplifies the use of generic * techniques on the resulting data structures. */ template<typename T> class implicit_reference_wrapper:public boost::reference_wrapper<T> { private: typedef boost::reference_wrapper<T> super; public: implicit_reference_wrapper(T& t):super(t){} }; typedef std::vector<implicit_reference_wrapper<const int> > deck_view; /* Riffle shuffle is modeled like this: A cut is selected in the deck * following a binomial distribution. Then, cards are randomly selected * from one packet or the other with probability proportional to * packet size. */ template<typename RandomAccessIterator,typename OutputIterator> void riffle_shuffle( RandomAccessIterator first,RandomAccessIterator last, OutputIterator out) { static boost::mt19937 rnd_gen; typedef typename boost::detail::iterator_traits< RandomAccessIterator>::difference_type difference_type; typedef boost::binomial_distribution< difference_type> rnd_cut_select_type; typedef boost::uniform_real<> rnd_deck_select_type; rnd_cut_select_type cut_select(last-first); RandomAccessIterator middle=first+cut_select(rnd_gen); difference_type s0=middle-first; difference_type s1=last-middle; rnd_deck_select_type deck_select; while(s0!=0&&s1!=0){ if(deck_select(rnd_gen)<(double)s0/(s0+s1)){ *out++=*first++; --s0; } else{ *out++=*middle++; --s1; } } std::copy(first,first+s0,out); std::copy(middle,middle+s1,out); } struct riffle_shuffler { void operator()(deck& d)const { dv.clear(); dv.reserve(d.size()); riffle_shuffle( d.begin(),d.end(),std::back_inserter(dv)); /* do the shuffling */ d.rearrange(dv.begin()); /* apply to the deck */ } private: mutable deck_view dv; }; /* A truly random shuffle (up to stdlib implementation quality) using * std::shuffle. */ struct random_shuffler { void operator()(deck& d) { dv.clear(); dv.reserve(d.size()); std::copy(d.begin(),d.end(),std::back_inserter(dv)); shuffle_view(); d.rearrange(dv.begin()); /* apply to the deck */ } private: deck_view dv; #if !defined(BOOST_NO_CXX11_HDR_RANDOM) std::mt19937 e; void shuffle_view() { std::shuffle(dv.begin(),dv.end(),e); } #else /* for pre-C++11 compilers we use std::random_shuffle */ void shuffle_view() { std::random_shuffle(dv.begin(),dv.end()); } #endif }; /* Repeat a given shuffling algorithm repeats_num times * and obtain the resulting rising sequences number. Average * for tests_num trials. */ template<typename Shuffler> double shuffle_test( unsigned int repeats_num,unsigned int tests_num BOOST_APPEND_EXPLICIT_TEMPLATE_TYPE(Shuffler)) { deck d; Shuffler sh; unsigned long total=0; for(unsigned int n=0;n<tests_num;++n){ for(unsigned m=0;m<repeats_num;++m)sh(d); total+=d.rising_sequences(); d.reset(); } return (double)total/tests_num; } int main() { unsigned rifs_num=0; unsigned tests_num=0; std::cout<<"number of riffle shuffles (vg 5):"; std::cin>>rifs_num; std::cout<<"number of tests (vg 1000):"; std::cin>>tests_num; std::cout<<"shuffling..."<<std::endl; std::cout<<"riffle shuffling\n" " avg number of rising sequences: " <<shuffle_test<riffle_shuffler>(rifs_num,tests_num) <<std::endl; std::cout<<"random shuffling\n" " avg number of rising sequences: " <<shuffle_test<random_shuffler>(1,tests_num) <<std::endl; return 0; }
apache-2.0
TiVo/kafka
clients/src/main/java/org/apache/kafka/common/errors/NotEnoughReplicasAfterAppendException.java
1320
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.common.errors; /** * Number of insync replicas for the partition is lower than min.insync.replicas This exception is raised when the low * ISR size is discovered *after* the message was already appended to the log. Producer retries will cause duplicates. */ public class NotEnoughReplicasAfterAppendException extends RetriableException { private static final long serialVersionUID = 1L; public NotEnoughReplicasAfterAppendException(String message) { super(message); } }
apache-2.0
dsebastien/DefinitelyTyped
types/es-abstract/operations/2016.d.ts
5202
import ES2015Operations = require('./2015'); import ES2016 = require('../es2016'); interface ES2016Operations extends Record<keyof ES2016, string>, ES2015Operations { // Unimplemented operations: abs: string; AddRestrictedFunctionProperties: string; AllocateArrayBuffer: string; AllocateTypedArray: string; AllocateTypedArrayBuffer: string; BlockDeclarationInstantiation: string; BoundFunctionCreate: string; Canonicalize: string; CharacterRange: string; CharacterRangeOrUnion: string; CharacterSetMatcher: string; CloneArrayBuffer: string; Completion: string; CopyDataBlockBytes: string; CreateArrayIterator: string; CreateBuiltinFunction: string; CreateByteDataBlock: string; CreateDynamicFunction: string; CreateIntrinsics: string; CreateMapIterator: string; CreateMappedArgumentsObject: string; CreatePerIterationEnvironment: string; CreateRealm: string; CreateResolvingFunctions: string; CreateSetIterator: string; CreateStringIterator: string; CreateUnmappedArgumentsObject: string; Decode: string; DetachArrayBuffer: string; Encode: string; EnqueueJob: string; EnumerateObjectProperties: string; EscapeRegExpPattern: string; EvalDeclarationInstantiation: string; EvaluateCall: string; EvaluateDirectCall: string; EvaluateNew: string; floor: string; ForBodyEvaluation: string; 'ForIn/OfBodyEvaluation': string; 'ForIn/OfHeadEvaluation': string; FulfillPromise: string; FunctionAllocate: string; FunctionCreate: string; FunctionDeclarationInstantiation: string; FunctionInitialize: string; GeneratorFunctionCreate: string; GeneratorResume: string; GeneratorResumeAbrupt: string; GeneratorStart: string; GeneratorValidate: string; GeneratorYield: string; GetActiveScriptOrModule: string; GetFunctionRealm: string; GetGlobalObject: string; GetIdentifierReference: string; GetModuleNamespace: string; GetNewTarget: string; GetSuperConstructor: string; GetTemplateObject: string; GetThisEnvironment: string; GetThisValue: string; GetValue: string; GetValueFromBuffer: string; GetViewValue: string; GlobalDeclarationInstantiation: string; HostPromiseRejectionTracker: string; HostReportErrors: string; HostResolveImportedModule: string; IfAbruptRejectPromise: string; ImportedLocalNames: string; InitializeBoundName: string; InitializeHostDefinedRealm: string; InitializeReferencedBinding: string; IntegerIndexedElementGet: string; IntegerIndexedElementSet: string; IntegerIndexedObjectCreate: string; InternalizeJSONProperty: string; IsAnonymousFunctionDefinition: string; IsCompatiblePropertyDescriptor: string; IsDetachedBuffer: string; IsInTailPosition: string; IsLabelledFunction: string; IsWordChar: string; LocalTime: string; LoopContinues: string; MakeArgGetter: string; MakeArgSetter: string; MakeClassConstructor: string; MakeConstructor: string; MakeMethod: string; MakeSuperPropertyReference: string; max: string; min: string; ModuleNamespaceCreate: string; NewDeclarativeEnvironment: string; NewFunctionEnvironment: string; NewGlobalEnvironment: string; NewModuleEnvironment: string; NewObjectEnvironment: string; NewPromiseCapability: string; NextJob: string; ObjectDefineProperties: string; OrdinaryCallBindThis: string; OrdinaryCallEvaluateBody: string; OrdinaryCreateFromConstructor: string; OrdinaryDelete: string; OrdinaryGet: string; OrdinaryIsExtensible: string; OrdinaryOwnPropertyKeys: string; OrdinaryPreventExtensions: string; OrdinarySet: string; ParseModule: string; ParseScript: string; PerformEval: string; PerformPromiseAll: string; PerformPromiseRace: string; PerformPromiseThen: string; PrepareForOrdinaryCall: string; PrepareForTailCall: string; PromiseReactionJob: string; PromiseResolveThenableJob: string; ProxyCreate: string; PutValue: string; QuoteJSONString: string; RegExpAlloc: string; RegExpCreate: string; RegExpInitialize: string; RejectPromise: string; RepeatMatcher: string; ResolveBinding: string; ResolveThisBinding: string; ReturnIfAbrupt: string; ScriptEvaluation: string; ScriptEvaluationJob: string; SerializeJSONArray: string; SerializeJSONObject: string; SerializeJSONProperty: string; SetDefaultGlobalBindings: string; SetRealmGlobalObject: string; SetValueInBuffer: string; SetViewValue: string; SortCompare: string; SplitMatch: string; StringCreate: string; TopLevelModuleEvaluationJob: string; 'ToString Applied to the Number Type': string; TriggerPromiseReactions: string; TypedArrayCreate: string; TypedArraySpeciesCreate: string; UpdateEmpty: string; UTC: string; UTF16Decode: string; UTF16Encoding: string; ValidateTypedArray: string; } declare const ES2016Operations: ES2016Operations; export = ES2016Operations;
mit
alyssa-labs/pragtico
cake/tests/groups/console.group.php
2297
<?php /** * ConsoleGroupTest file * * PHP versions 4 and 5 * * CakePHP(tm) Tests <http://book.cakephp.org/view/1196/Testing> * Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The Open Group Test Suite License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://book.cakephp.org/view/1196/Testing CakePHP(tm) Tests * @package cake * @subpackage cake.tests.groups * @since CakePHP(tm) v 1.2.0.4206 * @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License */ /** * ConsoleGroupTest class * * This test group will run all console tests * * @package cake * @subpackage cake.tests.groups */ class ConsoleGroupTest extends TestSuite { /** * label property * * @var string 'All core cache engines' * @access public */ var $label = 'ShellDispatcher, Shell and all Tasks'; /** * ConsoleGroupTest method * * @access public * @return void */ function ConsoleGroupTest() { TestManager::addTestFile($this, CORE_TEST_CASES . DS . 'console' . DS . 'cake'); TestManager::addTestFile($this, CORE_TEST_CASES . DS . 'console' . DS . 'libs' . DS . 'acl'); TestManager::addTestFile($this, CORE_TEST_CASES . DS . 'console' . DS . 'libs' . DS . 'api'); TestManager::addTestFile($this, CORE_TEST_CASES . DS . 'console' . DS . 'libs' . DS . 'bake'); TestManager::addTestFile($this, CORE_TEST_CASES . DS . 'console' . DS . 'libs' . DS . 'schema'); TestManager::addTestFile($this, CORE_TEST_CASES . DS . 'console' . DS . 'libs' . DS . 'shell'); $path = CORE_TEST_CASES . DS . 'console' . DS . 'libs' . DS . 'tasks' . DS; TestManager::addTestFile($this, $path . 'controller'); TestManager::addTestFile($this, $path . 'db_config'); TestManager::addTestFile($this, $path . 'extract'); TestManager::addTestFile($this, $path . 'fixture'); TestManager::addTestFile($this, $path . 'model'); TestManager::addTestFile($this, $path . 'plugin'); TestManager::addTestFile($this, $path . 'project'); TestManager::addTestFile($this, $path . 'test'); TestManager::addTestFile($this, $path . 'view'); } }
mit