code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
<?php
return array (
'template' => 'default',
'connectionId' => 'db',
'tablePrefix' => '',
'modelPath' => 'application.models',
'baseClass' => 'CActiveRecord',
'buildRelations' => '1',
);
| learning-layers/reflect-app | web_ponty/protected/runtime/gii-1.1.13/ModelCode.php | PHP | apache-2.0 | 200 |
<?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_Dfareporting_UserRolePermissionsListResponse extends Google_Collection
{
protected $collection_key = 'userRolePermissions';
public $kind;
protected $userRolePermissionsType = 'Google_Service_Dfareporting_UserRolePermission';
protected $userRolePermissionsDataType = 'array';
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setUserRolePermissions($userRolePermissions)
{
$this->userRolePermissions = $userRolePermissions;
}
public function getUserRolePermissions()
{
return $this->userRolePermissions;
}
}
| Molkobain/home-cortex | vendor/google/apiclient-services/src/Google/Service/Dfareporting/UserRolePermissionsListResponse.php | PHP | mit | 1,247 |
<?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_AdExchangeSeller_SavedReport extends Google_Model
{
public $id;
public $kind;
public $name;
public function setId($id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
}
| siege123/export-to-google-drive | vendor/google/apiclient-services/src/Google/Service/AdExchangeSeller/SavedReport.php | PHP | mit | 1,086 |
/////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2007-2014
//
// 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/intrusive for documentation.
//
/////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_INTRUSIVE_COMMON_SLIST_ALGORITHMS_HPP
#define BOOST_INTRUSIVE_COMMON_SLIST_ALGORITHMS_HPP
#ifndef BOOST_CONFIG_HPP
# include <boost/config.hpp>
#endif
#if defined(BOOST_HAS_PRAGMA_ONCE)
# pragma once
#endif
#include <boost/intrusive/intrusive_fwd.hpp>
#include <boost/intrusive/detail/assert.hpp>
#include <boost/intrusive/detail/algo_type.hpp>
#include <boost/core/no_exceptions_support.hpp>
#include <cstddef>
namespace boost {
namespace intrusive {
namespace detail {
template<class NodeTraits>
class common_slist_algorithms
{
public:
typedef typename NodeTraits::node node;
typedef typename NodeTraits::node_ptr node_ptr;
typedef typename NodeTraits::const_node_ptr const_node_ptr;
typedef NodeTraits node_traits;
static node_ptr get_previous_node(node_ptr p, const node_ptr & this_node)
{
for( node_ptr p_next
; this_node != (p_next = NodeTraits::get_next(p))
; p = p_next){
//Logic error: possible use of linear lists with
//operations only permitted with circular lists
BOOST_INTRUSIVE_INVARIANT_ASSERT(p);
}
return p;
}
BOOST_INTRUSIVE_FORCEINLINE static void init(node_ptr this_node)
{ NodeTraits::set_next(this_node, node_ptr()); }
BOOST_INTRUSIVE_FORCEINLINE static bool unique(const const_node_ptr & this_node)
{
node_ptr next = NodeTraits::get_next(this_node);
return !next || next == this_node;
}
BOOST_INTRUSIVE_FORCEINLINE static bool inited(const const_node_ptr & this_node)
{ return !NodeTraits::get_next(this_node); }
BOOST_INTRUSIVE_FORCEINLINE static void unlink_after(node_ptr prev_node)
{
const_node_ptr this_node(NodeTraits::get_next(prev_node));
NodeTraits::set_next(prev_node, NodeTraits::get_next(this_node));
}
BOOST_INTRUSIVE_FORCEINLINE static void unlink_after(node_ptr prev_node, node_ptr last_node)
{ NodeTraits::set_next(prev_node, last_node); }
BOOST_INTRUSIVE_FORCEINLINE static void link_after(node_ptr prev_node, node_ptr this_node)
{
NodeTraits::set_next(this_node, NodeTraits::get_next(prev_node));
NodeTraits::set_next(prev_node, this_node);
}
BOOST_INTRUSIVE_FORCEINLINE static void incorporate_after(node_ptr bp, node_ptr b, node_ptr be)
{
node_ptr p(NodeTraits::get_next(bp));
NodeTraits::set_next(bp, b);
NodeTraits::set_next(be, p);
}
static void transfer_after(node_ptr bp, node_ptr bb, node_ptr be)
{
if (bp != bb && bp != be && bb != be) {
node_ptr next_b = NodeTraits::get_next(bb);
node_ptr next_e = NodeTraits::get_next(be);
node_ptr next_p = NodeTraits::get_next(bp);
NodeTraits::set_next(bb, next_e);
NodeTraits::set_next(be, next_p);
NodeTraits::set_next(bp, next_b);
}
}
struct stable_partition_info
{
std::size_t num_1st_partition;
std::size_t num_2nd_partition;
node_ptr beg_2st_partition;
node_ptr new_last_node;
};
template<class Pred>
static void stable_partition(node_ptr before_beg, node_ptr end, Pred pred, stable_partition_info &info)
{
node_ptr bcur = before_beg;
node_ptr cur = node_traits::get_next(bcur);
node_ptr new_f = end;
std::size_t num1 = 0, num2 = 0;
while(cur != end){
if(pred(cur)){
++num1;
bcur = cur;
cur = node_traits::get_next(cur);
}
else{
++num2;
node_ptr last_to_remove = bcur;
new_f = cur;
bcur = cur;
cur = node_traits::get_next(cur);
BOOST_TRY{
//Main loop
while(cur != end){
if(pred(cur)){ //Might throw
++num1;
//Process current node
node_traits::set_next(last_to_remove, cur);
last_to_remove = cur;
node_ptr nxt = node_traits::get_next(cur);
node_traits::set_next(bcur, nxt);
cur = nxt;
}
else{
++num2;
bcur = cur;
cur = node_traits::get_next(cur);
}
}
}
BOOST_CATCH(...){
node_traits::set_next(last_to_remove, new_f);
BOOST_RETHROW;
}
BOOST_CATCH_END
node_traits::set_next(last_to_remove, new_f);
break;
}
}
info.num_1st_partition = num1;
info.num_2nd_partition = num2;
info.beg_2st_partition = new_f;
info.new_last_node = bcur;
}
//! <b>Requires</b>: f and l must be in a circular list.
//!
//! <b>Effects</b>: Returns the number of nodes in the range [f, l).
//!
//! <b>Complexity</b>: Linear
//!
//! <b>Throws</b>: Nothing.
static std::size_t distance(const const_node_ptr &f, const const_node_ptr &l)
{
const_node_ptr i(f);
std::size_t result = 0;
while(i != l){
i = NodeTraits::get_next(i);
++result;
}
return result;
}
};
/// @endcond
} //namespace detail
/// @cond
template<class NodeTraits>
struct get_algo<CommonSListAlgorithms, NodeTraits>
{
typedef detail::common_slist_algorithms<NodeTraits> type;
};
} //namespace intrusive
} //namespace boost
#endif //BOOST_INTRUSIVE_COMMON_SLIST_ALGORITHMS_HPP
| BeGe78/esood | vendor/bundle/ruby/3.0.0/gems/passenger-6.0.5/src/cxx_supportlib/vendor-modified/boost/intrusive/detail/common_slist_algorithms.hpp | C++ | gpl-3.0 | 5,974 |
# 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.
# ==============================================================================
"""Keras built-in optimizers."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Optimizer classes.
from tensorflow.contrib.keras.python.keras.optimizers import Adadelta
from tensorflow.contrib.keras.python.keras.optimizers import Adagrad
from tensorflow.contrib.keras.python.keras.optimizers import Adam
from tensorflow.contrib.keras.python.keras.optimizers import Adamax
from tensorflow.contrib.keras.python.keras.optimizers import Nadam
from tensorflow.contrib.keras.python.keras.optimizers import Optimizer
from tensorflow.contrib.keras.python.keras.optimizers import RMSprop
from tensorflow.contrib.keras.python.keras.optimizers import SGD
# Auxiliary utils.
# pylint: disable=g-bad-import-order
from tensorflow.contrib.keras.python.keras.optimizers import deserialize
from tensorflow.contrib.keras.python.keras.optimizers import serialize
from tensorflow.contrib.keras.python.keras.optimizers import get
del absolute_import
del division
del print_function
| unnikrishnankgs/va | venv/lib/python3.5/site-packages/tensorflow/contrib/keras/api/keras/optimizers/__init__.py | Python | bsd-2-clause | 1,718 |
// Type definitions for snake-case
// Project: https://github.com/blakeembrey/snake-case
// Definitions by: Sam Saint-Pettersen <https://github.com/stpettersens>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "snake-case" {
function snakeCase(string: string, locale?: string): string;
export = snakeCase;
}
| Pro/DefinitelyTyped | snake-case/snake-case.d.ts | TypeScript | mit | 345 |
<?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_Compute_DiskTypesScopedListWarningData extends Google_Model
{
public $key;
public $value;
public function setKey($key)
{
$this->key = $key;
}
public function getKey()
{
return $this->key;
}
public function setValue($value)
{
$this->value = $value;
}
public function getValue()
{
return $this->value;
}
}
| anhyeuviolet/module-videos | vendor/google/apiclient-services/src/Google/Service/Compute/DiskTypesScopedListWarningData.php | PHP | gpl-2.0 | 968 |
//
// Copyright (c) Microsoft and contributors. 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.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Management.ExpressRoute;
using Microsoft.WindowsAzure.Management.ExpressRoute.Models;
namespace Microsoft.WindowsAzure.Management.ExpressRoute
{
/// <summary>
/// The Express Route API provides programmatic access to the functionality
/// needed by the customer to set up Dedicated Circuits and Dedicated
/// Circuit Links. The Express Route Customer API is a REST API. All API
/// operations are performed over SSL and mutually authenticated using
/// X.509 v3 certificates. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460799.aspx for
/// more information)
/// </summary>
public static partial class BorderGatewayProtocolPeeringOperationsExtensions
{
/// <summary>
/// The New Border Gateway Protocol Peering operation creates a new
/// Border Gateway Protocol Peering
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ExpressRoute.IBorderGatewayProtocolPeeringOperations.
/// </param>
/// <param name='serviceKey'>
/// Required. The service key representing the relationship between
/// Azure and the customer.
/// </param>
/// <param name='accessType'>
/// Required. Whether the peering is private or public.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the New Border Gateway Protocol
/// Peering operation.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static ExpressRouteOperationResponse BeginNew(this IBorderGatewayProtocolPeeringOperations operations, string serviceKey, BgpPeeringAccessType accessType, BorderGatewayProtocolPeeringNewParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IBorderGatewayProtocolPeeringOperations)s).BeginNewAsync(serviceKey, accessType, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The New Border Gateway Protocol Peering operation creates a new
/// Border Gateway Protocol Peering
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ExpressRoute.IBorderGatewayProtocolPeeringOperations.
/// </param>
/// <param name='serviceKey'>
/// Required. The service key representing the relationship between
/// Azure and the customer.
/// </param>
/// <param name='accessType'>
/// Required. Whether the peering is private or public.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the New Border Gateway Protocol
/// Peering operation.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<ExpressRouteOperationResponse> BeginNewAsync(this IBorderGatewayProtocolPeeringOperations operations, string serviceKey, BgpPeeringAccessType accessType, BorderGatewayProtocolPeeringNewParameters parameters)
{
return operations.BeginNewAsync(serviceKey, accessType, parameters, CancellationToken.None);
}
/// <summary>
/// The Remove Border Gateway Protocol Peering operation deletes an
/// existing border gateway protocol peering.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ExpressRoute.IBorderGatewayProtocolPeeringOperations.
/// </param>
/// <param name='serviceKey'>
/// Required. Service Key representing the border gateway protocol
/// peering to be deleted.
/// </param>
/// <param name='accessType'>
/// Required. Whether the peering is private or public.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static ExpressRouteOperationResponse BeginRemove(this IBorderGatewayProtocolPeeringOperations operations, string serviceKey, BgpPeeringAccessType accessType)
{
return Task.Factory.StartNew((object s) =>
{
return ((IBorderGatewayProtocolPeeringOperations)s).BeginRemoveAsync(serviceKey, accessType);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Remove Border Gateway Protocol Peering operation deletes an
/// existing border gateway protocol peering.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ExpressRoute.IBorderGatewayProtocolPeeringOperations.
/// </param>
/// <param name='serviceKey'>
/// Required. Service Key representing the border gateway protocol
/// peering to be deleted.
/// </param>
/// <param name='accessType'>
/// Required. Whether the peering is private or public.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<ExpressRouteOperationResponse> BeginRemoveAsync(this IBorderGatewayProtocolPeeringOperations operations, string serviceKey, BgpPeeringAccessType accessType)
{
return operations.BeginRemoveAsync(serviceKey, accessType, CancellationToken.None);
}
/// <summary>
/// The Update Border Gateway Protocol Peering operation updates an
/// existing bgp peering.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ExpressRoute.IBorderGatewayProtocolPeeringOperations.
/// </param>
/// <param name='serviceKey'>
/// Required. The service key representing the relationship between
/// Azure and the customer.
/// </param>
/// <param name='accessType'>
/// Required. Whether the peering is private or public.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Update Border Gateway Protocol
/// Peering operation.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static ExpressRouteOperationResponse BeginUpdate(this IBorderGatewayProtocolPeeringOperations operations, string serviceKey, BgpPeeringAccessType accessType, BorderGatewayProtocolPeeringUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IBorderGatewayProtocolPeeringOperations)s).BeginUpdateAsync(serviceKey, accessType, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Update Border Gateway Protocol Peering operation updates an
/// existing bgp peering.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ExpressRoute.IBorderGatewayProtocolPeeringOperations.
/// </param>
/// <param name='serviceKey'>
/// Required. The service key representing the relationship between
/// Azure and the customer.
/// </param>
/// <param name='accessType'>
/// Required. Whether the peering is private or public.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Update Border Gateway Protocol
/// Peering operation.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<ExpressRouteOperationResponse> BeginUpdateAsync(this IBorderGatewayProtocolPeeringOperations operations, string serviceKey, BgpPeeringAccessType accessType, BorderGatewayProtocolPeeringUpdateParameters parameters)
{
return operations.BeginUpdateAsync(serviceKey, accessType, parameters, CancellationToken.None);
}
/// <summary>
/// The Get Border Gateway Protocol Peering operation retrieves the bgp
/// peering for the dedicated circuit with the specified service key.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ExpressRoute.IBorderGatewayProtocolPeeringOperations.
/// </param>
/// <param name='serviceKey'>
/// Required. The servicee key representing the dedicated circuit.
/// </param>
/// <param name='accessType'>
/// Required. Whether the peering is private or public.
/// </param>
/// <returns>
/// The Get Border Gateway Protocol Peering Operation Response.
/// </returns>
public static BorderGatewayProtocolPeeringGetResponse Get(this IBorderGatewayProtocolPeeringOperations operations, string serviceKey, BgpPeeringAccessType accessType)
{
return Task.Factory.StartNew((object s) =>
{
return ((IBorderGatewayProtocolPeeringOperations)s).GetAsync(serviceKey, accessType);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Get Border Gateway Protocol Peering operation retrieves the bgp
/// peering for the dedicated circuit with the specified service key.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ExpressRoute.IBorderGatewayProtocolPeeringOperations.
/// </param>
/// <param name='serviceKey'>
/// Required. The servicee key representing the dedicated circuit.
/// </param>
/// <param name='accessType'>
/// Required. Whether the peering is private or public.
/// </param>
/// <returns>
/// The Get Border Gateway Protocol Peering Operation Response.
/// </returns>
public static Task<BorderGatewayProtocolPeeringGetResponse> GetAsync(this IBorderGatewayProtocolPeeringOperations operations, string serviceKey, BgpPeeringAccessType accessType)
{
return operations.GetAsync(serviceKey, accessType, CancellationToken.None);
}
/// <summary>
/// The Get Express Route operation status gets information on the
/// status of Express Route operations in Windows Azure. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj154112.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ExpressRoute.IBorderGatewayProtocolPeeringOperations.
/// </param>
/// <param name='operationId'>
/// Required. The id of the operation.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static ExpressRouteOperationStatusResponse GetOperationStatus(this IBorderGatewayProtocolPeeringOperations operations, string operationId)
{
return Task.Factory.StartNew((object s) =>
{
return ((IBorderGatewayProtocolPeeringOperations)s).GetOperationStatusAsync(operationId);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Get Express Route operation status gets information on the
/// status of Express Route operations in Windows Azure. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj154112.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ExpressRoute.IBorderGatewayProtocolPeeringOperations.
/// </param>
/// <param name='operationId'>
/// Required. The id of the operation.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static Task<ExpressRouteOperationStatusResponse> GetOperationStatusAsync(this IBorderGatewayProtocolPeeringOperations operations, string operationId)
{
return operations.GetOperationStatusAsync(operationId, CancellationToken.None);
}
/// <summary>
/// The New Border Gateway Protocol Peering operation creates a new
/// border gateway protocol peering associated with the dedicated
/// circuit specified by the service key provided.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ExpressRoute.IBorderGatewayProtocolPeeringOperations.
/// </param>
/// <param name='serviceKey'>
/// Required. The service key representing the relationship between
/// Azure and the customer.
/// </param>
/// <param name='accessType'>
/// Required. Whether the peering is private or public.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the New Bgp Peering operation.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static ExpressRouteOperationStatusResponse New(this IBorderGatewayProtocolPeeringOperations operations, string serviceKey, BgpPeeringAccessType accessType, BorderGatewayProtocolPeeringNewParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IBorderGatewayProtocolPeeringOperations)s).NewAsync(serviceKey, accessType, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The New Border Gateway Protocol Peering operation creates a new
/// border gateway protocol peering associated with the dedicated
/// circuit specified by the service key provided.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ExpressRoute.IBorderGatewayProtocolPeeringOperations.
/// </param>
/// <param name='serviceKey'>
/// Required. The service key representing the relationship between
/// Azure and the customer.
/// </param>
/// <param name='accessType'>
/// Required. Whether the peering is private or public.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the New Bgp Peering operation.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static Task<ExpressRouteOperationStatusResponse> NewAsync(this IBorderGatewayProtocolPeeringOperations operations, string serviceKey, BgpPeeringAccessType accessType, BorderGatewayProtocolPeeringNewParameters parameters)
{
return operations.NewAsync(serviceKey, accessType, parameters, CancellationToken.None);
}
/// <summary>
/// The Remove Border Gateway Protocol Peering operation deletes an
/// existing border gateway protocol peering.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ExpressRoute.IBorderGatewayProtocolPeeringOperations.
/// </param>
/// <param name='serviceKey'>
/// Required. Service key associated with the border gateway protocol
/// peering to be deleted.
/// </param>
/// <param name='accessType'>
/// Required. Whether the peering is private or public.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static ExpressRouteOperationStatusResponse Remove(this IBorderGatewayProtocolPeeringOperations operations, string serviceKey, BgpPeeringAccessType accessType)
{
return Task.Factory.StartNew((object s) =>
{
return ((IBorderGatewayProtocolPeeringOperations)s).RemoveAsync(serviceKey, accessType);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Remove Border Gateway Protocol Peering operation deletes an
/// existing border gateway protocol peering.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ExpressRoute.IBorderGatewayProtocolPeeringOperations.
/// </param>
/// <param name='serviceKey'>
/// Required. Service key associated with the border gateway protocol
/// peering to be deleted.
/// </param>
/// <param name='accessType'>
/// Required. Whether the peering is private or public.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static Task<ExpressRouteOperationStatusResponse> RemoveAsync(this IBorderGatewayProtocolPeeringOperations operations, string serviceKey, BgpPeeringAccessType accessType)
{
return operations.RemoveAsync(serviceKey, accessType, CancellationToken.None);
}
/// <summary>
/// The Update Border Gateway Protocol Peering operation updates an
/// existing border gateway protocol peering or creates a new one if
/// one doesn't exist.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ExpressRoute.IBorderGatewayProtocolPeeringOperations.
/// </param>
/// <param name='serviceKey'>
/// Required. The service key representing the relationship between
/// Azure and the customer.
/// </param>
/// <param name='accessType'>
/// Required. Whether the peering is private or public.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Update Border Gateway Protocol
/// Peering operation.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static ExpressRouteOperationStatusResponse Update(this IBorderGatewayProtocolPeeringOperations operations, string serviceKey, BgpPeeringAccessType accessType, BorderGatewayProtocolPeeringUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IBorderGatewayProtocolPeeringOperations)s).UpdateAsync(serviceKey, accessType, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Update Border Gateway Protocol Peering operation updates an
/// existing border gateway protocol peering or creates a new one if
/// one doesn't exist.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ExpressRoute.IBorderGatewayProtocolPeeringOperations.
/// </param>
/// <param name='serviceKey'>
/// Required. The service key representing the relationship between
/// Azure and the customer.
/// </param>
/// <param name='accessType'>
/// Required. Whether the peering is private or public.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Update Border Gateway Protocol
/// Peering operation.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static Task<ExpressRouteOperationStatusResponse> UpdateAsync(this IBorderGatewayProtocolPeeringOperations operations, string serviceKey, BgpPeeringAccessType accessType, BorderGatewayProtocolPeeringUpdateParameters parameters)
{
return operations.UpdateAsync(serviceKey, accessType, parameters, CancellationToken.None);
}
}
}
| yadavbdev/azure-sdk-for-net | src/ServiceManagement/ExpressRoute/ExpressRouteManagement/Generated/BorderGatewayProtocolPeeringOperationsExtensions.cs | C# | apache-2.0 | 27,351 |
/*
* 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.
*/
using System;
using System.Collections.Generic;
using Thrift.Server;
using Thrift.Transport;
namespace CSharpTutorial
{
public class CalculatorHandler : Calculator.Iface
{
Dictionary<int, SharedStruct> log;
public CalculatorHandler()
{
log = new Dictionary<int, SharedStruct>();
}
public void ping()
{
Console.WriteLine("ping()");
}
public int add(int n1, int n2)
{
Console.WriteLine("add({0},{1})", n1, n2);
return n1 + n2;
}
public int calculate(int logid, Work work)
{
Console.WriteLine("calculate({0}, [{1},{2},{3}])", logid, work.Op, work.Num1, work.Num2);
int val = 0;
switch (work.Op)
{
case Operation.ADD:
val = work.Num1 + work.Num2;
break;
case Operation.SUBTRACT:
val = work.Num1 - work.Num2;
break;
case Operation.MULTIPLY:
val = work.Num1 * work.Num2;
break;
case Operation.DIVIDE:
if (work.Num2 == 0)
{
InvalidOperation io = new InvalidOperation();
io.WhatOp = (int)work.Op;
io.Why = "Cannot divide by 0";
throw io;
}
val = work.Num1 / work.Num2;
break;
default:
{
InvalidOperation io = new InvalidOperation();
io.WhatOp = (int)work.Op;
io.Why = "Unknown operation";
throw io;
}
}
SharedStruct entry = new SharedStruct();
entry.Key = logid;
entry.Value = val.ToString();
log[logid] = entry;
return val;
}
public SharedStruct getStruct(int key)
{
Console.WriteLine("getStruct({0})", key);
return log[key];
}
public void zip()
{
Console.WriteLine("zip()");
}
}
public class CSharpServer
{
public static void Main()
{
try
{
CalculatorHandler handler = new CalculatorHandler();
Calculator.Processor processor = new Calculator.Processor(handler);
TServerTransport serverTransport = new TServerSocket(9090);
TServer server = new TSimpleServer(processor, serverTransport);
// Use this for a multithreaded server
// server = new TThreadPoolServer(processor, serverTransport);
Console.WriteLine("Starting the server...");
server.Serve();
}
catch (Exception x)
{
Console.WriteLine(x.StackTrace);
}
Console.WriteLine("done.");
}
}
}
| jcgruenhage/dendrite | vendor/src/github.com/apache/thrift/tutorial/csharp/CsharpServer/CsharpServer.cs | C# | apache-2.0 | 3,922 |
/*
* 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.index.sasi.utils;
import java.io.Closeable;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;
import com.google.common.annotations.VisibleForTesting;
public abstract class RangeIterator<K extends Comparable<K>, T extends CombinedValue<K>> extends AbstractIterator<T> implements Closeable
{
private final K min, max;
private final long count;
private K current;
protected RangeIterator(Builder.Statistics<K, T> statistics)
{
this(statistics.min, statistics.max, statistics.tokenCount);
}
public RangeIterator(RangeIterator<K, T> range)
{
this(range == null ? null : range.min, range == null ? null : range.max, range == null ? -1 : range.count);
}
public RangeIterator(K min, K max, long count)
{
if (min == null || max == null || count == 0)
assert min == null && max == null && (count == 0 || count == -1);
this.min = min;
this.current = min;
this.max = max;
this.count = count;
}
public final K getMinimum()
{
return min;
}
public final K getCurrent()
{
return current;
}
public final K getMaximum()
{
return max;
}
public final long getCount()
{
return count;
}
/**
* When called, this iterators current position should
* be skipped forwards until finding either:
* 1) an element equal to or bigger than next
* 2) the end of the iterator
*
* @param nextToken value to skip the iterator forward until matching
*
* @return The next current token after the skip was performed
*/
public final T skipTo(K nextToken)
{
if (min == null || max == null)
return endOfData();
if (current.compareTo(nextToken) >= 0)
return next == null ? recomputeNext() : next;
if (max.compareTo(nextToken) < 0)
return endOfData();
performSkipTo(nextToken);
return recomputeNext();
}
protected abstract void performSkipTo(K nextToken);
protected T recomputeNext()
{
return tryToComputeNext() ? peek() : endOfData();
}
protected boolean tryToComputeNext()
{
boolean hasNext = super.tryToComputeNext();
current = hasNext ? next.get() : getMaximum();
return hasNext;
}
public static abstract class Builder<K extends Comparable<K>, D extends CombinedValue<K>>
{
public enum IteratorType
{
UNION, INTERSECTION
}
@VisibleForTesting
protected final Statistics<K, D> statistics;
@VisibleForTesting
protected final PriorityQueue<RangeIterator<K, D>> ranges;
public Builder(IteratorType type)
{
statistics = new Statistics<>(type);
ranges = new PriorityQueue<>(16, (Comparator<RangeIterator<K, D>>) (a, b) -> a.getCurrent().compareTo(b.getCurrent()));
}
public K getMinimum()
{
return statistics.min;
}
public K getMaximum()
{
return statistics.max;
}
public long getTokenCount()
{
return statistics.tokenCount;
}
public int rangeCount()
{
return ranges.size();
}
public Builder<K, D> add(RangeIterator<K, D> range)
{
if (range == null)
return this;
if (range.getCount() > 0)
ranges.add(range);
statistics.update(range);
return this;
}
public Builder<K, D> add(List<RangeIterator<K, D>> ranges)
{
if (ranges == null || ranges.isEmpty())
return this;
ranges.forEach(this::add);
return this;
}
public final RangeIterator<K, D> build()
{
if (rangeCount() == 0)
return new EmptyRangeIterator<>();
else
return buildIterator();
}
public static class EmptyRangeIterator<K extends Comparable<K>, D extends CombinedValue<K>> extends RangeIterator<K, D>
{
EmptyRangeIterator() { super(null, null, 0); }
public D computeNext() { return endOfData(); }
protected void performSkipTo(K nextToken) { }
public void close() { }
}
protected abstract RangeIterator<K, D> buildIterator();
public static class Statistics<K extends Comparable<K>, D extends CombinedValue<K>>
{
protected final IteratorType iteratorType;
protected K min, max;
protected long tokenCount;
// iterator with the least number of items
protected RangeIterator<K, D> minRange;
// iterator with the most number of items
protected RangeIterator<K, D> maxRange;
// tracks if all of the added ranges overlap, which is useful in case of intersection,
// as it gives direct answer as to such iterator is going to produce any results.
private boolean isOverlapping = true;
public Statistics(IteratorType iteratorType)
{
this.iteratorType = iteratorType;
}
/**
* Update statistics information with the given range.
*
* Updates min/max of the combined range, token count and
* tracks range with the least/most number of tokens.
*
* @param range The range to update statistics with.
*/
public void update(RangeIterator<K, D> range)
{
switch (iteratorType)
{
case UNION:
min = nullSafeMin(min, range.getMinimum());
max = nullSafeMax(max, range.getMaximum());
break;
case INTERSECTION:
// minimum of the intersection is the biggest minimum of individual iterators
min = nullSafeMax(min, range.getMinimum());
// maximum of the intersection is the smallest maximum of individual iterators
max = nullSafeMin(max, range.getMaximum());
break;
default:
throw new IllegalStateException("Unknown iterator type: " + iteratorType);
}
// check if new range is disjoint with already added ranges, which means that this intersection
// is not going to produce any results, so we can cleanup range storage and never added anything to it.
isOverlapping &= isOverlapping(min, max, range);
minRange = minRange == null ? range : min(minRange, range);
maxRange = maxRange == null ? range : max(maxRange, range);
tokenCount += range.getCount();
}
private RangeIterator<K, D> min(RangeIterator<K, D> a, RangeIterator<K, D> b)
{
return a.getCount() > b.getCount() ? b : a;
}
private RangeIterator<K, D> max(RangeIterator<K, D> a, RangeIterator<K, D> b)
{
return a.getCount() > b.getCount() ? a : b;
}
public boolean isDisjoint()
{
return !isOverlapping;
}
public double sizeRatio()
{
return minRange.getCount() * 1d / maxRange.getCount();
}
}
}
@VisibleForTesting
protected static <K extends Comparable<K>, D extends CombinedValue<K>> boolean isOverlapping(RangeIterator<K, D> a, RangeIterator<K, D> b)
{
return isOverlapping(a.getCurrent(), a.getMaximum(), b);
}
/**
* Ranges are overlapping the following cases:
*
* * When they have a common subrange:
*
* min b.current max b.max
* +---------|--------------+------------|
*
* b.current min max b.max
* |--------------+---------+------------|
*
* min b.current b.max max
* +----------|-------------|------------+
*
*
* If either range is empty, they're disjoint.
*/
@VisibleForTesting
protected static <K extends Comparable<K>, D extends CombinedValue<K>> boolean isOverlapping(K min, K max, RangeIterator<K, D> b)
{
return (min != null && max != null) &&
b.getCount() != 0 &&
(min.compareTo(b.getMaximum()) <= 0 && b.getCurrent().compareTo(max) <= 0);
}
@SuppressWarnings("unchecked")
private static <T extends Comparable> T nullSafeMin(T a, T b)
{
if (a == null) return b;
if (b == null) return a;
return a.compareTo(b) > 0 ? b : a;
}
@SuppressWarnings("unchecked")
private static <T extends Comparable> T nullSafeMax(T a, T b)
{
if (a == null) return b;
if (b == null) return a;
return a.compareTo(b) > 0 ? a : b;
}
}
| Jollyplum/cassandra | src/java/org/apache/cassandra/index/sasi/utils/RangeIterator.java | Java | apache-2.0 | 10,066 |
#include <muduo/base/LogStream.h>
#include <algorithm>
#include <limits>
#include <boost/static_assert.hpp>
#include <boost/type_traits/is_arithmetic.hpp>
#include <assert.h>
#include <string.h>
#include <stdint.h>
#include <stdio.h>
using namespace muduo;
using namespace muduo::detail;
#if defined(__clang__)
#pragma clang diagnostic ignored "-Wtautological-compare"
#else
#pragma GCC diagnostic ignored "-Wtype-limits"
#endif
namespace muduo
{
namespace detail
{
const char digits[] = "9876543210123456789";
const char* zero = digits + 9;
BOOST_STATIC_ASSERT(sizeof(digits) == 20);
const char digitsHex[] = "0123456789ABCDEF";
BOOST_STATIC_ASSERT(sizeof digitsHex == 17);
// Efficient Integer to String Conversions, by Matthew Wilson.
template<typename T>
size_t convert(char buf[], T value)
{
T i = value;
char* p = buf;
do
{
int lsd = static_cast<int>(i % 10);
i /= 10;
*p++ = zero[lsd];
} while (i != 0);
if (value < 0)
{
*p++ = '-';
}
*p = '\0';
std::reverse(buf, p);
return p - buf;
}
size_t convertHex(char buf[], uintptr_t value)
{
uintptr_t i = value;
char* p = buf;
do
{
int lsd = static_cast<int>(i % 16);
i /= 16;
*p++ = digitsHex[lsd];
} while (i != 0);
*p = '\0';
std::reverse(buf, p);
return p - buf;
}
template class FixedBuffer<kSmallBuffer>;
template class FixedBuffer<kLargeBuffer>;
}
}
template<int SIZE>
const char* FixedBuffer<SIZE>::debugString()
{
*cur_ = '\0';
return data_;
}
template<int SIZE>
void FixedBuffer<SIZE>::cookieStart()
{
}
template<int SIZE>
void FixedBuffer<SIZE>::cookieEnd()
{
}
void LogStream::staticCheck()
{
BOOST_STATIC_ASSERT(kMaxNumericSize - 10 > std::numeric_limits<double>::digits10);
BOOST_STATIC_ASSERT(kMaxNumericSize - 10 > std::numeric_limits<long double>::digits10);
BOOST_STATIC_ASSERT(kMaxNumericSize - 10 > std::numeric_limits<long>::digits10);
BOOST_STATIC_ASSERT(kMaxNumericSize - 10 > std::numeric_limits<long long>::digits10);
}
template<typename T>
void LogStream::formatInteger(T v)
{
if (buffer_.avail() >= kMaxNumericSize)
{
size_t len = convert(buffer_.current(), v);
buffer_.add(len);
}
}
LogStream& LogStream::operator<<(short v)
{
*this << static_cast<int>(v);
return *this;
}
LogStream& LogStream::operator<<(unsigned short v)
{
*this << static_cast<unsigned int>(v);
return *this;
}
LogStream& LogStream::operator<<(int v)
{
formatInteger(v);
return *this;
}
LogStream& LogStream::operator<<(unsigned int v)
{
formatInteger(v);
return *this;
}
LogStream& LogStream::operator<<(long v)
{
formatInteger(v);
return *this;
}
LogStream& LogStream::operator<<(unsigned long v)
{
formatInteger(v);
return *this;
}
LogStream& LogStream::operator<<(long long v)
{
formatInteger(v);
return *this;
}
LogStream& LogStream::operator<<(unsigned long long v)
{
formatInteger(v);
return *this;
}
LogStream& LogStream::operator<<(const void* p)
{
uintptr_t v = reinterpret_cast<uintptr_t>(p);
if (buffer_.avail() >= kMaxNumericSize)
{
char* buf = buffer_.current();
buf[0] = '0';
buf[1] = 'x';
size_t len = convertHex(buf+2, v);
buffer_.add(len+2);
}
return *this;
}
// FIXME: replace this with Grisu3 by Florian Loitsch.
LogStream& LogStream::operator<<(double v)
{
if (buffer_.avail() >= kMaxNumericSize)
{
int len = snprintf(buffer_.current(), kMaxNumericSize, "%.12g", v);
buffer_.add(len);
}
return *this;
}
template<typename T>
Fmt::Fmt(const char* fmt, T val)
{
BOOST_STATIC_ASSERT(boost::is_arithmetic<T>::value == true);
length_ = snprintf(buf_, sizeof buf_, fmt, val);
assert(static_cast<size_t>(length_) < sizeof buf_);
}
// Explicit instantiations
template Fmt::Fmt(const char* fmt, char);
template Fmt::Fmt(const char* fmt, short);
template Fmt::Fmt(const char* fmt, unsigned short);
template Fmt::Fmt(const char* fmt, int);
template Fmt::Fmt(const char* fmt, unsigned int);
template Fmt::Fmt(const char* fmt, long);
template Fmt::Fmt(const char* fmt, unsigned long);
template Fmt::Fmt(const char* fmt, long long);
template Fmt::Fmt(const char* fmt, unsigned long long);
template Fmt::Fmt(const char* fmt, float);
template Fmt::Fmt(const char* fmt, double);
| DongweiLee/muduo | muduo/base/LogStream.cc | C++ | bsd-3-clause | 4,244 |
import * as React from 'react';
import { IconBaseProps } from 'react-icon-base';
declare class MdEvStation extends React.Component<IconBaseProps> { }
export = MdEvStation;
| zuzusik/DefinitelyTyped | types/react-icons/lib/md/ev-station.d.ts | TypeScript | mit | 172 |
<?php
/**
* This file is part of cocur/slugify.
*
* (c) Florian Eckerstorfer <florian@eckerstorfer.co>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Cocur\Slugify;
/**
* SlugifyInterface
*
* @package org.cocur.slugify
* @author Florian Eckerstorfer <florian@eckerstorfer.co>
* @author Marchenko Alexandr
* @copyright 2012-2014 Florian Eckerstorfer
* @license http://www.opensource.org/licenses/MIT The MIT License
*/
interface SlugifyInterface
{
/**
* Return a URL safe version of a string.
*
* @param string $string
* @param string $separator
*
* @return string
*/
public function slugify($string, $separator = '-');
}
| sonata-project/sandbox-build | vendor/cocur/slugify/src/SlugifyInterface.php | PHP | mit | 785 |
'use strict'
module.exports = Math.PI.toString().slice(0, 6)
| wooorm/mdast-usage | test/fixtures/require-last/index.js | JavaScript | mit | 62 |
/**
* Copyright (c) 2010-2015, openHAB.org and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.enphaseenergy.internal.messages;
import static org.apache.commons.lang.builder.ToStringStyle.SHORT_PREFIX_STYLE;
import org.apache.commons.lang.builder.ToStringBuilder;
/**
* Base class for all messages.
*
* @author Markus Fritze
* @since 1.7.0
*/
public class AbstractMessage {
@Override
public String toString() {
final ToStringBuilder builder = createToStringBuilder();
return builder.toString();
}
protected final ToStringBuilder createToStringBuilder() {
return new ToStringBuilder(this, SHORT_PREFIX_STYLE);
}
}
| bakrus/openhab | bundles/binding/org.openhab.binding.enphaseenergy/src/main/java/org/openhab/binding/enphaseenergy/internal/messages/AbstractMessage.java | Java | epl-1.0 | 879 |
// Copyright (c) 2011 Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Original author: Jim Blandy <jimb@mozilla.com> <jimb@red-bean.com>
// module.cc: Implement google_breakpad::Module. See module.h.
#include "common/module.h"
#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <utility>
namespace google_breakpad {
using std::dec;
using std::endl;
using std::hex;
Module::Module(const string &name, const string &os,
const string &architecture, const string &id) :
name_(name),
os_(os),
architecture_(architecture),
id_(id),
load_address_(0) { }
Module::~Module() {
for (FileByNameMap::iterator it = files_.begin(); it != files_.end(); ++it)
delete it->second;
for (FunctionSet::iterator it = functions_.begin();
it != functions_.end(); ++it) {
delete *it;
}
for (vector<StackFrameEntry *>::iterator it = stack_frame_entries_.begin();
it != stack_frame_entries_.end(); ++it) {
delete *it;
}
for (ExternSet::iterator it = externs_.begin(); it != externs_.end(); ++it)
delete *it;
}
void Module::SetLoadAddress(Address address) {
load_address_ = address;
}
void Module::AddFunction(Function *function) {
// FUNC lines must not hold an empty name, so catch the problem early if
// callers try to add one.
assert(!function->name.empty());
std::pair<FunctionSet::iterator,bool> ret = functions_.insert(function);
if (!ret.second) {
// Free the duplicate that was not inserted because this Module
// now owns it.
delete function;
}
}
void Module::AddFunctions(vector<Function *>::iterator begin,
vector<Function *>::iterator end) {
for (vector<Function *>::iterator it = begin; it != end; ++it)
AddFunction(*it);
}
void Module::AddStackFrameEntry(StackFrameEntry *stack_frame_entry) {
stack_frame_entries_.push_back(stack_frame_entry);
}
void Module::AddExtern(Extern *ext) {
std::pair<ExternSet::iterator,bool> ret = externs_.insert(ext);
if (!ret.second) {
// Free the duplicate that was not inserted because this Module
// now owns it.
delete ext;
}
}
void Module::GetFunctions(vector<Function *> *vec,
vector<Function *>::iterator i) {
vec->insert(i, functions_.begin(), functions_.end());
}
void Module::GetExterns(vector<Extern *> *vec,
vector<Extern *>::iterator i) {
vec->insert(i, externs_.begin(), externs_.end());
}
Module::File *Module::FindFile(const string &name) {
// A tricky bit here. The key of each map entry needs to be a
// pointer to the entry's File's name string. This means that we
// can't do the initial lookup with any operation that would create
// an empty entry for us if the name isn't found (like, say,
// operator[] or insert do), because such a created entry's key will
// be a pointer the string passed as our argument. Since the key of
// a map's value type is const, we can't fix it up once we've
// created our file. lower_bound does the lookup without doing an
// insertion, and returns a good hint iterator to pass to insert.
// Our "destiny" is where we belong, whether we're there or not now.
FileByNameMap::iterator destiny = files_.lower_bound(&name);
if (destiny == files_.end()
|| *destiny->first != name) { // Repeated string comparison, boo hoo.
File *file = new File;
file->name = name;
file->source_id = -1;
destiny = files_.insert(destiny,
FileByNameMap::value_type(&file->name, file));
}
return destiny->second;
}
Module::File *Module::FindFile(const char *name) {
string name_string = name;
return FindFile(name_string);
}
Module::File *Module::FindExistingFile(const string &name) {
FileByNameMap::iterator it = files_.find(&name);
return (it == files_.end()) ? NULL : it->second;
}
void Module::GetFiles(vector<File *> *vec) {
vec->clear();
for (FileByNameMap::iterator it = files_.begin(); it != files_.end(); ++it)
vec->push_back(it->second);
}
void Module::GetStackFrameEntries(vector<StackFrameEntry *> *vec) {
*vec = stack_frame_entries_;
}
void Module::AssignSourceIds() {
// First, give every source file an id of -1.
for (FileByNameMap::iterator file_it = files_.begin();
file_it != files_.end(); ++file_it) {
file_it->second->source_id = -1;
}
// Next, mark all files actually cited by our functions' line number
// info, by setting each one's source id to zero.
for (FunctionSet::const_iterator func_it = functions_.begin();
func_it != functions_.end(); ++func_it) {
Function *func = *func_it;
for (vector<Line>::iterator line_it = func->lines.begin();
line_it != func->lines.end(); ++line_it)
line_it->file->source_id = 0;
}
// Finally, assign source ids to those files that have been marked.
// We could have just assigned source id numbers while traversing
// the line numbers, but doing it this way numbers the files in
// lexicographical order by name, which is neat.
int next_source_id = 0;
for (FileByNameMap::iterator file_it = files_.begin();
file_it != files_.end(); ++file_it) {
if (!file_it->second->source_id)
file_it->second->source_id = next_source_id++;
}
}
bool Module::ReportError() {
fprintf(stderr, "error writing symbol file: %s\n",
strerror(errno));
return false;
}
bool Module::WriteRuleMap(const RuleMap &rule_map, std::ostream &stream) {
for (RuleMap::const_iterator it = rule_map.begin();
it != rule_map.end(); ++it) {
if (it != rule_map.begin())
stream << ' ';
stream << it->first << ": " << it->second;
}
return stream.good();
}
bool Module::Write(std::ostream &stream, SymbolData symbol_data) {
stream << "MODULE " << os_ << " " << architecture_ << " "
<< id_ << " " << name_ << endl;
if (!stream.good())
return ReportError();
if (symbol_data != ONLY_CFI) {
AssignSourceIds();
// Write out files.
for (FileByNameMap::iterator file_it = files_.begin();
file_it != files_.end(); ++file_it) {
File *file = file_it->second;
if (file->source_id >= 0) {
stream << "FILE " << file->source_id << " " << file->name << endl;
if (!stream.good())
return ReportError();
}
}
// Write out functions and their lines.
for (FunctionSet::const_iterator func_it = functions_.begin();
func_it != functions_.end(); ++func_it) {
Function *func = *func_it;
stream << "FUNC " << hex
<< (func->address - load_address_) << " "
<< func->size << " "
<< func->parameter_size << " "
<< func->name << dec << endl;
if (!stream.good())
return ReportError();
for (vector<Line>::iterator line_it = func->lines.begin();
line_it != func->lines.end(); ++line_it) {
stream << hex
<< (line_it->address - load_address_) << " "
<< line_it->size << " "
<< dec
<< line_it->number << " "
<< line_it->file->source_id << endl;
if (!stream.good())
return ReportError();
}
}
// Write out 'PUBLIC' records.
for (ExternSet::const_iterator extern_it = externs_.begin();
extern_it != externs_.end(); ++extern_it) {
Extern *ext = *extern_it;
stream << "PUBLIC " << hex
<< (ext->address - load_address_) << " 0 "
<< ext->name << dec << endl;
}
}
if (symbol_data != NO_CFI) {
// Write out 'STACK CFI INIT' and 'STACK CFI' records.
vector<StackFrameEntry *>::const_iterator frame_it;
for (frame_it = stack_frame_entries_.begin();
frame_it != stack_frame_entries_.end(); ++frame_it) {
StackFrameEntry *entry = *frame_it;
stream << "STACK CFI INIT " << hex
<< (entry->address - load_address_) << " "
<< entry->size << " " << dec;
if (!stream.good()
|| !WriteRuleMap(entry->initial_rules, stream))
return ReportError();
stream << endl;
// Write out this entry's delta rules as 'STACK CFI' records.
for (RuleChangeMap::const_iterator delta_it = entry->rule_changes.begin();
delta_it != entry->rule_changes.end(); ++delta_it) {
stream << "STACK CFI " << hex
<< (delta_it->first - load_address_) << " " << dec;
if (!stream.good()
|| !WriteRuleMap(delta_it->second, stream))
return ReportError();
stream << endl;
}
}
}
return true;
}
} // namespace google_breakpad
| BozhkoAlexander/mtasa-blue | vendor/google-breakpad/src/common/module.cc | C++ | gpl-3.0 | 10,178 |
package com.google.samplesolutions.mobileassistant;
import java.io.IOException;
import com.google.samplesolutions.mobileassistant.messageEndpoint.MessageEndpoint;
import com.google.samplesolutions.mobileassistant.messageEndpoint.model.CollectionResponseMessageData;
import com.google.samplesolutions.mobileassistant.messageEndpoint.model.MessageData;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.json.jackson.JacksonFactory;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.TextView;
/**
* An activity that communicates with your App Engine backend via Cloud
* Endpoints.
*
* When the user hits the "Register" button, a message is sent to the backend
* (over endpoints) indicating that the device would like to receive broadcast
* messages from it. Clicking "Register" also has the effect of registering this
* device for Google Cloud Messaging (GCM). Whenever the backend wants to
* broadcast a message, it does it via GCM, so that the device does not need to
* keep polling the backend for messages.
*
* If you've generated an App Engine backend for an existing Android project,
* this activity will not be hooked in to your main activity as yet. You can
* easily do so by adding the following lines to your main activity:
*
* Intent intent = new Intent(this, RegisterActivity.class);
* startActivity(intent);
*
* To make the sample run, you need to set your PROJECT_NUMBER in
* GCMIntentService.java. If you're going to be running a local version of the
* App Engine backend (using the DevAppServer), you'll need to toggle the
* LOCAL_ANDROID_RUN flag in CloudEndpointUtils.java. See the javadoc in these
* classes for more details.
*
* For a comprehensive walkthrough, check out the documentation at
* http://developers.google.com/eclipse/docs/cloud_endpoints
*/
public class RegisterActivity extends Activity {
enum State {
REGISTERED, REGISTERING, UNREGISTERED, UNREGISTERING
}
private State curState = State.UNREGISTERED;
private OnTouchListener registerListener = null;
private OnTouchListener unregisterListener = null;
private MessageEndpoint messageEndpoint = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Button regButton = (Button) findViewById(R.id.regButton);
registerListener = new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
if (GCMIntentService.PROJECT_NUMBER == null
|| GCMIntentService.PROJECT_NUMBER.length() == 0) {
showDialog("Unable to register for Google Cloud Messaging. "
+ "Your application's PROJECT_NUMBER field is unset! You can change "
+ "it in GCMIntentService.java");
} else {
updateState(State.REGISTERING);
try {
GCMIntentService.register(getApplicationContext());
} catch (Exception e) {
Log.e(RegisterActivity.class.getName(),
"Exception received when attempting to register for Google Cloud "
+ "Messaging. Perhaps you need to set your virtual device's "
+ " target to Google APIs? "
+ "See https://developers.google.com/eclipse/docs/cloud_endpoints_android"
+ " for more information.", e);
showDialog("There was a problem when attempting to register for "
+ "Google Cloud Messaging. If you're running in the emulator, "
+ "is the target of your virtual device set to 'Google APIs?' "
+ "See the Android log for more details.");
updateState(State.UNREGISTERED);
}
}
return true;
case MotionEvent.ACTION_UP:
return true;
default:
return false;
}
}
};
unregisterListener = new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
updateState(State.UNREGISTERING);
GCMIntentService.unregister(getApplicationContext());
return true;
case MotionEvent.ACTION_UP:
return true;
default:
return false;
}
}
};
regButton.setOnTouchListener(registerListener);
/*
* build the messaging endpoint so we can access old messages via an endpoint call
*/
MessageEndpoint.Builder endpointBuilder = new MessageEndpoint.Builder(
AndroidHttp.newCompatibleTransport(),
new JacksonFactory(),
new HttpRequestInitializer() {
public void initialize(HttpRequest httpRequest) { }
});
messageEndpoint = CloudEndpointUtils.updateBuilder(endpointBuilder).build();
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
/*
* If we are dealing with an intent generated by the GCMIntentService
* class, then display the provided message.
*/
if (intent.getBooleanExtra("gcmIntentServiceMessage", false)) {
showDialog(intent.getStringExtra("message"));
if (intent.getBooleanExtra("registrationMessage", false)) {
if (intent.getBooleanExtra("error", false)) {
/*
* If we get a registration/unregistration-related error,
* and we're in the process of registering, then we move
* back to the unregistered state. If we're in the process
* of unregistering, then we move back to the registered
* state.
*/
if (curState == State.REGISTERING) {
updateState(State.UNREGISTERED);
} else {
updateState(State.REGISTERED);
}
} else {
/*
* If we get a registration/unregistration-related success,
* and we're in the process of registering, then we move to
* the registered state. If we're in the process of
* unregistering, the we move back to the unregistered
* state.
*/
if (curState == State.REGISTERING) {
updateState(State.REGISTERED);
} else {
updateState(State.UNREGISTERED);
}
}
}
else {
/*
* if we didn't get a registration/unregistration message then
* go get the last 5 messages from app-engine
*/
new QueryMessagesTask(this, messageEndpoint).execute();
}
}
}
private void updateState(State newState) {
Button registerButton = (Button) findViewById(R.id.regButton);
switch (newState) {
case REGISTERED:
registerButton.setText("Unregister");
registerButton.setOnTouchListener(unregisterListener);
registerButton.setEnabled(true);
break;
case REGISTERING:
registerButton.setText("Registering...");
registerButton.setEnabled(false);
break;
case UNREGISTERED:
registerButton.setText("Register");
registerButton.setOnTouchListener(registerListener);
registerButton.setEnabled(true);
break;
case UNREGISTERING:
registerButton.setText("Unregistering...");
registerButton.setEnabled(false);
break;
}
curState = newState;
}
private void showDialog(String message) {
new AlertDialog.Builder(this)
.setMessage(message)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
}).show();
}
/*
* Need to run this in background so we don't hold up the UI thread,
* this task will ask the App Engine backend for the last 5 messages
* sent to it
*/
private class QueryMessagesTask
extends AsyncTask<Void, Void, CollectionResponseMessageData> {
Exception exceptionThrown = null;
Activity activity;
MessageEndpoint messageEndpoint;
public QueryMessagesTask(Activity activity, MessageEndpoint messageEndpoint) {
this.activity = activity;
this.messageEndpoint = messageEndpoint;
}
@Override
protected CollectionResponseMessageData doInBackground(Void... params) {
try {
CollectionResponseMessageData messages =
messageEndpoint.listMessages().setLimit(5).execute();
return messages;
} catch (IOException e) {
exceptionThrown = e;
return null;
//Handle exception in PostExecute
}
}
protected void onPostExecute(CollectionResponseMessageData messages) {
// Check if exception was thrown
if (exceptionThrown != null) {
Log.e(RegisterActivity.class.getName(),
"Exception when listing Messages", exceptionThrown);
showDialog("Failed to retrieve the last 5 messages from " +
"the endpoint at " + messageEndpoint.getBaseUrl() +
", check log for details");
}
else {
TextView messageView = (TextView) findViewById(R.id.msgView);
messageView.setText("Last 5 Messages read from " +
messageEndpoint.getBaseUrl() + ":\n");
for(MessageData message : messages.getItems()) {
messageView.append(message.getMessage() + "\n");
}
}
}
}
}
| hiaihua/solutions-mobile-shopping-assistant-backend-java | MobileAssistant-Tutorial/MobileAssistant/src/com/google/samplesolutions/mobileassistant/RegisterActivity.java | Java | apache-2.0 | 10,098 |
/*
* Copyright (c) 2003, 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.awt.X11;
public interface XStateProtocol {
/**
* Returns whether or not the protocol supports the transition to the state
* represented by <code>state</code>. <code>State</code> contains encoded state
* as a bit mask of state defined in java.awt.Frame
*/
boolean supportsState(int state);
/**
* Moves window into the state.
*/
void setState(XWindowPeer window, int state);
/**
* Returns current state of the window
*/
int getState(XWindowPeer window);
/**
* Detects whether or not this event is indicates state change
*/
boolean isStateChange(XPropertyEvent e);
/**
* Work around for 4775545.
*/
void unshadeKludge(XWindowPeer window);
}
| rokn/Count_Words_2015 | testing/openjdk2/jdk/src/solaris/classes/sun/awt/X11/XStateProtocol.java | Java | mit | 1,965 |
/*! UIkit 2.24.2 | http://www.getuikit.com | (c) 2014 YOOtheme | MIT License */
(function(addon) {
var component;
if (window.UIkit) {
component = addon(UIkit);
}
if (typeof define == "function" && define.amd) {
define("uikit-sticky", ["uikit"], function(){
return component || addon(UIkit);
});
}
})(function(UI){
"use strict";
var $win = UI.$win,
$doc = UI.$doc,
sticked = [],
direction = 1;
UI.component('sticky', {
defaults: {
top : 0,
bottom : 0,
animation : '',
clsinit : 'uk-sticky-init',
clsactive : 'uk-active',
clsinactive : '',
getWidthFrom : '',
showup : false,
boundary : false,
media : false,
target : false,
disabled : false
},
boot: function() {
// should be more efficient than using $win.scroll(checkscrollposition):
UI.$doc.on('scrolling.uk.document', function(e, data) {
if (!data || !data.dir) return;
direction = data.dir.y;
checkscrollposition();
});
UI.$win.on('resize orientationchange', UI.Utils.debounce(function() {
if (!sticked.length) return;
for (var i = 0; i < sticked.length; i++) {
sticked[i].reset(true);
//sticked[i].self.computeWrapper();
}
checkscrollposition();
}, 100));
// init code
UI.ready(function(context) {
setTimeout(function(){
UI.$("[data-uk-sticky]", context).each(function(){
var $ele = UI.$(this);
if(!$ele.data("sticky")) {
UI.sticky($ele, UI.Utils.options($ele.attr('data-uk-sticky')));
}
});
checkscrollposition();
}, 0);
});
},
init: function() {
var wrapper = UI.$('<div class="uk-sticky-placeholder"></div>'), boundary = this.options.boundary, boundtoparent;
this.wrapper = this.element.css('margin', 0).wrap(wrapper).parent();
this.computeWrapper();
if (boundary) {
if (boundary === true || boundary[0] === '!') {
boundary = boundary === true ? this.wrapper.parent() : this.wrapper.closest(boundary.substr(1));
boundtoparent = true;
} else if (typeof boundary === "string") {
boundary = UI.$(boundary);
}
}
this.sticky = {
self : this,
options : this.options,
element : this.element,
currentTop : null,
wrapper : this.wrapper,
init : false,
getWidthFrom : UI.$(this.options.getWidthFrom || this.wrapper),
boundary : boundary,
boundtoparent : boundtoparent,
top : 0,
calcTop : function() {
var top = this.options.top;
// dynamic top parameter
if (this.options.top && typeof(this.options.top) == 'string') {
// e.g. 50vh
if (this.options.top.match(/^(-|)(\d+)vh$/)) {
top = window.innerHeight * parseInt(this.options.top, 10)/100;
// e.g. #elementId, or .class-1,class-2,.class-3 (first found is used)
} else {
var topElement = UI.$(this.options.top).first();
if (topElement.length && topElement.is(':visible')) {
top = -1 * ((topElement.offset().top + topElement.outerHeight()) - this.wrapper.offset().top);
}
}
}
this.top = top;
},
reset: function(force) {
this.calcTop();
var finalize = function() {
this.element.css({"position":"", "top":"", "width":"", "left":"", "margin":"0"});
this.element.removeClass([this.options.animation, 'uk-animation-reverse', this.options.clsactive].join(' '));
this.element.addClass(this.options.clsinactive);
this.element.trigger('inactive.uk.sticky');
this.currentTop = null;
this.animate = false;
}.bind(this);
if (!force && this.options.animation && UI.support.animation && !UI.Utils.isInView(this.wrapper)) {
this.animate = true;
this.element.removeClass(this.options.animation).one(UI.support.animation.end, function(){
finalize();
}).width(); // force redraw
this.element.addClass(this.options.animation+' '+'uk-animation-reverse');
} else {
finalize();
}
},
check: function() {
if (this.options.disabled) {
return false;
}
if (this.options.media) {
switch(typeof(this.options.media)) {
case 'number':
if (window.innerWidth < this.options.media) {
return false;
}
break;
case 'string':
if (window.matchMedia && !window.matchMedia(this.options.media).matches) {
return false;
}
break;
}
}
var scrollTop = $win.scrollTop(),
documentHeight = $doc.height(),
dwh = documentHeight - window.innerHeight,
extra = (scrollTop > dwh) ? dwh - scrollTop : 0,
elementTop = this.wrapper.offset().top,
etse = elementTop - this.top - extra,
active = (scrollTop >= etse);
if (active && this.options.showup) {
// set inactiv if scrolling down
if (direction == 1) {
active = false;
}
// set inactive when wrapper is still in view
if (direction == -1 && !this.element.hasClass(this.options.clsactive) && UI.Utils.isInView(this.wrapper)) {
active = false;
}
}
return active;
}
};
this.sticky.calcTop();
sticked.push(this.sticky);
},
update: function() {
checkscrollposition(this.sticky);
},
enable: function() {
this.options.disabled = false;
this.update();
},
disable: function(force) {
this.options.disabled = true;
this.sticky.reset(force);
},
computeWrapper: function() {
this.wrapper.css({
'height' : ['absolute','fixed'].indexOf(this.element.css('position')) == -1 ? this.element.outerHeight() : '',
'float' : this.element.css('float') != 'none' ? this.element.css('float') : '',
'margin' : this.element.css('margin')
});
if (this.element.css('position') == 'fixed') {
this.element.css({
width: this.sticky.getWidthFrom.length ? this.sticky.getWidthFrom.width() : this.element.width()
});
}
}
});
function checkscrollposition(direction) {
var stickies = arguments.length ? arguments : sticked;
if (!stickies.length || $win.scrollTop() < 0) return;
var scrollTop = $win.scrollTop(),
documentHeight = $doc.height(),
windowHeight = $win.height(),
dwh = documentHeight - windowHeight,
extra = (scrollTop > dwh) ? dwh - scrollTop : 0,
newTop, containerBottom, stickyHeight, sticky;
for (var i = 0; i < stickies.length; i++) {
sticky = stickies[i];
if (!sticky.element.is(":visible") || sticky.animate) {
continue;
}
if (!sticky.check()) {
if (sticky.currentTop !== null) {
sticky.reset();
}
} else {
if (sticky.top < 0) {
newTop = 0;
} else {
stickyHeight = sticky.element.outerHeight();
newTop = documentHeight - stickyHeight - sticky.top - sticky.options.bottom - scrollTop - extra;
newTop = newTop < 0 ? newTop + sticky.top : sticky.top;
}
if (sticky.boundary && sticky.boundary.length) {
var bTop = sticky.boundary.offset().top;
if (sticky.boundtoparent) {
containerBottom = documentHeight - (bTop + sticky.boundary.outerHeight()) + parseInt(sticky.boundary.css('padding-bottom'));
} else {
containerBottom = documentHeight - bTop - parseInt(sticky.boundary.css('margin-top'));
}
newTop = (scrollTop + stickyHeight) > (documentHeight - containerBottom - (sticky.top < 0 ? 0 : sticky.top)) ? (documentHeight - containerBottom) - (scrollTop + stickyHeight) : newTop;
}
if (sticky.currentTop != newTop) {
sticky.element.css({
position : "fixed",
top : newTop,
width : sticky.getWidthFrom.length ? sticky.getWidthFrom.width() : sticky.element.width(),
left : sticky.wrapper.offset().left
});
if (!sticky.init) {
sticky.element.addClass(sticky.options.clsinit);
if (location.hash && scrollTop > 0 && sticky.options.target) {
var $target = UI.$(location.hash);
if ($target.length) {
setTimeout((function($target, sticky){
return function() {
sticky.element.width(); // force redraw
var offset = $target.offset(),
maxoffset = offset.top + $target.outerHeight(),
stickyOffset = sticky.element.offset(),
stickyHeight = sticky.element.outerHeight(),
stickyMaxOffset = stickyOffset.top + stickyHeight;
if (stickyOffset.top < maxoffset && offset.top < stickyMaxOffset) {
scrollTop = offset.top - stickyHeight - sticky.options.target;
window.scrollTo(0, scrollTop);
}
};
})($target, sticky), 0);
}
}
}
sticky.element.addClass(sticky.options.clsactive).removeClass(sticky.options.clsinactive);
sticky.element.trigger('active.uk.sticky');
sticky.element.css('margin', '');
if (sticky.options.animation && sticky.init && !UI.Utils.isInView(sticky.wrapper)) {
sticky.element.addClass(sticky.options.animation);
}
sticky.currentTop = newTop;
}
}
sticky.init = true;
}
}
return UI.sticky;
});
| dumengnanbuaa/awesome-python-webapp | www/static/js/components/sticky.js | JavaScript | gpl-2.0 | 12,883 |
YUI.add('moodle-core-blocks', function (Y, NAME) {
/**
* Provides drag and drop functionality for blocks.
*
* @module moodle-core-blockdraganddrop
*/
var AJAXURL = '/lib/ajax/blocks.php',
CSS = {
BLOCK : 'block',
BLOCKREGION : 'block-region',
BLOCKADMINBLOCK : 'block_adminblock',
EDITINGMOVE : 'editing_move',
HEADER : 'header',
LIGHTBOX : 'lightbox',
REGIONCONTENT : 'region-content',
SKIPBLOCK : 'skip-block',
SKIPBLOCKTO : 'skip-block-to',
MYINDEX : 'page-my-index',
REGIONMAIN : 'region-main',
BLOCKSMOVING : 'blocks-moving'
};
var SELECTOR = {
DRAGHANDLE : '.' + CSS.HEADER + ' .commands .moodle-core-dragdrop-draghandle'
};
/**
* Legacy drag and drop manager.
* This drag and drop manager is specifically designed for themes using side-pre and side-post
* that do not make use of the block output methods introduced by MDL-39824.
*
* @namespace M.core.blockdraganddrop
* @class LegacyManager
* @constructor
* @extends M.core.dragdrop
*/
var DRAGBLOCK = function() {
DRAGBLOCK.superclass.constructor.apply(this, arguments);
};
Y.extend(DRAGBLOCK, M.core.dragdrop, {
skipnodetop : null,
skipnodebottom : null,
dragsourceregion : null,
initializer : function() {
// Set group for parent class
this.groups = ['block'];
this.samenodeclass = CSS.BLOCK;
this.parentnodeclass = CSS.REGIONCONTENT;
// Add relevant classes and ID to 'content' block region on My Home page.
var myhomecontent = Y.Node.all('body#'+CSS.MYINDEX+' #'+CSS.REGIONMAIN+' > .'+CSS.REGIONCONTENT);
if (myhomecontent.size() > 0) {
var contentregion = myhomecontent.item(0);
contentregion.addClass(CSS.BLOCKREGION);
contentregion.set('id', CSS.REGIONCONTENT);
contentregion.one('div').addClass(CSS.REGIONCONTENT);
}
// Initialise blocks dragging
// Find all block regions on the page
var blockregionlist = Y.Node.all('div.'+CSS.BLOCKREGION);
if (blockregionlist.size() === 0) {
return false;
}
// See if we are missing either of block regions,
// if yes we need to add an empty one to use as target
if (blockregionlist.size() !== this.get('regions').length) {
var blockregion = Y.Node.create('<div></div>')
.addClass(CSS.BLOCKREGION);
var regioncontent = Y.Node.create('<div></div>')
.addClass(CSS.REGIONCONTENT);
blockregion.appendChild(regioncontent);
var pre = blockregionlist.filter('#region-pre');
var post = blockregionlist.filter('#region-post');
if (pre.size() === 0 && post.size() === 1) {
// pre block is missing, instert it before post
blockregion.setAttrs({id : 'region-pre'});
post.item(0).insert(blockregion, 'before');
blockregionlist.unshift(blockregion);
} else if (post.size() === 0 && pre.size() === 1) {
// post block is missing, instert it after pre
blockregion.setAttrs({id : 'region-post'});
pre.item(0).insert(blockregion, 'after');
blockregionlist.push(blockregion);
}
}
blockregionlist.each(function(blockregionnode) {
// Setting blockregion as droptarget (the case when it is empty)
// The region-post (the right one)
// is very narrow, so add extra padding on the left to drop block on it.
new Y.DD.Drop({
node: blockregionnode.one('div.'+CSS.REGIONCONTENT),
groups: this.groups,
padding: '40 240 40 240'
});
// Make each div element in the list of blocks draggable
var del = new Y.DD.Delegate({
container: blockregionnode,
nodes: '.'+CSS.BLOCK,
target: true,
handles: [SELECTOR.DRAGHANDLE],
invalid: '.block-hider-hide, .block-hider-show, .moveto',
dragConfig: {groups: this.groups}
});
del.dd.plug(Y.Plugin.DDProxy, {
// Don't move the node at the end of the drag
moveOnEnd: false
});
del.dd.plug(Y.Plugin.DDWinScroll);
var blocklist = blockregionnode.all('.'+CSS.BLOCK);
blocklist.each(function(blocknode) {
var move = blocknode.one('a.'+CSS.EDITINGMOVE);
if (move) {
move.replace(this.get_drag_handle(move.getAttribute('title'), '', 'iconsmall', true));
blocknode.one(SELECTOR.DRAGHANDLE).setStyle('cursor', 'move');
}
}, this);
}, this);
},
get_block_id : function(node) {
return Number(node.get('id').replace(/inst/i, ''));
},
get_block_region : function(node) {
var region = node.ancestor('div.'+CSS.BLOCKREGION).get('id').replace(/region-/i, '');
if (Y.Array.indexOf(this.get('regions'), region) === -1) {
// Must be standard side-X
if (right_to_left()) {
if (region === 'post') {
region = 'pre';
} else if (region === 'pre') {
region = 'post';
}
}
return 'side-' + region;
}
// Perhaps custom region
return region;
},
get_region_id : function(node) {
return node.get('id').replace(/region-/i, '');
},
drag_start : function(e) {
// Get our drag object
var drag = e.target;
// Store the parent node of original drag node (block)
// we will need it later for show/hide empty regions
this.dragsourceregion = drag.get('node').ancestor('div.'+CSS.BLOCKREGION);
// Determine skipnodes and store them
if (drag.get('node').previous() && drag.get('node').previous().hasClass(CSS.SKIPBLOCK)) {
this.skipnodetop = drag.get('node').previous();
}
if (drag.get('node').next() && drag.get('node').next().hasClass(CSS.SKIPBLOCKTO)) {
this.skipnodebottom = drag.get('node').next();
}
// Add the blocks-moving class so that the theme can respond if need be.
Y.one('body').addClass(CSS.BLOCKSMOVING);
},
drop_over : function(e) {
// Get a reference to our drag and drop nodes
var drag = e.drag.get('node');
var drop = e.drop.get('node');
// We need to fix the case when parent drop over event has determined
// 'goingup' and appended the drag node after admin-block.
if (drop.hasClass(this.parentnodeclass) && drop.one('.'+CSS.BLOCKADMINBLOCK) && drop.one('.'+CSS.BLOCKADMINBLOCK).next('.'+CSS.BLOCK)) {
drop.prepend(drag);
}
// Block is moved within the same region
// stop here, no need to modify anything.
if (this.dragsourceregion.contains(drop)) {
return false;
}
// TODO: Hiding-displaying block region only works for base theme blocks
// (region-pre, region-post) at the moment. It should be improved
// to work with custom block regions as well.
// TODO: Fix this for the case when user drag block towards empty section,
// then the section appears, then user chnages his mind and moving back to
// original section. The opposite section remains opened and empty.
var documentbody = Y.one('body');
// Moving block towards hidden region-content, display it
var regionname = this.get_region_id(this.dragsourceregion);
if (documentbody.hasClass('side-'+regionname+'-only')) {
documentbody.removeClass('side-'+regionname+'-only');
}
// Moving from empty region-content towards the opposite one,
// hide empty one (only for region-pre, region-post areas at the moment).
regionname = this.get_region_id(drop.ancestor('div.'+CSS.BLOCKREGION));
if (this.dragsourceregion.all('.'+CSS.BLOCK).size() === 0 && this.dragsourceregion.get('id').match(/(region-pre|region-post)/i)) {
if (!documentbody.hasClass('side-'+regionname+'-only')) {
documentbody.addClass('side-'+regionname+'-only');
}
}
},
drag_end : function() {
// clear variables
this.skipnodetop = null;
this.skipnodebottom = null;
this.dragsourceregion = null;
// Remove the blocks moving class once the drag-drop is over.
Y.one('body').removeClass(CSS.BLOCKSMOVING);
},
drag_dropmiss : function(e) {
// Missed the target, but we assume the user intended to drop it
// on the last last ghost node location, e.drag and e.drop should be
// prepared by global_drag_dropmiss parent so simulate drop_hit(e).
this.drop_hit(e);
},
drop_hit : function(e) {
var drag = e.drag;
// Get a reference to our drag node
var dragnode = drag.get('node');
var dropnode = e.drop.get('node');
// Amend existing skipnodes
if (dragnode.previous() && dragnode.previous().hasClass(CSS.SKIPBLOCK)) {
// the one that belongs to block below move below
dragnode.insert(dragnode.previous(), 'after');
}
// Move original skipnodes
if (this.skipnodetop) {
dragnode.insert(this.skipnodetop, 'before');
}
if (this.skipnodebottom) {
dragnode.insert(this.skipnodebottom, 'after');
}
// Add lightbox if it not there
var lightbox = M.util.add_lightbox(Y, dragnode);
// Prepare request parameters
var params = {
sesskey : M.cfg.sesskey,
courseid : this.get('courseid'),
pagelayout : this.get('pagelayout'),
pagetype : this.get('pagetype'),
subpage : this.get('subpage'),
contextid : this.get('contextid'),
action : 'move',
bui_moveid : this.get_block_id(dragnode),
bui_newregion : this.get_block_region(dropnode)
};
if (this.get('cmid')) {
params.cmid = this.get('cmid');
}
if (dragnode.next('.'+this.samenodeclass) && !dragnode.next('.'+this.samenodeclass).hasClass(CSS.BLOCKADMINBLOCK)) {
params.bui_beforeid = this.get_block_id(dragnode.next('.'+this.samenodeclass));
}
// Do AJAX request
Y.io(M.cfg.wwwroot+AJAXURL, {
method: 'POST',
data: params,
on: {
start : function() {
lightbox.show();
},
success: function(tid, response) {
window.setTimeout(function() {
lightbox.hide();
}, 250);
try {
var responsetext = Y.JSON.parse(response.responseText);
if (responsetext.error) {
new M.core.ajaxException(responsetext);
}
} catch (e) {}
},
failure: function(tid, response) {
this.ajax_failure(response);
lightbox.hide();
}
},
context:this
});
}
}, {
NAME : 'core-blocks-dragdrop',
ATTRS : {
courseid : {
value : null
},
cmid : {
value : null
},
contextid : {
value : null
},
pagelayout : {
value : null
},
pagetype : {
value : null
},
subpage : {
value : null
},
regions : {
value : null
}
}
});
M.core = M.core || {};
M.core.blockdraganddrop = M.core.blockdraganddrop || {};
/**
* True if the page is using the new blocks methods.
* @private
* @static
* @property M.core.blockdraganddrop._isusingnewblocksmethod
* @type Boolean
* @default null
*/
M.core.blockdraganddrop._isusingnewblocksmethod = null;
/**
* Returns true if the page is using the new blocks methods.
* @static
* @method M.core.blockdraganddrop.is_using_blocks_render_method
* @return Boolean
*/
M.core.blockdraganddrop.is_using_blocks_render_method = function() {
if (this._isusingnewblocksmethod === null) {
var goodregions = Y.all('.block-region[data-blockregion]').size();
var allregions = Y.all('.block-region').size();
this._isusingnewblocksmethod = (allregions === goodregions);
if (goodregions > 0 && allregions > 0 && goodregions !== allregions) {
}
}
return this._isusingnewblocksmethod;
};
/**
* Initialises a drag and drop manager.
* This should only ever be called once for a page.
* @static
* @method M.core.blockdraganddrop.init
* @param {Object} params
* @return Manager
*/
M.core.blockdraganddrop.init = function(params) {
if (this.is_using_blocks_render_method()) {
new MANAGER(params);
} else {
new DRAGBLOCK(params);
}
};
/*
* Legacy code to keep things working.
*/
M.core_blocks = M.core_blocks || {};
M.core_blocks.init_dragdrop = function(params) {
M.core.blockdraganddrop.init(params);
};
/**
* This file contains the drag and drop manager class.
*
* Provides drag and drop functionality for blocks.
*
* @module moodle-core-blockdraganddrop
*/
/**
* Constructs a new Block drag and drop manager.
*
* @namespace M.core.blockdraganddrop
* @class Manager
* @constructor
* @extends M.core.dragdrop
*/
var MANAGER = function() {
MANAGER.superclass.constructor.apply(this, arguments);
};
MANAGER.prototype = {
/**
* The skip block link from above the block being dragged while a drag is in progress.
* Required by the M.core.dragdrop from whom this class extends.
* @private
* @property skipnodetop
* @type Node
* @default null
*/
skipnodetop : null,
/**
* The skip block link from below the block being dragged while a drag is in progress.
* Required by the M.core.dragdrop from whom this class extends.
* @private
* @property skipnodebottom
* @type Node
* @default null
*/
skipnodebottom : null,
/**
* An associative object of regions and the
* @property regionobjects
* @type {Object} Primitive object mocking an associative array.
* @type {BLOCKREGION} [regionname]* Each item uses the region name as the key with the value being
* an instance of the BLOCKREGION class.
*/
regionobjects : {},
/**
* Called during the initialisation process of the object.
* @method initializer
*/
initializer : function() {
var regionnames = this.get('regions'),
i = 0,
region,
regionname,
dragdelegation;
// Evil required by M.core.dragdrop.
this.groups = ['block'];
this.samenodeclass = CSS.BLOCK;
this.parentnodeclass = CSS.BLOCKREGION;
// Add relevant classes and ID to 'content' block region on My Home page.
var myhomecontent = Y.Node.all('body#'+CSS.MYINDEX+' #'+CSS.REGIONMAIN+' > .'+CSS.REGIONCONTENT);
if (myhomecontent.size() > 0) {
var contentregion = myhomecontent.item(0);
contentregion.addClass(CSS.BLOCKREGION);
contentregion.set('id', CSS.REGIONCONTENT);
contentregion.one('div').addClass(CSS.REGIONCONTENT);
}
for (i in regionnames) {
regionname = regionnames[i];
region = new BLOCKREGION({
manager : this,
region : regionname,
node : Y.one('#block-region-'+regionname)
});
this.regionobjects[regionname] = region;
// Setting blockregion as droptarget (the case when it is empty)
// The region-post (the right one)
// is very narrow, so add extra padding on the left to drop block on it.
new Y.DD.Drop({
node: region.get_droptarget(),
groups: this.groups,
padding: '40 240 40 240'
});
// Make each div element in the list of blocks draggable
dragdelegation = new Y.DD.Delegate({
container: region.get_droptarget(),
nodes: '.'+CSS.BLOCK,
target: true,
handles: [SELECTOR.DRAGHANDLE],
invalid: '.block-hider-hide, .block-hider-show, .moveto, .block_fake',
dragConfig: {groups: this.groups}
});
dragdelegation.dd.plug(Y.Plugin.DDProxy, {
// Don't move the node at the end of the drag
moveOnEnd: false
});
dragdelegation.dd.plug(Y.Plugin.DDWinScroll);
// On the DD Manager start operation, we enable all block regions so that they can be drop targets. This
// must be done *before* drag:start but after dragging has been initialised.
Y.DD.DDM.on('ddm:start', this.enable_all_regions, this);
region.change_block_move_icons(this);
}
},
/**
* Returns the ID of the block the given node represents.
* @method get_block_id
* @param {Node} node
* @return {int} The blocks ID in the database.
*/
get_block_id : function(node) {
return Number(node.get('id').replace(/inst/i, ''));
},
/**
* Returns the block region that the node is part of or belonging to.
* @method get_block_region
* @param {Y.Node} node
* @return {string} The region name.
*/
get_block_region : function(node) {
if (!node.test('[data-blockregion]')) {
node = node.ancestor('[data-blockregion]');
}
return node.getData('blockregion');
},
/**
* Returns the BLOCKREGION instance that represents the block region the given node is part of.
* @method get_region_object
* @param {Y.Node} node
* @return {BLOCKREGION}
*/
get_region_object : function(node) {
return this.regionobjects[this.get_block_region(node)];
},
/**
* Enables all fo the regions so that they are all visible while dragging is occuring.
*
* @method enable_all_regions
*/
enable_all_regions : function() {
var groups = Y.DD.DDM.activeDrag.get('groups');
// As we're called by Y.DD.DDM, we can't be certain that the call
// relates specifically to a block drag/drop operation. Test
// whether the relevant group applies here.
if (!groups || Y.Array.indexOf(groups, 'block') === -1) {
return;
}
var i;
for (i in this.regionobjects) {
if (!this.regionobjects.hasOwnProperty(i)) {
continue;
}
this.regionobjects[i].enable();
}
},
/**
* Disables enabled regions if they contain no blocks.
* @method disable_regions_if_required
*/
disable_regions_if_required : function() {
var i = 0;
for (i in this.regionobjects) {
this.regionobjects[i].disable_if_required();
}
},
/**
* Called by M.core.dragdrop.global_drag_start when dragging starts.
* @method drag_start
* @param {Event} e
*/
drag_start : function(e) {
// Get our drag object
var drag = e.target;
// Store the parent node of original drag node (block)
// we will need it later for show/hide empty regions
// Determine skipnodes and store them
if (drag.get('node').previous() && drag.get('node').previous().hasClass(CSS.SKIPBLOCK)) {
this.skipnodetop = drag.get('node').previous();
}
if (drag.get('node').next() && drag.get('node').next().hasClass(CSS.SKIPBLOCKTO)) {
this.skipnodebottom = drag.get('node').next();
}
},
/**
* Called by M.core.dragdrop.global_drop_over when something is dragged over a drop target.
* @method drop_over
* @param {Event} e
*/
drop_over : function(e) {
// Get a reference to our drag and drop nodes
var drag = e.drag.get('node');
var drop = e.drop.get('node');
// We need to fix the case when parent drop over event has determined
// 'goingup' and appended the drag node after admin-block.
if (drop.hasClass(CSS.REGIONCONTENT) && drop.one('.'+CSS.BLOCKADMINBLOCK) && drop.one('.'+CSS.BLOCKADMINBLOCK).next('.'+CSS.BLOCK)) {
drop.prepend(drag);
}
},
/**
* Called by M.core.dragdrop.global_drop_end when a drop has been completed.
* @method drop_end
*/
drop_end : function() {
// Clear variables.
this.skipnodetop = null;
this.skipnodebottom = null;
this.disable_regions_if_required();
},
/**
* Called by M.core.dragdrop.global_drag_dropmiss when something has been dropped on a node that isn't contained by a drop target.
* @method drag_dropmiss
* @param {Event} e
*/
drag_dropmiss : function(e) {
// Missed the target, but we assume the user intended to drop it
// on the last ghost node location, e.drag and e.drop should be
// prepared by global_drag_dropmiss parent so simulate drop_hit(e).
this.drop_hit(e);
},
/**
* Called by M.core.dragdrop.global_drag_hit when something has been dropped on a drop target.
* @method drop_hit
* @param {Event} e
*/
drop_hit : function(e) {
// Get a reference to our drag node
var dragnode = e.drag.get('node');
var dropnode = e.drop.get('node');
// Amend existing skipnodes
if (dragnode.previous() && dragnode.previous().hasClass(CSS.SKIPBLOCK)) {
// the one that belongs to block below move below
dragnode.insert(dragnode.previous(), 'after');
}
// Move original skipnodes
if (this.skipnodetop) {
dragnode.insert(this.skipnodetop, 'before');
}
if (this.skipnodebottom) {
dragnode.insert(this.skipnodebottom, 'after');
}
// Add lightbox if it not there
var lightbox = M.util.add_lightbox(Y, dragnode);
// Prepare request parameters
var params = {
sesskey : M.cfg.sesskey,
courseid : this.get('courseid'),
pagelayout : this.get('pagelayout'),
pagetype : this.get('pagetype'),
subpage : this.get('subpage'),
contextid : this.get('contextid'),
action : 'move',
bui_moveid : this.get_block_id(dragnode),
bui_newregion : this.get_block_region(dropnode)
};
if (this.get('cmid')) {
params.cmid = this.get('cmid');
}
if (dragnode.next('.'+CSS.BLOCK) && !dragnode.next('.'+CSS.BLOCK).hasClass(CSS.BLOCKADMINBLOCK)) {
params.bui_beforeid = this.get_block_id(dragnode.next('.'+CSS.BLOCK));
}
// Do AJAX request
Y.io(M.cfg.wwwroot+AJAXURL, {
method: 'POST',
data: params,
on: {
start : function() {
lightbox.show();
},
success: function(tid, response) {
window.setTimeout(function() {
lightbox.hide();
}, 250);
try {
var responsetext = Y.JSON.parse(response.responseText);
if (responsetext.error) {
new M.core.ajaxException(responsetext);
}
} catch (e) {}
},
failure: function(tid, response) {
this.ajax_failure(response);
lightbox.hide();
},
complete : function() {
this.disable_regions_if_required();
}
},
context:this
});
}
};
Y.extend(MANAGER, M.core.dragdrop, MANAGER.prototype, {
NAME : 'core-blocks-dragdrop-manager',
ATTRS : {
/**
* The Course ID if there is one.
* @attribute courseid
* @type int|null
* @default null
*/
courseid : {
value : null
},
/**
* The Course Module ID if there is one.
* @attribute cmid
* @type int|null
* @default null
*/
cmid : {
value : null
},
/**
* The Context ID.
* @attribute contextid
* @type int|null
* @default null
*/
contextid : {
value : null
},
/**
* The current page layout.
* @attribute pagelayout
* @type string|null
* @default null
*/
pagelayout : {
value : null
},
/**
* The page type string, should be used as the id for the body tag in the theme.
* @attribute pagetype
* @type string|null
* @default null
*/
pagetype : {
value : null
},
/**
* The subpage identifier, if any.
* @attribute subpage
* @type string|null
* @default null
*/
subpage : {
value : null
},
/**
* An array of block regions that are present on the page.
* @attribute regions
* @type array|null
* @default Array[]
*/
regions : {
value : []
}
}
});
/**
* This file contains the Block Region class used by the drag and drop manager.
*
* Provides drag and drop functionality for blocks.
*
* @module moodle-core-blockdraganddrop
*/
/**
* Constructs a new block region object.
*
* @namespace M.core.blockdraganddrop
* @class BlockRegion
* @constructor
* @extends Base
*/
var BLOCKREGION = function() {
BLOCKREGION.superclass.constructor.apply(this, arguments);
};
BLOCKREGION.prototype = {
/**
* Called during the initialisation process of the object.
* @method initializer
*/
initializer : function() {
var node = this.get('node');
if (!node) {
node = this.create_and_add_node();
}
var body = Y.one('body'),
hasblocks = node.all('.'+CSS.BLOCK).size() > 0,
hasregionclass = this.get_has_region_class();
this.set('hasblocks', hasblocks);
if (!body.hasClass(hasregionclass)) {
body.addClass(hasregionclass);
}
body.addClass((hasblocks) ? this.get_used_region_class() : this.get_empty_region_class());
body.removeClass((hasblocks) ? this.get_empty_region_class() : this.get_used_region_class());
},
/**
* Creates a generic block region node and adds it to the DOM at the best guess location.
* Any calling of this method is an unfortunate circumstance.
* @method create_and_add_node
* @return Node The newly created Node
*/
create_and_add_node : function() {
var c = Y.Node.create,
region = this.get('region'),
node = c('<div id="block-region-'+region+'" data-droptarget="1"></div>')
.addClass(CSS.BLOCKREGION)
.setData('blockregion', region),
regions = this.get('manager').get('regions'),
i,
haspre = false,
haspost = false,
added = false,
pre,
post;
for (i in regions) {
if (regions[i].match(/(pre|left)/)) {
haspre = regions[i];
} else if (regions[i].match(/(post|right)/)) {
haspost = regions[i];
}
}
if (haspre !== false && haspost !== false) {
if (region === haspre) {
post = Y.one('#block-region-'+haspost);
if (post) {
post.insert(node, 'before');
added = true;
}
} else {
pre = Y.one('#block-region-'+haspre);
if (pre) {
pre.insert(node, 'after');
added = true;
}
}
}
if (added === false) {
Y.one('body').append(node);
}
this.set('node', node);
return node;
},
/**
* Change the move icons to enhanced drag handles and changes the cursor to a move icon when over the header.
* @param M.core.dragdrop the block manager
* @method change_block_move_icons
*/
change_block_move_icons : function(manager) {
var handle, icon;
this.get('node').all('.'+CSS.BLOCK+' a.'+CSS.EDITINGMOVE).each(function(moveicon){
moveicon.setStyle('cursor', 'move');
handle = manager.get_drag_handle(moveicon.getAttribute('title'), '', 'icon', true);
icon = handle.one('img');
icon.addClass('iconsmall');
icon.removeClass('icon');
moveicon.replace(handle);
});
},
/**
* Returns the class name on the body that signifies the document knows about this region.
* @method get_has_region_class
* @return String
*/
get_has_region_class : function() {
return 'has-region-'+this.get('region');
},
/**
* Returns the class name to use on the body if the region contains no blocks.
* @method get_empty_region_class
* @return String
*/
get_empty_region_class : function() {
return 'empty-region-'+this.get('region');
},
/**
* Returns the class name to use on the body if the region contains blocks.
* @method get_used_region_class
* @return String
*/
get_used_region_class : function() {
return 'used-region-'+this.get('region');
},
/**
* Returns the node to use as the drop target for this region.
* @method get_droptarget
* @return Node
*/
get_droptarget : function() {
var node = this.get('node');
if (node.test('[data-droptarget="1"]')) {
return node;
}
return node.one('[data-droptarget="1"]');
},
/**
* Enables the block region so that we can be sure the user can see it.
* This is done even if it is empty.
* @method enable
*/
enable : function() {
Y.one('body').addClass(this.get_used_region_class()).removeClass(this.get_empty_region_class());
},
/**
* Disables the region if it contains no blocks, essentially hiding it from the user.
* @method disable_if_required
*/
disable_if_required : function() {
if (this.get('node').all('.'+CSS.BLOCK).size() === 0) {
Y.one('body').addClass(this.get_empty_region_class()).removeClass(this.get_used_region_class());
}
}
};
Y.extend(BLOCKREGION, Y.Base, BLOCKREGION.prototype, {
NAME : 'core-blocks-dragdrop-blockregion',
ATTRS : {
/**
* The drag and drop manager that created this block region instance.
* @attribute manager
* @type M.core.blockdraganddrop.Manager
* @writeOnce
*/
manager : {
// Can only be set during initialisation and must be set then.
writeOnce : 'initOnly',
validator : function (value) {
return Y.Lang.isObject(value) && value instanceof MANAGER;
}
},
/**
* The name of the block region this object represents.
* @attribute region
* @type String
* @writeOnce
*/
region : {
// Can only be set during initialisation and must be set then.
writeOnce : 'initOnly',
validator : function (value) {
return Y.Lang.isString(value);
}
},
/**
* The node the block region HTML starts at.s
* @attribute region
* @type Y.Node
*/
node : {
validator : function (value) {
return Y.Lang.isObject(value) || Y.Lang.isNull(value);
}
},
/**
* True if the block region currently contains blocks.
* @attribute hasblocks
* @type Boolean
* @default false
*/
hasblocks : {
value : false,
validator : function (value) {
return Y.Lang.isBoolean(value);
}
}
}
});
}, '@VERSION@', {
"requires": [
"base",
"node",
"io",
"dom",
"dd",
"dd-scroll",
"moodle-core-dragdrop",
"moodle-core-notification"
]
});
| sameertechworks/wpmoodle | moodle/lib/yui/build/moodle-core-blocks/moodle-core-blocks.js | JavaScript | gpl-2.0 | 33,181 |
/// <reference path="express-minify.d.ts" />
import express = require('express');
import minify = require('express-minify');
import uglifyJS = require('uglify-js');
var app = express();
app.use(minify());
app.use(minify({
cache: false,
cssmin: require('cssmin'),
uglifyJS: require('uglify-js')
}));
app.get('/', function (req: express.Request, res: express.Response) {
res._skip = true;
res._no_minify = false;
res._no_cache = true;
res._uglifyMangle = false;
var outputOptions: uglifyJS.BeautifierOptions = {
beautify: true,
comments: false
};
res._uglifyOutput = outputOptions;
res._uglifyCompress = false;
var compressionOptions: uglifyJS.CompressorOptions = {
cascade: true
};
res._uglifyCompress = compressionOptions;
}) | mareek/DefinitelyTyped | express-minify/express-minify-tests.ts | TypeScript | mit | 833 |
/* ===========================================================
* by.js
* Belarusian translation for Trumbowyg
* http://alex-d.github.com/Trumbowyg
* ===========================================================
* Author : Yury Karalkou
*/
jQuery.trumbowyg.langs.by = {
viewHTML: 'Паглядзець HTML',
undo: 'Скасаваць',
redo: 'Паўтарыць',
formatting: 'Фарматаванне',
p: 'Звычайны',
blockquote: 'Цытата',
code: 'Код',
header: 'Загаловак',
bold: 'Паўтлусты',
italic: 'Курсіў',
strikethrough: 'Закрэслены',
underline: 'Падкрэслены',
strong: 'Паўтлусты',
em: 'Курсіў',
del: 'Закрэслены',
superscript: 'Верхні індэкс',
subscript: 'Індэкс',
unorderedList: 'Звычайны спіс',
orderedList: 'Нумараваны спіс',
insertImage: 'Уставіць выяву',
insertVideo: 'Уставіць відэа',
link: 'Спасылка',
createLink: 'Уставіць спасылку',
unlink: 'Выдаліць спасылку',
justifyLeft: 'Па леваму боку',
justifyCenter: 'У цэнтры',
justifyRight: 'Па праваму боку',
justifyFull: 'Па шырыні',
horizontalRule: 'Гарызантальная лінія',
removeformat: 'Ачысціць фарматаванне',
fullscreen: 'На ўвесь экран',
close: 'Зачыніць',
submit: 'Уставіць',
reset: 'Скасаваць',
required: 'Абавязкова',
description: 'Апісанне',
title: 'Падказка',
text: 'Тэкст'
};
| sandino/django-trumbowyg | trumbowyg/static/trumbowyg/langs/by.js | JavaScript | mit | 1,762 |
<?php
namespace Doctrine\Tests\Models\ValueConversionType;
/**
* @Entity
* @Table(name="vct_owning_onetoone")
*/
class OwningOneToOneEntity
{
/**
* @Column(type="rot13")
* @Id
*/
public $id2;
/**
* @OneToOne(targetEntity="InversedOneToOneEntity", inversedBy="associatedEntity")
* @JoinColumn(name="associated_id", referencedColumnName="id1")
*/
public $associatedEntity;
}
| julianodecezaro/zf2 | vendor/doctrine/orm/tests/Doctrine/Tests/Models/ValueConversionType/OwningOneToOneEntity.php | PHP | bsd-3-clause | 425 |
class Strongswan < Formula
desc "VPN based on IPsec"
homepage "https://www.strongswan.org"
url "https://download.strongswan.org/strongswan-5.3.2.tar.bz2"
sha256 "a4a9bc8c4e42bdc4366a87a05a02bf9f425169a7ab0c6f4482d347e44acbf225"
bottle do
sha256 "dcb83dc117ee1f0b145408d14ef5a832ea8931cedd6d2f3a7c97c157cc577bff" => :yosemite
sha256 "bc642bdf33694216316a17fd2d64054b6b7aac5bc73cf5cd231aa868b1108b88" => :mavericks
sha256 "f3601206f55048e0d67802fc4d32091cfe3a6bef4c98fa38a2f1e9ddbb832e85" => :mountain_lion
end
head do
url "https://git.strongswan.org/strongswan.git"
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "libtool" => :build
depends_on "pkg-config" => :build
depends_on "gettext" => :build
depends_on "bison" => :build
end
option "with-curl", "Build with libcurl based fetcher"
option "with-suite-b", "Build with Suite B support (does not use the IPsec implementation provided by the kernel)"
depends_on "openssl"
depends_on "curl" => :optional
def install
args = %W[
--disable-dependency-tracking
--prefix=#{prefix}
--sbindir=#{bin}
--sysconfdir=#{etc}
--disable-defaults
--enable-charon
--enable-cmd
--enable-constraints
--enable-eap-gtc
--enable-eap-identity
--enable-eap-md5
--enable-eap-mschapv2
--enable-ikev1
--enable-ikev2
--enable-kernel-pfroute
--enable-nonce
--enable-openssl
--enable-osx-attr
--enable-pem
--enable-pgp
--enable-pkcs1
--enable-pkcs8
--enable-pki
--enable-pubkey
--enable-revocation
--enable-scepclient
--enable-socket-default
--enable-sshkey
--enable-stroke
--enable-swanctl
--enable-unity
--enable-updown
--enable-x509
--enable-xauth-generic
]
args << "--enable-curl" if build.with? "curl"
if build.with? "suite-b"
args << "--enable-kernel-libipsec"
else
args << "--enable-kernel-pfkey"
end
system "./autogen.sh" if build.head?
system "./configure", *args
system "make", "install"
end
def caveats
msg = <<-EOS.undent
strongSwan's configuration files are placed in:
#{etc}
You will have to run both "ipsec" and "charon-cmd" with "sudo".
EOS
if build.with? "suite-b"
msg += <<-EOS.undent
If you previously ran strongSwan without Suite B support it might be
required to execute "sudo sysctl -w net.inet.ipsec.esp_port=0" in order
to receive packets.
EOS
end
msg
end
end
| mattbostock/homebrew | Library/Formula/strongswan.rb | Ruby | bsd-2-clause | 2,642 |
module FavoritesHelper
end
| jphacks/TK_07 | server/app/helpers/favorites_helper.rb | Ruby | mit | 27 |
<?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 license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Pdf
* @subpackage Actions
* @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: Launch.php 20096 2010-01-06 02:05:09Z bkarwin $
*/
/** Zend_Pdf_Action */
require_once 'Zend/Pdf/Action.php';
/**
* PDF 'Launch an application, usually to open a file' action
*
* @package Zend_Pdf
* @subpackage Actions
* @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_Pdf_Action_Launch extends Zend_Pdf_Action
{
}
| chisimba/modules | zend/resources/Zend/Pdf/Action/Launch.php | PHP | gpl-2.0 | 1,172 |
/*
* Copyright 2000-2012 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 org.jetbrains.jps.model.impl;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.model.JpsCompositeElement;
import org.jetbrains.jps.model.JpsElementCollection;
import org.jetbrains.jps.model.JpsElementReference;
import org.jetbrains.jps.model.JpsNamedElement;
import org.jetbrains.jps.model.ex.JpsElementCollectionRole;
/**
* @author nik
*/
public abstract class JpsNamedElementReferenceImpl<T extends JpsNamedElement, Self extends JpsNamedElementReferenceImpl<T, Self>> extends JpsNamedElementReferenceBase<T, T, Self> {
protected final JpsElementCollectionRole<? extends T> myCollectionRole;
protected JpsNamedElementReferenceImpl(@NotNull JpsElementCollectionRole<? extends T> role, @NotNull String elementName,
@NotNull JpsElementReference<? extends JpsCompositeElement> parentReference) {
super(elementName, parentReference);
myCollectionRole = role;
}
protected JpsNamedElementReferenceImpl(JpsNamedElementReferenceImpl<T, Self> original) {
super(original);
myCollectionRole = original.myCollectionRole;
}
@Override
protected T resolve(T element) {
return element;
}
@Nullable
protected JpsElementCollection<? extends T> getCollection(@NotNull JpsCompositeElement parent) {
return parent.getContainer().getChild(myCollectionRole);
}
}
| asedunov/intellij-community | jps/model-impl/src/org/jetbrains/jps/model/impl/JpsNamedElementReferenceImpl.java | Java | apache-2.0 | 2,005 |
/*
Copyright 2014 Google Inc. 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 com.google.security.zynamics.zylib.io;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
/**
* Tests for the {@link StreamUtils} class.
*
* @author cblichmann@google.com (Christian Blichmann)
*/
@RunWith(JUnit4.class)
public class StreamUtilsTests {
@Test
public void testReadLinesFromReader() throws IOException {
final Reader validReader = new StringReader("3.2.2\n2011-08-03");
final String[] expected = new String[] {"3.2.2", "2011-08-03"};
assertArrayEquals(expected, StreamUtils.readLinesFromReader(validReader).toArray());
final Reader emptyReader = new StringReader("");
assertTrue(StreamUtils.readLinesFromReader(emptyReader).isEmpty());
}
}
| guiquanz/binnavi | src/test/java/com/google/security/zynamics/zylib/io/StreamUtilsTests.java | Java | apache-2.0 | 1,486 |
/**
* Module dependencies.
*/
var fs = require('fs');
var path = require('path');
var assert = require('assert');
var degenerator = require('../');
describe('degenerator()', function () {
describe('"expected" fixture tests', function () {
fs.readdirSync(__dirname).forEach(function (n) {
if ('test.js' == n) return;
if (/\.expected\.js$/.test(n)) return;
var expectedName = path.basename(n, '.js') + '.expected.js';
it(n + ' → ' + expectedName, function () {
var sourceName = path.resolve(__dirname, n);
var compiledName = path.resolve(__dirname, expectedName);
var js = fs.readFileSync(sourceName, 'utf8');
var expected = fs.readFileSync(compiledName, 'utf8');
// the test case can define the `names` to use as a
// comment on the first line of the file
var names = js.match(/\/\/\s*(.*)/);
if (names) {
// the comment should be a comma-separated list of function names
names = names[1].split(/,\s*/);
} else {
// if no function names were passed in then convert them all
names = [ /.*/ ];
}
var compiled = degenerator(js, names);
assert.equal(expected.trim(), compiled.trim());
});
});
});
});
| jphacks/TK_23 | web/node_modules/degenerator/test/test.js | JavaScript | mit | 1,288 |
require 'spec_helper'
describe Admin::AdminController do
context 'index' do
it 'needs you to be logged in' do
lambda { xhr :get, :index }.should raise_error(Discourse::NotLoggedIn)
end
it "raises an error if you aren't an admin" do
user = log_in
xhr :get, :index
response.should be_forbidden
end
end
end
| andrewroth/discourse | spec/controllers/admin/admin_controller_spec.rb | Ruby | gpl-2.0 | 355 |
#!/usr/bin/python
#
# Copyright (c) 2011 The Chromium OS Authors.
#
# See file CREDITS for list of people who contributed to this
# project.
#
# This program 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 2 of
# the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# 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
#
"""See README for more information"""
from optparse import OptionParser
import os
import re
import sys
import unittest
# Our modules
import checkpatch
import command
import gitutil
import patchstream
import terminal
import test
parser = OptionParser()
parser.add_option('-H', '--full-help', action='store_true', dest='full_help',
default=False, help='Display the README file')
parser.add_option('-c', '--count', dest='count', type='int',
default=-1, help='Automatically create patches from top n commits')
parser.add_option('-i', '--ignore-errors', action='store_true',
dest='ignore_errors', default=False,
help='Send patches email even if patch errors are found')
parser.add_option('-n', '--dry-run', action='store_true', dest='dry_run',
default=False, help="Do a try run (create but don't email patches)")
parser.add_option('-s', '--start', dest='start', type='int',
default=0, help='Commit to start creating patches from (0 = HEAD)')
parser.add_option('-t', '--test', action='store_true', dest='test',
default=False, help='run tests')
parser.add_option('-v', '--verbose', action='store_true', dest='verbose',
default=False, help='Verbose output of errors and warnings')
parser.add_option('--cc-cmd', dest='cc_cmd', type='string', action='store',
default=None, help='Output cc list for patch file (used by git)')
parser.add_option('--no-tags', action='store_false', dest='process_tags',
default=True, help="Don't process subject tags as aliaes")
parser.usage = """patman [options]
Create patches from commits in a branch, check them and email them as
specified by tags you place in the commits. Use -n to """
(options, args) = parser.parse_args()
# Run our meagre tests
if options.test:
import doctest
sys.argv = [sys.argv[0]]
suite = unittest.TestLoader().loadTestsFromTestCase(test.TestPatch)
result = unittest.TestResult()
suite.run(result)
suite = doctest.DocTestSuite('gitutil')
suite.run(result)
# TODO: Surely we can just 'print' result?
print result
for test, err in result.errors:
print err
for test, err in result.failures:
print err
# Called from git with a patch filename as argument
# Printout a list of additional CC recipients for this patch
elif options.cc_cmd:
fd = open(options.cc_cmd, 'r')
re_line = re.compile('(\S*) (.*)')
for line in fd.readlines():
match = re_line.match(line)
if match and match.group(1) == args[0]:
for cc in match.group(2).split(', '):
cc = cc.strip()
if cc:
print cc
fd.close()
elif options.full_help:
pager = os.getenv('PAGER')
if not pager:
pager = 'more'
fname = os.path.join(os.path.dirname(sys.argv[0]), 'README')
command.Run(pager, fname)
# Process commits, produce patches files, check them, email them
else:
gitutil.Setup()
if options.count == -1:
# Work out how many patches to send if we can
options.count = gitutil.CountCommitsToBranch() - options.start
col = terminal.Color()
if not options.count:
str = 'No commits found to process - please use -c flag'
print col.Color(col.RED, str)
sys.exit(1)
# Read the metadata from the commits
if options.count:
series = patchstream.GetMetaData(options.start, options.count)
cover_fname, args = gitutil.CreatePatches(options.start, options.count,
series)
# Fix up the patch files to our liking, and insert the cover letter
series = patchstream.FixPatches(series, args)
if series and cover_fname and series.get('cover'):
patchstream.InsertCoverLetter(cover_fname, series, options.count)
# Do a few checks on the series
series.DoChecks()
# Check the patches, and run them through 'git am' just to be sure
ok = checkpatch.CheckPatches(options.verbose, args)
if not gitutil.ApplyPatches(options.verbose, args,
options.count + options.start):
ok = False
# Email the patches out (giving the user time to check / cancel)
cmd = ''
if ok or options.ignore_errors:
cc_file = series.MakeCcFile(options.process_tags)
cmd = gitutil.EmailPatches(series, cover_fname, args,
options.dry_run, cc_file)
os.remove(cc_file)
# For a dry run, just show our actions as a sanity check
if options.dry_run:
series.ShowActions(args, cmd, options.process_tags)
| MarvellEmbeddedProcessors/u-boot-armada38x | tools/patman/patman.py | Python | gpl-2.0 | 5,394 |
from __future__ import unicode_literals
import sys
from django.conf import settings
from django.template import Library, Node, TemplateSyntaxError, Variable
from django.template.base import TOKEN_TEXT, TOKEN_VAR, render_value_in_context
from django.template.defaulttags import token_kwargs
from django.utils import six, translation
register = Library()
class GetAvailableLanguagesNode(Node):
def __init__(self, variable):
self.variable = variable
def render(self, context):
context[self.variable] = [(k, translation.ugettext(v)) for k, v in settings.LANGUAGES]
return ''
class GetLanguageInfoNode(Node):
def __init__(self, lang_code, variable):
self.lang_code = lang_code
self.variable = variable
def render(self, context):
lang_code = self.lang_code.resolve(context)
context[self.variable] = translation.get_language_info(lang_code)
return ''
class GetLanguageInfoListNode(Node):
def __init__(self, languages, variable):
self.languages = languages
self.variable = variable
def get_language_info(self, language):
# ``language`` is either a language code string or a sequence
# with the language code as its first item
if len(language[0]) > 1:
return translation.get_language_info(language[0])
else:
return translation.get_language_info(str(language))
def render(self, context):
langs = self.languages.resolve(context)
context[self.variable] = [self.get_language_info(lang) for lang in langs]
return ''
class GetCurrentLanguageNode(Node):
def __init__(self, variable):
self.variable = variable
def render(self, context):
context[self.variable] = translation.get_language()
return ''
class GetCurrentLanguageBidiNode(Node):
def __init__(self, variable):
self.variable = variable
def render(self, context):
context[self.variable] = translation.get_language_bidi()
return ''
class TranslateNode(Node):
def __init__(self, filter_expression, noop, asvar=None,
message_context=None):
self.noop = noop
self.asvar = asvar
self.message_context = message_context
self.filter_expression = filter_expression
if isinstance(self.filter_expression.var, six.string_types):
self.filter_expression.var = Variable("'%s'" %
self.filter_expression.var)
def render(self, context):
self.filter_expression.var.translate = not self.noop
if self.message_context:
self.filter_expression.var.message_context = (
self.message_context.resolve(context))
output = self.filter_expression.resolve(context)
value = render_value_in_context(output, context)
if self.asvar:
context[self.asvar] = value
return ''
else:
return value
class BlockTranslateNode(Node):
def __init__(self, extra_context, singular, plural=None, countervar=None,
counter=None, message_context=None, trimmed=False, asvar=None):
self.extra_context = extra_context
self.singular = singular
self.plural = plural
self.countervar = countervar
self.counter = counter
self.message_context = message_context
self.trimmed = trimmed
self.asvar = asvar
def render_token_list(self, tokens):
result = []
vars = []
for token in tokens:
if token.token_type == TOKEN_TEXT:
result.append(token.contents.replace('%', '%%'))
elif token.token_type == TOKEN_VAR:
result.append('%%(%s)s' % token.contents)
vars.append(token.contents)
msg = ''.join(result)
if self.trimmed:
msg = translation.trim_whitespace(msg)
return msg, vars
def render(self, context, nested=False):
if self.message_context:
message_context = self.message_context.resolve(context)
else:
message_context = None
tmp_context = {}
for var, val in self.extra_context.items():
tmp_context[var] = val.resolve(context)
# Update() works like a push(), so corresponding context.pop() is at
# the end of function
context.update(tmp_context)
singular, vars = self.render_token_list(self.singular)
if self.plural and self.countervar and self.counter:
count = self.counter.resolve(context)
context[self.countervar] = count
plural, plural_vars = self.render_token_list(self.plural)
if message_context:
result = translation.npgettext(message_context, singular,
plural, count)
else:
result = translation.ungettext(singular, plural, count)
vars.extend(plural_vars)
else:
if message_context:
result = translation.pgettext(message_context, singular)
else:
result = translation.ugettext(singular)
default_value = context.template.engine.string_if_invalid
def render_value(key):
if key in context:
val = context[key]
else:
val = default_value % key if '%s' in default_value else default_value
return render_value_in_context(val, context)
data = {v: render_value(v) for v in vars}
context.pop()
try:
result = result % data
except (KeyError, ValueError):
if nested:
# Either string is malformed, or it's a bug
raise TemplateSyntaxError("'blocktrans' is unable to format "
"string returned by gettext: %r using %r" % (result, data))
with translation.override(None):
result = self.render(context, nested=True)
if self.asvar:
context[self.asvar] = result
return ''
else:
return result
class LanguageNode(Node):
def __init__(self, nodelist, language):
self.nodelist = nodelist
self.language = language
def render(self, context):
with translation.override(self.language.resolve(context)):
output = self.nodelist.render(context)
return output
@register.tag("get_available_languages")
def do_get_available_languages(parser, token):
"""
This will store a list of available languages
in the context.
Usage::
{% get_available_languages as languages %}
{% for language in languages %}
...
{% endfor %}
This will just pull the LANGUAGES setting from
your setting file (or the default settings) and
put it into the named variable.
"""
# token.split_contents() isn't useful here because this tag doesn't accept variable as arguments
args = token.contents.split()
if len(args) != 3 or args[1] != 'as':
raise TemplateSyntaxError("'get_available_languages' requires 'as variable' (got %r)" % args)
return GetAvailableLanguagesNode(args[2])
@register.tag("get_language_info")
def do_get_language_info(parser, token):
"""
This will store the language information dictionary for the given language
code in a context variable.
Usage::
{% get_language_info for LANGUAGE_CODE as l %}
{{ l.code }}
{{ l.name }}
{{ l.name_translated }}
{{ l.name_local }}
{{ l.bidi|yesno:"bi-directional,uni-directional" }}
"""
args = token.split_contents()
if len(args) != 5 or args[1] != 'for' or args[3] != 'as':
raise TemplateSyntaxError("'%s' requires 'for string as variable' (got %r)" % (args[0], args[1:]))
return GetLanguageInfoNode(parser.compile_filter(args[2]), args[4])
@register.tag("get_language_info_list")
def do_get_language_info_list(parser, token):
"""
This will store a list of language information dictionaries for the given
language codes in a context variable. The language codes can be specified
either as a list of strings or a settings.LANGUAGES style list (or any
sequence of sequences whose first items are language codes).
Usage::
{% get_language_info_list for LANGUAGES as langs %}
{% for l in langs %}
{{ l.code }}
{{ l.name }}
{{ l.name_translated }}
{{ l.name_local }}
{{ l.bidi|yesno:"bi-directional,uni-directional" }}
{% endfor %}
"""
args = token.split_contents()
if len(args) != 5 or args[1] != 'for' or args[3] != 'as':
raise TemplateSyntaxError("'%s' requires 'for sequence as variable' (got %r)" % (args[0], args[1:]))
return GetLanguageInfoListNode(parser.compile_filter(args[2]), args[4])
@register.filter
def language_name(lang_code):
return translation.get_language_info(lang_code)['name']
@register.filter
def language_name_translated(lang_code):
english_name = translation.get_language_info(lang_code)['name']
return translation.ugettext(english_name)
@register.filter
def language_name_local(lang_code):
return translation.get_language_info(lang_code)['name_local']
@register.filter
def language_bidi(lang_code):
return translation.get_language_info(lang_code)['bidi']
@register.tag("get_current_language")
def do_get_current_language(parser, token):
"""
This will store the current language in the context.
Usage::
{% get_current_language as language %}
This will fetch the currently active language and
put it's value into the ``language`` context
variable.
"""
# token.split_contents() isn't useful here because this tag doesn't accept variable as arguments
args = token.contents.split()
if len(args) != 3 or args[1] != 'as':
raise TemplateSyntaxError("'get_current_language' requires 'as variable' (got %r)" % args)
return GetCurrentLanguageNode(args[2])
@register.tag("get_current_language_bidi")
def do_get_current_language_bidi(parser, token):
"""
This will store the current language layout in the context.
Usage::
{% get_current_language_bidi as bidi %}
This will fetch the currently active language's layout and
put it's value into the ``bidi`` context variable.
True indicates right-to-left layout, otherwise left-to-right
"""
# token.split_contents() isn't useful here because this tag doesn't accept variable as arguments
args = token.contents.split()
if len(args) != 3 or args[1] != 'as':
raise TemplateSyntaxError("'get_current_language_bidi' requires 'as variable' (got %r)" % args)
return GetCurrentLanguageBidiNode(args[2])
@register.tag("trans")
def do_translate(parser, token):
"""
This will mark a string for translation and will
translate the string for the current language.
Usage::
{% trans "this is a test" %}
This will mark the string for translation so it will
be pulled out by mark-messages.py into the .po files
and will run the string through the translation engine.
There is a second form::
{% trans "this is a test" noop %}
This will only mark for translation, but will return
the string unchanged. Use it when you need to store
values into forms that should be translated later on.
You can use variables instead of constant strings
to translate stuff you marked somewhere else::
{% trans variable %}
This will just try to translate the contents of
the variable ``variable``. Make sure that the string
in there is something that is in the .po file.
It is possible to store the translated string into a variable::
{% trans "this is a test" as var %}
{{ var }}
Contextual translations are also supported::
{% trans "this is a test" context "greeting" %}
This is equivalent to calling pgettext instead of (u)gettext.
"""
bits = token.split_contents()
if len(bits) < 2:
raise TemplateSyntaxError("'%s' takes at least one argument" % bits[0])
message_string = parser.compile_filter(bits[1])
remaining = bits[2:]
noop = False
asvar = None
message_context = None
seen = set()
invalid_context = {'as', 'noop'}
while remaining:
option = remaining.pop(0)
if option in seen:
raise TemplateSyntaxError(
"The '%s' option was specified more than once." % option,
)
elif option == 'noop':
noop = True
elif option == 'context':
try:
value = remaining.pop(0)
except IndexError:
msg = "No argument provided to the '%s' tag for the context option." % bits[0]
six.reraise(TemplateSyntaxError, TemplateSyntaxError(msg), sys.exc_info()[2])
if value in invalid_context:
raise TemplateSyntaxError(
"Invalid argument '%s' provided to the '%s' tag for the context option" % (value, bits[0]),
)
message_context = parser.compile_filter(value)
elif option == 'as':
try:
value = remaining.pop(0)
except IndexError:
msg = "No argument provided to the '%s' tag for the as option." % bits[0]
six.reraise(TemplateSyntaxError, TemplateSyntaxError(msg), sys.exc_info()[2])
asvar = value
else:
raise TemplateSyntaxError(
"Unknown argument for '%s' tag: '%s'. The only options "
"available are 'noop', 'context' \"xxx\", and 'as VAR'." % (
bits[0], option,
)
)
seen.add(option)
return TranslateNode(message_string, noop, asvar, message_context)
@register.tag("blocktrans")
def do_block_translate(parser, token):
"""
This will translate a block of text with parameters.
Usage::
{% blocktrans with bar=foo|filter boo=baz|filter %}
This is {{ bar }} and {{ boo }}.
{% endblocktrans %}
Additionally, this supports pluralization::
{% blocktrans count count=var|length %}
There is {{ count }} object.
{% plural %}
There are {{ count }} objects.
{% endblocktrans %}
This is much like ngettext, only in template syntax.
The "var as value" legacy format is still supported::
{% blocktrans with foo|filter as bar and baz|filter as boo %}
{% blocktrans count var|length as count %}
The translated string can be stored in a variable using `asvar`::
{% blocktrans with bar=foo|filter boo=baz|filter asvar var %}
This is {{ bar }} and {{ boo }}.
{% endblocktrans %}
{{ var }}
Contextual translations are supported::
{% blocktrans with bar=foo|filter context "greeting" %}
This is {{ bar }}.
{% endblocktrans %}
This is equivalent to calling pgettext/npgettext instead of
(u)gettext/(u)ngettext.
"""
bits = token.split_contents()
options = {}
remaining_bits = bits[1:]
asvar = None
while remaining_bits:
option = remaining_bits.pop(0)
if option in options:
raise TemplateSyntaxError('The %r option was specified more '
'than once.' % option)
if option == 'with':
value = token_kwargs(remaining_bits, parser, support_legacy=True)
if not value:
raise TemplateSyntaxError('"with" in %r tag needs at least '
'one keyword argument.' % bits[0])
elif option == 'count':
value = token_kwargs(remaining_bits, parser, support_legacy=True)
if len(value) != 1:
raise TemplateSyntaxError('"count" in %r tag expected exactly '
'one keyword argument.' % bits[0])
elif option == "context":
try:
value = remaining_bits.pop(0)
value = parser.compile_filter(value)
except Exception:
msg = (
'"context" in %r tag expected '
'exactly one argument.') % bits[0]
six.reraise(TemplateSyntaxError, TemplateSyntaxError(msg), sys.exc_info()[2])
elif option == "trimmed":
value = True
elif option == "asvar":
try:
value = remaining_bits.pop(0)
except IndexError:
msg = "No argument provided to the '%s' tag for the asvar option." % bits[0]
six.reraise(TemplateSyntaxError, TemplateSyntaxError(msg), sys.exc_info()[2])
asvar = value
else:
raise TemplateSyntaxError('Unknown argument for %r tag: %r.' %
(bits[0], option))
options[option] = value
if 'count' in options:
countervar, counter = list(options['count'].items())[0]
else:
countervar, counter = None, None
if 'context' in options:
message_context = options['context']
else:
message_context = None
extra_context = options.get('with', {})
trimmed = options.get("trimmed", False)
singular = []
plural = []
while parser.tokens:
token = parser.next_token()
if token.token_type in (TOKEN_VAR, TOKEN_TEXT):
singular.append(token)
else:
break
if countervar and counter:
if token.contents.strip() != 'plural':
raise TemplateSyntaxError("'blocktrans' doesn't allow other block tags inside it")
while parser.tokens:
token = parser.next_token()
if token.token_type in (TOKEN_VAR, TOKEN_TEXT):
plural.append(token)
else:
break
if token.contents.strip() != 'endblocktrans':
raise TemplateSyntaxError("'blocktrans' doesn't allow other block tags (seen %r) inside it" % token.contents)
return BlockTranslateNode(extra_context, singular, plural, countervar,
counter, message_context, trimmed=trimmed,
asvar=asvar)
@register.tag
def language(parser, token):
"""
This will enable the given language just for this block.
Usage::
{% language "de" %}
This is {{ bar }} and {{ boo }}.
{% endlanguage %}
"""
bits = token.split_contents()
if len(bits) != 2:
raise TemplateSyntaxError("'%s' takes one argument (language)" % bits[0])
language = parser.compile_filter(bits[1])
nodelist = parser.parse(('endlanguage',))
parser.delete_first_token()
return LanguageNode(nodelist, language)
| vitaly4uk/django | django/templatetags/i18n.py | Python | bsd-3-clause | 18,976 |
<?php
/**
* @package Joomla.Platform
* @subpackage Session
*
* @copyright Copyright (C) 2005 - 2016 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* XCache session storage handler
*
* @since 11.1
*/
class JSessionStorageXcache extends JSessionStorage
{
/**
* Constructor
*
* @param array $options Optional parameters.
*
* @since 11.1
* @throws RuntimeException
*/
public function __construct($options = array())
{
if (!self::isSupported())
{
throw new RuntimeException('XCache Extension is not available', 404);
}
parent::__construct($options);
}
/**
* Read the data for a particular session identifier from the SessionHandler backend.
*
* @param string $id The session identifier.
*
* @return string The session data.
*
* @since 11.1
*/
public function read($id)
{
$sess_id = 'sess_' . $id;
// Check if id exists
if (!xcache_isset($sess_id))
{
return;
}
return (string) xcache_get($sess_id);
}
/**
* Write session data to the SessionHandler backend.
*
* @param string $id The session identifier.
* @param string $session_data The session data.
*
* @return boolean True on success, false otherwise.
*
* @since 11.1
*/
public function write($id, $session_data)
{
$sess_id = 'sess_' . $id;
return xcache_set($sess_id, $session_data, ini_get("session.gc_maxlifetime"));
}
/**
* Destroy the data for a particular session identifier in the SessionHandler backend.
*
* @param string $id The session identifier.
*
* @return boolean True on success, false otherwise.
*
* @since 11.1
*/
public function destroy($id)
{
$sess_id = 'sess_' . $id;
if (!xcache_isset($sess_id))
{
return true;
}
return xcache_unset($sess_id);
}
/**
* Test to see if the SessionHandler is available.
*
* @return boolean True on success, false otherwise.
*
* @since 12.1
*/
public static function isSupported()
{
return (extension_loaded('xcache'));
}
}
| Suki00789/escb-mysql | site/libraries/joomla/session/storage/xcache.php | PHP | gpl-3.0 | 2,155 |
export class DOMSerializer {
elementSelector(element) {
// iterate up the dom
var selectors = [];
while (element.tagName !== 'HTML') {
var selector = element.tagName.toLowerCase();
var id = element.getAttribute('id');
if (id) {
selector += "#" + id;
}
var className = element.className;
if (className) {
var classes = className.split(' ');
for (var i = 0; i < classes.length; i++) {
var c = classes[i];
if (c) {
selector += '.' + c;
}
}
}
if (!element.parentNode) {
return null;
}
var childIndex = Array.prototype.indexOf.call(element.parentNode.children, element);
selector += ':nth-child(' + (childIndex + 1) + ')';
element = element.parentNode;
selectors.push(selector);
}
return selectors.reverse().join('>');
}
elementName(element) {
// 1. ion-track-name directive
var name = element.getAttribute('ion-track-name');
if (name) {
return name;
}
// 2. id
var id = element.getAttribute('id');
if (id) {
return id;
}
// 3. no unique identifier --> return null
return null;
}
}
| IsaacMiguel/aidaScan-App | www/lib/ionic-platform-web-client/src/analytics/serializers.js | JavaScript | mit | 1,227 |
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var important = function important(node) {
return node.important;
};
var unimportant = function unimportant(node) {
return !node.important;
};
var hasInherit = function hasInherit(node) {
return ~node.value.indexOf('inherit');
};
var hasInitial = function hasInitial(node) {
return ~node.value.indexOf('initial');
};
exports['default'] = function () {
for (var _len = arguments.length, props = Array(_len), _key = 0; _key < _len; _key++) {
props[_key] = arguments[_key];
}
if (props.some(hasInherit) || props.some(hasInitial)) {
return false;
}
return props.every(important) || props.every(unimportant);
};
module.exports = exports['default']; | puyanLiu/LPYFramework | 前端练习/autoFramework/webpack-demo3/node_modules/postcss-merge-longhand/dist/lib/canMerge.js | JavaScript | apache-2.0 | 780 |
var assert = require('assert');
var cp = require('child_process');
var fs = require('fs');
var fs_extra = require('fs-extra');
var curDir = fs.realpathSync('.');
var exec_path = process.execPath;
var app_path = path.join(curDir, 'internal');
describe('chromium-args', function() {
describe('--disable-javascript', function() {
var child;
before(function(done) {
this.timeout(0);
fs_extra.copy(path.join(app_path, 'package1.json'), path.join(app_path, 'package.json'), function (err) {
if (err) {
throw err;
}
child = spawnChildProcess(path.join(curDir, 'internal'));
});
setTimeout(function(){done();}, 2500);
});
after(function() {
if (child)
child.kill();
fs.unlink(path.join(app_path, 'hi'), function(err) {if(err && err.code !== 'ENOENT') throw err});
fs.unlink(path.join(app_path, 'package.json'), function(err) {if(err && err.code !== 'ENOENT') throw err});
});
it('javascript should not be executed', function() {
var result = fs.existsSync(path.join(app_path, 'hi'));
assert.equal(result, false);
});
});
describe('--app=url', function() {
var result = false, result2 = false;
var child, server;
before(function(done) {
this.timeout(0);
fs_extra.copy(path.join(app_path, 'package2.json'), path.join(app_path, 'package.json'), function (err) {
if (err) {
throw err;
}
server = createTCPServer(13013);
server.on('connection', function(socket) {
socket.setEncoding('utf8');
socket.on('data', function(data) {
result2 = data;
result = true;
done();
});
});
child = spawnChildProcess(path.join(curDir, 'internal'));
setTimeout(function() {
if (!result) {
child.kill();
done('timeout');
}
}, 4500);
});
});
after(function(done) {
this.timeout(0);
child.kill();
server.close();
fs.unlink(path.join(app_path, 'package.json'), function(err) {if(err && err.code !== 'ENOENT') throw err});
fs.unlink(path.join(app_path, 'hi'), function(err) {if(err && err.code !== 'ENOENT') throw err});
done();
});
it('website should be the url', function() {
assert.equal(result2, true);
});
});
});
| 280455936/nw.js | tests/automation/chromium-args/mocha_test.js | JavaScript | mit | 2,565 |
// 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;
using Xunit;
namespace System.Threading.Tasks.Tests
{
public class TaskCanceledExceptionTests
{
[Fact]
public void TaskCanceledException_Ctor_StringExceptionToken()
{
string message = "my exception message";
var ioe = new InvalidOperationException();
var cts = new CancellationTokenSource();
cts.Cancel();
var tce = new TaskCanceledException(message, ioe, cts.Token);
Assert.Equal(message, tce.Message);
Assert.Null(tce.Task);
Assert.Same(ioe, tce.InnerException);
Assert.Equal(cts.Token, tce.CancellationToken);
}
}
}
| BrennanConroy/corefx | src/System.Threading.Tasks/tests/Task/TaskCanceledExceptionTests.netcoreapp.cs | C# | mit | 891 |
/*
* Copyright 2000-2014 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.
*/
/**
*
* Inspection that reports unresolved and unused references.
* You can inject logic to mark some unused imports as used. See extension points in this package.
* @author Ilya.Kazakevich
*/
package com.jetbrains.python.inspections.unresolvedReference; | asedunov/intellij-community | python/src/com/jetbrains/python/inspections/unresolvedReference/package-info.java | Java | apache-2.0 | 861 |
<?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 license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_View
* @subpackage Helper
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Links.php 25239 2013-01-22 09:45:01Z frosch $
*/
/**
* @see Zend_View_Helper_Navigation_HelperAbstract
*/
require_once 'Zend/View/Helper/Navigation/HelperAbstract.php';
/**
* Helper for printing <link> elements
*
* @category Zend
* @package Zend_View
* @subpackage Helper
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_View_Helper_Navigation_Links
extends Zend_View_Helper_Navigation_HelperAbstract
{
/**#@+
* Constants used for specifying which link types to find and render
*
* @var int
*/
const RENDER_ALTERNATE = 0x0001;
const RENDER_STYLESHEET = 0x0002;
const RENDER_START = 0x0004;
const RENDER_NEXT = 0x0008;
const RENDER_PREV = 0x0010;
const RENDER_CONTENTS = 0x0020;
const RENDER_INDEX = 0x0040;
const RENDER_GLOSSARY = 0x0080;
const RENDER_COPYRIGHT = 0x0100;
const RENDER_CHAPTER = 0x0200;
const RENDER_SECTION = 0x0400;
const RENDER_SUBSECTION = 0x0800;
const RENDER_APPENDIX = 0x1000;
const RENDER_HELP = 0x2000;
const RENDER_BOOKMARK = 0x4000;
const RENDER_CUSTOM = 0x8000;
const RENDER_ALL = 0xffff;
/**#@+**/
/**
* Maps render constants to W3C link types
*
* @var array
*/
protected static $_RELATIONS = array(
self::RENDER_ALTERNATE => 'alternate',
self::RENDER_STYLESHEET => 'stylesheet',
self::RENDER_START => 'start',
self::RENDER_NEXT => 'next',
self::RENDER_PREV => 'prev',
self::RENDER_CONTENTS => 'contents',
self::RENDER_INDEX => 'index',
self::RENDER_GLOSSARY => 'glossary',
self::RENDER_COPYRIGHT => 'copyright',
self::RENDER_CHAPTER => 'chapter',
self::RENDER_SECTION => 'section',
self::RENDER_SUBSECTION => 'subsection',
self::RENDER_APPENDIX => 'appendix',
self::RENDER_HELP => 'help',
self::RENDER_BOOKMARK => 'bookmark'
);
/**
* The helper's render flag
*
* @see render()
* @see setRenderFlag()
* @var int
*/
protected $_renderFlag = self::RENDER_ALL;
/**
* Root container
*
* Used for preventing methods to traverse above the container given to
* the {@link render()} method.
*
* @see _findRoot()
*
* @var Zend_Navigation_Container
*/
protected $_root;
/**
* View helper entry point:
* Retrieves helper and optionally sets container to operate on
*
* @param Zend_Navigation_Container $container [optional] container to
* operate on
* @return Zend_View_Helper_Navigation_Links fluent interface, returns
* self
*/
public function links(Zend_Navigation_Container $container = null)
{
if (null !== $container) {
$this->setContainer($container);
}
return $this;
}
/**
* Magic overload: Proxy calls to {@link findRelation()} or container
*
* Examples of finder calls:
* <code>
* // METHOD // SAME AS
* $h->findRelNext($page); // $h->findRelation($page, 'rel', 'next')
* $h->findRevSection($page); // $h->findRelation($page, 'rev', 'section');
* $h->findRelFoo($page); // $h->findRelation($page, 'rel', 'foo');
* </code>
*
* @param string $method method name
* @param array $arguments method arguments
* @throws Zend_Navigation_Exception if method does not exist in container
*/
public function __call($method, array $arguments = array())
{
if (@preg_match('/find(Rel|Rev)(.+)/', $method, $match)) {
return $this->findRelation($arguments[0],
strtolower($match[1]),
strtolower($match[2]));
}
return parent::__call($method, $arguments);
}
// Accessors:
/**
* Sets the helper's render flag
*
* The helper uses the bitwise '&' operator against the hex values of the
* render constants. This means that the flag can is "bitwised" value of
* the render constants. Examples:
* <code>
* // render all links except glossary
* $flag = Zend_View_Helper_Navigation_Links:RENDER_ALL ^
* Zend_View_Helper_Navigation_Links:RENDER_GLOSSARY;
* $helper->setRenderFlag($flag);
*
* // render only chapters and sections
* $flag = Zend_View_Helper_Navigation_Links:RENDER_CHAPTER |
* Zend_View_Helper_Navigation_Links:RENDER_SECTION;
* $helper->setRenderFlag($flag);
*
* // render only relations that are not native W3C relations
* $helper->setRenderFlag(Zend_View_Helper_Navigation_Links:RENDER_CUSTOM);
*
* // render all relations (default)
* $helper->setRenderFlag(Zend_View_Helper_Navigation_Links:RENDER_ALL);
* </code>
*
* Note that custom relations can also be rendered directly using the
* {@link renderLink()} method.
*
* @param int $renderFlag render flag
* @return Zend_View_Helper_Navigation_Links fluent interface, returns self
*/
public function setRenderFlag($renderFlag)
{
$this->_renderFlag = (int) $renderFlag;
return $this;
}
/**
* Returns the helper's render flag
*
* @return int render flag
*/
public function getRenderFlag()
{
return $this->_renderFlag;
}
// Finder methods:
/**
* Finds all relations (forward and reverse) for the given $page
*
* The form of the returned array:
* <code>
* // $page denotes an instance of Zend_Navigation_Page
* $returned = array(
* 'rel' => array(
* 'alternate' => array($page, $page, $page),
* 'start' => array($page),
* 'next' => array($page),
* 'prev' => array($page),
* 'canonical' => array($page)
* ),
* 'rev' => array(
* 'section' => array($page)
* )
* );
* </code>
*
* @param Zend_Navigation_Page $page page to find links for
* @return array related pages
*/
public function findAllRelations(Zend_Navigation_Page $page,
$flag = null)
{
if (!is_int($flag)) {
$flag = self::RENDER_ALL;
}
$result = array('rel' => array(), 'rev' => array());
$native = array_values(self::$_RELATIONS);
foreach (array_keys($result) as $rel) {
$meth = 'getDefined' . ucfirst($rel);
$types = array_merge($native, array_diff($page->$meth(), $native));
foreach ($types as $type) {
if (!$relFlag = array_search($type, self::$_RELATIONS)) {
$relFlag = self::RENDER_CUSTOM;
}
if (!($flag & $relFlag)) {
continue;
}
if ($found = $this->findRelation($page, $rel, $type)) {
if (!is_array($found)) {
$found = array($found);
}
$result[$rel][$type] = $found;
}
}
}
return $result;
}
/**
* Finds relations of the given $rel=$type from $page
*
* This method will first look for relations in the page instance, then
* by searching the root container if nothing was found in the page.
*
* @param Zend_Navigation_Page $page page to find relations for
* @param string $rel relation, "rel" or "rev"
* @param string $type link type, e.g. 'start', 'next'
* @return Zend_Navigaiton_Page|array|null page(s), or null if not found
* @throws Zend_View_Exception if $rel is not "rel" or "rev"
*/
public function findRelation(Zend_Navigation_Page $page, $rel, $type)
{
if (!in_array($rel, array('rel', 'rev'))) {
require_once 'Zend/View/Exception.php';
$e = new Zend_View_Exception(sprintf(
'Invalid argument: $rel must be "rel" or "rev"; "%s" given',
$rel));
$e->setView($this->view);
throw $e;
}
if (!$result = $this->_findFromProperty($page, $rel, $type)) {
$result = $this->_findFromSearch($page, $rel, $type);
}
return $result;
}
/**
* Finds relations of given $type for $page by checking if the
* relation is specified as a property of $page
*
* @param Zend_Navigation_Page $page page to find relations for
* @param string $rel relation, 'rel' or 'rev'
* @param string $type link type, e.g. 'start', 'next'
* @return Zend_Navigation_Page|array|null page(s), or null if not found
*/
protected function _findFromProperty(Zend_Navigation_Page $page, $rel, $type)
{
$method = 'get' . ucfirst($rel);
if ($result = $page->$method($type)) {
if ($result = $this->_convertToPages($result)) {
if (!is_array($result)) {
$result = array($result);
}
foreach ($result as $key => $page) {
if (!$this->accept($page)) {
unset($result[$key]);
}
}
return count($result) == 1 ? $result[0] : $result;
}
}
return null;
}
/**
* Finds relations of given $rel=$type for $page by using the helper to
* search for the relation in the root container
*
* @param Zend_Navigation_Page $page page to find relations for
* @param string $rel relation, 'rel' or 'rev'
* @param string $type link type, e.g. 'start', 'next', etc
* @return array|null array of pages, or null if not found
*/
protected function _findFromSearch(Zend_Navigation_Page $page, $rel, $type)
{
$found = null;
$method = 'search' . ucfirst($rel) . ucfirst($type);
if (method_exists($this, $method)) {
$found = $this->$method($page);
}
return $found;
}
// Search methods:
/**
* Searches the root container for the forward 'start' relation of the given
* $page
*
* From {@link http://www.w3.org/TR/html4/types.html#type-links}:
* Refers to the first document in a collection of documents. This link type
* tells search engines which document is considered by the author to be the
* starting point of the collection.
*
* @param Zend_Navigation_Page $page page to find relation for
* @return Zend_Navigation_Page|null page or null
*/
public function searchRelStart(Zend_Navigation_Page $page)
{
$found = $this->_findRoot($page);
if (!$found instanceof Zend_Navigation_Page) {
$found->rewind();
$found = $found->current();
}
if ($found === $page || !$this->accept($found)) {
$found = null;
}
return $found;
}
/**
* Searches the root container for the forward 'next' relation of the given
* $page
*
* From {@link http://www.w3.org/TR/html4/types.html#type-links}:
* Refers to the next document in a linear sequence of documents. User
* agents may choose to preload the "next" document, to reduce the perceived
* load time.
*
* @param Zend_Navigation_Page $page page to find relation for
* @return Zend_Navigation_Page|null page(s) or null
*/
public function searchRelNext(Zend_Navigation_Page $page)
{
$found = null;
$break = false;
$iterator = new RecursiveIteratorIterator($this->_findRoot($page),
RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $intermediate) {
if ($intermediate === $page) {
// current page; break at next accepted page
$break = true;
continue;
}
if ($break && $this->accept($intermediate)) {
$found = $intermediate;
break;
}
}
return $found;
}
/**
* Searches the root container for the forward 'prev' relation of the given
* $page
*
* From {@link http://www.w3.org/TR/html4/types.html#type-links}:
* Refers to the previous document in an ordered series of documents. Some
* user agents also support the synonym "Previous".
*
* @param Zend_Navigation_Page $page page to find relation for
* @return Zend_Navigation_Page|null page or null
*/
public function searchRelPrev(Zend_Navigation_Page $page)
{
$found = null;
$prev = null;
$iterator = new RecursiveIteratorIterator(
$this->_findRoot($page),
RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $intermediate) {
if (!$this->accept($intermediate)) {
continue;
}
if ($intermediate === $page) {
$found = $prev;
break;
}
$prev = $intermediate;
}
return $found;
}
/**
* Searches the root container for forward 'chapter' relations of the given
* $page
*
* From {@link http://www.w3.org/TR/html4/types.html#type-links}:
* Refers to a document serving as a chapter in a collection of documents.
*
* @param Zend_Navigation_Page $page page to find relation for
* @return Zend_Navigation_Page|array|null page(s) or null
*/
public function searchRelChapter(Zend_Navigation_Page $page)
{
$found = array();
// find first level of pages
$root = $this->_findRoot($page);
// find start page(s)
$start = $this->findRelation($page, 'rel', 'start');
if (!is_array($start)) {
$start = array($start);
}
foreach ($root as $chapter) {
// exclude self and start page from chapters
if ($chapter !== $page &&
!in_array($chapter, $start) &&
$this->accept($chapter)) {
$found[] = $chapter;
}
}
switch (count($found)) {
case 0:
return null;
case 1:
return $found[0];
default:
return $found;
}
}
/**
* Searches the root container for forward 'section' relations of the given
* $page
*
* From {@link http://www.w3.org/TR/html4/types.html#type-links}:
* Refers to a document serving as a section in a collection of documents.
*
* @param Zend_Navigation_Page $page page to find relation for
* @return Zend_Navigation_Page|array|null page(s) or null
*/
public function searchRelSection(Zend_Navigation_Page $page)
{
$found = array();
// check if given page has pages and is a chapter page
if ($page->hasPages() && $this->_findRoot($page)->hasPage($page)) {
foreach ($page as $section) {
if ($this->accept($section)) {
$found[] = $section;
}
}
}
switch (count($found)) {
case 0:
return null;
case 1:
return $found[0];
default:
return $found;
}
}
/**
* Searches the root container for forward 'subsection' relations of the
* given $page
*
* From {@link http://www.w3.org/TR/html4/types.html#type-links}:
* Refers to a document serving as a subsection in a collection of
* documents.
*
* @param Zend_Navigation_Page $page page to find relation for
* @return Zend_Navigation_Page|array|null page(s) or null
*/
public function searchRelSubsection(Zend_Navigation_Page $page)
{
$found = array();
if ($page->hasPages()) {
// given page has child pages, loop chapters
foreach ($this->_findRoot($page) as $chapter) {
// is page a section?
if ($chapter->hasPage($page)) {
foreach ($page as $subsection) {
if ($this->accept($subsection)) {
$found[] = $subsection;
}
}
}
}
}
switch (count($found)) {
case 0:
return null;
case 1:
return $found[0];
default:
return $found;
}
}
/**
* Searches the root container for the reverse 'section' relation of the
* given $page
*
* From {@link http://www.w3.org/TR/html4/types.html#type-links}:
* Refers to a document serving as a section in a collection of documents.
*
* @param Zend_Navigation_Page $page page to find relation for
* @return Zend_Navigation_Page|null page(s) or null
*/
public function searchRevSection(Zend_Navigation_Page $page)
{
$found = null;
if ($parent = $page->getParent()) {
if ($parent instanceof Zend_Navigation_Page &&
$this->_findRoot($page)->hasPage($parent)) {
$found = $parent;
}
}
return $found;
}
/**
* Searches the root container for the reverse 'section' relation of the
* given $page
*
* From {@link http://www.w3.org/TR/html4/types.html#type-links}:
* Refers to a document serving as a subsection in a collection of
* documents.
*
* @param Zend_Navigation_Page $page page to find relation for
* @return Zend_Navigation_Page|null page(s) or null
*/
public function searchRevSubsection(Zend_Navigation_Page $page)
{
$found = null;
if ($parent = $page->getParent()) {
if ($parent instanceof Zend_Navigation_Page) {
$root = $this->_findRoot($page);
foreach ($root as $chapter) {
if ($chapter->hasPage($parent)) {
$found = $parent;
break;
}
}
}
}
return $found;
}
// Util methods:
/**
* Returns the root container of the given page
*
* When rendering a container, the render method still store the given
* container as the root container, and unset it when done rendering. This
* makes sure finder methods will not traverse above the container given
* to the render method.
*
* @param Zend_Navigaiton_Page $page page to find root for
* @return Zend_Navigation_Container the root container of the given page
*/
protected function _findRoot(Zend_Navigation_Page $page)
{
if ($this->_root) {
return $this->_root;
}
$root = $page;
while ($parent = $page->getParent()) {
$root = $parent;
if ($parent instanceof Zend_Navigation_Page) {
$page = $parent;
} else {
break;
}
}
return $root;
}
/**
* Converts a $mixed value to an array of pages
*
* @param mixed $mixed mixed value to get page(s) from
* @param bool $recursive whether $value should be looped
* if it is an array or a config
* @return Zend_Navigation_Page|array|null empty if unable to convert
*/
protected function _convertToPages($mixed, $recursive = true)
{
if (is_object($mixed)) {
if ($mixed instanceof Zend_Navigation_Page) {
// value is a page instance; return directly
return $mixed;
} elseif ($mixed instanceof Zend_Navigation_Container) {
// value is a container; return pages in it
$pages = array();
foreach ($mixed as $page) {
$pages[] = $page;
}
return $pages;
} elseif ($mixed instanceof Zend_Config) {
// convert config object to array and extract
return $this->_convertToPages($mixed->toArray(), $recursive);
}
} elseif (is_string($mixed)) {
// value is a string; make an URI page
return Zend_Navigation_Page::factory(array(
'type' => 'uri',
'uri' => $mixed
));
} elseif (is_array($mixed) && !empty($mixed)) {
if ($recursive && is_numeric(key($mixed))) {
// first key is numeric; assume several pages
$pages = array();
foreach ($mixed as $value) {
if ($value = $this->_convertToPages($value, false)) {
$pages[] = $value;
}
}
return $pages;
} else {
// pass array to factory directly
try {
$page = Zend_Navigation_Page::factory($mixed);
return $page;
} catch (Exception $e) {
}
}
}
// nothing found
return null;
}
// Render methods:
/**
* Renders the given $page as a link element, with $attrib = $relation
*
* @param Zend_Navigation_Page $page the page to render the link for
* @param string $attrib the attribute to use for $type,
* either 'rel' or 'rev'
* @param string $relation relation type, muse be one of;
* alternate, appendix, bookmark,
* chapter, contents, copyright,
* glossary, help, home, index, next,
* prev, section, start, stylesheet,
* subsection
* @return string rendered link element
* @throws Zend_View_Exception if $attrib is invalid
*/
public function renderLink(Zend_Navigation_Page $page, $attrib, $relation)
{
if (!in_array($attrib, array('rel', 'rev'))) {
require_once 'Zend/View/Exception.php';
$e = new Zend_View_Exception(sprintf(
'Invalid relation attribute "%s", must be "rel" or "rev"',
$attrib));
$e->setView($this->view);
throw $e;
}
if (!$href = $page->getHref()) {
return '';
}
// TODO: add more attribs
// http://www.w3.org/TR/html401/struct/links.html#h-12.2
$attribs = array(
$attrib => $relation,
'href' => $href,
'title' => $page->getLabel()
);
return '<link' .
$this->_htmlAttribs($attribs) .
$this->getClosingBracket();
}
// Zend_View_Helper_Navigation_Helper:
/**
* Renders helper
*
* Implements {@link Zend_View_Helper_Navigation_Helper::render()}.
*
* @param Zend_Navigation_Container $container [optional] container to
* render. Default is to
* render the container
* registered in the helper.
* @return string helper output
*/
public function render(Zend_Navigation_Container $container = null)
{
if (null === $container) {
$container = $this->getContainer();
}
if ($active = $this->findActive($container)) {
$active = $active['page'];
} else {
// no active page
return '';
}
$output = '';
$indent = $this->getIndent();
$this->_root = $container;
$result = $this->findAllRelations($active, $this->getRenderFlag());
foreach ($result as $attrib => $types) {
foreach ($types as $relation => $pages) {
foreach ($pages as $page) {
if ($r = $this->renderLink($page, $attrib, $relation)) {
$output .= $indent . $r . $this->getEOL();
}
}
}
}
$this->_root = null;
// return output (trim last newline by spec)
return strlen($output) ? rtrim($output, self::EOL) : '';
}
}
| Nyaoh/Mz | webapp/library/Zend/View/Helper/Navigation/Links.php | PHP | gpl-3.0 | 26,140 |
public class Foo {
void m(boolean b) {
b.if<caret>
value = null;
}
} | asedunov/intellij-community | java/java-tests/testData/codeInsight/template/postfix/templates/if/beforeAssignment.java | Java | apache-2.0 | 93 |
a = "two"
"one %s three" % a | idea4bsd/idea4bsd | python/testData/refactoring/introduceVariable/substringInExpressionStatement.after.py | Python | apache-2.0 | 28 |
<?php
namespace Illuminate\Database\Eloquent\Relations;
use BadMethodCallException;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
class MorphTo extends BelongsTo
{
/**
* The type of the polymorphic relation.
*
* @var string
*/
protected $morphType;
/**
* The models whose relations are being eager loaded.
*
* @var \Illuminate\Database\Eloquent\Collection
*/
protected $models;
/**
* All of the models keyed by ID.
*
* @var array
*/
protected $dictionary = [];
/**
* A buffer of dynamic calls to query macros.
*
* @var array
*/
protected $macroBuffer = [];
/**
* Create a new morph to relationship instance.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param \Illuminate\Database\Eloquent\Model $parent
* @param string $foreignKey
* @param string $ownerKey
* @param string $type
* @param string $relation
* @return void
*/
public function __construct(Builder $query, Model $parent, $foreignKey, $ownerKey, $type, $relation)
{
$this->morphType = $type;
parent::__construct($query, $parent, $foreignKey, $ownerKey, $relation);
}
/**
* Set the constraints for an eager load of the relation.
*
* @param array $models
* @return void
*/
public function addEagerConstraints(array $models)
{
$this->buildDictionary($this->models = Collection::make($models));
}
/**
* Build a dictionary with the models.
*
* @param \Illuminate\Database\Eloquent\Collection $models
* @return void
*/
protected function buildDictionary(Collection $models)
{
foreach ($models as $model) {
if ($model->{$this->morphType}) {
$this->dictionary[$model->{$this->morphType}][$model->{$this->foreignKey}][] = $model;
}
}
}
/**
* Get the results of the relationship.
*
* @return mixed
*/
public function getResults()
{
return $this->ownerKey ? $this->query->first() : null;
}
/**
* Get the results of the relationship.
*
* Called via eager load method of Eloquent query builder.
*
* @return mixed
*/
public function getEager()
{
foreach (array_keys($this->dictionary) as $type) {
$this->matchToMorphParents($type, $this->getResultsByType($type));
}
return $this->models;
}
/**
* Get all of the relation results for a type.
*
* @param string $type
* @return \Illuminate\Database\Eloquent\Collection
*/
protected function getResultsByType($type)
{
$instance = $this->createModelByType($type);
$query = $this->replayMacros($instance->newQuery())
->mergeConstraintsFrom($this->getQuery())
->with($this->getQuery()->getEagerLoads());
return $query->whereIn(
$instance->getTable().'.'.$instance->getKeyName(), $this->gatherKeysByType($type)
)->get();
}
/**
* Gather all of the foreign keys for a given type.
*
* @param string $type
* @return array
*/
protected function gatherKeysByType($type)
{
return collect($this->dictionary[$type])->map(function ($models) {
return head($models)->{$this->foreignKey};
})->values()->unique()->all();
}
/**
* Create a new model instance by type.
*
* @param string $type
* @return \Illuminate\Database\Eloquent\Model
*/
public function createModelByType($type)
{
$class = Model::getActualClassNameForMorph($type);
return new $class;
}
/**
* Match the eagerly loaded results to their parents.
*
* @param array $models
* @param \Illuminate\Database\Eloquent\Collection $results
* @param string $relation
* @return array
*/
public function match(array $models, Collection $results, $relation)
{
return $models;
}
/**
* Match the results for a given type to their parents.
*
* @param string $type
* @param \Illuminate\Database\Eloquent\Collection $results
* @return void
*/
protected function matchToMorphParents($type, Collection $results)
{
foreach ($results as $result) {
if (isset($this->dictionary[$type][$result->getKey()])) {
foreach ($this->dictionary[$type][$result->getKey()] as $model) {
$model->setRelation($this->relation, $result);
}
}
}
}
/**
* Associate the model instance to the given parent.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @return \Illuminate\Database\Eloquent\Model
*/
public function associate($model)
{
$this->parent->setAttribute($this->foreignKey, $model->getKey());
$this->parent->setAttribute($this->morphType, $model->getMorphClass());
return $this->parent->setRelation($this->relation, $model);
}
/**
* Dissociate previously associated model from the given parent.
*
* @return \Illuminate\Database\Eloquent\Model
*/
public function dissociate()
{
$this->parent->setAttribute($this->foreignKey, null);
$this->parent->setAttribute($this->morphType, null);
return $this->parent->setRelation($this->relation, null);
}
/**
* Get the foreign key "type" name.
*
* @return string
*/
public function getMorphType()
{
return $this->morphType;
}
/**
* Get the dictionary used by the relationship.
*
* @return array
*/
public function getDictionary()
{
return $this->dictionary;
}
/**
* Replay stored macro calls on the actual related instance.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @return \Illuminate\Database\Eloquent\Builder
*/
protected function replayMacros(Builder $query)
{
foreach ($this->macroBuffer as $macro) {
$query->{$macro['method']}(...$macro['parameters']);
}
return $query;
}
/**
* Handle dynamic method calls to the relationship.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public function __call($method, $parameters)
{
try {
return parent::__call($method, $parameters);
}
// If we tried to call a method that does not exist on the parent Builder instance,
// we'll assume that we want to call a query macro (e.g. withTrashed) that only
// exists on related models. We will just store the call and replay it later.
catch (BadMethodCallException $e) {
$this->macroBuffer[] = compact('method', 'parameters');
return $this;
}
}
}
| aloha1003/poseitech_assignment | workspace/assignment/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/MorphTo.php | PHP | mit | 7,153 |
<?php
/**
* @package Joomla.Administrator
* @subpackage com_messages
*
* @copyright Copyright (C) 2005 - 2016 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
/**
* Messages list controller class.
*
* @since 1.6
*/
class MessagesControllerMessages extends JControllerAdmin
{
/**
* Method to get a model object, loading it if required.
*
* @param string $name The model name. Optional.
* @param string $prefix The class prefix. Optional.
* @param array $config Configuration array for model. Optional.
*
* @return object The model.
*
* @since 1.6
*/
public function getModel($name = 'Message', $prefix = 'MessagesModel', $config = array('ignore_request' => true))
{
return parent::getModel($name, $prefix, $config);
}
}
| yaelduckwen/lo_imaginario | web2/administrator/components/com_messages/controllers/messages.php | PHP | mit | 889 |
import java.util.*;
public class Varargs {
private List<String> <caret>method(String... values) {
return Arrays.asList(values);
}
private void context() {
List<String> list1 = Arrays.asList("hi", "bye");
List<String> list2 = Arrays.asList("hi");
List<String> list3 = Arrays.asList(new String[] {});
String[] sa = new String[] {};
List<String> list4 = Arrays.asList(sa);
List listA = Arrays.asList(0);
}
}
| caot/intellij-community | java/java-tests/testData/refactoring/methodDuplicates/Varargs.java | Java | apache-2.0 | 425 |
/**
* jQRangeSlider
* A javascript slider selector that supports dates
*
* Copyright (C) Guillaume Gautreau 2012
* Dual licensed under the MIT or GPL Version 2 licenses.
*/
(function($, undefined){
"use strict";
$.widget("ui.rangeSliderDraggable", $.ui.rangeSliderMouseTouch, {
cache: null,
options: {
containment: null
},
_create: function(){
setTimeout($.proxy(this._initElement, this), 10);
},
_initElement: function(){
this._mouseInit();
this._cache();
},
_setOption: function(key, value){
if (key == "containment"){
if (value === null || $(value).length == 0){
this.options.containment = null
}else{
this.options.containment = $(value);
}
}
},
/*
* UI mouse widget
*/
_mouseStart: function(event){
this._cache();
this.cache.click = {
left: event.pageX,
top: event.pageY
};
this.cache.initialOffset = this.element.offset();
this._triggerMouseEvent("mousestart");
return true;
},
_mouseDrag: function(event){
var position = event.pageX - this.cache.click.left;
position = this._constraintPosition(position + this.cache.initialOffset.left);
this._applyPosition(position);
this._triggerMouseEvent("drag");
return false;
},
_mouseStop: function(event){
this._triggerMouseEvent("stop");
},
/*
* To be overriden
*/
_constraintPosition: function(position){
if (this.element.parent().length !== 0 && this.cache.parent.offset != null){
position = Math.min(position,
this.cache.parent.offset.left + this.cache.parent.width - this.cache.width.outer);
position = Math.max(position, this.cache.parent.offset.left);
}
return position;
},
_applyPosition: function(position){
var offset = {
top: this.cache.offset.top,
left: position
}
this.element.offset({left:position});
this.cache.offset = offset;
},
/*
* Private utils
*/
_cacheIfNecessary: function(){
if (this.cache === null){
this._cache();
}
},
_cache: function(){
this.cache = {};
this._cacheMargins();
this._cacheParent();
this._cacheDimensions();
this.cache.offset = this.element.offset();
},
_cacheMargins: function(){
this.cache.margin = {
left: this._parsePixels(this.element, "marginLeft"),
right: this._parsePixels(this.element, "marginRight"),
top: this._parsePixels(this.element, "marginTop"),
bottom: this._parsePixels(this.element, "marginBottom")
};
},
_cacheParent: function(){
if (this.options.parent !== null){
var container = this.element.parent();
this.cache.parent = {
offset: container.offset(),
width: container.width()
}
}else{
this.cache.parent = null;
}
},
_cacheDimensions: function(){
this.cache.width = {
outer: this.element.outerWidth(),
inner: this.element.width()
}
},
_parsePixels: function(element, string){
return parseInt(element.css(string), 10) || 0;
},
_triggerMouseEvent: function(event){
var data = this._prepareEventData();
this.element.trigger(event, data);
},
_prepareEventData: function(){
return {
element: this.element,
offset: this.cache.offset || null
};
}
});
})(jQuery); | gaearon/cdnjs | ajax/libs/jQRangeSlider/4.2.4/jQRangeSliderDraggable.js | JavaScript | mit | 3,375 |
// Type definitions for path-is-inside 1.0
// Project: https://github.com/domenic/path-is-inside#readme
// Definitions by: Alexander Marks <https://github.com/aomarks>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare function pathIsInside(thePath: string,
potentialParent: string): boolean;
export = pathIsInside;
| borisyankov/DefinitelyTyped | types/path-is-inside/index.d.ts | TypeScript | mit | 371 |
require_relative "../../../base"
require Vagrant.source_root.join("plugins/provisioners/file/provisioner")
describe VagrantPlugins::FileUpload::Provisioner do
include_context "unit"
subject { described_class.new(machine, config) }
let(:iso_env) do
# We have to create a Vagrantfile so there is a root path
env = isolated_environment
env.vagrantfile("")
env.create_vagrant_env
end
let(:machine) { iso_env.machine(iso_env.machine_names[0], :dummy) }
let(:config) { double("config") }
let(:communicator) { double("comm") }
let(:guest) { double("guest") }
before do
machine.stub(communicate: communicator)
machine.stub(guest: guest)
communicator.stub(execute: true)
communicator.stub(upload: true)
guest.stub(capability?: false)
end
describe "#provision" do
it "creates the destination directory" do
config.stub(source: "/source")
config.stub(destination: "/foo/bar")
expect(communicator).to receive(:execute).with("mkdir -p /foo")
subject.provision
end
it "uploads the file" do
config.stub(source: "/source")
config.stub(destination: "/foo/bar")
expect(communicator).to receive(:upload).with("/source", "/foo/bar")
subject.provision
end
it "expands the source file path" do
config.stub(source: "source")
config.stub(destination: "/foo/bar")
expect(communicator).to receive(:upload).with(
File.expand_path("source"), "/foo/bar")
subject.provision
end
it "expands the destination file path if capable" do
config.stub(source: "/source")
config.stub(destination: "$HOME/foo")
expect(guest).to receive(:capability?).
with(:shell_expand_guest_path).and_return(true)
expect(guest).to receive(:capability).
with(:shell_expand_guest_path, "$HOME/foo").and_return("/home/foo")
expect(communicator).to receive(:upload).with("/source", "/home/foo")
subject.provision
end
end
end
| kamazee/vagrant | test/unit/plugins/provisioners/file/provisioner_test.rb | Ruby | mit | 2,022 |
/*****************************************************************************
* Copyright © 2011 VideoLAN
* $Id$
*
* Authors: Filipe Azevedo, aka PasNox
*
* This program 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 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.
*****************************************************************************/
#ifndef DECKBUTTONLAYOUT_H
#define DECKBUTTONLAYOUT_H
#include <QLayout>
#include <QPointer>
#include <QAbstractButton>
class QWidget;
class QAbstractButton;
class DeckButtonsLayout : public QLayout
{
Q_OBJECT
public:
DeckButtonsLayout( QWidget* parent = 0 );
virtual ~DeckButtonsLayout();
virtual QSize sizeHint() const;
virtual int count() const;
void setBackwardButton( QAbstractButton* button );
void setRoundButton( QAbstractButton* button );
void setForwardButton( QAbstractButton* button );
protected:
QWidgetItem* backwardItem;
QWidgetItem* goItem;
QWidgetItem* forwardItem;
QPointer<QAbstractButton> backwardButton;
QPointer<QAbstractButton> RoundButton;
QPointer<QAbstractButton> forwardButton;
virtual void setGeometry( const QRect& r );
virtual void addItem( QLayoutItem* item );
virtual QLayoutItem* itemAt( int index ) const;
virtual QLayoutItem* takeAt( int index );
};
#endif // DECKBUTTONLAYOUT_H
| DDTChen/CookieVLC | vlc/modules/gui/qt4/util/buttons/DeckButtonsLayout.hpp | C++ | gpl-2.0 | 1,955 |
/*!
* Backbone.Notifier 3D Module v0.0.3
* Copyright 2012, Eyal Weiss
* Backbone.Notifier 3D Module be freely distributed under the MIT license.
*/
(function (Notifier, $) {
Notifier.regModule({
name: '3d',
enabled: false,
extend: {
defaults: {
'3d': true
}
},
events: {
'beforeAnimateInMsgEl': function (settings, msgEl, msgInner, msgView) {
if (settings['3d']) {
var module = this.module,
fn = msgView.handle3d = function () { module.mouseMoveHandler.apply(module, arguments) };
$('body').bind('mousemove', {msgInner: msgInner}, fn);
}
},
'beforeHideMsgEl': function (settings, msgEl, msgInner, msgView) {
if (settings['3d']) {
$('body').unbind('mousemove', msgView.handle3d);
}
}
},
mouseMoveHandler: function (e) {
var winH = $(window).innerHeight(),
winW = $(window).innerWidth(),
pX = (.5 - (e.clientX / winW)) * 2,
degX = -(pX * 10).toFixed(2),
pY = (.5 - (e.clientY / winH)) * 2,
degY = (pY * 20).toFixed(2),
sX = (pX * 10),
sY = (pY * 10),
sD = Math.abs(sX) + Math.abs(sY),
sA = .8 - ((Math.abs(pX) + Math.abs(pY)) / 2) * .4,
shadow = sX.toFixed(2) + 'px ' + sY.toFixed(2) + 'px' + ' ' + sD.toFixed(2) + 'px rgba(0,0,0,' + sA.toFixed(2) + ')',
css = {};
css[this.transformAttr] = 'perspective(800px) rotateX(' + degY + 'deg) rotateY(' + degX + 'deg)';
css[this.shadowAttr] = shadow;
e.data.msgInner.css(css);
},
getVendorPrefix: function (prefix) {
var prefixes = $.map(['', '-webkit-', '-moz-', '-ms-', '-o-'], function (attr) {
return attr + prefix;
});
var tmp = document.createElement("div"),
res = prefix;
for (var i = 0; i < prefixes.length; ++i) {
if (typeof tmp.style[prefixes[i]] !== 'undefined') {
res = prefixes[i];
break;
}
}
return res;
},
register: function () {
this.transformAttr = this.getVendorPrefix('transform');
this.shadowAttr = this.getVendorPrefix('box-shadow');
//console.log(this.name + ' module was registered');
},
enable: function () {
//console.log(this.name + ' module was activated');
},
disable: function () {
//console.log(this.name + ' module was stopped');
}
});
})(Backbone.Notifier, jQuery); | gregorypratt/jsdelivr | files/backbone.notifier/0.2.5/js/modules/3d.js | JavaScript | mit | 2,876 |
// Copyright 2013 the V8 project authors. All rights reserved.
// Copyright (C) 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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.
description(
"This tests that passing an inconsistent compareFn to sort() doesn't cause a crash."
);
for (var attempt = 0; attempt < 100; ++attempt) {
var arr = [];
for (var i = 0; i < 64; ++i)
arr[i] = i;
arr.sort(function() { return 0.5 - Math.random(); });
}
// Sorting objects that change each time sort() looks at them is the same as using a random compareFn.
function RandomObject() {
this.toString = function() { return (Math.random() * 100).toString(); }
}
for (var attempt = 0; attempt < 100; ++attempt) {
var arr = [];
for (var i = 0; i < 64; ++i)
arr[i] = new RandomObject;
arr.sort();
}
| zero-ui/miniblink49 | v8_7_5/test/webkit/sort-randomly.js | JavaScript | gpl-3.0 | 2,084 |
'use strict';
!function($) {
/**
* DropdownMenu module.
* @module foundation.dropdown-menu
* @requires foundation.util.keyboard
* @requires foundation.util.box
* @requires foundation.util.nest
*/
class DropdownMenu {
/**
* Creates a new instance of DropdownMenu.
* @class
* @fires DropdownMenu#init
* @param {jQuery} element - jQuery object to make into a dropdown menu.
* @param {Object} options - Overrides to the default plugin settings.
*/
constructor(element, options) {
this.$element = element;
this.options = $.extend({}, DropdownMenu.defaults, this.$element.data(), options);
Foundation.Nest.Feather(this.$element, 'dropdown');
this._init();
Foundation.registerPlugin(this, 'DropdownMenu');
Foundation.Keyboard.register('DropdownMenu', {
'ENTER': 'open',
'SPACE': 'open',
'ARROW_RIGHT': 'next',
'ARROW_UP': 'up',
'ARROW_DOWN': 'down',
'ARROW_LEFT': 'previous',
'ESCAPE': 'close'
});
}
/**
* Initializes the plugin, and calls _prepareMenu
* @private
* @function
*/
_init() {
var subs = this.$element.find('li.is-dropdown-submenu-parent');
this.$element.children('.is-dropdown-submenu-parent').children('.is-dropdown-submenu').addClass('first-sub');
this.$menuItems = this.$element.find('[role="menuitem"]');
this.$tabs = this.$element.children('[role="menuitem"]');
this.$tabs.find('ul.is-dropdown-submenu').addClass(this.options.verticalClass);
if (this.$element.hasClass(this.options.rightClass) || this.options.alignment === 'right' || Foundation.rtl() || this.$element.parents('.top-bar-right').is('*')) {
this.options.alignment = 'right';
subs.addClass('opens-left');
} else {
subs.addClass('opens-right');
}
this.changed = false;
this._events();
};
/**
* Adds event listeners to elements within the menu
* @private
* @function
*/
_events() {
var _this = this,
hasTouch = 'ontouchstart' in window || (typeof window.ontouchstart !== 'undefined'),
parClass = 'is-dropdown-submenu-parent';
// used for onClick and in the keyboard handlers
var handleClickFn = function(e) {
var $elem = $(e.target).parentsUntil('ul', `.${parClass}`),
hasSub = $elem.hasClass(parClass),
hasClicked = $elem.attr('data-is-click') === 'true',
$sub = $elem.children('.is-dropdown-submenu');
if (hasSub) {
if (hasClicked) {
if (!_this.options.closeOnClick || (!_this.options.clickOpen && !hasTouch) || (_this.options.forceFollow && hasTouch)) { return; }
else {
e.stopImmediatePropagation();
e.preventDefault();
_this._hide($elem);
}
} else {
e.preventDefault();
e.stopImmediatePropagation();
_this._show($elem.children('.is-dropdown-submenu'));
$elem.add($elem.parentsUntil(_this.$element, `.${parClass}`)).attr('data-is-click', true);
}
} else { return; }
};
if (this.options.clickOpen || hasTouch) {
this.$menuItems.on('click.zf.dropdownmenu touchstart.zf.dropdownmenu', handleClickFn);
}
if (!this.options.disableHover) {
this.$menuItems.on('mouseenter.zf.dropdownmenu', function(e) {
var $elem = $(this),
hasSub = $elem.hasClass(parClass);
if (hasSub) {
clearTimeout(_this.delay);
_this.delay = setTimeout(function() {
_this._show($elem.children('.is-dropdown-submenu'));
}, _this.options.hoverDelay);
}
}).on('mouseleave.zf.dropdownmenu', function(e) {
var $elem = $(this),
hasSub = $elem.hasClass(parClass);
if (hasSub && _this.options.autoclose) {
if ($elem.attr('data-is-click') === 'true' && _this.options.clickOpen) { return false; }
clearTimeout(_this.delay);
_this.delay = setTimeout(function() {
_this._hide($elem);
}, _this.options.closingTime);
}
});
}
this.$menuItems.on('keydown.zf.dropdownmenu', function(e) {
var $element = $(e.target).parentsUntil('ul', '[role="menuitem"]'),
isTab = _this.$tabs.index($element) > -1,
$elements = isTab ? _this.$tabs : $element.siblings('li').add($element),
$prevElement,
$nextElement;
$elements.each(function(i) {
if ($(this).is($element)) {
$prevElement = $elements.eq(i-1);
$nextElement = $elements.eq(i+1);
return;
}
});
var nextSibling = function() {
if (!$element.is(':last-child')) {
$nextElement.children('a:first').focus();
e.preventDefault();
}
}, prevSibling = function() {
$prevElement.children('a:first').focus();
e.preventDefault();
}, openSub = function() {
var $sub = $element.children('ul.is-dropdown-submenu');
if ($sub.length) {
_this._show($sub);
$element.find('li > a:first').focus();
e.preventDefault();
} else { return; }
}, closeSub = function() {
//if ($element.is(':first-child')) {
var close = $element.parent('ul').parent('li');
close.children('a:first').focus();
_this._hide(close);
e.preventDefault();
//}
};
var functions = {
open: openSub,
close: function() {
_this._hide(_this.$element);
_this.$menuItems.find('a:first').focus(); // focus to first element
e.preventDefault();
},
handled: function() {
e.stopImmediatePropagation();
}
};
if (isTab) {
if (_this.$element.hasClass(_this.options.verticalClass)) { // vertical menu
if (_this.options.alignment === 'left') { // left aligned
$.extend(functions, {
down: nextSibling,
up: prevSibling,
next: openSub,
previous: closeSub
});
} else { // right aligned
$.extend(functions, {
down: nextSibling,
up: prevSibling,
next: closeSub,
previous: openSub
});
}
} else { // horizontal menu
$.extend(functions, {
next: nextSibling,
previous: prevSibling,
down: openSub,
up: closeSub
});
}
} else { // not tabs -> one sub
if (_this.options.alignment === 'left') { // left aligned
$.extend(functions, {
next: openSub,
previous: closeSub,
down: nextSibling,
up: prevSibling
});
} else { // right aligned
$.extend(functions, {
next: closeSub,
previous: openSub,
down: nextSibling,
up: prevSibling
});
}
}
Foundation.Keyboard.handleKey(e, 'DropdownMenu', functions);
});
}
/**
* Adds an event handler to the body to close any dropdowns on a click.
* @function
* @private
*/
_addBodyHandler() {
var $body = $(document.body),
_this = this;
$body.off('mouseup.zf.dropdownmenu touchend.zf.dropdownmenu')
.on('mouseup.zf.dropdownmenu touchend.zf.dropdownmenu', function(e) {
var $link = _this.$element.find(e.target);
if ($link.length) { return; }
_this._hide();
$body.off('mouseup.zf.dropdownmenu touchend.zf.dropdownmenu');
});
}
/**
* Opens a dropdown pane, and checks for collisions first.
* @param {jQuery} $sub - ul element that is a submenu to show
* @function
* @private
* @fires DropdownMenu#show
*/
_show($sub) {
var idx = this.$tabs.index(this.$tabs.filter(function(i, el) {
return $(el).find($sub).length > 0;
}));
var $sibs = $sub.parent('li.is-dropdown-submenu-parent').siblings('li.is-dropdown-submenu-parent');
this._hide($sibs, idx);
$sub.css('visibility', 'hidden').addClass('js-dropdown-active').attr({'aria-hidden': false})
.parent('li.is-dropdown-submenu-parent').addClass('is-active')
.attr({'aria-expanded': true});
var clear = Foundation.Box.ImNotTouchingYou($sub, null, true);
if (!clear) {
var oldClass = this.options.alignment === 'left' ? '-right' : '-left',
$parentLi = $sub.parent('.is-dropdown-submenu-parent');
$parentLi.removeClass(`opens${oldClass}`).addClass(`opens-${this.options.alignment}`);
clear = Foundation.Box.ImNotTouchingYou($sub, null, true);
if (!clear) {
$parentLi.removeClass(`opens-${this.options.alignment}`).addClass('opens-inner');
}
this.changed = true;
}
$sub.css('visibility', '');
if (this.options.closeOnClick) { this._addBodyHandler(); }
/**
* Fires when the new dropdown pane is visible.
* @event DropdownMenu#show
*/
this.$element.trigger('show.zf.dropdownmenu', [$sub]);
}
/**
* Hides a single, currently open dropdown pane, if passed a parameter, otherwise, hides everything.
* @function
* @param {jQuery} $elem - element with a submenu to hide
* @param {Number} idx - index of the $tabs collection to hide
* @private
*/
_hide($elem, idx) {
var $toClose;
if ($elem && $elem.length) {
$toClose = $elem;
} else if (idx !== undefined) {
$toClose = this.$tabs.not(function(i, el) {
return i === idx;
});
}
else {
$toClose = this.$element;
}
var somethingToClose = $toClose.hasClass('is-active') || $toClose.find('.is-active').length > 0;
if (somethingToClose) {
$toClose.find('li.is-active').add($toClose).attr({
'aria-expanded': false,
'data-is-click': false
}).removeClass('is-active');
$toClose.find('ul.js-dropdown-active').attr({
'aria-hidden': true
}).removeClass('js-dropdown-active');
if (this.changed || $toClose.find('opens-inner').length) {
var oldClass = this.options.alignment === 'left' ? 'right' : 'left';
$toClose.find('li.is-dropdown-submenu-parent').add($toClose)
.removeClass(`opens-inner opens-${this.options.alignment}`)
.addClass(`opens-${oldClass}`);
this.changed = false;
}
/**
* Fires when the open menus are closed.
* @event DropdownMenu#hide
*/
this.$element.trigger('hide.zf.dropdownmenu', [$toClose]);
}
}
/**
* Destroys the plugin.
* @function
*/
destroy() {
this.$menuItems.off('.zf.dropdownmenu').removeAttr('data-is-click')
.removeClass('is-right-arrow is-left-arrow is-down-arrow opens-right opens-left opens-inner');
$(document.body).off('.zf.dropdownmenu');
Foundation.Nest.Burn(this.$element, 'dropdown');
Foundation.unregisterPlugin(this);
}
}
/**
* Default settings for plugin
*/
DropdownMenu.defaults = {
/**
* Disallows hover events from opening submenus
* @option
* @example false
*/
disableHover: false,
/**
* Allow a submenu to automatically close on a mouseleave event, if not clicked open.
* @option
* @example true
*/
autoclose: true,
/**
* Amount of time to delay opening a submenu on hover event.
* @option
* @example 50
*/
hoverDelay: 50,
/**
* Allow a submenu to open/remain open on parent click event. Allows cursor to move away from menu.
* @option
* @example true
*/
clickOpen: false,
/**
* Amount of time to delay closing a submenu on a mouseleave event.
* @option
* @example 500
*/
closingTime: 500,
/**
* Position of the menu relative to what direction the submenus should open. Handled by JS.
* @option
* @example 'left'
*/
alignment: 'left',
/**
* Allow clicks on the body to close any open submenus.
* @option
* @example true
*/
closeOnClick: true,
/**
* Class applied to vertical oriented menus, Foundation default is `vertical`. Update this if using your own class.
* @option
* @example 'vertical'
*/
verticalClass: 'vertical',
/**
* Class applied to right-side oriented menus, Foundation default is `align-right`. Update this if using your own class.
* @option
* @example 'align-right'
*/
rightClass: 'align-right',
/**
* Boolean to force overide the clicking of links to perform default action, on second touch event for mobile.
* @option
* @example false
*/
forceFollow: true
};
// Window exports
Foundation.plugin(DropdownMenu, 'DropdownMenu');
}(jQuery);
| mj-wilson/Rachel-Marc-Wedding | wp-content/themes/RachelMarcWedding/assets/components/foundation-sites/js/foundation.dropdownMenu.js | JavaScript | gpl-2.0 | 12,679 |
// - operator on string type
var STRING: string;
var STRING1: string[] = ["", "abc"];
function foo(): string { return "abc"; }
class A {
public a: string;
static foo() { return ""; }
}
module M {
export var n: string;
}
var objA = new A();
// string type var
var ResultIsNumber1 = -STRING;
var ResultIsNumber2 = -STRING1;
// string type literal
var ResultIsNumber3 = -"";
var ResultIsNumber4 = -{ x: "", y: "" };
var ResultIsNumber5 = -{ x: "", y: (s: string) => { return s; } };
// string type expressions
var ResultIsNumber6 = -objA.a;
var ResultIsNumber7 = -M.n;
var ResultIsNumber8 = -STRING1[0];
var ResultIsNumber9 = -foo();
var ResultIsNumber10 = -A.foo();
var ResultIsNumber11 = -(STRING + STRING);
var ResultIsNumber12 = -STRING.charAt(0);
// miss assignment operators
-"";
-STRING;
-STRING1;
-foo();
-objA.a,M.n; | enginekit/TypeScript | tests/cases/conformance/expressions/unaryOperators/negateOperator/negateOperatorWithStringType.ts | TypeScript | apache-2.0 | 841 |
/*
YUI 3.16.0 (build 76f0e08)
Copyright 2014 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add('event-touch', function (Y, NAME) {
/**
Adds touch event facade normalization properties (touches, changedTouches, targetTouches etc.) to the DOM event facade. Adds
touch events to the DOM events whitelist.
@example
YUI().use('event-touch', function (Y) {
Y.one('#myDiv').on('touchstart', function(e) {
...
});
});
@module event
@submodule event-touch
*/
var SCALE = "scale",
ROTATION = "rotation",
IDENTIFIER = "identifier",
win = Y.config.win,
GESTURE_MAP = {};
/**
* Adds touch event facade normalization properties to the DOM event facade
*
* @method _touch
* @for DOMEventFacade
* @private
* @param ev {Event} the DOM event
* @param currentTarget {HTMLElement} the element the listener was attached to
* @param wrapper {CustomEvent} the custom event wrapper for this DOM event
*/
Y.DOMEventFacade.prototype._touch = function(e, currentTarget, wrapper) {
var i,l, etCached, et,touchCache;
if (e.touches) {
/**
* Array of individual touch events for touch points that are still in
* contact with the touch surface.
*
* @property touches
* @type {DOMEventFacade[]}
*/
this.touches = [];
touchCache = {};
for (i = 0, l = e.touches.length; i < l; ++i) {
et = e.touches[i];
touchCache[Y.stamp(et)] = this.touches[i] = new Y.DOMEventFacade(et, currentTarget, wrapper);
}
}
if (e.targetTouches) {
/**
* Array of individual touch events still in contact with the touch
* surface and whose `touchstart` event occurred inside the same taregt
* element as the current target element.
*
* @property targetTouches
* @type {DOMEventFacade[]}
*/
this.targetTouches = [];
for (i = 0, l = e.targetTouches.length; i < l; ++i) {
et = e.targetTouches[i];
etCached = touchCache && touchCache[Y.stamp(et, true)];
this.targetTouches[i] = etCached || new Y.DOMEventFacade(et, currentTarget, wrapper);
}
}
if (e.changedTouches) {
/**
An array of event-specific touch events.
For `touchstart`, the touch points that became active with the current
event.
For `touchmove`, the touch points that have changed since the last
event.
For `touchend`, the touch points that have been removed from the touch
surface.
@property changedTouches
@type {DOMEventFacade[]}
**/
this.changedTouches = [];
for (i = 0, l = e.changedTouches.length; i < l; ++i) {
et = e.changedTouches[i];
etCached = touchCache && touchCache[Y.stamp(et, true)];
this.changedTouches[i] = etCached || new Y.DOMEventFacade(et, currentTarget, wrapper);
}
}
if (SCALE in e) {
this[SCALE] = e[SCALE];
}
if (ROTATION in e) {
this[ROTATION] = e[ROTATION];
}
if (IDENTIFIER in e) {
this[IDENTIFIER] = e[IDENTIFIER];
}
};
//Adding MSPointer events to whitelisted DOM Events. MSPointer event payloads
//have the same properties as mouse events.
if (Y.Node.DOM_EVENTS) {
Y.mix(Y.Node.DOM_EVENTS, {
touchstart:1,
touchmove:1,
touchend:1,
touchcancel:1,
gesturestart:1,
gesturechange:1,
gestureend:1,
MSPointerDown:1,
MSPointerUp:1,
MSPointerMove:1,
MSPointerCancel:1,
pointerdown:1,
pointerup:1,
pointermove:1,
pointercancel:1
});
}
//Add properties to Y.EVENT.GESTURE_MAP based on feature detection.
if ((win && ("ontouchstart" in win)) && !(Y.UA.chrome && Y.UA.chrome < 6)) {
GESTURE_MAP.start = ["touchstart", "mousedown"];
GESTURE_MAP.end = ["touchend", "mouseup"];
GESTURE_MAP.move = ["touchmove", "mousemove"];
GESTURE_MAP.cancel = ["touchcancel", "mousecancel"];
}
else if (win && win.PointerEvent) {
GESTURE_MAP.start = "pointerdown";
GESTURE_MAP.end = "pointerup";
GESTURE_MAP.move = "pointermove";
GESTURE_MAP.cancel = "pointercancel";
}
else if (win && ("msPointerEnabled" in win.navigator)) {
GESTURE_MAP.start = "MSPointerDown";
GESTURE_MAP.end = "MSPointerUp";
GESTURE_MAP.move = "MSPointerMove";
GESTURE_MAP.cancel = "MSPointerCancel";
}
else {
GESTURE_MAP.start = "mousedown";
GESTURE_MAP.end = "mouseup";
GESTURE_MAP.move = "mousemove";
GESTURE_MAP.cancel = "mousecancel";
}
/**
* A object literal with keys "start", "end", and "move". The value for each key is a
* string representing the event for that environment. For touch environments, the respective
* values are "touchstart", "touchend" and "touchmove". Mouse and MSPointer environments are also
* supported via feature detection.
*
* @property _GESTURE_MAP
* @type Object
* @static
*/
Y.Event._GESTURE_MAP = GESTURE_MAP;
}, '3.16.0', {"requires": ["node-base"]});
| dandv/jsdelivr | files/yui/3.16.0/event-touch/event-touch.js | JavaScript | mit | 5,190 |
/*
* Copyright (C) 2007 The Android Open Source Project
*
* 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.android.dx.dex.code;
import com.android.dx.rop.code.RegisterSpecList;
import com.android.dx.rop.code.SourcePosition;
/**
* Pseudo-instruction which is used to track an address within a code
* array. Instances are used for such things as branch targets and
* exception handler ranges. Its code size is zero, and so instances
* do not in general directly wind up in any output (either
* human-oriented or binary file).
*/
public final class CodeAddress extends ZeroSizeInsn {
/** If this address should bind closely to the following real instruction */
private final boolean bindsClosely;
/**
* Constructs an instance. The output address of this instance is initially
* unknown ({@code -1}).
*
* @param position {@code non-null;} source position
*/
public CodeAddress(SourcePosition position) {
this(position, false);
}
/**
* Constructs an instance. The output address of this instance is initially
* unknown ({@code -1}).
*
* @param position {@code non-null;} source position
* @param bindsClosely if the address should bind closely to the following
* real instruction.
*/
public CodeAddress(SourcePosition position, boolean bindsClosely) {
super(position);
this.bindsClosely = bindsClosely;
}
/** {@inheritDoc} */
@Override
public final DalvInsn withRegisters(RegisterSpecList registers) {
return new CodeAddress(getPosition());
}
/** {@inheritDoc} */
@Override
protected String argString() {
return null;
}
/** {@inheritDoc} */
@Override
protected String listingString0(boolean noteIndices) {
return "code-address";
}
/**
* Gets whether this address binds closely to the following "real"
* (non-zero-length) instruction.
*
* When a prefix is added to an instruction (for example, to move a value
* from a high register to a low register), this determines whether this
* {@code CodeAddress} will point to the prefix, or to the instruction
* itself.
*
* If bindsClosely is true, the address will point to the instruction
* itself, otherwise it will point to the prefix (if any)
*
* @return true if this address binds closely to the next real instruction
*/
public boolean getBindsClosely() {
return bindsClosely;
}
}
| raviagarwal7/buck | third-party/java/dx/src/com/android/dx/dex/code/CodeAddress.java | Java | apache-2.0 | 3,056 |
class Radare2 < Formula
desc "Reverse engineering framework"
homepage "http://radare.org"
stable do
url "http://radare.org/get/radare2-0.9.8.tar.xz"
sha256 "8e72caaebdac10300fd7ec86a5d06b1cbecfc6914e5fea4007c6e06e667bfa5a"
resource "bindings" do
url "http://radare.org/get/radare2-bindings-0.9.8.tar.xz"
sha256 "28326effb7d1eda9f6df2ef08954774c16617046a33046501bd0332324519f39"
end
end
bottle do
sha256 "98747f4956734786ab429187042f2371b6c0b13d29c79af71c465a800e45e60b" => :yosemite
sha256 "f1896970ded3c078f49c17b674565992a9a9eb291318d1d0ec4003cb17d97433" => :mavericks
sha256 "939af3b23d3918860ff985156f2a42ad2bff56cd48b8545e9c73bb8cf96a0038" => :mountain_lion
end
head do
url "https://github.com/radare/radare2.git"
resource "bindings" do
url "https://github.com/radare/radare2-bindings.git"
end
end
depends_on "pkg-config" => :build
depends_on "valabind" => :build
depends_on "swig" => :build
depends_on "gobject-introspection" => :build
depends_on "libewf"
depends_on "libmagic"
depends_on "gmp"
depends_on "lua51" # It seems to latch onto Lua51 rather than Lua. Enquire this upstream.
depends_on "openssl"
def install
# Build Radare2 before bindings, otherwise compile = nope.
system "./configure", "--prefix=#{prefix}", "--with-openssl"
system "make"
system "make", "install"
resource("bindings").stage do
ENV.append_path "PKG_CONFIG_PATH", "#{lib}/pkgconfig"
system "./configure", "--prefix=#{prefix}"
system "make"
system "make", "install", "DESTDIR=#{prefix}"
end
end
end
| woodruffw/homebrew-test | Library/Formula/radare2.rb | Ruby | bsd-2-clause | 1,635 |
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: google/cloud/ml/v1beta1/model_service.proto
package ml
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import _ "google.golang.org/genproto/googleapis/api/annotations"
import _ "google.golang.org/genproto/googleapis/api/serviceconfig"
import google_longrunning "google.golang.org/genproto/googleapis/longrunning"
import google_protobuf2 "github.com/golang/protobuf/ptypes/timestamp"
import (
context "golang.org/x/net/context"
grpc "google.golang.org/grpc"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// Represents a machine learning solution.
//
// A model can have multiple versions, each of which is a deployed, trained
// model ready to receive prediction requests. The model itself is just a
// container.
type Model struct {
// Required. The name specified for the model when it was created.
//
// The model name must be unique within the project it is created in.
Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
// Optional. The description specified for the model when it was created.
Description string `protobuf:"bytes,2,opt,name=description" json:"description,omitempty"`
// Output only. The default version of the model. This version will be used to
// handle prediction requests that do not specify a version.
//
// You can change the default version by calling
// [projects.methods.versions.setDefault](/ml/reference/rest/v1beta1/projects.models.versions/setDefault).
DefaultVersion *Version `protobuf:"bytes,3,opt,name=default_version,json=defaultVersion" json:"default_version,omitempty"`
// Optional. The list of regions where the model is going to be deployed.
// Currently only one region per model is supported.
// Defaults to 'us-central1' if nothing is set.
Regions []string `protobuf:"bytes,4,rep,name=regions" json:"regions,omitempty"`
// Optional. If true, enables StackDriver Logging for online prediction.
// Default is false.
OnlinePredictionLogging bool `protobuf:"varint,5,opt,name=online_prediction_logging,json=onlinePredictionLogging" json:"online_prediction_logging,omitempty"`
}
func (m *Model) Reset() { *m = Model{} }
func (m *Model) String() string { return proto.CompactTextString(m) }
func (*Model) ProtoMessage() {}
func (*Model) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{0} }
func (m *Model) GetName() string {
if m != nil {
return m.Name
}
return ""
}
func (m *Model) GetDescription() string {
if m != nil {
return m.Description
}
return ""
}
func (m *Model) GetDefaultVersion() *Version {
if m != nil {
return m.DefaultVersion
}
return nil
}
func (m *Model) GetRegions() []string {
if m != nil {
return m.Regions
}
return nil
}
func (m *Model) GetOnlinePredictionLogging() bool {
if m != nil {
return m.OnlinePredictionLogging
}
return false
}
// Represents a version of the model.
//
// Each version is a trained model deployed in the cloud, ready to handle
// prediction requests. A model can have multiple versions. You can get
// information about all of the versions of a given model by calling
// [projects.models.versions.list](/ml/reference/rest/v1beta1/projects.models.versions/list).
type Version struct {
// Required.The name specified for the version when it was created.
//
// The version name must be unique within the model it is created in.
Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
// Optional. The description specified for the version when it was created.
Description string `protobuf:"bytes,2,opt,name=description" json:"description,omitempty"`
// Output only. If true, this version will be used to handle prediction
// requests that do not specify a version.
//
// You can change the default version by calling
// [projects.methods.versions.setDefault](/ml/reference/rest/v1beta1/projects.models.versions/setDefault).
IsDefault bool `protobuf:"varint,3,opt,name=is_default,json=isDefault" json:"is_default,omitempty"`
// Required. The Google Cloud Storage location of the trained model used to
// create the version. See the
// [overview of model deployment](/ml/docs/concepts/deployment-overview) for
// more informaiton.
//
// When passing Version to
// [projects.models.versions.create](/ml/reference/rest/v1beta1/projects.models.versions/create)
// the model service uses the specified location as the source of the model.
// Once deployed, the model version is hosted by the prediction service, so
// this location is useful only as a historical record.
DeploymentUri string `protobuf:"bytes,4,opt,name=deployment_uri,json=deploymentUri" json:"deployment_uri,omitempty"`
// Output only. The time the version was created.
CreateTime *google_protobuf2.Timestamp `protobuf:"bytes,5,opt,name=create_time,json=createTime" json:"create_time,omitempty"`
// Output only. The time the version was last used for prediction.
LastUseTime *google_protobuf2.Timestamp `protobuf:"bytes,6,opt,name=last_use_time,json=lastUseTime" json:"last_use_time,omitempty"`
// Optional. The Google Cloud ML runtime version to use for this deployment.
// If not set, Google Cloud ML will choose a version.
RuntimeVersion string `protobuf:"bytes,8,opt,name=runtime_version,json=runtimeVersion" json:"runtime_version,omitempty"`
// Optional. Manually select the number of nodes to use for serving the
// model. If unset (i.e., by default), the number of nodes used to serve
// the model automatically scales with traffic. However, care should be
// taken to ramp up traffic according to the model's ability to scale. If
// your model needs to handle bursts of traffic beyond it's ability to
// scale, it is recommended you set this field appropriately.
ManualScaling *ManualScaling `protobuf:"bytes,9,opt,name=manual_scaling,json=manualScaling" json:"manual_scaling,omitempty"`
}
func (m *Version) Reset() { *m = Version{} }
func (m *Version) String() string { return proto.CompactTextString(m) }
func (*Version) ProtoMessage() {}
func (*Version) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{1} }
func (m *Version) GetName() string {
if m != nil {
return m.Name
}
return ""
}
func (m *Version) GetDescription() string {
if m != nil {
return m.Description
}
return ""
}
func (m *Version) GetIsDefault() bool {
if m != nil {
return m.IsDefault
}
return false
}
func (m *Version) GetDeploymentUri() string {
if m != nil {
return m.DeploymentUri
}
return ""
}
func (m *Version) GetCreateTime() *google_protobuf2.Timestamp {
if m != nil {
return m.CreateTime
}
return nil
}
func (m *Version) GetLastUseTime() *google_protobuf2.Timestamp {
if m != nil {
return m.LastUseTime
}
return nil
}
func (m *Version) GetRuntimeVersion() string {
if m != nil {
return m.RuntimeVersion
}
return ""
}
func (m *Version) GetManualScaling() *ManualScaling {
if m != nil {
return m.ManualScaling
}
return nil
}
// Options for manually scaling a model.
type ManualScaling struct {
// The number of nodes to allocate for this model. These nodes are always up,
// starting from the time the model is deployed, so the cost of operating
// this model will be proportional to nodes * number of hours since
// deployment.
Nodes int32 `protobuf:"varint,1,opt,name=nodes" json:"nodes,omitempty"`
}
func (m *ManualScaling) Reset() { *m = ManualScaling{} }
func (m *ManualScaling) String() string { return proto.CompactTextString(m) }
func (*ManualScaling) ProtoMessage() {}
func (*ManualScaling) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{2} }
func (m *ManualScaling) GetNodes() int32 {
if m != nil {
return m.Nodes
}
return 0
}
// Request message for the CreateModel method.
type CreateModelRequest struct {
// Required. The project name.
//
// Authorization: requires `Editor` role on the specified project.
Parent string `protobuf:"bytes,1,opt,name=parent" json:"parent,omitempty"`
// Required. The model to create.
Model *Model `protobuf:"bytes,2,opt,name=model" json:"model,omitempty"`
}
func (m *CreateModelRequest) Reset() { *m = CreateModelRequest{} }
func (m *CreateModelRequest) String() string { return proto.CompactTextString(m) }
func (*CreateModelRequest) ProtoMessage() {}
func (*CreateModelRequest) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{3} }
func (m *CreateModelRequest) GetParent() string {
if m != nil {
return m.Parent
}
return ""
}
func (m *CreateModelRequest) GetModel() *Model {
if m != nil {
return m.Model
}
return nil
}
// Request message for the ListModels method.
type ListModelsRequest struct {
// Required. The name of the project whose models are to be listed.
//
// Authorization: requires `Viewer` role on the specified project.
Parent string `protobuf:"bytes,1,opt,name=parent" json:"parent,omitempty"`
// Optional. A page token to request the next page of results.
//
// You get the token from the `next_page_token` field of the response from
// the previous call.
PageToken string `protobuf:"bytes,4,opt,name=page_token,json=pageToken" json:"page_token,omitempty"`
// Optional. The number of models to retrieve per "page" of results. If there
// are more remaining results than this number, the response message will
// contain a valid value in the `next_page_token` field.
//
// The default value is 20, and the maximum page size is 100.
PageSize int32 `protobuf:"varint,5,opt,name=page_size,json=pageSize" json:"page_size,omitempty"`
}
func (m *ListModelsRequest) Reset() { *m = ListModelsRequest{} }
func (m *ListModelsRequest) String() string { return proto.CompactTextString(m) }
func (*ListModelsRequest) ProtoMessage() {}
func (*ListModelsRequest) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{4} }
func (m *ListModelsRequest) GetParent() string {
if m != nil {
return m.Parent
}
return ""
}
func (m *ListModelsRequest) GetPageToken() string {
if m != nil {
return m.PageToken
}
return ""
}
func (m *ListModelsRequest) GetPageSize() int32 {
if m != nil {
return m.PageSize
}
return 0
}
// Response message for the ListModels method.
type ListModelsResponse struct {
// The list of models.
Models []*Model `protobuf:"bytes,1,rep,name=models" json:"models,omitempty"`
// Optional. Pass this token as the `page_token` field of the request for a
// subsequent call.
NextPageToken string `protobuf:"bytes,2,opt,name=next_page_token,json=nextPageToken" json:"next_page_token,omitempty"`
}
func (m *ListModelsResponse) Reset() { *m = ListModelsResponse{} }
func (m *ListModelsResponse) String() string { return proto.CompactTextString(m) }
func (*ListModelsResponse) ProtoMessage() {}
func (*ListModelsResponse) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{5} }
func (m *ListModelsResponse) GetModels() []*Model {
if m != nil {
return m.Models
}
return nil
}
func (m *ListModelsResponse) GetNextPageToken() string {
if m != nil {
return m.NextPageToken
}
return ""
}
// Request message for the GetModel method.
type GetModelRequest struct {
// Required. The name of the model.
//
// Authorization: requires `Viewer` role on the parent project.
Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
}
func (m *GetModelRequest) Reset() { *m = GetModelRequest{} }
func (m *GetModelRequest) String() string { return proto.CompactTextString(m) }
func (*GetModelRequest) ProtoMessage() {}
func (*GetModelRequest) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{6} }
func (m *GetModelRequest) GetName() string {
if m != nil {
return m.Name
}
return ""
}
// Request message for the DeleteModel method.
type DeleteModelRequest struct {
// Required. The name of the model.
//
// Authorization: requires `Editor` role on the parent project.
Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
}
func (m *DeleteModelRequest) Reset() { *m = DeleteModelRequest{} }
func (m *DeleteModelRequest) String() string { return proto.CompactTextString(m) }
func (*DeleteModelRequest) ProtoMessage() {}
func (*DeleteModelRequest) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{7} }
func (m *DeleteModelRequest) GetName() string {
if m != nil {
return m.Name
}
return ""
}
// Uploads the provided trained model version to Cloud Machine Learning.
type CreateVersionRequest struct {
// Required. The name of the model.
//
// Authorization: requires `Editor` role on the parent project.
Parent string `protobuf:"bytes,1,opt,name=parent" json:"parent,omitempty"`
// Required. The version details.
Version *Version `protobuf:"bytes,2,opt,name=version" json:"version,omitempty"`
}
func (m *CreateVersionRequest) Reset() { *m = CreateVersionRequest{} }
func (m *CreateVersionRequest) String() string { return proto.CompactTextString(m) }
func (*CreateVersionRequest) ProtoMessage() {}
func (*CreateVersionRequest) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{8} }
func (m *CreateVersionRequest) GetParent() string {
if m != nil {
return m.Parent
}
return ""
}
func (m *CreateVersionRequest) GetVersion() *Version {
if m != nil {
return m.Version
}
return nil
}
// Request message for the ListVersions method.
type ListVersionsRequest struct {
// Required. The name of the model for which to list the version.
//
// Authorization: requires `Viewer` role on the parent project.
Parent string `protobuf:"bytes,1,opt,name=parent" json:"parent,omitempty"`
// Optional. A page token to request the next page of results.
//
// You get the token from the `next_page_token` field of the response from
// the previous call.
PageToken string `protobuf:"bytes,4,opt,name=page_token,json=pageToken" json:"page_token,omitempty"`
// Optional. The number of versions to retrieve per "page" of results. If
// there are more remaining results than this number, the response message
// will contain a valid value in the `next_page_token` field.
//
// The default value is 20, and the maximum page size is 100.
PageSize int32 `protobuf:"varint,5,opt,name=page_size,json=pageSize" json:"page_size,omitempty"`
}
func (m *ListVersionsRequest) Reset() { *m = ListVersionsRequest{} }
func (m *ListVersionsRequest) String() string { return proto.CompactTextString(m) }
func (*ListVersionsRequest) ProtoMessage() {}
func (*ListVersionsRequest) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{9} }
func (m *ListVersionsRequest) GetParent() string {
if m != nil {
return m.Parent
}
return ""
}
func (m *ListVersionsRequest) GetPageToken() string {
if m != nil {
return m.PageToken
}
return ""
}
func (m *ListVersionsRequest) GetPageSize() int32 {
if m != nil {
return m.PageSize
}
return 0
}
// Response message for the ListVersions method.
type ListVersionsResponse struct {
// The list of versions.
Versions []*Version `protobuf:"bytes,1,rep,name=versions" json:"versions,omitempty"`
// Optional. Pass this token as the `page_token` field of the request for a
// subsequent call.
NextPageToken string `protobuf:"bytes,2,opt,name=next_page_token,json=nextPageToken" json:"next_page_token,omitempty"`
}
func (m *ListVersionsResponse) Reset() { *m = ListVersionsResponse{} }
func (m *ListVersionsResponse) String() string { return proto.CompactTextString(m) }
func (*ListVersionsResponse) ProtoMessage() {}
func (*ListVersionsResponse) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{10} }
func (m *ListVersionsResponse) GetVersions() []*Version {
if m != nil {
return m.Versions
}
return nil
}
func (m *ListVersionsResponse) GetNextPageToken() string {
if m != nil {
return m.NextPageToken
}
return ""
}
// Request message for the GetVersion method.
type GetVersionRequest struct {
// Required. The name of the version.
//
// Authorization: requires `Viewer` role on the parent project.
Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
}
func (m *GetVersionRequest) Reset() { *m = GetVersionRequest{} }
func (m *GetVersionRequest) String() string { return proto.CompactTextString(m) }
func (*GetVersionRequest) ProtoMessage() {}
func (*GetVersionRequest) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{11} }
func (m *GetVersionRequest) GetName() string {
if m != nil {
return m.Name
}
return ""
}
// Request message for the DeleteVerionRequest method.
type DeleteVersionRequest struct {
// Required. The name of the version. You can get the names of all the
// versions of a model by calling
// [projects.models.versions.list](/ml/reference/rest/v1beta1/projects.models.versions/list).
//
// Authorization: requires `Editor` role on the parent project.
Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
}
func (m *DeleteVersionRequest) Reset() { *m = DeleteVersionRequest{} }
func (m *DeleteVersionRequest) String() string { return proto.CompactTextString(m) }
func (*DeleteVersionRequest) ProtoMessage() {}
func (*DeleteVersionRequest) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{12} }
func (m *DeleteVersionRequest) GetName() string {
if m != nil {
return m.Name
}
return ""
}
// Request message for the SetDefaultVersion request.
type SetDefaultVersionRequest struct {
// Required. The name of the version to make the default for the model. You
// can get the names of all the versions of a model by calling
// [projects.models.versions.list](/ml/reference/rest/v1beta1/projects.models.versions/list).
//
// Authorization: requires `Editor` role on the parent project.
Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
}
func (m *SetDefaultVersionRequest) Reset() { *m = SetDefaultVersionRequest{} }
func (m *SetDefaultVersionRequest) String() string { return proto.CompactTextString(m) }
func (*SetDefaultVersionRequest) ProtoMessage() {}
func (*SetDefaultVersionRequest) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{13} }
func (m *SetDefaultVersionRequest) GetName() string {
if m != nil {
return m.Name
}
return ""
}
func init() {
proto.RegisterType((*Model)(nil), "google.cloud.ml.v1beta1.Model")
proto.RegisterType((*Version)(nil), "google.cloud.ml.v1beta1.Version")
proto.RegisterType((*ManualScaling)(nil), "google.cloud.ml.v1beta1.ManualScaling")
proto.RegisterType((*CreateModelRequest)(nil), "google.cloud.ml.v1beta1.CreateModelRequest")
proto.RegisterType((*ListModelsRequest)(nil), "google.cloud.ml.v1beta1.ListModelsRequest")
proto.RegisterType((*ListModelsResponse)(nil), "google.cloud.ml.v1beta1.ListModelsResponse")
proto.RegisterType((*GetModelRequest)(nil), "google.cloud.ml.v1beta1.GetModelRequest")
proto.RegisterType((*DeleteModelRequest)(nil), "google.cloud.ml.v1beta1.DeleteModelRequest")
proto.RegisterType((*CreateVersionRequest)(nil), "google.cloud.ml.v1beta1.CreateVersionRequest")
proto.RegisterType((*ListVersionsRequest)(nil), "google.cloud.ml.v1beta1.ListVersionsRequest")
proto.RegisterType((*ListVersionsResponse)(nil), "google.cloud.ml.v1beta1.ListVersionsResponse")
proto.RegisterType((*GetVersionRequest)(nil), "google.cloud.ml.v1beta1.GetVersionRequest")
proto.RegisterType((*DeleteVersionRequest)(nil), "google.cloud.ml.v1beta1.DeleteVersionRequest")
proto.RegisterType((*SetDefaultVersionRequest)(nil), "google.cloud.ml.v1beta1.SetDefaultVersionRequest")
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion4
// Client API for ModelService service
type ModelServiceClient interface {
// Creates a model which will later contain one or more versions.
//
// You must add at least one version before you can request predictions from
// the model. Add versions by calling
// [projects.models.versions.create](/ml/reference/rest/v1beta1/projects.models.versions/create).
CreateModel(ctx context.Context, in *CreateModelRequest, opts ...grpc.CallOption) (*Model, error)
// Lists the models in a project.
//
// Each project can contain multiple models, and each model can have multiple
// versions.
ListModels(ctx context.Context, in *ListModelsRequest, opts ...grpc.CallOption) (*ListModelsResponse, error)
// Gets information about a model, including its name, the description (if
// set), and the default version (if at least one version of the model has
// been deployed).
GetModel(ctx context.Context, in *GetModelRequest, opts ...grpc.CallOption) (*Model, error)
// Deletes a model.
//
// You can only delete a model if there are no versions in it. You can delete
// versions by calling
// [projects.models.versions.delete](/ml/reference/rest/v1beta1/projects.models.versions/delete).
DeleteModel(ctx context.Context, in *DeleteModelRequest, opts ...grpc.CallOption) (*google_longrunning.Operation, error)
// Creates a new version of a model from a trained TensorFlow model.
//
// If the version created in the cloud by this call is the first deployed
// version of the specified model, it will be made the default version of the
// model. When you add a version to a model that already has one or more
// versions, the default version does not automatically change. If you want a
// new version to be the default, you must call
// [projects.models.versions.setDefault](/ml/reference/rest/v1beta1/projects.models.versions/setDefault).
CreateVersion(ctx context.Context, in *CreateVersionRequest, opts ...grpc.CallOption) (*google_longrunning.Operation, error)
// Gets basic information about all the versions of a model.
//
// If you expect that a model has a lot of versions, or if you need to handle
// only a limited number of results at a time, you can request that the list
// be retrieved in batches (called pages):
ListVersions(ctx context.Context, in *ListVersionsRequest, opts ...grpc.CallOption) (*ListVersionsResponse, error)
// Gets information about a model version.
//
// Models can have multiple versions. You can call
// [projects.models.versions.list](/ml/reference/rest/v1beta1/projects.models.versions/list)
// to get the same information that this method returns for all of the
// versions of a model.
GetVersion(ctx context.Context, in *GetVersionRequest, opts ...grpc.CallOption) (*Version, error)
// Deletes a model version.
//
// Each model can have multiple versions deployed and in use at any given
// time. Use this method to remove a single version.
//
// Note: You cannot delete the version that is set as the default version
// of the model unless it is the only remaining version.
DeleteVersion(ctx context.Context, in *DeleteVersionRequest, opts ...grpc.CallOption) (*google_longrunning.Operation, error)
// Designates a version to be the default for the model.
//
// The default version is used for prediction requests made against the model
// that don't specify a version.
//
// The first version to be created for a model is automatically set as the
// default. You must make any subsequent changes to the default version
// setting manually using this method.
SetDefaultVersion(ctx context.Context, in *SetDefaultVersionRequest, opts ...grpc.CallOption) (*Version, error)
}
type modelServiceClient struct {
cc *grpc.ClientConn
}
func NewModelServiceClient(cc *grpc.ClientConn) ModelServiceClient {
return &modelServiceClient{cc}
}
func (c *modelServiceClient) CreateModel(ctx context.Context, in *CreateModelRequest, opts ...grpc.CallOption) (*Model, error) {
out := new(Model)
err := grpc.Invoke(ctx, "/google.cloud.ml.v1beta1.ModelService/CreateModel", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *modelServiceClient) ListModels(ctx context.Context, in *ListModelsRequest, opts ...grpc.CallOption) (*ListModelsResponse, error) {
out := new(ListModelsResponse)
err := grpc.Invoke(ctx, "/google.cloud.ml.v1beta1.ModelService/ListModels", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *modelServiceClient) GetModel(ctx context.Context, in *GetModelRequest, opts ...grpc.CallOption) (*Model, error) {
out := new(Model)
err := grpc.Invoke(ctx, "/google.cloud.ml.v1beta1.ModelService/GetModel", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *modelServiceClient) DeleteModel(ctx context.Context, in *DeleteModelRequest, opts ...grpc.CallOption) (*google_longrunning.Operation, error) {
out := new(google_longrunning.Operation)
err := grpc.Invoke(ctx, "/google.cloud.ml.v1beta1.ModelService/DeleteModel", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *modelServiceClient) CreateVersion(ctx context.Context, in *CreateVersionRequest, opts ...grpc.CallOption) (*google_longrunning.Operation, error) {
out := new(google_longrunning.Operation)
err := grpc.Invoke(ctx, "/google.cloud.ml.v1beta1.ModelService/CreateVersion", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *modelServiceClient) ListVersions(ctx context.Context, in *ListVersionsRequest, opts ...grpc.CallOption) (*ListVersionsResponse, error) {
out := new(ListVersionsResponse)
err := grpc.Invoke(ctx, "/google.cloud.ml.v1beta1.ModelService/ListVersions", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *modelServiceClient) GetVersion(ctx context.Context, in *GetVersionRequest, opts ...grpc.CallOption) (*Version, error) {
out := new(Version)
err := grpc.Invoke(ctx, "/google.cloud.ml.v1beta1.ModelService/GetVersion", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *modelServiceClient) DeleteVersion(ctx context.Context, in *DeleteVersionRequest, opts ...grpc.CallOption) (*google_longrunning.Operation, error) {
out := new(google_longrunning.Operation)
err := grpc.Invoke(ctx, "/google.cloud.ml.v1beta1.ModelService/DeleteVersion", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *modelServiceClient) SetDefaultVersion(ctx context.Context, in *SetDefaultVersionRequest, opts ...grpc.CallOption) (*Version, error) {
out := new(Version)
err := grpc.Invoke(ctx, "/google.cloud.ml.v1beta1.ModelService/SetDefaultVersion", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// Server API for ModelService service
type ModelServiceServer interface {
// Creates a model which will later contain one or more versions.
//
// You must add at least one version before you can request predictions from
// the model. Add versions by calling
// [projects.models.versions.create](/ml/reference/rest/v1beta1/projects.models.versions/create).
CreateModel(context.Context, *CreateModelRequest) (*Model, error)
// Lists the models in a project.
//
// Each project can contain multiple models, and each model can have multiple
// versions.
ListModels(context.Context, *ListModelsRequest) (*ListModelsResponse, error)
// Gets information about a model, including its name, the description (if
// set), and the default version (if at least one version of the model has
// been deployed).
GetModel(context.Context, *GetModelRequest) (*Model, error)
// Deletes a model.
//
// You can only delete a model if there are no versions in it. You can delete
// versions by calling
// [projects.models.versions.delete](/ml/reference/rest/v1beta1/projects.models.versions/delete).
DeleteModel(context.Context, *DeleteModelRequest) (*google_longrunning.Operation, error)
// Creates a new version of a model from a trained TensorFlow model.
//
// If the version created in the cloud by this call is the first deployed
// version of the specified model, it will be made the default version of the
// model. When you add a version to a model that already has one or more
// versions, the default version does not automatically change. If you want a
// new version to be the default, you must call
// [projects.models.versions.setDefault](/ml/reference/rest/v1beta1/projects.models.versions/setDefault).
CreateVersion(context.Context, *CreateVersionRequest) (*google_longrunning.Operation, error)
// Gets basic information about all the versions of a model.
//
// If you expect that a model has a lot of versions, or if you need to handle
// only a limited number of results at a time, you can request that the list
// be retrieved in batches (called pages):
ListVersions(context.Context, *ListVersionsRequest) (*ListVersionsResponse, error)
// Gets information about a model version.
//
// Models can have multiple versions. You can call
// [projects.models.versions.list](/ml/reference/rest/v1beta1/projects.models.versions/list)
// to get the same information that this method returns for all of the
// versions of a model.
GetVersion(context.Context, *GetVersionRequest) (*Version, error)
// Deletes a model version.
//
// Each model can have multiple versions deployed and in use at any given
// time. Use this method to remove a single version.
//
// Note: You cannot delete the version that is set as the default version
// of the model unless it is the only remaining version.
DeleteVersion(context.Context, *DeleteVersionRequest) (*google_longrunning.Operation, error)
// Designates a version to be the default for the model.
//
// The default version is used for prediction requests made against the model
// that don't specify a version.
//
// The first version to be created for a model is automatically set as the
// default. You must make any subsequent changes to the default version
// setting manually using this method.
SetDefaultVersion(context.Context, *SetDefaultVersionRequest) (*Version, error)
}
func RegisterModelServiceServer(s *grpc.Server, srv ModelServiceServer) {
s.RegisterService(&_ModelService_serviceDesc, srv)
}
func _ModelService_CreateModel_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(CreateModelRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ModelServiceServer).CreateModel(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/google.cloud.ml.v1beta1.ModelService/CreateModel",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ModelServiceServer).CreateModel(ctx, req.(*CreateModelRequest))
}
return interceptor(ctx, in, info, handler)
}
func _ModelService_ListModels_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ListModelsRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ModelServiceServer).ListModels(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/google.cloud.ml.v1beta1.ModelService/ListModels",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ModelServiceServer).ListModels(ctx, req.(*ListModelsRequest))
}
return interceptor(ctx, in, info, handler)
}
func _ModelService_GetModel_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetModelRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ModelServiceServer).GetModel(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/google.cloud.ml.v1beta1.ModelService/GetModel",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ModelServiceServer).GetModel(ctx, req.(*GetModelRequest))
}
return interceptor(ctx, in, info, handler)
}
func _ModelService_DeleteModel_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(DeleteModelRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ModelServiceServer).DeleteModel(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/google.cloud.ml.v1beta1.ModelService/DeleteModel",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ModelServiceServer).DeleteModel(ctx, req.(*DeleteModelRequest))
}
return interceptor(ctx, in, info, handler)
}
func _ModelService_CreateVersion_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(CreateVersionRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ModelServiceServer).CreateVersion(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/google.cloud.ml.v1beta1.ModelService/CreateVersion",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ModelServiceServer).CreateVersion(ctx, req.(*CreateVersionRequest))
}
return interceptor(ctx, in, info, handler)
}
func _ModelService_ListVersions_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ListVersionsRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ModelServiceServer).ListVersions(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/google.cloud.ml.v1beta1.ModelService/ListVersions",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ModelServiceServer).ListVersions(ctx, req.(*ListVersionsRequest))
}
return interceptor(ctx, in, info, handler)
}
func _ModelService_GetVersion_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetVersionRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ModelServiceServer).GetVersion(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/google.cloud.ml.v1beta1.ModelService/GetVersion",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ModelServiceServer).GetVersion(ctx, req.(*GetVersionRequest))
}
return interceptor(ctx, in, info, handler)
}
func _ModelService_DeleteVersion_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(DeleteVersionRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ModelServiceServer).DeleteVersion(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/google.cloud.ml.v1beta1.ModelService/DeleteVersion",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ModelServiceServer).DeleteVersion(ctx, req.(*DeleteVersionRequest))
}
return interceptor(ctx, in, info, handler)
}
func _ModelService_SetDefaultVersion_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(SetDefaultVersionRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ModelServiceServer).SetDefaultVersion(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/google.cloud.ml.v1beta1.ModelService/SetDefaultVersion",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ModelServiceServer).SetDefaultVersion(ctx, req.(*SetDefaultVersionRequest))
}
return interceptor(ctx, in, info, handler)
}
var _ModelService_serviceDesc = grpc.ServiceDesc{
ServiceName: "google.cloud.ml.v1beta1.ModelService",
HandlerType: (*ModelServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "CreateModel",
Handler: _ModelService_CreateModel_Handler,
},
{
MethodName: "ListModels",
Handler: _ModelService_ListModels_Handler,
},
{
MethodName: "GetModel",
Handler: _ModelService_GetModel_Handler,
},
{
MethodName: "DeleteModel",
Handler: _ModelService_DeleteModel_Handler,
},
{
MethodName: "CreateVersion",
Handler: _ModelService_CreateVersion_Handler,
},
{
MethodName: "ListVersions",
Handler: _ModelService_ListVersions_Handler,
},
{
MethodName: "GetVersion",
Handler: _ModelService_GetVersion_Handler,
},
{
MethodName: "DeleteVersion",
Handler: _ModelService_DeleteVersion_Handler,
},
{
MethodName: "SetDefaultVersion",
Handler: _ModelService_SetDefaultVersion_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "google/cloud/ml/v1beta1/model_service.proto",
}
func init() { proto.RegisterFile("google/cloud/ml/v1beta1/model_service.proto", fileDescriptor1) }
var fileDescriptor1 = []byte{
// 1013 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x57, 0xcf, 0x6f, 0x1b, 0x45,
0x14, 0xd6, 0x26, 0x71, 0x62, 0x3f, 0xd7, 0x89, 0x32, 0x04, 0x6a, 0x0c, 0xa1, 0xd6, 0x56, 0x69,
0x2d, 0xa7, 0xdd, 0x25, 0x06, 0x55, 0x8a, 0x0b, 0x45, 0x2a, 0x91, 0x2a, 0xa4, 0x46, 0x44, 0x9b,
0x96, 0x03, 0x97, 0xd5, 0xc6, 0x9e, 0x2e, 0x53, 0x76, 0x67, 0xb6, 0x3b, 0xb3, 0x11, 0x14, 0x7a,
0x80, 0x03, 0x47, 0x0e, 0x20, 0xae, 0x5c, 0xb8, 0xf3, 0xcf, 0x70, 0xe7, 0x84, 0xf8, 0x23, 0x38,
0xa1, 0xf9, 0xb1, 0xce, 0x3a, 0xfe, 0xb1, 0x1b, 0x24, 0x6e, 0x9e, 0x37, 0xdf, 0x9b, 0xf7, 0xcd,
0xfb, 0xde, 0x7b, 0x3b, 0x86, 0xfd, 0x90, 0xb1, 0x30, 0xc2, 0xee, 0x28, 0x62, 0xd9, 0xd8, 0x8d,
0x23, 0xf7, 0xfc, 0xe0, 0x0c, 0x8b, 0xe0, 0xc0, 0x8d, 0xd9, 0x18, 0x47, 0x3e, 0xc7, 0xe9, 0x39,
0x19, 0x61, 0x27, 0x49, 0x99, 0x60, 0xe8, 0xba, 0x06, 0x3b, 0x0a, 0xec, 0xc4, 0x91, 0x63, 0xc0,
0x9d, 0xb7, 0xcd, 0x29, 0x41, 0x42, 0xdc, 0x80, 0x52, 0x26, 0x02, 0x41, 0x18, 0xe5, 0xda, 0xad,
0xf3, 0x7a, 0x71, 0x37, 0x13, 0x5f, 0x18, 0xf3, 0x4d, 0x63, 0x8e, 0x18, 0x0d, 0xd3, 0x8c, 0x52,
0x42, 0x43, 0x97, 0x25, 0x38, 0x9d, 0xf2, 0xbd, 0x61, 0x40, 0x6a, 0x75, 0x96, 0x3d, 0x73, 0x05,
0x89, 0x31, 0x17, 0x41, 0x9c, 0x68, 0x80, 0xfd, 0xa7, 0x05, 0xb5, 0x63, 0xc9, 0x15, 0x21, 0x58,
0xa3, 0x41, 0x8c, 0xdb, 0x56, 0xd7, 0xea, 0x35, 0x3c, 0xf5, 0x1b, 0x75, 0xa1, 0x39, 0xc6, 0x7c,
0x94, 0x92, 0x44, 0x1e, 0xda, 0x5e, 0x51, 0x5b, 0x45, 0x13, 0xfa, 0x04, 0xb6, 0xc6, 0xf8, 0x59,
0x90, 0x45, 0xc2, 0x3f, 0xc7, 0x29, 0x97, 0xa8, 0xd5, 0xae, 0xd5, 0x6b, 0x0e, 0xba, 0xce, 0x82,
0xdb, 0x3a, 0x9f, 0x69, 0x9c, 0xb7, 0x69, 0x1c, 0xcd, 0x1a, 0xb5, 0x61, 0x23, 0xc5, 0xa1, 0x24,
0xdf, 0x5e, 0xeb, 0xae, 0xf6, 0x1a, 0x5e, 0xbe, 0x44, 0x43, 0x78, 0x93, 0xd1, 0x88, 0x50, 0xec,
0x27, 0x29, 0x1e, 0x93, 0x91, 0x8c, 0xec, 0x47, 0x2c, 0x0c, 0x09, 0x0d, 0xdb, 0xb5, 0xae, 0xd5,
0xab, 0x7b, 0xd7, 0x35, 0xe0, 0x64, 0xb2, 0xff, 0x58, 0x6f, 0xdb, 0xff, 0xac, 0xc0, 0x46, 0x1e,
0xe1, 0xbf, 0x5d, 0x71, 0x17, 0x80, 0x70, 0xdf, 0x90, 0x55, 0xb7, 0xab, 0x7b, 0x0d, 0xc2, 0x8f,
0xb4, 0x01, 0xed, 0xc1, 0xe6, 0x18, 0x27, 0x11, 0xfb, 0x3a, 0xc6, 0x54, 0xf8, 0x59, 0x4a, 0xda,
0x6b, 0xea, 0x8c, 0xd6, 0x85, 0xf5, 0x69, 0x4a, 0xd0, 0x7d, 0x68, 0x8e, 0x52, 0x1c, 0x08, 0xec,
0x4b, 0x09, 0x14, 0xeb, 0xe6, 0xa0, 0x93, 0x27, 0x29, 0xd7, 0xc7, 0x79, 0x92, 0xeb, 0xe3, 0x81,
0x86, 0x4b, 0x03, 0x7a, 0x00, 0xad, 0x28, 0xe0, 0xc2, 0xcf, 0xb8, 0x71, 0x5f, 0x2f, 0x75, 0x6f,
0x4a, 0x87, 0xa7, 0x5c, 0xfb, 0xdf, 0x86, 0xad, 0x34, 0xa3, 0xd2, 0x73, 0xa2, 0x52, 0x5d, 0x91,
0xdc, 0x34, 0xe6, 0x3c, 0x43, 0xc7, 0xb0, 0x19, 0x07, 0x34, 0x0b, 0x22, 0x9f, 0x8f, 0x82, 0x48,
0xa6, 0xb7, 0xa1, 0x22, 0xdd, 0x5a, 0xa8, 0xe6, 0xb1, 0x82, 0x9f, 0x6a, 0xb4, 0xd7, 0x8a, 0x8b,
0x4b, 0x7b, 0x0f, 0x5a, 0x53, 0xfb, 0x68, 0x07, 0x6a, 0x94, 0x8d, 0x31, 0x57, 0x12, 0xd4, 0x3c,
0xbd, 0xb0, 0xcf, 0x00, 0x7d, 0xac, 0x2e, 0xab, 0x2a, 0xd1, 0xc3, 0x2f, 0x32, 0xcc, 0x05, 0x7a,
0x03, 0xd6, 0x93, 0x20, 0xc5, 0x54, 0x18, 0xbd, 0xcc, 0x0a, 0xbd, 0x0f, 0x35, 0xd5, 0x5d, 0x4a,
0xab, 0xe6, 0xe0, 0x9d, 0xc5, 0xd4, 0xd4, 0x69, 0x1a, 0x6c, 0x87, 0xb0, 0xfd, 0x98, 0x70, 0xa1,
0x6c, 0xbc, 0x2c, 0xc4, 0x2e, 0x40, 0x12, 0x84, 0xd8, 0x17, 0xec, 0x4b, 0x4c, 0x8d, 0x9e, 0x0d,
0x69, 0x79, 0x22, 0x0d, 0xe8, 0x2d, 0x50, 0x0b, 0x9f, 0x93, 0x97, 0x5a, 0xc9, 0x9a, 0x57, 0x97,
0x86, 0x53, 0xf2, 0x12, 0xdb, 0x02, 0x50, 0x31, 0x10, 0x4f, 0x18, 0xe5, 0x18, 0xdd, 0x83, 0x75,
0xc5, 0x43, 0xde, 0x7c, 0xb5, 0x02, 0x6b, 0x83, 0x46, 0xb7, 0x60, 0x8b, 0xe2, 0xaf, 0x84, 0x5f,
0xa0, 0xa3, 0x4b, 0xb4, 0x25, 0xcd, 0x27, 0x39, 0x25, 0x7b, 0x0f, 0xb6, 0x1e, 0x61, 0x31, 0x95,
0xbf, 0x39, 0xd5, 0x6e, 0xf7, 0x00, 0x1d, 0xe1, 0x08, 0x5f, 0xca, 0xf4, 0x3c, 0xe4, 0x73, 0xd8,
0xd1, 0x9a, 0xe4, 0xed, 0x5a, 0x92, 0xb2, 0x21, 0x6c, 0xe4, 0xa5, 0xb5, 0x52, 0x71, 0x00, 0xe4,
0x0e, 0x36, 0x81, 0xd7, 0x64, 0xca, 0x8c, 0xfd, 0x7f, 0x55, 0xe7, 0x5b, 0xd8, 0x99, 0x0e, 0x65,
0xf4, 0xf9, 0x00, 0xea, 0x86, 0x4d, 0xae, 0x50, 0x39, 0xff, 0x89, 0x47, 0x65, 0x95, 0x6e, 0xc3,
0xf6, 0x23, 0x2c, 0x2e, 0x65, 0x74, 0x5e, 0xf6, 0xfb, 0xb0, 0xa3, 0x75, 0xaa, 0x80, 0x75, 0xa0,
0x7d, 0x8a, 0xc5, 0xd1, 0xd4, 0x30, 0x5d, 0x82, 0x1f, 0xfc, 0x0d, 0x70, 0x4d, 0xc9, 0x7f, 0xaa,
0xbf, 0x4e, 0xe8, 0x47, 0x0b, 0x9a, 0x85, 0xfe, 0x43, 0xfb, 0x0b, 0x6f, 0x3e, 0xdb, 0xa5, 0x9d,
0x92, 0x42, 0xb6, 0x07, 0xdf, 0xff, 0xf1, 0xd7, 0xcf, 0x2b, 0x77, 0xec, 0x9b, 0x93, 0x4f, 0xe3,
0x37, 0x5a, 0xc6, 0x0f, 0x93, 0x94, 0x3d, 0xc7, 0x23, 0xc1, 0xdd, 0xfe, 0x2b, 0xfd, 0xb9, 0xe4,
0x43, 0xdd, 0xab, 0xe8, 0x27, 0x0b, 0xe0, 0xa2, 0x87, 0x50, 0x7f, 0x61, 0x88, 0x99, 0x8e, 0xee,
0xec, 0x57, 0xc2, 0x6a, 0xd1, 0xed, 0x7d, 0xc5, 0x6d, 0x0f, 0x55, 0xe1, 0x86, 0xbe, 0xb3, 0xa0,
0x9e, 0xb7, 0x18, 0xea, 0x2d, 0x0c, 0x73, 0xa9, 0x0b, 0x4b, 0xf3, 0x33, 0x87, 0x83, 0x54, 0xa9,
0xc0, 0xc0, 0x10, 0x70, 0xfb, 0xaf, 0xd0, 0x0f, 0x16, 0x34, 0x0b, 0xfd, 0xbb, 0x44, 0xa9, 0xd9,
0x2e, 0xef, 0xec, 0xe6, 0xe0, 0xc2, 0x8b, 0xc1, 0xf9, 0x34, 0x7f, 0x31, 0xe4, 0x44, 0xfa, 0x95,
0x88, 0xfc, 0x6a, 0x41, 0x6b, 0x6a, 0x3c, 0xa0, 0xbb, 0x25, 0x45, 0x33, 0x5d, 0x98, 0x65, 0x64,
0x3e, 0x52, 0x64, 0x0e, 0x6d, 0x67, 0x89, 0x32, 0x17, 0x74, 0xdc, 0xbc, 0x11, 0x87, 0xf9, 0x48,
0x41, 0xbf, 0x59, 0x70, 0xad, 0xd8, 0xe8, 0xe8, 0xce, 0xd2, 0xc2, 0xb8, 0x34, 0x7a, 0x3a, 0x77,
0x2b, 0xa2, 0x4d, 0x21, 0xdd, 0x53, 0x74, 0xdf, 0x45, 0x57, 0xa4, 0xab, 0x0a, 0xfd, 0x62, 0x20,
0x2c, 0x29, 0xf4, 0x99, 0xa9, 0xd1, 0x29, 0x1d, 0x4f, 0xf3, 0x48, 0x2d, 0x12, 0x74, 0xc2, 0x48,
0x6a, 0xfb, 0x8b, 0x05, 0xad, 0xa9, 0xe1, 0xb3, 0x44, 0xdb, 0x79, 0x43, 0xaa, 0x4c, 0x5b, 0xc3,
0xab, 0x7f, 0x55, 0x5e, 0xbf, 0x5b, 0xb0, 0x3d, 0x33, 0xe8, 0xd0, 0xc1, 0x42, 0x6e, 0x8b, 0x86,
0x62, 0x85, 0xd4, 0x1d, 0x29, 0x8a, 0x0f, 0xec, 0xc3, 0xab, 0x51, 0x1c, 0xf2, 0x49, 0xc8, 0xa1,
0xd5, 0x7f, 0xf8, 0x02, 0x6e, 0x8c, 0x58, 0x3c, 0x13, 0x2c, 0x48, 0x48, 0x1e, 0xf0, 0xe1, 0x76,
0x71, 0x10, 0x9f, 0xc8, 0x57, 0xdc, 0x89, 0xf5, 0xf9, 0xa1, 0xf1, 0x08, 0x59, 0x14, 0xd0, 0xd0,
0x61, 0x69, 0xe8, 0x86, 0x98, 0xaa, 0x37, 0x9e, 0xab, 0xb7, 0x82, 0x84, 0xf0, 0x99, 0xff, 0x1c,
0xf7, 0xe3, 0xe8, 0x6c, 0x5d, 0xa1, 0xde, 0xfb, 0x37, 0x00, 0x00, 0xff, 0xff, 0x04, 0x39, 0xff,
0x08, 0x98, 0x0c, 0x00, 0x00,
}
| wjiangjay/origin | vendor/google.golang.org/genproto/googleapis/cloud/ml/v1beta1/model_service.pb.go | GO | apache-2.0 | 44,072 |
/*
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.
*/
package genericclioptions
import (
"github.com/spf13/cobra"
"k8s.io/cli-runtime/pkg/printers"
)
// KubeTemplatePrintFlags composes print flags that provide both a JSONPath and a go-template printer.
// This is necessary if dealing with cases that require support both both printers, since both sets of flags
// require overlapping flags.
type KubeTemplatePrintFlags struct {
GoTemplatePrintFlags *GoTemplatePrintFlags
JSONPathPrintFlags *JSONPathPrintFlags
AllowMissingKeys *bool
TemplateArgument *string
}
func (f *KubeTemplatePrintFlags) AllowedFormats() []string {
if f == nil {
return []string{}
}
return append(f.GoTemplatePrintFlags.AllowedFormats(), f.JSONPathPrintFlags.AllowedFormats()...)
}
func (f *KubeTemplatePrintFlags) ToPrinter(outputFormat string) (printers.ResourcePrinter, error) {
if f == nil {
return nil, NoCompatiblePrinterError{}
}
if p, err := f.JSONPathPrintFlags.ToPrinter(outputFormat); !IsNoCompatiblePrinterError(err) {
return p, err
}
return f.GoTemplatePrintFlags.ToPrinter(outputFormat)
}
// AddFlags receives a *cobra.Command reference and binds
// flags related to template printing to it
func (f *KubeTemplatePrintFlags) AddFlags(c *cobra.Command) {
if f == nil {
return
}
if f.TemplateArgument != nil {
c.Flags().StringVar(f.TemplateArgument, "template", *f.TemplateArgument, "Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].")
c.MarkFlagFilename("template")
}
if f.AllowMissingKeys != nil {
c.Flags().BoolVar(f.AllowMissingKeys, "allow-missing-template-keys", *f.AllowMissingKeys, "If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats.")
}
}
// NewKubeTemplatePrintFlags returns flags associated with
// --template printing, with default values set.
func NewKubeTemplatePrintFlags() *KubeTemplatePrintFlags {
allowMissingKeysPtr := true
templateArgPtr := ""
return &KubeTemplatePrintFlags{
GoTemplatePrintFlags: &GoTemplatePrintFlags{
TemplateArgument: &templateArgPtr,
AllowMissingKeys: &allowMissingKeysPtr,
},
JSONPathPrintFlags: &JSONPathPrintFlags{
TemplateArgument: &templateArgPtr,
AllowMissingKeys: &allowMissingKeysPtr,
},
TemplateArgument: &templateArgPtr,
AllowMissingKeys: &allowMissingKeysPtr,
}
}
| pweil-/origin | vendor/k8s.io/kubernetes/staging/src/k8s.io/cli-runtime/pkg/genericclioptions/kube_template_flags.go | GO | apache-2.0 | 3,020 |
/*
Package pagination contains utilities and convenience structs that implement common pagination idioms within OpenStack APIs.
*/
package pagination
| kgrygiel/autoscaler | vertical-pod-autoscaler/vendor/github.com/gophercloud/gophercloud/pagination/pkg.go | GO | apache-2.0 | 150 |
<?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 license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Dom
* @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$
*/
/** Zend_Exception */
require_once 'Zend/Exception.php';
/**
* Zend_Dom Exceptions
*
* @category Zend
* @package Zend_Dom
* @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_Dom_Exception extends Zend_Exception
{
}
| angusty/symfony-study | vendor/Zend/Dom/Exception.php | PHP | mit | 1,050 |
# test equality for classes/instances to other types
class A:
pass
class B:
pass
class C(A):
pass
print(A == None)
print(None == A)
print(A == A)
print(A() == A)
print(A() == A())
print(A == B)
print(A() == B)
print(A() == B())
print(A == C)
print(A() == C)
print(A() == C())
| mhoffma/micropython | tests/basics/equal_class.py | Python | mit | 295 |
/**
* 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.camel.component.jackson;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;
public class JacksonIncludeDefaultTest extends CamelTestSupport {
@Test
public void testMmarshalPojo() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:marshal");
mock.expectedMessageCount(1);
mock.message(0).body(String.class).isEqualTo("{\"name\":\"Camel\",\"country\":null}");
TestOtherPojo pojo = new TestOtherPojo();
pojo.setName("Camel");
template.sendBody("direct:marshal", pojo);
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
JacksonDataFormat format = new JacksonDataFormat();
from("direct:marshal").marshal(format).to("mock:marshal");
}
};
}
}
| YMartsynkevych/camel | components/camel-jackson/src/test/java/org/apache/camel/component/jackson/JacksonIncludeDefaultTest.java | Java | apache-2.0 | 1,906 |
// 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.VisualStudio.LanguageServices.Implementation.RQName.SimpleTree;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.RQName.Nodes
{
internal class RQPointerType : RQArrayOrPointerType
{
public RQPointerType(RQType elementType) : base(elementType) { }
public override SimpleTreeNode ToSimpleTree()
{
return new SimpleGroupNode(RQNameStrings.Pointer, ElementType.ToSimpleTree());
}
}
}
| JohnHamby/roslyn | src/VisualStudio/Core/Def/Implementation/RQName/Nodes/RQPointerType.cs | C# | apache-2.0 | 632 |
#include <com.badlogic.gdx.physics.box2d.joints.PrismaticJoint.h>
//@line:28
#include <Box2D/Box2D.h>
JNIEXPORT void JNICALL Java_com_badlogic_gdx_physics_box2d_joints_PrismaticJoint_jniGetLocalAnchorA(JNIEnv* env, jobject object, jlong addr, jfloatArray obj_anchor) {
float* anchor = (float*)env->GetPrimitiveArrayCritical(obj_anchor, 0);
//@line:47
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
anchor[0] = joint->GetLocalAnchorA().x;
anchor[1] = joint->GetLocalAnchorA().y;
env->ReleasePrimitiveArrayCritical(obj_anchor, anchor, 0);
}
JNIEXPORT void JNICALL Java_com_badlogic_gdx_physics_box2d_joints_PrismaticJoint_jniGetLocalAnchorB(JNIEnv* env, jobject object, jlong addr, jfloatArray obj_anchor) {
float* anchor = (float*)env->GetPrimitiveArrayCritical(obj_anchor, 0);
//@line:59
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
anchor[0] = joint->GetLocalAnchorB().x;
anchor[1] = joint->GetLocalAnchorB().y;
env->ReleasePrimitiveArrayCritical(obj_anchor, anchor, 0);
}
JNIEXPORT void JNICALL Java_com_badlogic_gdx_physics_box2d_joints_PrismaticJoint_jniGetLocalAxisA(JNIEnv* env, jobject object, jlong addr, jfloatArray obj_anchor) {
float* anchor = (float*)env->GetPrimitiveArrayCritical(obj_anchor, 0);
//@line:71
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
anchor[0] = joint->GetLocalAxisA().x;
anchor[1] = joint->GetLocalAxisA().y;
env->ReleasePrimitiveArrayCritical(obj_anchor, anchor, 0);
}
JNIEXPORT jfloat JNICALL Java_com_badlogic_gdx_physics_box2d_joints_PrismaticJoint_jniGetJointTranslation(JNIEnv* env, jobject object, jlong addr) {
//@line:82
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
return joint->GetJointTranslation();
}
JNIEXPORT jfloat JNICALL Java_com_badlogic_gdx_physics_box2d_joints_PrismaticJoint_jniGetJointSpeed(JNIEnv* env, jobject object, jlong addr) {
//@line:92
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
return joint->GetJointSpeed();
}
JNIEXPORT jboolean JNICALL Java_com_badlogic_gdx_physics_box2d_joints_PrismaticJoint_jniIsLimitEnabled(JNIEnv* env, jobject object, jlong addr) {
//@line:102
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
return joint->IsLimitEnabled();
}
JNIEXPORT void JNICALL Java_com_badlogic_gdx_physics_box2d_joints_PrismaticJoint_jniEnableLimit(JNIEnv* env, jobject object, jlong addr, jboolean flag) {
//@line:112
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
joint->EnableLimit(flag);
}
JNIEXPORT jfloat JNICALL Java_com_badlogic_gdx_physics_box2d_joints_PrismaticJoint_jniGetLowerLimit(JNIEnv* env, jobject object, jlong addr) {
//@line:122
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
return joint->GetLowerLimit();
}
JNIEXPORT jfloat JNICALL Java_com_badlogic_gdx_physics_box2d_joints_PrismaticJoint_jniGetUpperLimit(JNIEnv* env, jobject object, jlong addr) {
//@line:132
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
return joint->GetUpperLimit();
}
JNIEXPORT void JNICALL Java_com_badlogic_gdx_physics_box2d_joints_PrismaticJoint_jniSetLimits(JNIEnv* env, jobject object, jlong addr, jfloat lower, jfloat upper) {
//@line:142
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
joint->SetLimits(lower, upper );
}
JNIEXPORT jboolean JNICALL Java_com_badlogic_gdx_physics_box2d_joints_PrismaticJoint_jniIsMotorEnabled(JNIEnv* env, jobject object, jlong addr) {
//@line:152
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
return joint->IsMotorEnabled();
}
JNIEXPORT void JNICALL Java_com_badlogic_gdx_physics_box2d_joints_PrismaticJoint_jniEnableMotor(JNIEnv* env, jobject object, jlong addr, jboolean flag) {
//@line:162
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
joint->EnableMotor(flag);
}
JNIEXPORT void JNICALL Java_com_badlogic_gdx_physics_box2d_joints_PrismaticJoint_jniSetMotorSpeed(JNIEnv* env, jobject object, jlong addr, jfloat speed) {
//@line:172
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
joint->SetMotorSpeed(speed);
}
JNIEXPORT jfloat JNICALL Java_com_badlogic_gdx_physics_box2d_joints_PrismaticJoint_jniGetMotorSpeed(JNIEnv* env, jobject object, jlong addr) {
//@line:182
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
return joint->GetMotorSpeed();
}
JNIEXPORT void JNICALL Java_com_badlogic_gdx_physics_box2d_joints_PrismaticJoint_jniSetMaxMotorForce(JNIEnv* env, jobject object, jlong addr, jfloat force) {
//@line:192
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
joint->SetMaxMotorForce(force);
}
JNIEXPORT jfloat JNICALL Java_com_badlogic_gdx_physics_box2d_joints_PrismaticJoint_jniGetMotorForce(JNIEnv* env, jobject object, jlong addr, jfloat invDt) {
//@line:202
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
return joint->GetMotorForce(invDt);
}
JNIEXPORT jfloat JNICALL Java_com_badlogic_gdx_physics_box2d_joints_PrismaticJoint_jniGetMaxMotorForce(JNIEnv* env, jobject object, jlong addr) {
//@line:212
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
return joint->GetMaxMotorForce();
}
JNIEXPORT jfloat JNICALL Java_com_badlogic_gdx_physics_box2d_joints_PrismaticJoint_jniGetReferenceAngle(JNIEnv* env, jobject object, jlong addr) {
//@line:222
b2PrismaticJoint* joint = (b2PrismaticJoint*)addr;
return joint->GetReferenceAngle();
}
| GreenLightning/libgdx | extensions/gdx-box2d/gdx-box2d/jni/com.badlogic.gdx.physics.box2d.joints.PrismaticJoint.cpp | C++ | apache-2.0 | 5,331 |
// Bug: We weren't doing the normal replacement of array with pointer
// for deduction in the context of a call because of the initializer list.
// { dg-do compile { target c++11 } }
#include <initializer_list>
struct string
{
string (const char *);
};
template <class T>
struct vector
{
template <class U>
vector (std::initializer_list<U>);
};
vector<string> v = { "a", "b", "c" };
| selmentdev/selment-toolchain | source/gcc-latest/gcc/testsuite/g++.dg/cpp0x/initlist14.C | C++ | gpl-3.0 | 393 |
/*
* DOM event listener abstraction layer
* @module event
* @submodule event-base
*/
(function() {
// Unlike most of the library, this code has to be executed as soon as it is
// introduced into the page -- and it should only be executed one time
// regardless of the number of instances that use it.
var stateChangeListener,
GLOBAL_ENV = YUI.Env,
config = YUI.config,
doc = config.doc,
docElement = doc.documentElement,
doScrollCap = docElement.doScroll,
add = YUI.Env.add,
remove = YUI.Env.remove,
targetEvent = (doScrollCap) ? 'onreadystatechange' : 'DOMContentLoaded',
pollInterval = config.pollInterval || 40,
_ready = function(e) {
GLOBAL_ENV._ready();
};
if (!GLOBAL_ENV._ready) {
GLOBAL_ENV._ready = function() {
if (!GLOBAL_ENV.DOMReady) {
GLOBAL_ENV.DOMReady = true;
remove(doc, targetEvent, _ready); // remove DOMContentLoaded listener
}
};
/*! DOMReady: based on work by: Dean Edwards/John Resig/Matthias Miller/Diego Perini */
// Internet Explorer: use the doScroll() method on the root element. This isolates what
// appears to be a safe moment to manipulate the DOM prior to when the document's readyState
// suggests it is safe to do so.
if (doScrollCap) {
if (self !== self.top) {
stateChangeListener = function() {
if (doc.readyState == 'complete') {
remove(doc, targetEvent, stateChangeListener); // remove onreadystatechange listener
_ready();
}
};
add(doc, targetEvent, stateChangeListener); // add onreadystatechange listener
} else {
GLOBAL_ENV._dri = setInterval(function() {
try {
docElement.doScroll('left');
clearInterval(GLOBAL_ENV._dri);
GLOBAL_ENV._dri = null;
_ready();
} catch (domNotReady) { }
}, pollInterval);
}
} else { // FireFox, Opera, Safari 3+ provide an event for this moment.
add(doc, targetEvent, _ready); // add DOMContentLoaded listener
}
}
})();
YUI.add('event-base', function(Y) {
(function() {
/*
* DOM event listener abstraction layer
* @module event
* @submodule event-base
*/
var GLOBAL_ENV = YUI.Env,
yready = function() {
Y.fire('domready');
};
/**
* The domready event fires at the moment the browser's DOM is
* usable. In most cases, this is before images are fully
* downloaded, allowing you to provide a more responsive user
* interface.
*
* In YUI 3, domready subscribers will be notified immediately if
* that moment has already passed when the subscription is created.
*
* One exception is if the yui.js file is dynamically injected into
* the page. If this is done, you must tell the YUI instance that
* you did this in order for DOMReady (and window load events) to
* fire normally. That configuration option is 'injected' -- set
* it to true if the yui.js script is not included inline.
*
* This method is part of the 'event-ready' module, which is a
* submodule of 'event'.
*
* @event domready
* @for YUI
*/
Y.publish('domready', {
fireOnce: true
});
if (GLOBAL_ENV.DOMReady) {
// console.log('DOMReady already fired', 'info', 'event');
yready();
} else {
// console.log('setting up before listener', 'info', 'event');
// console.log('env: ' + YUI.Env.windowLoaded, 'info', 'event');
Y.before(yready, GLOBAL_ENV, "_ready");
}
})();
(function() {
/**
* Custom event engine, DOM event listener abstraction layer, synthetic DOM
* events.
* @module event
* @submodule event-base
*/
/**
* Wraps a DOM event, properties requiring browser abstraction are
* fixed here. Provids a security layer when required.
* @class DOMEventFacade
* @param ev {Event} the DOM event
* @param currentTarget {HTMLElement} the element the listener was attached to
* @param wrapper {Event.Custom} the custom event wrapper for this DOM event
*/
/*
* @TODO constants? LEFTBUTTON, MIDDLEBUTTON, RIGHTBUTTON, keys
*/
/*
var whitelist = {
altKey : 1,
// "button" : 1, // we supply
// "bubbles" : 1, // needed?
// "cancelable" : 1, // needed?
// "charCode" : 1, // we supply
cancelBubble : 1,
// "currentTarget" : 1, // we supply
ctrlKey : 1,
clientX : 1, // needed?
clientY : 1, // needed?
detail : 1, // not fully implemented
// "fromElement" : 1,
keyCode : 1,
// "height" : 1, // needed?
// "initEvent" : 1, // need the init events?
// "initMouseEvent" : 1,
// "initUIEvent" : 1,
// "layerX" : 1, // needed?
// "layerY" : 1, // needed?
metaKey : 1,
// "modifiers" : 1, // needed?
// "offsetX" : 1, // needed?
// "offsetY" : 1, // needed?
// "preventDefault" : 1, // we supply
// "reason" : 1, // IE proprietary
// "relatedTarget" : 1,
// "returnValue" : 1, // needed?
shiftKey : 1,
// "srcUrn" : 1, // IE proprietary
// "srcElement" : 1,
// "srcFilter" : 1, IE proprietary
// "stopPropagation" : 1, // we supply
// "target" : 1,
// "timeStamp" : 1, // needed?
// "toElement" : 1,
type : 1,
// "view" : 1,
// "which" : 1, // we supply
// "width" : 1, // needed?
x : 1,
y : 1
},
*/
var ua = Y.UA,
/**
* webkit key remapping required for Safari < 3.1
* @property webkitKeymap
* @private
*/
webkitKeymap = {
63232: 38, // up
63233: 40, // down
63234: 37, // left
63235: 39, // right
63276: 33, // page up
63277: 34, // page down
25: 9, // SHIFT-TAB (Safari provides a different key code in
// this case, even though the shiftKey modifier is set)
63272: 46, // delete
63273: 36, // home
63275: 35 // end
},
/**
* Returns a wrapped node. Intended to be used on event targets,
* so it will return the node's parent if the target is a text
* node.
*
* If accessing a property of the node throws an error, this is
* probably the anonymous div wrapper Gecko adds inside text
* nodes. This likely will only occur when attempting to access
* the relatedTarget. In this case, we now return null because
* the anonymous div is completely useless and we do not know
* what the related target was because we can't even get to
* the element's parent node.
*
* @method resolve
* @private
*/
resolve = function(n) {
try {
if (n && 3 == n.nodeType) {
n = n.parentNode;
}
} catch(e) {
return null;
}
return Y.one(n);
};
// provide a single event with browser abstractions resolved
//
// include all properties for both browers?
// include only DOM2 spec properties?
// provide browser-specific facade?
Y.DOMEventFacade = function(ev, currentTarget, wrapper) {
wrapper = wrapper || {};
var e = ev, ot = currentTarget, d = Y.config.doc, b = d.body,
x = e.pageX, y = e.pageY, c, t,
overrides = wrapper.overrides || {};
this.altKey = e.altKey;
this.ctrlKey = e.ctrlKey;
this.metaKey = e.metaKey;
this.shiftKey = e.shiftKey;
this.type = overrides.type || e.type;
this.clientX = e.clientX;
this.clientY = e.clientY;
//////////////////////////////////////////////////////
if (!x && 0 !== x) {
x = e.clientX || 0;
y = e.clientY || 0;
if (ua.ie) {
x += Math.max(d.documentElement.scrollLeft, b.scrollLeft);
y += Math.max(d.documentElement.scrollTop, b.scrollTop);
}
}
this._yuifacade = true;
/**
* The native event
* @property _event
*/
this._event = e;
/**
* The X location of the event on the page (including scroll)
* @property pageX
* @type int
*/
this.pageX = x;
/**
* The Y location of the event on the page (including scroll)
* @property pageY
* @type int
*/
this.pageY = y;
//////////////////////////////////////////////////////
c = e.keyCode || e.charCode || 0;
if (ua.webkit && (c in webkitKeymap)) {
c = webkitKeymap[c];
}
/**
* The keyCode for key events. Uses charCode if keyCode is not available
* @property keyCode
* @type int
*/
this.keyCode = c;
/**
* The charCode for key events. Same as keyCode
* @property charCode
* @type int
*/
this.charCode = c;
//////////////////////////////////////////////////////
/**
* The button that was pushed.
* @property button
* @type int
*/
this.button = e.which || e.button;
/**
* The button that was pushed. Same as button.
* @property which
* @type int
*/
this.which = this.button;
//////////////////////////////////////////////////////
/**
* Node reference for the targeted element
* @propery target
* @type Node
*/
this.target = resolve(e.target || e.srcElement);
/**
* Node reference for the element that the listener was attached to.
* @propery currentTarget
* @type Node
*/
this.currentTarget = resolve(ot);
t = e.relatedTarget;
if (!t) {
if (e.type == "mouseout") {
t = e.toElement;
} else if (e.type == "mouseover") {
t = e.fromElement;
}
}
/**
* Node reference to the relatedTarget
* @propery relatedTarget
* @type Node
*/
this.relatedTarget = resolve(t);
/**
* Number representing the direction and velocity of the movement of the mousewheel.
* Negative is down, the higher the number, the faster. Applies to the mousewheel event.
* @property wheelDelta
* @type int
*/
if (e.type == "mousewheel" || e.type == "DOMMouseScroll") {
this.wheelDelta = (e.detail) ? (e.detail * -1) : Math.round(e.wheelDelta / 80) || ((e.wheelDelta < 0) ? -1 : 1);
}
//////////////////////////////////////////////////////
// methods
/**
* Stops the propagation to the next bubble target
* @method stopPropagation
*/
this.stopPropagation = function() {
if (e.stopPropagation) {
e.stopPropagation();
} else {
e.cancelBubble = true;
}
wrapper.stopped = 1;
};
/**
* Stops the propagation to the next bubble target and
* prevents any additional listeners from being exectued
* on the current target.
* @method stopImmediatePropagation
*/
this.stopImmediatePropagation = function() {
if (e.stopImmediatePropagation) {
e.stopImmediatePropagation();
} else {
this.stopPropagation();
}
wrapper.stopped = 2;
};
/**
* Prevents the event's default behavior
* @method preventDefault
* @param returnValue {string} sets the returnValue of the event to this value
* (rather than the default false value). This can be used to add a customized
* confirmation query to the beforeunload event).
*/
this.preventDefault = function(returnValue) {
if (e.preventDefault) {
e.preventDefault();
}
e.returnValue = returnValue || false;
wrapper.prevented = 1;
};
/**
* Stops the event propagation and prevents the default
* event behavior.
* @method halt
* @param immediate {boolean} if true additional listeners
* on the current target will not be executed
*/
this.halt = function(immediate) {
if (immediate) {
this.stopImmediatePropagation();
} else {
this.stopPropagation();
}
this.preventDefault();
};
};
})();
(function() {
/**
* DOM event listener abstraction layer
* @module event
* @submodule event-base
*/
/**
* The event utility provides functions to add and remove event listeners,
* event cleansing. It also tries to automatically remove listeners it
* registers during the unload event.
*
* @class Event
* @static
*/
Y.Env.evt.dom_wrappers = {};
Y.Env.evt.dom_map = {};
var _eventenv = Y.Env.evt,
add = YUI.Env.add,
remove = YUI.Env.remove,
onLoad = function() {
YUI.Env.windowLoaded = true;
Y.Event._load();
remove(window, "load", onLoad);
},
onUnload = function() {
Y.Event._unload();
remove(window, "unload", onUnload);
},
EVENT_READY = 'domready',
COMPAT_ARG = '~yui|2|compat~',
shouldIterate = function(o) {
try {
return (o && typeof o !== "string" && Y.Lang.isNumber(o.length) && !o.tagName && !o.alert);
} catch(ex) {
Y.log("collection check failure", "warn", "event");
return false;
}
},
Event = function() {
/**
* True after the onload event has fired
* @property _loadComplete
* @type boolean
* @static
* @private
*/
var _loadComplete = false,
/**
* The number of times to poll after window.onload. This number is
* increased if additional late-bound handlers are requested after
* the page load.
* @property _retryCount
* @static
* @private
*/
_retryCount = 0,
/**
* onAvailable listeners
* @property _avail
* @static
* @private
*/
_avail = [],
/**
* Custom event wrappers for DOM events. Key is
* 'event:' + Element uid stamp + event type
* @property _wrappers
* @type Y.Event.Custom
* @static
* @private
*/
_wrappers = _eventenv.dom_wrappers,
_windowLoadKey = null,
/**
* Custom event wrapper map DOM events. Key is
* Element uid stamp. Each item is a hash of custom event
* wrappers as provided in the _wrappers collection. This
* provides the infrastructure for getListeners.
* @property _el_events
* @static
* @private
*/
_el_events = _eventenv.dom_map;
return {
/**
* The number of times we should look for elements that are not
* in the DOM at the time the event is requested after the document
* has been loaded. The default is 1000@amp;40 ms, so it will poll
* for 40 seconds or until all outstanding handlers are bound
* (whichever comes first).
* @property POLL_RETRYS
* @type int
* @static
* @final
*/
POLL_RETRYS: 1000,
/**
* The poll interval in milliseconds
* @property POLL_INTERVAL
* @type int
* @static
* @final
*/
POLL_INTERVAL: 40,
/**
* addListener/removeListener can throw errors in unexpected scenarios.
* These errors are suppressed, the method returns false, and this property
* is set
* @property lastError
* @static
* @type Error
*/
lastError: null,
/**
* poll handle
* @property _interval
* @static
* @private
*/
_interval: null,
/**
* document readystate poll handle
* @property _dri
* @static
* @private
*/
_dri: null,
/**
* True when the document is initially usable
* @property DOMReady
* @type boolean
* @static
*/
DOMReady: false,
/**
* @method startInterval
* @static
* @private
*/
startInterval: function() {
if (!Event._interval) {
Event._interval = setInterval(Y.bind(Event._poll, Event), Event.POLL_INTERVAL);
}
},
/**
* Executes the supplied callback when the item with the supplied
* id is found. This is meant to be used to execute behavior as
* soon as possible as the page loads. If you use this after the
* initial page load it will poll for a fixed time for the element.
* The number of times it will poll and the frequency are
* configurable. By default it will poll for 10 seconds.
*
* <p>The callback is executed with a single parameter:
* the custom object parameter, if provided.</p>
*
* @method onAvailable
*
* @param {string||string[]} id the id of the element, or an array
* of ids to look for.
* @param {function} fn what to execute when the element is found.
* @param {object} p_obj an optional object to be passed back as
* a parameter to fn.
* @param {boolean|object} p_override If set to true, fn will execute
* in the context of p_obj, if set to an object it
* will execute in the context of that object
* @param checkContent {boolean} check child node readiness (onContentReady)
* @static
* @deprecated Use Y.on("available")
*/
// @TODO fix arguments
onAvailable: function(id, fn, p_obj, p_override, checkContent, compat) {
var a = Y.Array(id), i, availHandle;
// Y.log('onAvailable registered for: ' + id);
for (i=0; i<a.length; i=i+1) {
_avail.push({
id: a[i],
fn: fn,
obj: p_obj,
override: p_override,
checkReady: checkContent,
compat: compat
});
}
_retryCount = this.POLL_RETRYS;
// We want the first test to be immediate, but async
setTimeout(Y.bind(Event._poll, Event), 0);
availHandle = new Y.EventHandle({
_delete: function() {
// set by the event system for lazy DOM listeners
if (availHandle.handle) {
availHandle.handle.detach();
return;
}
var i, j;
// otherwise try to remove the onAvailable listener(s)
for (i = 0; i < a.length; i++) {
for (j = 0; j < _avail.length; j++) {
if (a[i] === _avail[j].id) {
_avail.splice(j, 1);
}
}
}
}
});
return availHandle;
},
/**
* Works the same way as onAvailable, but additionally checks the
* state of sibling elements to determine if the content of the
* available element is safe to modify.
*
* <p>The callback is executed with a single parameter:
* the custom object parameter, if provided.</p>
*
* @method onContentReady
*
* @param {string} id the id of the element to look for.
* @param {function} fn what to execute when the element is ready.
* @param {object} p_obj an optional object to be passed back as
* a parameter to fn.
* @param {boolean|object} p_override If set to true, fn will execute
* in the context of p_obj. If an object, fn will
* exectute in the context of that object
*
* @static
* @deprecated Use Y.on("contentready")
*/
// @TODO fix arguments
onContentReady: function(id, fn, p_obj, p_override, compat) {
return this.onAvailable(id, fn, p_obj, p_override, true, compat);
},
/**
* Adds an event listener
*
* @method attach
*
* @param {String} type The type of event to append
* @param {Function} fn The method the event invokes
* @param {String|HTMLElement|Array|NodeList} el An id, an element
* reference, or a collection of ids and/or elements to assign the
* listener to.
* @param {Object} context optional context object
* @param {Boolean|object} args 0..n arguments to pass to the callback
* @return {EventHandle} an object to that can be used to detach the listener
*
* @static
*/
attach: function(type, fn, el, context) {
return Event._attach(Y.Array(arguments, 0, true));
},
_createWrapper: function (el, type, capture, compat, facade) {
var cewrapper,
ek = Y.stamp(el),
key = 'event:' + ek + type;
if (false === facade) {
key += 'native';
}
if (capture) {
key += 'capture';
}
cewrapper = _wrappers[key];
if (!cewrapper) {
// create CE wrapper
cewrapper = Y.publish(key, {
silent: true,
bubbles: false,
contextFn: function() {
if (compat) {
return cewrapper.el;
} else {
cewrapper.nodeRef = cewrapper.nodeRef || Y.one(cewrapper.el);
return cewrapper.nodeRef;
}
}
});
cewrapper.overrides = {};
// for later removeListener calls
cewrapper.el = el;
cewrapper.key = key;
cewrapper.domkey = ek;
cewrapper.type = type;
cewrapper.fn = function(e) {
cewrapper.fire(Event.getEvent(e, el, (compat || (false === facade))));
};
cewrapper.capture = capture;
if (el == Y.config.win && type == "load") {
// window load happens once
cewrapper.fireOnce = true;
_windowLoadKey = key;
}
_wrappers[key] = cewrapper;
_el_events[ek] = _el_events[ek] || {};
_el_events[ek][key] = cewrapper;
add(el, type, cewrapper.fn, capture);
}
return cewrapper;
},
_attach: function(args, config) {
var compat,
handles, oEl, cewrapper, context,
fireNow = false, ret,
type = args[0],
fn = args[1],
el = args[2] || Y.config.win,
facade = config && config.facade,
capture = config && config.capture,
overrides = config && config.overrides;
if (args[args.length-1] === COMPAT_ARG) {
compat = true;
// trimmedArgs.pop();
}
if (!fn || !fn.call) {
// throw new TypeError(type + " attach call failed, callback undefined");
Y.log(type + " attach call failed, invalid callback", "error", "event");
return false;
}
// The el argument can be an array of elements or element ids.
if (shouldIterate(el)) {
handles=[];
Y.each(el, function(v, k) {
args[2] = v;
handles.push(Event._attach(args, config));
});
// return (handles.length === 1) ? handles[0] : handles;
return new Y.EventHandle(handles);
// If the el argument is a string, we assume it is
// actually the id of the element. If the page is loaded
// we convert el to the actual element, otherwise we
// defer attaching the event until the element is
// ready
} else if (Y.Lang.isString(el)) {
// oEl = (compat) ? Y.DOM.byId(el) : Y.Selector.query(el);
if (compat) {
oEl = Y.DOM.byId(el);
} else {
oEl = Y.Selector.query(el);
switch (oEl.length) {
case 0:
oEl = null;
break;
case 1:
oEl = oEl[0];
break;
default:
args[2] = oEl;
return Event._attach(args, config);
}
}
if (oEl) {
el = oEl;
// Not found = defer adding the event until the element is available
} else {
// Y.log(el + ' not found');
ret = this.onAvailable(el, function() {
// Y.log('lazy attach: ' + args);
ret.handle = Event._attach(args, config);
}, Event, true, false, compat);
return ret;
}
}
// Element should be an html element or node
if (!el) {
Y.log("unable to attach event " + type, "warn", "event");
return false;
}
if (Y.Node && el instanceof Y.Node) {
el = Y.Node.getDOMNode(el);
}
cewrapper = this._createWrapper(el, type, capture, compat, facade);
if (overrides) {
Y.mix(cewrapper.overrides, overrides);
}
if (el == Y.config.win && type == "load") {
// if the load is complete, fire immediately.
// all subscribers, including the current one
// will be notified.
if (YUI.Env.windowLoaded) {
fireNow = true;
}
}
if (compat) {
args.pop();
}
context = args[3];
// set context to the Node if not specified
// ret = cewrapper.on.apply(cewrapper, trimmedArgs);
ret = cewrapper._on(fn, context, (args.length > 4) ? args.slice(4) : null);
if (fireNow) {
cewrapper.fire();
}
return ret;
},
/**
* Removes an event listener. Supports the signature the event was bound
* with, but the preferred way to remove listeners is using the handle
* that is returned when using Y.on
*
* @method detach
*
* @param {String} type the type of event to remove.
* @param {Function} fn the method the event invokes. If fn is
* undefined, then all event handlers for the type of event are
* removed.
* @param {String|HTMLElement|Array|NodeList|EventHandle} el An
* event handle, an id, an element reference, or a collection
* of ids and/or elements to remove the listener from.
* @return {boolean} true if the unbind was successful, false otherwise.
* @static
*/
detach: function(type, fn, el, obj) {
var args=Y.Array(arguments, 0, true), compat, l, ok, i,
id, ce;
if (args[args.length-1] === COMPAT_ARG) {
compat = true;
// args.pop();
}
if (type && type.detach) {
return type.detach();
}
// The el argument can be a string
if (typeof el == "string") {
// el = (compat) ? Y.DOM.byId(el) : Y.all(el);
if (compat) {
el = Y.DOM.byId(el);
} else {
el = Y.Selector.query(el);
l = el.length;
if (l < 1) {
el = null;
} else if (l == 1) {
el = el[0];
}
}
// return Event.detach.apply(Event, args);
}
if (!el) {
return false;
}
if (el.detach) {
args.splice(2, 1);
return el.detach.apply(el, args);
// The el argument can be an array of elements or element ids.
} else if (shouldIterate(el)) {
ok = true;
for (i=0, l=el.length; i<l; ++i) {
args[2] = el[i];
ok = ( Y.Event.detach.apply(Y.Event, args) && ok );
}
return ok;
}
if (!type || !fn || !fn.call) {
return this.purgeElement(el, false, type);
}
id = 'event:' + Y.stamp(el) + type;
ce = _wrappers[id];
if (ce) {
return ce.detach(fn);
} else {
return false;
}
},
/**
* Finds the event in the window object, the caller's arguments, or
* in the arguments of another method in the callstack. This is
* executed automatically for events registered through the event
* manager, so the implementer should not normally need to execute
* this function at all.
* @method getEvent
* @param {Event} e the event parameter from the handler
* @param {HTMLElement} el the element the listener was attached to
* @return {Event} the event
* @static
*/
getEvent: function(e, el, noFacade) {
var ev = e || window.event;
return (noFacade) ? ev :
new Y.DOMEventFacade(ev, el, _wrappers['event:' + Y.stamp(el) + e.type]);
},
/**
* Generates an unique ID for the element if it does not already
* have one.
* @method generateId
* @param el the element to create the id for
* @return {string} the resulting id of the element
* @static
*/
generateId: function(el) {
var id = el.id;
if (!id) {
id = Y.stamp(el);
el.id = id;
}
return id;
},
/**
* We want to be able to use getElementsByTagName as a collection
* to attach a group of events to. Unfortunately, different
* browsers return different types of collections. This function
* tests to determine if the object is array-like. It will also
* fail if the object is an array, but is empty.
* @method _isValidCollection
* @param o the object to test
* @return {boolean} true if the object is array-like and populated
* @deprecated was not meant to be used directly
* @static
* @private
*/
_isValidCollection: shouldIterate,
/**
* hook up any deferred listeners
* @method _load
* @static
* @private
*/
_load: function(e) {
if (!_loadComplete) {
// Y.log('Load Complete', 'info', 'event');
_loadComplete = true;
// Just in case DOMReady did not go off for some reason
// E._ready();
if (Y.fire) {
Y.fire(EVENT_READY);
}
// Available elements may not have been detected before the
// window load event fires. Try to find them now so that the
// the user is more likely to get the onAvailable notifications
// before the window load notification
Event._poll();
}
},
/**
* Polling function that runs before the onload event fires,
* attempting to attach to DOM Nodes as soon as they are
* available
* @method _poll
* @static
* @private
*/
_poll: function() {
if (this.locked) {
return;
}
if (Y.UA.ie && !YUI.Env.DOMReady) {
// Hold off if DOMReady has not fired and check current
// readyState to protect against the IE operation aborted
// issue.
this.startInterval();
return;
}
this.locked = true;
// Y.log.debug("poll");
// keep trying until after the page is loaded. We need to
// check the page load state prior to trying to bind the
// elements so that we can be certain all elements have been
// tested appropriately
var i, len, item, el, notAvail, executeItem,
tryAgain = !_loadComplete;
if (!tryAgain) {
tryAgain = (_retryCount > 0);
}
// onAvailable
notAvail = [];
executeItem = function (el, item) {
var context, ov = item.override;
if (item.compat) {
if (item.override) {
if (ov === true) {
context = item.obj;
} else {
context = ov;
}
} else {
context = el;
}
item.fn.call(context, item.obj);
} else {
context = item.obj || Y.one(el);
item.fn.apply(context, (Y.Lang.isArray(ov)) ? ov : []);
}
};
// onAvailable
for (i=0,len=_avail.length; i<len; ++i) {
item = _avail[i];
if (item && !item.checkReady) {
// el = (item.compat) ? Y.DOM.byId(item.id) : Y.one(item.id);
el = (item.compat) ? Y.DOM.byId(item.id) : Y.Selector.query(item.id, null, true);
if (el) {
// Y.log('avail: ' + el);
executeItem(el, item);
_avail[i] = null;
} else {
// Y.log('NOT avail: ' + el);
notAvail.push(item);
}
}
}
// onContentReady
for (i=0,len=_avail.length; i<len; ++i) {
item = _avail[i];
if (item && item.checkReady) {
// el = (item.compat) ? Y.DOM.byId(item.id) : Y.one(item.id);
el = (item.compat) ? Y.DOM.byId(item.id) : Y.Selector.query(item.id, null, true);
if (el) {
// The element is available, but not necessarily ready
// @todo should we test parentNode.nextSibling?
if (_loadComplete || (el.get && el.get('nextSibling')) || el.nextSibling) {
executeItem(el, item);
_avail[i] = null;
}
} else {
notAvail.push(item);
}
}
}
_retryCount = (notAvail.length === 0) ? 0 : _retryCount - 1;
if (tryAgain) {
// we may need to strip the nulled out items here
this.startInterval();
} else {
clearInterval(this._interval);
this._interval = null;
}
this.locked = false;
return;
},
/**
* Removes all listeners attached to the given element via addListener.
* Optionally, the node's children can also be purged.
* Optionally, you can specify a specific type of event to remove.
* @method purgeElement
* @param {HTMLElement} el the element to purge
* @param {boolean} recurse recursively purge this element's children
* as well. Use with caution.
* @param {string} type optional type of listener to purge. If
* left out, all listeners will be removed
* @static
*/
purgeElement: function(el, recurse, type) {
// var oEl = (Y.Lang.isString(el)) ? Y.one(el) : el,
var oEl = (Y.Lang.isString(el)) ? Y.Selector.query(el, null, true) : el,
lis = this.getListeners(oEl, type), i, len, props, children, child;
if (recurse && oEl) {
lis = lis || [];
children = Y.Selector.query('*', oEl);
i = 0;
len = children.length;
for (; i < len; ++i) {
child = this.getListeners(children[i], type);
if (child) {
lis = lis.concat(child);
}
}
}
if (lis) {
i = 0;
len = lis.length;
for (; i < len; ++i) {
props = lis[i];
props.detachAll();
remove(props.el, props.type, props.fn, props.capture);
delete _wrappers[props.key];
delete _el_events[props.domkey][props.key];
}
}
},
/**
* Returns all listeners attached to the given element via addListener.
* Optionally, you can specify a specific type of event to return.
* @method getListeners
* @param el {HTMLElement|string} the element or element id to inspect
* @param type {string} optional type of listener to return. If
* left out, all listeners will be returned
* @return {Y.Custom.Event} the custom event wrapper for the DOM event(s)
* @static
*/
getListeners: function(el, type) {
var ek = Y.stamp(el, true), evts = _el_events[ek],
results=[] , key = (type) ? 'event:' + ek + type : null;
if (!evts) {
return null;
}
if (key) {
if (evts[key]) {
results.push(evts[key]);
}
// get native events as well
key += 'native';
if (evts[key]) {
results.push(evts[key]);
}
} else {
Y.each(evts, function(v, k) {
results.push(v);
});
}
return (results.length) ? results : null;
},
/**
* Removes all listeners registered by pe.event. Called
* automatically during the unload event.
* @method _unload
* @static
* @private
*/
_unload: function(e) {
Y.each(_wrappers, function(v, k) {
v.detachAll();
remove(v.el, v.type, v.fn, v.capture);
delete _wrappers[k];
delete _el_events[v.domkey][k];
});
},
/**
* Adds a DOM event directly without the caching, cleanup, context adj, etc
*
* @method nativeAdd
* @param {HTMLElement} el the element to bind the handler to
* @param {string} type the type of event handler
* @param {function} fn the callback to invoke
* @param {boolen} capture capture or bubble phase
* @static
* @private
*/
nativeAdd: add,
/**
* Basic remove listener
*
* @method nativeRemove
* @param {HTMLElement} el the element to bind the handler to
* @param {string} type the type of event handler
* @param {function} fn the callback to invoke
* @param {boolen} capture capture or bubble phase
* @static
* @private
*/
nativeRemove: remove
};
}();
Y.Event = Event;
if (Y.config.injected || YUI.Env.windowLoaded) {
onLoad();
} else {
add(window, "load", onLoad);
}
// Process onAvailable/onContentReady items when when the DOM is ready in IE
if (Y.UA.ie) {
Y.on(EVENT_READY, Event._poll, Event, true);
}
Y.on("unload", onUnload);
Event.Custom = Y.CustomEvent;
Event.Subscriber = Y.Subscriber;
Event.Target = Y.EventTarget;
Event.Handle = Y.EventHandle;
Event.Facade = Y.EventFacade;
Event._poll();
})();
/**
* DOM event listener abstraction layer
* @module event
* @submodule event-base
*/
/**
* Executes the callback as soon as the specified element
* is detected in the DOM.
* @event available
* @param type {string} 'available'
* @param fn {function} the callback function to execute.
* @param el {string|HTMLElement|collection} the element(s) to attach
* @param context optional argument that specifies what 'this' refers to.
* @param args* 0..n additional arguments to pass on to the callback function.
* These arguments will be added after the event object.
* @return {EventHandle} the detach handle
* @for YUI
*/
Y.Env.evt.plugins.available = {
on: function(type, fn, id, o) {
var a = arguments.length > 4 ? Y.Array(arguments, 4, true) : [];
return Y.Event.onAvailable.call(Y.Event, id, fn, o, a);
}
};
/**
* Executes the callback as soon as the specified element
* is detected in the DOM with a nextSibling property
* (indicating that the element's children are available)
* @event contentready
* @param type {string} 'contentready'
* @param fn {function} the callback function to execute.
* @param el {string|HTMLElement|collection} the element(s) to attach
* @param context optional argument that specifies what 'this' refers to.
* @param args* 0..n additional arguments to pass on to the callback function.
* These arguments will be added after the event object.
* @return {EventHandle} the detach handle
* @for YUI
*/
Y.Env.evt.plugins.contentready = {
on: function(type, fn, id, o) {
var a = arguments.length > 4 ? Y.Array(arguments, 4, true) : [];
return Y.Event.onContentReady.call(Y.Event, id, fn, o, a);
}
};
}, '@VERSION@' ,{requires:['event-custom-base']});
YUI.add('event-delegate', function(Y) {
/**
* Adds event delegation support to the library.
*
* @module event
* @submodule event-delegate
*/
var Event = Y.Event,
Lang = Y.Lang,
delegates = {},
specialTypes = {
mouseenter: "mouseover",
mouseleave: "mouseout"
},
resolveTextNode = function(n) {
try {
if (n && 3 == n.nodeType) {
return n.parentNode;
}
} catch(e) { }
return n;
},
delegateHandler = function(delegateKey, e, el) {
var target = resolveTextNode((e.target || e.srcElement)),
tests = delegates[delegateKey],
spec,
ename,
matched,
fn,
ev;
var getMatch = function(el, selector, container) {
var returnVal;
if (!el || el === container) {
returnVal = false;
}
else {
returnVal = Y.Selector.test(el, selector, container) ? el: getMatch(el.parentNode, selector, container);
}
return returnVal;
};
for (spec in tests) {
if (tests.hasOwnProperty(spec)) {
ename = tests[spec];
fn = tests.fn;
matched = null;
if (Y.Selector.test(target, spec, el)) {
matched = target;
}
else if (Y.Selector.test(target, ((spec.replace(/,/gi, " *,")) + " *"), el)) {
// The target is a descendant of an element matching
// the selector, so crawl up to find the ancestor that
// matches the selector
matched = getMatch(target, spec, el);
}
if (matched) {
if (!ev) {
ev = new Y.DOMEventFacade(e, el);
ev.container = ev.currentTarget;
}
ev.currentTarget = Y.one(matched);
Y.publish(ename, {
contextFn: function() {
return ev.currentTarget;
}
});
if (fn) {
fn(ev, ename);
}
else {
Y.fire(ename, ev);
}
}
}
}
},
attach = function (type, key, element) {
var focusMethods = {
focus: Event._attachFocus,
blur: Event._attachBlur
},
attachFn = focusMethods[type],
args = [type,
function (e) {
delegateHandler(key, (e || window.event), element);
},
element];
if (attachFn) {
return attachFn(args, { capture: true, facade: false });
}
else {
return Event._attach(args, { facade: false });
}
},
sanitize = Y.cached(function(str) {
return str.replace(/[|,:]/g, '~');
});
/**
* Sets up event delegation on a container element. The delegated event
* will use a supplied selector to test if the target or one of the
* descendants of the target match it. The supplied callback function
* will only be executed if a match was encountered, and, in fact,
* will be executed for each element that matches if you supply an
* ambiguous selector.
*
* The event object for the delegated event is supplied to the callback
* function. It is modified slightly in order to support all properties
* that may be needed for event delegation. 'currentTarget' is set to
* the element that matched the delegation specifcation. 'container' is
* set to the element that the listener is bound to (this normally would
* be the 'currentTarget').
*
* @method delegate
* @param type {string} the event type to delegate
* @param fn {function} the callback function to execute. This function
* will be provided the event object for the delegated event.
* @param el {string|node} the element that is the delegation container
* @param spec {string} a selector that must match the target of the
* event.
* @param context optional argument that specifies what 'this' refers to.
* @param args* 0..n additional arguments to pass on to the callback function.
* These arguments will be added after the event object.
* @return {EventHandle} the detach handle
* @for YUI
*/
Event.delegate = function (type, fn, el, spec) {
if (!spec) {
Y.log('delegate: no spec, nothing to do', 'warn', 'event');
return false;
}
var args = Y.Array(arguments, 0, true),
element = el, // HTML element serving as the delegation container
availHandle;
if (Lang.isString(el)) {
// Y.Selector.query returns an array of matches unless specified
// to return just the first match. Since the primary use case for
// event delegation is to use a single event handler on a container,
// Y.delegate doesn't currently support being able to bind a
// single listener to multiple containers.
element = Y.Selector.query(el, null, true);
if (!element) { // Not found, check using onAvailable
availHandle = Event.onAvailable(el, function() {
availHandle.handle = Event.delegate.apply(Event, args);
}, Event, true, false);
return availHandle;
}
}
element = Y.Node.getDOMNode(element);
var guid = Y.stamp(element),
// The Custom Event for the delegation spec
ename = 'delegate:' + guid + type + sanitize(spec),
// The key to the listener for the event type and container
delegateKey = type + guid,
delegate = delegates[delegateKey],
domEventHandle,
ceHandle,
listeners;
if (!delegate) {
delegate = {};
if (specialTypes[type]) {
if (!Event._fireMouseEnter) {
Y.log("Delegating a " + type + " event requires the event-mouseenter submodule.", "error", "Event");
return false;
}
type = specialTypes[type];
delegate.fn = Event._fireMouseEnter;
}
// Create the DOM Event wrapper that will fire the Custom Event
domEventHandle = attach(type, delegateKey, element);
// Hook into the _delete method for the Custom Event wrapper of this
// DOM Event in order to clean up the 'delegates' map and unsubscribe
// the associated Custom Event listeners fired by this DOM event
// listener if/when the user calls "purgeElement" OR removes all
// listeners of the Custom Event.
Y.after(function (sub) {
if (domEventHandle.sub == sub) {
// Delete this event from the map of known delegates
delete delegates[delegateKey];
Y.log("DOM event listener associated with the " + ename + " Custom Event removed. Removing all " + ename + " listeners.", "info", "Event");
// Unsubscribe all listeners of the Custom Event fired
// by this DOM event.
Y.detachAll(ename);
}
}, domEventHandle.evt, "_delete");
delegate.handle = domEventHandle;
delegates[delegateKey] = delegate;
}
listeners = delegate.listeners;
delegate.listeners = listeners ? (listeners + 1) : 1;
delegate[spec] = ename;
args[0] = ename;
// Remove element, delegation spec
args.splice(2, 2);
// Subscribe to the Custom Event for the delegation spec
ceHandle = Y.on.apply(Y, args);
// Hook into the detach method of the handle in order to clean up the
// 'delegates' map and remove the associated DOM event handler
// responsible for firing this Custom Event if all listener for this
// event have been removed.
Y.after(function () {
delegate.listeners = (delegate.listeners - 1);
if (delegate.listeners === 0) {
Y.log("No more listeners for the " + ename + " Custom Event. Removing its associated DOM event listener.", "info", "Event");
delegate.handle.detach();
}
}, ceHandle, "detach");
return ceHandle;
};
Y.delegate = Event.delegate;
}, '@VERSION@' ,{requires:['node-base']});
YUI.add('event-mousewheel', function(Y) {
/**
* Adds mousewheel event support
* @module event
* @submodule event-mousewheel
*/
var DOM_MOUSE_SCROLL = 'DOMMouseScroll',
fixArgs = function(args) {
var a = Y.Array(args, 0, true), target;
if (Y.UA.gecko) {
a[0] = DOM_MOUSE_SCROLL;
target = Y.config.win;
} else {
target = Y.config.doc;
}
if (a.length < 3) {
a[2] = target;
} else {
a.splice(2, 0, target);
}
return a;
};
/**
* Mousewheel event. This listener is automatically attached to the
* correct target, so one should not be supplied. Mouse wheel
* direction and velocity is stored in the 'mouseDelta' field.
* @event mousewheel
* @param type {string} 'mousewheel'
* @param fn {function} the callback to execute
* @param context optional context object
* @param args 0..n additional arguments to provide to the listener.
* @return {EventHandle} the detach handle
* @for YUI
*/
Y.Env.evt.plugins.mousewheel = {
on: function() {
return Y.Event._attach(fixArgs(arguments));
},
detach: function() {
return Y.Event.detach.apply(Y.Event, fixArgs(arguments));
}
};
}, '@VERSION@' ,{requires:['node-base']});
YUI.add('event-mouseenter', function(Y) {
/**
* Adds support for mouseenter/mouseleave events
* @module event
* @submodule event-mouseenter
*/
var Event = Y.Event,
Lang = Y.Lang,
plugins = Y.Env.evt.plugins,
listeners = {},
eventConfig = {
on: function(type, fn, el) {
var args = Y.Array(arguments, 0, true),
element = el,
availHandle;
if (Lang.isString(el)) {
// Need to use Y.all because if el is a string it could be a
// selector that returns a NodeList
element = Y.all(el);
if (element.size() === 0) { // Not found, check using onAvailable
availHandle = Event.onAvailable(el, function() {
availHandle.handle = Y.on.apply(Y, args);
}, Event, true, false);
return availHandle;
}
}
var sDOMEvent = (type === "mouseenter") ? "mouseover" : "mouseout",
// The name of the custom event
sEventName = type + ":" + Y.stamp(element) + sDOMEvent,
listener = listeners[sEventName],
domEventHandle,
ceHandle,
nListeners;
// Bind an actual DOM event listener that will call the
// the custom event
if (!listener) {
domEventHandle = Y.on(sDOMEvent, Y.rbind(Event._fireMouseEnter, Y, sEventName), element);
// Hook into the _delete method for the Custom Event wrapper of this
// DOM Event in order to clean up the 'listeners' map and unsubscribe
// the associated Custom Event listeners fired by this DOM event
// listener if/when the user calls "purgeElement" OR removes all
// listeners of the Custom Event.
Y.after(function (sub) {
if (domEventHandle.sub == sub) {
// Delete this event from the map of known mouseenter
// and mouseleave listeners
delete listeners[sEventName];
Y.log("DOM event listener associated with the " + sEventName + " Custom Event removed. Removing all " + sEventName + " listeners.", "info", "Event");
// Unsubscribe all listeners of the Custom Event fired
// by this DOM event.
Y.detachAll(sEventName);
}
}, domEventHandle.evt, "_delete");
listener = {};
listener.handle = domEventHandle;
listeners[sEventName] = listener;
}
nListeners = listener.count;
listener.count = nListeners ? (nListeners + 1) : 1;
args[0] = sEventName;
// Remove the element from the args
args.splice(2, 1);
// Subscribe to the custom event
ceHandle = Y.on.apply(Y, args);
// Hook into the detach method of the handle in order to clean up the
// 'listeners' map and remove the associated DOM event handler
// responsible for firing this Custom Event if all listener for this
// event have been removed.
Y.after(function () {
listener.count = (listener.count - 1);
if (listener.count === 0) {
Y.log("No more listeners for the " + sEventName + " Custom Event. Removing its associated DOM event listener.", "info", "Event");
listener.handle.detach();
}
}, ceHandle, "detach");
return ceHandle;
}
};
Event._fireMouseEnter = function (e, eventName) {
var relatedTarget = e.relatedTarget,
currentTarget = e.currentTarget;
if (currentTarget !== relatedTarget &&
!currentTarget.contains(relatedTarget)) {
Y.publish(eventName, {
contextFn: function() {
return currentTarget;
}
});
Y.fire(eventName, e);
}
};
/**
* Sets up a "mouseenter" listener—a listener that is called the first time
* the user's mouse enters the specified element(s).
*
* @event mouseenter
* @param type {string} "mouseenter"
* @param fn {function} The method the event invokes.
* @param el {string|node} The element(s) to assign the listener to.
* @param spec {string} Optional. String representing a selector that must
* match the target of the event in order for the listener to be called.
* @return {EventHandle} the detach handle
* @for YUI
*/
plugins.mouseenter = eventConfig;
/**
* Sets up a "mouseleave" listener—a listener that is called the first time
* the user's mouse leaves the specified element(s).
*
* @event mouseleave
* @param type {string} "mouseleave"
* @param fn {function} The method the event invokes.
* @param el {string|node} The element(s) to assign the listener to.
* @param spec {string} Optional. String representing a selector that must
* match the target of the event in order for the listener to be called.
* @return {EventHandle} the detach handle
* @for YUI
*/
plugins.mouseleave = eventConfig;
}, '@VERSION@' ,{requires:['node-base']});
YUI.add('event-key', function(Y) {
/**
* Functionality to listen for one or more specific key combinations.
* @module event
* @submodule event-key
*/
/**
* Add a key listener. The listener will only be notified if the
* keystroke detected meets the supplied specification. The
* spec consists of the key event type, followed by a colon,
* followed by zero or more comma separated key codes, followed
* by zero or more modifiers delimited by a plus sign. Ex:
* press:12,65+shift+ctrl
* @event key
* @for YUI
* @param type {string} 'key'
* @param fn {function} the function to execute
* @param id {string|HTMLElement|collection} the element(s) to bind
* @param spec {string} the keyCode and modifier specification
* @param o optional context object
* @param args 0..n additional arguments to provide to the listener.
* @return {Event.Handle} the detach handle
*/
Y.Env.evt.plugins.key = {
on: function(type, fn, id, spec, o) {
var a = Y.Array(arguments, 0, true), parsed, etype, criteria, ename;
parsed = spec && spec.split(':');
if (!spec || spec.indexOf(':') == -1 || !parsed[1]) {
Y.log('Illegal key spec, creating a regular keypress listener instead.', 'info', 'event');
a[0] = 'key' + ((parsed && parsed[0]) || 'press');
return Y.on.apply(Y, a);
}
// key event type: 'down', 'up', or 'press'
etype = parsed[0];
// list of key codes optionally followed by modifiers
criteria = (parsed[1]) ? parsed[1].split(/,|\+/) : null;
// the name of the custom event that will be created for the spec
ename = (Y.Lang.isString(id) ? id : Y.stamp(id)) + spec;
ename = ename.replace(/,/g, '_');
if (!Y.getEvent(ename)) {
// subscribe spec validator to the DOM event
Y.on(type + etype, function(e) {
// Y.log('keylistener: ' + e.keyCode);
var passed = false, failed = false, i, crit, critInt;
for (i=0; i<criteria.length; i=i+1) {
crit = criteria[i];
critInt = parseInt(crit, 10);
// pass this section if any supplied keyCode
// is found
if (Y.Lang.isNumber(critInt)) {
if (e.charCode === critInt) {
// Y.log('passed: ' + crit);
passed = true;
} else {
failed = true;
// Y.log('failed: ' + crit);
}
// only check modifier if no keyCode was specified
// or the keyCode check was successful. pass only
// if every modifier passes
} else if (passed || !failed) {
passed = (e[crit + 'Key']);
failed = !passed;
// Y.log(crit + ": " + passed);
}
}
// fire spec custom event if spec if met
if (passed) {
Y.fire(ename, e);
}
}, id);
}
// subscribe supplied listener to custom event for spec validator
// remove element and spec.
a.splice(2, 2);
a[0] = ename;
return Y.on.apply(Y, a);
}
};
}, '@VERSION@' ,{requires:['node-base']});
YUI.add('event-focus', function(Y) {
/**
* Adds focus and blur event listener support. These events normally
* do not bubble, so this adds support for that so these events
* can be used in event delegation scenarios.
*
* @module event
* @submodule event-focus
*/
(function() {
var UA = Y.UA,
Event = Y.Event,
plugins = Y.Env.evt.plugins,
ie = UA.ie,
bUseMutation = (UA.opera || UA.webkit),
eventNames = {
focus: (ie ? 'focusin' : (bUseMutation ? 'DOMFocusIn' : 'focus')),
blur: (ie ? 'focusout' : (bUseMutation ? 'DOMFocusOut' : 'blur'))
},
// Only need to use capture phase for Gecko since it doesn't support
// focusin, focusout, DOMFocusIn, or DOMFocusOut
CAPTURE_CONFIG = { capture: (UA.gecko ? true : false) },
attach = function (args, config) {
var a = Y.Array(args, 0, true),
el = args[2];
config.overrides = config.overrides || {};
config.overrides.type = args[0];
if (el) {
if (Y.DOM.isWindow(el)) {
config.capture = false;
}
else {
a[0] = eventNames[a[0]];
}
}
return Event._attach(a, config);
},
eventAdapter = {
on: function () {
return attach(arguments, CAPTURE_CONFIG);
}
};
Event._attachFocus = attach;
Event._attachBlur = attach;
/**
* Adds a DOM focus listener. Uses the focusin event in IE,
* DOMFocusIn for Opera and Webkit, and the capture phase for Gecko so that
* the event propagates in a way that enables event delegation.
*
* @for YUI
* @event focus
* @param type {string} 'focus'
* @param fn {function} the callback function to execute
* @param o {string|HTMLElement|collection} the element(s) to bind
* @param context optional context object
* @param args 0..n additional arguments to provide to the listener.
* @return {EventHandle} the detach handle
*/
plugins.focus = eventAdapter;
/**
* Adds a DOM blur listener. Uses the focusout event in IE,
* DOMFocusOut for Opera and Webkit, and the capture phase for Gecko so that
* the event propagates in a way that enables event delegation.
*
* @for YUI
* @event blur
* @param type {string} 'blur'
* @param fn {function} the callback function to execute
* @param o {string|HTMLElement|collection} the element(s) to bind
* @param context optional context object
* @param args 0..n additional arguments to provide to the listener.
* @return {EventHandle} the detach handle
*/
plugins.blur = eventAdapter;
})();
}, '@VERSION@' ,{requires:['node-base']});
YUI.add('event-resize', function(Y) {
/**
* Adds a window resize event that has its behavior normalized to fire at the
* end of the resize rather than constantly during the resize.
* @module event
* @submodule event-resize
*/
(function() {
var detachHandle,
timerHandle,
CE_NAME = 'window:resize',
handler = function(e) {
if (Y.UA.gecko) {
Y.fire(CE_NAME, e);
} else {
if (timerHandle) {
timerHandle.cancel();
}
timerHandle = Y.later(Y.config.windowResizeDelay || 40, Y, function() {
Y.fire(CE_NAME, e);
});
}
};
/**
* Firefox fires the window resize event once when the resize action
* finishes, other browsers fire the event periodically during the
* resize. This code uses timeout logic to simulate the Firefox
* behavior in other browsers.
* @event windowresize
* @for YUI
*/
Y.Env.evt.plugins.windowresize = {
on: function(type, fn) {
// check for single window listener and add if needed
if (!detachHandle) {
detachHandle = Y.Event._attach(['resize', handler]);
}
var a = Y.Array(arguments, 0, true);
a[0] = CE_NAME;
return Y.on.apply(Y, a);
}
};
})();
}, '@VERSION@' ,{requires:['node-base']});
YUI.add('event', function(Y){}, '@VERSION@' ,{use:['event-base', 'event-delegate', 'event-mousewheel', 'event-mouseenter', 'event-key', 'event-focus', 'event-resize']});
| pcarrier/cdnjs | ajax/libs/yui/3.1.0pr2/event/event-debug.js | JavaScript | mit | 64,193 |
/**
* 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.camel.component.jmx;
/**
* Reports a problem formatting the Notification. This will be a JAXB related issue.
*/
public class NotificationFormatException extends Exception {
private static final long serialVersionUID = -3460338958670572299L;
public NotificationFormatException(Exception aCausedBy) {
super(aCausedBy);
}
}
| YMartsynkevych/camel | components/camel-jmx/src/main/java/org/apache/camel/component/jmx/NotificationFormatException.java | Java | apache-2.0 | 1,170 |
<?php
namespace Guzzle\Tests\Common;
use Guzzle\Common\Event;
class EventTest extends \Guzzle\Tests\GuzzleTestCase
{
/**
* @return Event
*/
private function getEvent()
{
return new Event(array(
'test' => '123',
'other' => '456',
'event' => 'test.notify'
));
}
/**
* @covers Guzzle\Common\Event::__construct
*/
public function testAllowsParameterInjection()
{
$event = new Event(array(
'test' => '123'
));
$this->assertEquals('123', $event['test']);
}
/**
* @covers Guzzle\Common\Event::offsetGet
* @covers Guzzle\Common\Event::offsetSet
* @covers Guzzle\Common\Event::offsetUnset
* @covers Guzzle\Common\Event::offsetExists
*/
public function testImplementsArrayAccess()
{
$event = $this->getEvent();
$this->assertEquals('123', $event['test']);
$this->assertNull($event['foobar']);
$this->assertTrue($event->offsetExists('test'));
$this->assertFalse($event->offsetExists('foobar'));
unset($event['test']);
$this->assertFalse($event->offsetExists('test'));
$event['test'] = 'new';
$this->assertEquals('new', $event['test']);
}
/**
* @covers Guzzle\Common\Event::getIterator
*/
public function testImplementsIteratorAggregate()
{
$event = $this->getEvent();
$this->assertInstanceOf('ArrayIterator', $event->getIterator());
}
/**
* @covers Guzzle\Common\Event::toArray
*/
public function testConvertsToArray()
{
$this->assertEquals(array(
'test' => '123',
'other' => '456',
'event' => 'test.notify'
), $this->getEvent()->toArray());
}
}
| LenLamberg/LenEntire_June_5 | winkler/profiles/commerce_kickstart/libraries/yotpo-php/vendor/guzzle/http/Guzzle/Http/tests/Guzzle/Tests/Common/EventTest.php | PHP | gpl-2.0 | 1,819 |
/*
backgrid
http://github.com/wyuenho/backgrid
Copyright (c) 2013 Jimmy Yuen Ho Wong
Licensed under the MIT @license.
*/
(function (root, $, _, Backbone) {
"use strict";
/*
backgrid
http://github.com/wyuenho/backgrid
Copyright (c) 2013 Jimmy Yuen Ho Wong
Licensed under the MIT @license.
*/
var window = root;
var Backgrid = root.Backgrid = {
VERSION: "0.1.3",
Extension: {}
};
// Copyright 2009, 2010 Kristopher Michael Kowal
// https://github.com/kriskowal/es5-shim
// ES5 15.5.4.20
// http://es5.github.com/#x15.5.4.20
var ws = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003" +
"\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" +
"\u2029\uFEFF";
if (!String.prototype.trim || ws.trim()) {
// http://blog.stevenlevithan.com/archives/faster-trim-javascript
// http://perfectionkills.com/whitespace-deviations/
ws = "[" + ws + "]";
var trimBeginRegexp = new RegExp("^" + ws + ws + "*"),
trimEndRegexp = new RegExp(ws + ws + "*$");
String.prototype.trim = function trim() {
if (this === undefined || this === null) {
throw new TypeError("can't convert " + this + " to object");
}
return String(this)
.replace(trimBeginRegexp, "")
.replace(trimEndRegexp, "");
};
}
function capitalize(s) {
return String.fromCharCode(s.charCodeAt(0) - 32) + s.slice(1);
}
function lpad(str, length, padstr) {
var paddingLen = length - (str + '').length;
paddingLen = paddingLen < 0 ? 0 : paddingLen;
var padding = '';
for (var i = 0; i < paddingLen; i++) {
padding = padding + padstr;
}
return padding + str;
}
function requireOptions(options, requireOptionKeys) {
for (var i = 0; i < requireOptionKeys.length; i++) {
var key = requireOptionKeys[i];
if (_.isUndefined(options[key])) {
throw new TypeError("'" + key + "' is required");
}
}
}
function resolveNameToClass(name, suffix) {
if (_.isString(name)) {
var key = capitalize(name) + suffix;
var klass = Backgrid[key] || Backgrid.Extension[key];
if (_.isUndefined(klass)) {
throw new ReferenceError("Class '" + key + "' not found");
}
return klass;
}
return name;
}
/*
backgrid
http://github.com/wyuenho/backgrid
Copyright (c) 2013 Jimmy Yuen Ho Wong
Licensed under the MIT @license.
*/
/**
Just a convenient class for interested parties to subclass.
The default Cell classes don't require the formatter to be a subclass of
Formatter as long as the fromRaw(rawData) and toRaw(formattedData) methods
are defined.
@abstract
@class Backgrid.CellFormatter
@constructor
*/
var CellFormatter = Backgrid.CellFormatter = function () {};
_.extend(CellFormatter.prototype, {
/**
Takes a raw value from a model and returns a formatted string for display.
@member Backgrid.CellFormatter
@param {*} rawData
@return {string}
*/
fromRaw: function (rawData) {
return rawData;
},
/**
Takes a formatted string, usually from user input, and returns a
appropriately typed value for persistence in the model.
If the user input is invalid or unable to be converted to a raw value
suitable for persistence in the model, toRaw must return `undefined`.
@member Backgrid.CellFormatter
@param {string} formattedData
@return {*|undefined}
*/
toRaw: function (formattedData) {
return formattedData;
}
});
/**
A floating point number formatter. Doesn't understand notation at the moment.
@class Backgrid.NumberFormatter
@extends Backgrid.CellFormatter
@constructor
@throws {RangeError} If decimals < 0 or > 20.
*/
var NumberFormatter = Backgrid.NumberFormatter = function (options) {
options = options ? _.clone(options) : {};
_.extend(this, this.defaults, options);
if (this.decimals < 0 || this.decimals > 20) {
throw new RangeError("decimals must be between 0 and 20");
}
};
NumberFormatter.prototype = new CellFormatter;
_.extend(NumberFormatter.prototype, {
/**
@member Backgrid.NumberFormatter
@cfg {Object} options
@cfg {number} [options.decimals=2] Number of decimals to display. Must be an integer.
@cfg {string} [options.decimalSeparator='.'] The separator to use when
displaying decimals.
@cfg {string} [options.orderSeparator=','] The separator to use to
separator thousands. May be an empty string.
*/
defaults: {
decimals: 2,
decimalSeparator: '.',
orderSeparator: ','
},
HUMANIZED_NUM_RE: /(\d)(?=(?:\d{3})+$)/g,
/**
Takes a floating point number and convert it to a formatted string where
every thousand is separated by `orderSeparator`, with a `decimal` number of
decimals separated by `decimalSeparator`. The number returned is rounded
the usual way.
@member Backgrid.NumberFormatter
@param {number} number
@return {string}
*/
fromRaw: function (number) {
if (isNaN(number) || number === null) return '';
number = number.toFixed(~~this.decimals);
var parts = number.split('.');
var integerPart = parts[0];
var decimalPart = parts[1] ? (this.decimalSeparator || '.') + parts[1] : '';
return integerPart.replace(this.HUMANIZED_NUM_RE, '$1' + this.orderSeparator) + decimalPart;
},
/**
Takes a string, possibly formatted with `orderSeparator` and/or
`decimalSeparator`, and convert it back to a number.
@member Backgrid.NumberFormatter
@param {string} formattedData
@return {number|undefined} Undefined if the string cannot be converted to
a number.
*/
toRaw: function (formattedData) {
var rawData = '';
var thousands = formattedData.trim().split(this.orderSeparator);
for (var i = 0; i < thousands.length; i++) {
rawData += thousands[i];
}
var decimalParts = rawData.split(this.decimalSeparator);
rawData = '';
for (var i = 0; i < decimalParts.length; i++) {
rawData = rawData + decimalParts[i] + '.';
}
if (rawData[rawData.length - 1] === '.') {
rawData = rawData.slice(0, rawData.length - 1);
}
var result = (rawData * 1).toFixed(~~this.decimals) * 1;
if (_.isNumber(result) && !_.isNaN(result)) return result;
}
});
/**
Formatter to converts between various datetime string formats.
This class only understands ISO-8601 formatted datetime strings. See
Backgrid.Extension.MomentFormatter if you need a much more flexible datetime
formatter.
@class Backgrid.DatetimeFormatter
@extends Backgrid.CellFormatter
@constructor
@throws {Error} If both `includeDate` and `includeTime` are false.
*/
var DatetimeFormatter = Backgrid.DatetimeFormatter = function (options) {
options = options ? _.clone(options) : {};
_.extend(this, this.defaults, options);
if (!this.includeDate && !this.includeTime) {
throw new Error("Either includeDate or includeTime must be true");
}
};
DatetimeFormatter.prototype = new CellFormatter;
_.extend(DatetimeFormatter.prototype, {
/**
@member Backgrid.DatetimeFormatter
@cfg {Object} options
@cfg {boolean} [options.includeDate=true] Whether the values include the
date part.
@cfg {boolean} [options.includeTime=true] Whether the values include the
time part.
@cfg {boolean} [options.includeMilli=false] If `includeTime` is true,
whether to include the millisecond part, if it exists.
*/
defaults: {
includeDate: true,
includeTime: true,
includeMilli: false
},
DATE_RE: /^([+\-]?\d{4})-(\d{2})-(\d{2})$/,
TIME_RE: /^(\d{2}):(\d{2}):(\d{2})(\.(\d{3}))?$/,
ISO_SPLITTER_RE: /T|Z| +/,
_convert: function (data, validate) {
if (_.isNull(data) || _.isUndefined(data)) return data;
data = data.trim();
var parts = data.split(this.ISO_SPLITTER_RE) || [];
var date = this.DATE_RE.test(parts[0]) ? parts[0] : '';
var time = date && parts[1] ? parts[1] : this.TIME_RE.test(parts[0]) ? parts[0] : '';
var YYYYMMDD = this.DATE_RE.exec(date) || [];
var HHmmssSSS = this.TIME_RE.exec(time) || [];
if (validate) {
if (this.includeDate && _.isUndefined(YYYYMMDD[0])) return;
if (this.includeTime && _.isUndefined(HHmmssSSS[0])) return;
if (!this.includeDate && date) return;
if (!this.includeTime && time) return;
}
var jsDate = new Date(Date.UTC(YYYYMMDD[1] * 1 || 0,
YYYYMMDD[2] * 1 - 1 || 0,
YYYYMMDD[3] * 1 || 0,
HHmmssSSS[1] * 1 || null,
HHmmssSSS[2] * 1 || null,
HHmmssSSS[3] * 1 || null,
HHmmssSSS[5] * 1 || null));
var result = '';
if (this.includeDate) {
result = lpad(jsDate.getUTCFullYear(), 4, 0) + '-' + lpad(jsDate.getUTCMonth() + 1, 2, 0) + '-' + lpad(jsDate.getUTCDate(), 2, 0);
}
if (this.includeTime) {
result = result + (this.includeDate ? 'T' : '') + lpad(jsDate.getUTCHours(), 2, 0) + ':' + lpad(jsDate.getUTCMinutes(), 2, 0) + ':' + lpad(jsDate.getUTCSeconds(), 2, 0);
if (this.includeMilli) {
result = result + '.' + lpad(jsDate.getUTCMilliseconds(), 3, 0);
}
}
if (this.includeDate && this.includeTime) {
result += "Z";
}
return result;
},
/**
Converts an ISO-8601 formatted datetime string to a datetime string, date
string or a time string. The timezone is ignored if supplied.
@member Backgrid.DatetimeFormatter
@param {string} rawData
@return {string|null|undefined} ISO-8601 string in UTC. Null and undefined values are returned as is.
*/
fromRaw: function (rawData) {
return this._convert(rawData);
},
/**
Converts an ISO-8601 formatted datetime string to a datetime string, date
string or a time string. The timezone is ignored if supplied. This method
parses the input values exactly the same way as
Backgrid.Extension.MomentFormatter#fromRaw(), in addition to doing some
sanity checks.
@member Backgrid.DatetimeFormatter
@param {string} formattedData
@return {string|undefined} ISO-8601 string in UTC. Undefined if a date is
found `includeDate` is false, or a time is found if `includeTime` is false,
or if `includeDate` is true and a date is not found, or if `includeTime` is
true and a time is not found.
*/
toRaw: function (formattedData) {
return this._convert(formattedData, true);
}
});
/*
backgrid
http://github.com/wyuenho/backgrid
Copyright (c) 2013 Jimmy Yuen Ho Wong
Licensed under the MIT @license.
*/
/**
Generic cell editor base class. Only defines an initializer for a number of
required parameters.
@abstract
@class Backgrid.CellEditor
@extends Backbone.View
*/
var CellEditor = Backgrid.CellEditor = Backbone.View.extend({
/**
Initializer.
@param {Object} options
@param {*} options.parent
@param {Backgrid.CellFormatter} options.formatter
@param {Backgrid.Column} options.column
@param {Backbone.Model} options.model
@throws {TypeError} If `formatter` is not a formatter instance, or when
`model` or `column` are undefined.
*/
initialize: function (options) {
requireOptions(options, ["formatter", "column", "model"]);
this.parent = options.parent;
this.formatter = options.formatter;
this.column = options.column;
if (!(this.column instanceof Column)) {
this.column = new Column(this.column);
}
if (this.parent && _.isFunction(this.parent.on)) {
this.listenTo(this.parent, "editing", this.postRender);
}
},
/**
Post-rendering setup and initialization. Focuses the cell editor's `el` in
this default implementation. **Should** be called by Cell classes after
calling Backgrid.CellEditor#render.
*/
postRender: function () {
this.$el.focus();
return this;
}
});
/**
InputCellEditor the cell editor type used by most core cell types. This cell
editor renders a text input box as its editor. The input will render a
placeholder if the value is empty on supported browsers.
@class Backgrid.InputCellEditor
@extends Backgrid.CellEditor
*/
var InputCellEditor = Backgrid.InputCellEditor = CellEditor.extend({
/** @property */
tagName: "input",
/** @property */
attributes: {
type: "text"
},
/** @property */
events: {
"blur": "saveOrCancel",
"keydown": "saveOrCancel"
},
/**
Initializer. Removes this `el` from the DOM when a `done` event is
triggered.
@param {Object} options
@param {Backgrid.CellFormatter} options.formatter
@param {Backgrid.Column} options.column
@param {Backbone.Model} options.model
@param {string} [options.placeholder]
*/
initialize: function (options) {
CellEditor.prototype.initialize.apply(this, arguments);
if (options.placeholder) {
this.$el.attr("placeholder", options.placeholder);
}
this.listenTo(this, "done", this.remove);
},
/**
Renders a text input with the cell value formatted for display, if it
exists.
*/
render: function () {
this.$el.val(this.formatter.fromRaw(this.model.get(this.column.get("name"))));
return this;
},
/**
If the key pressed is `enter` or `tab`, converts the value in the editor to
a raw value for the model using the formatter.
If the key pressed is `esc` the changes are undone.
If the editor's value was changed and goes out of focus (`blur`), the event
is intercepted, cancelled so the cell remains in focus pending for further
action.
Triggers a Backbone `done` event when successful. `error` if the value
cannot be converted. Classes listening to the `error` event, usually the
Cell classes, should respond appropriately, usually by rendering some kind
of error feedback.
@param {Event} e
*/
saveOrCancel: function (e) {
if (e.type === "keydown") {
// enter or tab
if (e.keyCode === 13 || e.keyCode === 9) {
e.preventDefault();
var valueToSet = this.formatter.toRaw(this.$el.val());
if (_.isUndefined(valueToSet) ||
!this.model.set(this.column.get("name"), valueToSet,
{validate: true})) {
this.trigger("error");
}
else {
this.trigger("done");
}
}
// esc
else if (e.keyCode === 27) {
// undo
e.stopPropagation();
this.trigger("done");
}
}
else if (e.type === "blur") {
if (this.formatter.fromRaw(this.model.get(this.column.get("name"))) === this.$el.val()) {
this.trigger("done");
}
else {
var self = this;
var timeout = window.setTimeout(function () {
self.$el.focus();
window.clearTimeout(timeout);
}, 1);
}
}
},
postRender: function () {
// move the cursor to the end on firefox if text is right aligned
if (this.$el.css("text-align") === "right") {
var val = this.$el.val();
this.$el.focus().val(null).val(val);
}
else {
this.$el.focus();
}
return this;
}
});
/**
The super-class for all Cell types. By default, this class renders a plain
table cell with the model value converted to a string using the
formatter. The table cell is clickable, upon which the cell will go into
editor mode, which is rendered by a Backgrid.InputCellEditor instance by
default. Upon any formatting errors, this class will add a `error` CSS class
to the table cell.
@abstract
@class Backgrid.Cell
@extends Backbone.View
*/
var Cell = Backgrid.Cell = Backbone.View.extend({
/** @property */
tagName: "td",
/**
@property {Backgrid.CellFormatter|Object|string} [formatter=new CellFormatter()]
*/
formatter: new CellFormatter(),
/**
@property {Backgrid.CellEditor} [editor=Backgrid.InputCellEditor] The
default editor for all cell instances of this class. This value must be a
class, it will be automatically instantiated upon entering edit mode.
See Backgrid.CellEditor
*/
editor: InputCellEditor,
/** @property */
events: {
"click": "enterEditMode"
},
/**
Initializer.
@param {Object} options
@param {Backbone.Model} options.model
@param {Backgrid.Column} options.column
@throws {ReferenceError} If formatter is a string but a formatter class of
said name cannot be found in the Backgrid module.
*/
initialize: function (options) {
requireOptions(options, ["model", "column"]);
this.column = options.column;
if (!(this.column instanceof Column)) {
this.column = new Column(this.column);
}
this.formatter = resolveNameToClass(this.formatter, "Formatter");
this.editor = resolveNameToClass(this.editor, "CellEditor");
this.listenTo(this.model, "change:" + this.column.get("name"), function () {
if (!this.$el.hasClass("editor")) this.render();
});
},
/**
Render a text string in a table cell. The text is converted from the
model's raw value for this cell's column.
*/
render: function () {
this.$el.empty().text(this.formatter.fromRaw(this.model.get(this.column.get("name"))));
return this;
},
/**
If this column is editable, a new CellEditor instance is instantiated with
its required parameters and listens on the editor's `done` and `error`
events. When the editor is `done`, edit mode is exited. When the editor
triggers an `error` event, it means the editor is unable to convert the
current user input to an apprpriate value for the model's column. An
`editor` CSS class is added to the cell upon entering edit mode.
*/
enterEditMode: function (e) {
if (this.column.get("editable")) {
this.currentEditor = new this.editor({
parent: this,
column: this.column,
model: this.model,
formatter: this.formatter
});
/**
Backbone Event. Fired when a cell is entering edit mode and an editor
instance has been constructed, but before it is rendered and inserted
into the DOM.
@event edit
@param {Backgrid.Cell} cell This cell instance.
@param {Backgrid.CellEditor} editor The cell editor constructed.
*/
this.trigger("edit", this, this.currentEditor);
this.listenTo(this.currentEditor, "done", this.exitEditMode);
this.listenTo(this.currentEditor, "error", this.renderError);
this.$el.empty();
this.undelegateEvents();
this.$el.append(this.currentEditor.$el);
this.currentEditor.render();
this.$el.addClass("editor");
/**
Backbone Event. Fired when a cell has finished switching to edit mode.
@event editing
@param {Backgrid.Cell} cell This cell instance.
@param {Backgrid.CellEditor} editor The cell editor constructed.
*/
this.trigger("editing", this, this.currentEditor);
}
},
/**
Put an `error` CSS class on the table cell.
*/
renderError: function () {
this.$el.addClass("error");
},
/**
Removes the editor and re-render in display mode.
*/
exitEditMode: function () {
this.$el.removeClass("error");
this.currentEditor.off(null, null, this);
this.currentEditor.remove();
delete this.currentEditor;
this.$el.removeClass("editor");
this.render();
this.delegateEvents();
},
/**
Clean up this cell.
@chainable
*/
remove: function () {
if (this.currentEditor) {
this.currentEditor.remove.apply(this, arguments);
delete this.currentEditor;
}
return Backbone.View.prototype.remove.apply(this, arguments);
}
});
/**
StringCell displays HTML escaped strings and accepts anything typed in.
@class Backgrid.StringCell
@extends Backgrid.Cell
*/
var StringCell = Backgrid.StringCell = Cell.extend({
/** @property */
className: "string-cell"
// No formatter needed. Strings call auto-escaped by jQuery on insertion.
});
/**
UriCell renders an HTML `<a>` anchor for the value and accepts URIs as user
input values. A URI input is URI encoded using `encodeURI()` before writing
to the underlying model.
@class Backgrid.UriCell
@extends Backgrid.Cell
*/
var UriCell = Backgrid.UriCell = Cell.extend({
/** @property */
className: "uri-cell",
formatter: {
fromRaw: function (rawData) {
return rawData;
},
toRaw: function (formattedData) {
var result = encodeURI(formattedData);
return result === "undefined" ? undefined : result;
}
},
render: function () {
this.$el.empty();
var formattedValue = this.formatter.fromRaw(this.model.get(this.column.get("name")));
this.$el.append($("<a>", {
href: formattedValue,
title: formattedValue,
target: "_blank"
}).text(formattedValue));
return this;
}
});
/**
Like Backgrid.UriCell, EmailCell renders an HTML `<a>` anchor for the
value. The `href` in the anchor is prefixed with `mailto:`. EmailCell will
complain if the user enters a string that doesn't contain the `@` sign.
@class Backgrid.EmailCell
@extends Backgrid.Cell
*/
var EmailCell = Backgrid.EmailCell = Cell.extend({
/** @property */
className: "email-cell",
formatter: {
fromRaw: function (rawData) {
return rawData;
},
toRaw: function (formattedData) {
var parts = formattedData.split("@");
if (parts.length === 2 && _.all(parts)) {
return formattedData;
}
}
},
render: function () {
this.$el.empty();
var formattedValue = this.formatter.fromRaw(this.model.get(this.column.get("name")));
this.$el.append($("<a>", {
href: "mailto:" + formattedValue,
title: formattedValue
}).text(formattedValue));
return this;
}
});
/**
NumberCell is a generic cell that renders all numbers. Numbers are formatted
using a Backgrid.NumberFormatter.
@class Backgrid.NumberCell
@extends Backgrid.Cell
*/
var NumberCell = Backgrid.NumberCell = Cell.extend({
/** @property */
className: "number-cell",
/**
@property {number} [decimals=2] Must be an integer.
*/
decimals: NumberFormatter.prototype.defaults.decimals,
/** @property {string} [decimalSeparator='.'] */
decimalSeparator: NumberFormatter.prototype.defaults.decimalSeparator,
/** @property {string} [orderSeparator=','] */
orderSeparator: NumberFormatter.prototype.defaults.orderSeparator,
/** @property {Backgrid.CellFormatter} [formatter=Backgrid.NumberFormatter] */
formatter: NumberFormatter,
/**
Initializes this cell and the number formatter.
@param {Object} options
@param {Backbone.Model} options.model
@param {Backgrid.Column} options.column
*/
initialize: function (options) {
Cell.prototype.initialize.apply(this, arguments);
this.formatter = new this.formatter({
decimals: this.decimals,
decimalSeparator: this.decimalSeparator,
orderSeparator: this.orderSeparator
});
}
});
/**
An IntegerCell is just a Backgrid.NumberCell with 0 decimals. If a floating point
number is supplied, the number is simply rounded the usual way when
displayed.
@class Backgrid.IntegerCell
@extends Backgrid.NumberCell
*/
var IntegerCell = Backgrid.IntegerCell = NumberCell.extend({
/** @property */
className: "integer-cell",
/**
@property {number} decimals Must be an integer.
*/
decimals: 0
});
/**
DatetimeCell is a basic cell that accepts datetime string values in RFC-2822
or W3C's subset of ISO-8601 and displays them in ISO-8601 format. For a much
more sophisticated date time cell with better datetime formatting, take a
look at the Backgrid.Extension.MomentCell extension.
@class Backgrid.DatetimeCell
@extends Backgrid.Cell
See:
- Backgrid.Extension.MomentCell
- Backgrid.DatetimeFormatter
*/
var DatetimeCell = Backgrid.DatetimeCell = Cell.extend({
/** @property */
className: "datetime-cell",
/**
@property {boolean} [includeDate=true]
*/
includeDate: DatetimeFormatter.prototype.defaults.includeDate,
/**
@property {boolean} [includeTime=true]
*/
includeTime: DatetimeFormatter.prototype.defaults.includeTime,
/**
@property {boolean} [includeMilli=false]
*/
includeMilli: DatetimeFormatter.prototype.defaults.includeMilli,
/** @property {Backgrid.CellFormatter} [formatter=Backgrid.DatetimeFormatter] */
formatter: DatetimeFormatter,
/**
Initializes this cell and the datetime formatter.
@param {Object} options
@param {Backbone.Model} options.model
@param {Backgrid.Column} options.column
*/
initialize: function (options) {
Cell.prototype.initialize.apply(this, arguments);
this.formatter = new this.formatter({
includeDate: this.includeDate,
includeTime: this.includeTime,
includeMilli: this.includeMilli
});
var placeholder = this.includeDate ? "YYYY-MM-DD" : "";
placeholder += (this.includeDate && this.includeTime) ? "T" : "";
placeholder += this.includeTime ? "HH:mm:ss" : "";
placeholder += (this.includeTime && this.includeMilli) ? ".SSS" : "";
this.editor = this.editor.extend({
attributes: _.extend({}, this.editor.prototype.attributes, this.editor.attributes, {
placeholder: placeholder
})
});
}
});
/**
DateCell is a Backgrid.DatetimeCell without the time part.
@class Backgrid.DateCell
@extends Backgrid.DatetimeCell
*/
var DateCell = Backgrid.DateCell = DatetimeCell.extend({
/** @property */
className: "date-cell",
/** @property */
includeTime: false
});
/**
TimeCell is a Backgrid.DatetimeCell without the date part.
@class Backgrid.TimeCell
@extends Backgrid.DatetimeCell
*/
var TimeCell = Backgrid.TimeCell = DatetimeCell.extend({
/** @property */
className: "time-cell",
/** @property */
includeDate: false
});
/**
BooleanCell is a different kind of cell in that there's no difference between
display mode and edit mode and this cell type always renders a checkbox for
selection.
@class Backgrid.BooleanCell
@extends Backgrid.Cell
*/
var BooleanCell = Backgrid.BooleanCell = Cell.extend({
/** @property */
className: "boolean-cell",
/**
BooleanCell simple uses a default HTML checkbox template instead of a
CellEditor instance.
@property {function(Object, ?Object=): string} editor The Underscore.js template to
render the editor.
*/
editor: _.template("<input type='checkbox'<%= checked ? checked='checked' : '' %> />'"),
/**
Since the editor is not an instance of a CellEditor subclass, more things
need to be done in BooleanCell class to listen to editor mode events.
*/
events: {
"click": "enterEditMode",
"blur input[type=checkbox]": "exitEditMode",
"change input[type=checkbox]": "save"
},
/**
Renders a checkbox and check it if the model value of this column is true,
uncheck otherwise.
*/
render: function () {
this.$el.empty();
this.currentEditor = $(this.editor({
checked: this.formatter.fromRaw(this.model.get(this.column.get("name")))
}));
this.$el.append(this.currentEditor);
return this;
},
/**
Simple focuses the checkbox and add an `editor` CSS class to the cell.
*/
enterEditMode: function (e) {
this.$el.addClass("editor");
this.currentEditor.focus();
},
/**
Removed the `editor` CSS class from the cell.
*/
exitEditMode: function (e) {
this.$el.removeClass("editor");
},
/**
Set true to the model attribute if the checkbox is checked, false
otherwise.
*/
save: function (e) {
var val = this.formatter.toRaw(this.currentEditor.prop("checked"));
this.model.set(this.column.get("name"), val);
}
});
/**
SelectCellEditor renders an HTML `<select>` fragment as the editor.
@class Backgrid.SelectCellEditor
@extends Backgrid.CellEditor
*/
var SelectCellEditor = Backgrid.SelectCellEditor = CellEditor.extend({
/** @property */
tagName: "select",
/** @property */
events: {
"change": "save",
"blur": "save"
},
/** @property {function(Object, ?Object=): string} template */
template: _.template('<option value="<%- value %>" <%= selected ? \'selected="selected"\' : "" %>><%- text %></option>'),
setOptionValues: function (optionValues) {
this.optionValues = optionValues;
},
_renderOptions: function (nvps, currentValue) {
var options = '';
for (var i = 0; i < nvps.length; i++) {
options = options + this.template({
text: nvps[i][0],
value: nvps[i][1],
selected: currentValue == nvps[i][1]
});
}
return options;
},
/**
Renders the options if `optionValues` is a list of name-value pairs. The
options are contained inside option groups if `optionValues` is a list of
object hashes. The name is rendered at the option text and the value is the
option value. If `optionValues` is a function, it is called without a
parameter.
*/
render: function () {
this.$el.empty();
var optionValues = _.result(this, "optionValues");
var currentValue = this.model.get(this.column.get("name"));
if (!_.isArray(optionValues)) throw TypeError("optionValues must be an array");
var optionValue = null;
var optionText = null;
var optionValue = null;
var optgroupName = null;
var optgroup = null;
for (var i = 0; i < optionValues.length; i++) {
var optionValue = optionValues[i];
if (_.isArray(optionValue)) {
optionText = optionValue[0];
optionValue = optionValue[1];
this.$el.append(this.template({
text: optionText,
value: optionValue,
selected: optionValue == currentValue
}));
}
else if (_.isObject(optionValue)) {
optgroupName = optionValue.name;
optgroup = $("<optgroup></optgroup>", { label: optgroupName });
optgroup.append(this._renderOptions(optionValue.values, currentValue));
this.$el.append(optgroup);
}
else {
throw TypeError("optionValues elements must be a name-value pair or an object hash of { name: 'optgroup label', value: [option name-value pairs] }");
}
}
return this;
},
/**
Saves the value of the selected option to the model attribute. Triggers a
`done` Backbone event.
*/
save: function (e) {
this.model.set(this.column.get("name"), this.formatter.toRaw(this.$el.val()));
this.trigger("done");
}
});
/**
SelectCell is also a different kind of cell in that upon going into edit mode
the cell renders a list of options for to pick from, as opposed to an input
box.
SelectCell cannot be referenced by its string name when used in a column
definition because requires an `optionValues` class attribute to be
defined. `optionValues` can either be a list of name-value pairs, to be
rendered as options, or a list of object hashes which consist of a key *name*
which is the option group name, and a key *values* which is a list of
name-value pairs to be rendered as options under that option group.
In addition, `optionValues` can also be a parameter-less function that
returns one of the above. If the options are static, it is recommended the
returned values to be memoized. _.memoize() is a good function to help with
that.
@class Backgrid.SelectCell
@extends Backgrid.Cell
*/
var SelectCell = Backgrid.SelectCell = Cell.extend({
/** @property */
className: "select-cell",
/** @property */
editor: SelectCellEditor,
/**
@property {Array.<Array>|Array.<{name: string, values: Array.<Array>}>} optionValues
*/
optionValues: undefined,
/**
Initializer.
@param {Object} options
@param {Backbone.Model} options.model
@param {Backgrid.Column} options.column
@throws {TypeError} If `optionsValues` is undefined.
*/
initialize: function (options) {
Cell.prototype.initialize.apply(this, arguments);
requireOptions(this, ["optionValues"]);
this.optionValues = _.result(this, "optionValues");
this.listenTo(this, "edit", this.setOptionValues);
},
setOptionValues: function (cell, editor) {
editor.setOptionValues(this.optionValues);
},
/**
Renders the label using the raw value as key to look up from `optionValues`.
@throws {TypeError} If `optionValues` is malformed.
*/
render: function () {
this.$el.empty();
var optionValues = this.optionValues;
var rawData = this.formatter.fromRaw(this.model.get(this.column.get("name")));
try {
if (!_.isArray(optionValues) || _.isEmpty(optionValues)) throw new TypeError;
for (var i = 0; i < optionValues.length; i++) {
var optionValue = optionValues[i];
if (_.isArray(optionValue)) {
var optionText = optionValue[0];
var optionValue = optionValue[1];
if (optionValue == rawData) {
this.$el.append(optionText);
break;
}
}
else if (_.isObject(optionValue)) {
var optionGroupValues = optionValue.values;
for (var j = 0; j < optionGroupValues.length; j++) {
var optionGroupValue = optionGroupValues[j];
if (optionGroupValue[1] == rawData) {
this.$el.append(optionGroupValue[0]);
break;
}
}
}
else {
throw new TypeError;
}
}
}
catch (ex) {
if (ex instanceof TypeError) {
throw TypeError("'optionValues' must be of type {Array.<Array>|Array.<{name: string, values: Array.<Array>}>}");
}
throw ex;
}
return this;
}
});
/*
backgrid
http://github.com/wyuenho/backgrid
Copyright (c) 2013 Jimmy Yuen Ho Wong
Licensed under the MIT @license.
*/
/**
A Column is a placeholder for column metadata.
You usually don't need to create an instance of this class yourself as a
collection of column instances will be created for you from a list of column
attributes in the Backgrid.js view class constructors.
@class Backgrid.Column
@extends Backbone.Model
*/
var Column = Backgrid.Column = Backbone.Model.extend({
defaults: {
name: undefined,
label: undefined,
sortable: true,
editable: true,
renderable: true,
formatter: undefined,
cell: undefined,
headerCell: undefined
},
/**
Initializes this Column instance.
@param {Object} attrs Column attributes.
@param {string} attrs.name The name of the model attribute.
@param {string|Backgrid.Cell} attrs.cell The cell type.
If this is a string, the capitalized form will be used to look up a
cell class in Backbone, i.e.: string => StringCell. If a Cell subclass
is supplied, it is initialized with a hash of parameters. If a Cell
instance is supplied, it is used directly.
@param {string|Backgrid.HeaderCell} [attrs.headerCell] The header cell type.
@param {string} [attrs.label] The label to show in the header.
@param {boolean} [attrs.sortable=true]
@param {boolean} [attrs.editable=true]
@param {boolean} [attrs.renderable=true]
@param {Backgrid.CellFormatter|Object|string} [attrs.formatter] The
formatter to use to convert between raw model values and user input.
@throws {TypeError} If attrs.cell or attrs.options are not supplied.
@throws {ReferenceError} If attrs.cell is a string but a cell class of
said name cannot be found in the Backgrid module.
See:
- Backgrid.Cell
- Backgrid.CellFormatter
*/
initialize: function (attrs) {
requireOptions(attrs, ["cell", "name"]);
if (!this.has("label")) {
this.set({ label: this.get("name") }, { silent: true });
}
var cell = resolveNameToClass(this.get("cell"), "Cell");
this.set({ cell: cell }, { silent: true });
}
});
/**
A Backbone collection of Column instances.
@class Backgrid.Columns
@extends Backbone.Collection
*/
var Columns = Backgrid.Columns = Backbone.Collection.extend({
/**
@property {Backgrid.Column} model
*/
model: Column
});
/*
backgrid
http://github.com/wyuenho/backgrid
Copyright (c) 2013 Jimmy Yuen Ho Wong
Licensed under the MIT @license.
*/
/**
Row is a simple container view that takes a model instance and a list of
column metadata describing how each of the model's attribute is to be
rendered, and apply the appropriate cell to each attribute.
@class Backgrid.Row
@extends Backbone.View
*/
var Row = Backgrid.Row = Backbone.View.extend({
/** @property */
tagName: "tr",
/**
Initializes a row view instance.
@param {Object} options
@param {Backbone.Collection.<Backgrid.Column>|Array.<Backgrid.Column>|Array.<Object>} options.columns Column metadata.
@param {Backbone.Model} options.model The model instance to render.
@throws {TypeError} If options.columns or options.model is undefined.
*/
initialize: function (options) {
requireOptions(options, ["columns", "model"]);
var columns = this.columns = options.columns;
if (!(columns instanceof Backbone.Collection)) {
columns = this.columns = new Columns(columns);
}
this.listenTo(columns, "change:renderable", this.renderColumn);
var cells = this.cells = [];
for (var i = 0; i < columns.length; i++) {
var column = columns.at(i);
cells.push(new (column.get("cell"))({
column: column,
model: this.model
}));
}
this.listenTo(columns, "add", function (column, columns, options) {
options = _.defaults(options || {}, {render: true});
var at = columns.indexOf(column);
var cell = new (column.get("cell"))({
column: column,
model: this.model
});
cells.splice(at, 0, cell);
this.renderColumn(column, column.get("renderable") && options.render);
});
this.listenTo(columns, "remove", function (column) {
this.renderColumn(column, false);
});
},
/**
Backbone event handler. Insert a table cell to the right column in the row
if renderable is true, detach otherwise.
@param {Backgrid.Column} column
@param {boolean} renderable
*/
renderColumn: function (column, renderable) {
var cells = this.cells;
var columns = this.columns;
var spliceIndex = -1;
for (var i = 0; i < cells.length; i++) {
var cell = cells[i];
if (cell.column.get("name") == column.get("name")) {
spliceIndex = i;
break;
}
}
if (spliceIndex != -1) {
var $el = this.$el;
if (renderable) {
var cell = cells[spliceIndex];
if (spliceIndex === 0) {
$el.prepend(cell.render().$el);
}
else if (spliceIndex === columns.length - 1) {
$el.append(cell.render().$el);
}
else {
$el.children().eq(spliceIndex).before(cell.render().$el);
}
}
else {
$el.children().eq(spliceIndex).detach();
}
}
},
/**
Renders a row of cells for this row's model.
*/
render: function () {
this.$el.empty();
var fragment = document.createDocumentFragment();
for (var i = 0; i < this.cells.length; i++) {
var cell = this.cells[i];
if (cell.column.get("renderable")) {
fragment.appendChild(cell.render().el);
}
}
this.el.appendChild(fragment);
return this;
},
/**
Clean up this row and its cells.
@chainable
*/
remove: function () {
for (var i = 0; i < this.cells.length; i++) {
var cell = this.cells[i];
cell.remove.apply(cell, arguments);
}
return Backbone.View.prototype.remove.apply(this, arguments);
}
});
/*
backgrid
http://github.com/wyuenho/backgrid
Copyright (c) 2013 Jimmy Yuen Ho Wong
Licensed under the MIT @license.
*/
/**
HeaderCell is a special cell class that renders a column header cell. If the
column is sortable, a sorter is also rendered and will trigger a table
refresh after sorting.
@class Backgrid.HeaderCell
@extends Backbone.View
*/
var HeaderCell = Backgrid.HeaderCell = Backbone.View.extend({
/** @property */
tagName: "th",
/** @property */
events: {
"click a": "onClick"
},
/**
@property {null|"ascending"|"descending"} _direction The current sorting
direction of this column.
*/
_direction: null,
/**
Initializer.
@param {Object} options
@param {Backgrid.Column|Object} options.column
@throws {TypeError} If options.column or options.collection is undefined.
*/
initialize: function (options) {
requireOptions(options, ["column", "collection"]);
this.column = options.column;
if (!(this.column instanceof Column)) {
this.column = new Column(this.column);
}
this.listenTo(Backbone, "backgrid:sort", this._resetCellDirection);
},
/**
Gets or sets the direction of this cell. If called directly without
parameters, returns the current direction of this cell, otherwise sets
it. If a `null` is given, sets this cell back to the default order.
@param {null|"ascending"|"descending"} dir
@return {null|string} The current direction or the changed direction.
*/
direction: function (dir) {
if (arguments.length) {
if (this._direction) this.$el.removeClass(this._direction);
if (dir) this.$el.addClass(dir);
this._direction = dir;
}
return this._direction;
},
/**
Event handler for the Backbone `backgrid:sort` event. Resets this cell's
direction to default if sorting is being done on another column.
@private
*/
_resetCellDirection: function (sortByColName, direction, comparator, collection) {
if (collection == this.collection) {
if (sortByColName !== this.column.get("name")) this.direction(null);
else this.direction(direction);
}
},
/**
Event handler for the `click` event on the cell's anchor. If the column is
sortable, clicking on the anchor will cycle through 3 sorting orderings -
`ascending`, `descending`, and default.
*/
onClick: function (e) {
e.preventDefault();
var columnName = this.column.get("name");
if (this.column.get("sortable")) {
if (this.direction() === "ascending") {
this.sort(columnName, "descending", function (left, right) {
var leftVal = left.get(columnName);
var rightVal = right.get(columnName);
if (leftVal === rightVal) {
return 0;
}
else if (leftVal > rightVal) { return -1; }
return 1;
});
}
else if (this.direction() === "descending") {
this.sort(columnName, null);
}
else {
this.sort(columnName, "ascending", function (left, right) {
var leftVal = left.get(columnName);
var rightVal = right.get(columnName);
if (leftVal === rightVal) {
return 0;
}
else if (leftVal < rightVal) { return -1; }
return 1;
});
}
}
},
/**
If the underlying collection is a Backbone.PageableCollection in
server-mode or infinite-mode, a page of models is fetched after sorting is
done on the server.
If the underlying collection is a Backbone.PageableCollection in
client-mode, or any
[Backbone.Collection](http://backbonejs.org/#Collection) instance, sorting
is done on the client side. If the collection is an instance of a
Backbone.PageableCollection, sorting will be done globally on all the pages
and the current page will then be returned.
Triggers a Backbone `backgrid:sort` event when done.
@param {string} columnName
@param {null|"ascending"|"descending"} direction
@param {function(*, *): number} [comparator]
See [Backbone.Collection#comparator](http://backbonejs.org/#Collection-comparator)
*/
sort: function (columnName, direction, comparator) {
comparator = comparator || this._cidComparator;
var collection = this.collection;
if (Backbone.PageableCollection && collection instanceof Backbone.PageableCollection) {
var order;
if (direction === "ascending") order = -1;
else if (direction === "descending") order = 1;
else order = null;
collection.setSorting(order ? columnName : null, order);
if (collection.mode == "client") {
if (!collection.fullCollection.comparator) {
collection.fullCollection.comparator = comparator;
}
collection.fullCollection.sort();
}
else collection.fetch();
}
else {
collection.comparator = comparator;
collection.sort();
}
/**
Global Backbone event. Fired when the sorter is clicked on a sortable
column.
@event backgrid:sort
@param {string} columnName
@param {null|"ascending"|"descending"} direction
@param {function(*, *): number} comparator A Backbone.Collection#comparator.
@param {Backbone.Collection} collection
*/
Backbone.trigger("backgrid:sort", columnName, direction, comparator, this.collection);
},
/**
Default comparator for Backbone.Collections. Sorts cids in ascending
order. The cids of the models are assumed to be in insertion order.
@private
@param {*} left
@param {*} right
*/
_cidComparator: function (left, right) {
var lcid = left.cid, rcid = right.cid;
if (!_.isUndefined(lcid) && !_.isUndefined(rcid)) {
lcid = lcid.slice(1) * 1, rcid = rcid.slice(1) * 1;
if (lcid < rcid) return -1;
else if (lcid > rcid) return 1;
}
return 0;
},
/**
Renders a header cell with a sorter and a label.
*/
render: function () {
this.$el.empty();
var $label = $("<a>").text(this.column.get("label")).append("<b class='sort-caret'></b>");
this.$el.append($label);
return this;
}
});
/**
HeaderRow is a controller for a row of header cells.
@class Backgrid.HeaderRow
@extends Backgrid.Row
*/
var HeaderRow = Backgrid.HeaderRow = Backgrid.Row.extend({
/**
Initializer.
@param {Object} options
@param {Backbone.Collection.<Backgrid.Column>|Array.<Backgrid.Column>|Array.<Object>} options.columns
@param {Backgrid.HeaderCell} [options.headerCell] Customized default
HeaderCell for all the columns. Supply a HeaderCell class or instance to a
the `headerCell` key in a column definition for column-specific header
rendering.
@throws {TypeError} If options.columns or options.collection is undefined.
*/
initialize: function (options) {
requireOptions(options, ["columns", "collection"]);
var columns = this.columns = options.columns;
if (!(columns instanceof Backbone.Collection)) {
columns = this.columns = new Columns(columns);
}
this.listenTo(columns, "change:renderable", this.renderColumn);
var cells = this.cells = [];
for (var i = 0; i < columns.length; i++) {
var column = columns.at(i);
var headerCell = column.get("headerCell") || options.headerCell || HeaderCell;
cells.push(new headerCell({
column: column,
collection: this.collection
}));
}
this.listenTo(columns, "add", function (column, columns, opts) {
opts = _.defaults(opts || {}, {render: true});
var at = columns.indexOf(column);
var headerCell = column.get("headerCell") || options.headerCell || HeaderCell;
headerCell = new headerCell({
column: column,
collection: this.collection
});
cells.splice(at, 0, headerCell);
this.renderColumn(column, column.get("renderable") && opts.render);
});
this.listenTo(columns, "remove", function (column) {
this.renderColumn(column, false);
});
}
});
/**
Header is a special structural view class that renders a table head with a
single row of header cells.
@class Backgrid.Header
@extends Backbone.View
*/
var Header = Backgrid.Header = Backbone.View.extend({
/** @property */
tagName: "thead",
/**
Initializer. Initializes this table head view to contain a single header
row view.
@param {Object} options
@param {Backbone.Collection.<Backgrid.Column>|Array.<Backgrid.Column>|Array.<Object>} options.columns Column metadata.
@param {Backbone.Model} options.model The model instance to render.
@throws {TypeError} If options.columns or options.model is undefined.
*/
initialize: function (options) {
requireOptions(options, ["columns", "collection"]);
this.columns = options.columns;
if (!(this.columns instanceof Backbone.Collection)) {
this.columns = new Columns(this.columns);
}
this.row = new Backgrid.HeaderRow({
columns: this.columns,
collection: this.collection
});
},
/**
Renders this table head with a single row of header cells.
*/
render: function () {
this.$el.append(this.row.render().$el);
return this;
},
/**
Clean up this header and its row.
@chainable
*/
remove: function () {
this.row.remove.apply(this.row, arguments);
return Backbone.View.prototype.remove.apply(this, arguments);
}
});
/*
backgrid
http://github.com/wyuenho/backgrid
Copyright (c) 2013 Jimmy Yuen Ho Wong
Licensed under the MIT @license.
*/
/**
Body is the table body which contains the rows inside a table. Body is
responsible for refreshing the rows after sorting, insertion and removal.
@class Backgrid.Body
@extends Backbone.View
*/
var Body = Backgrid.Body = Backbone.View.extend({
/** @property */
tagName: "tbody",
/**
Initializer.
@param {Object} options
@param {Backbone.Collection} options.collection
@param {Backbone.Collection.<Backgrid.Column>|Array.<Backgrid.Column>|Array.<Object>} options.columns
Column metadata
@param {Backgrid.Row} [options.row=Backgrid.Row] The Row class to use.
@throws {TypeError} If options.columns or options.collection is undefined.
See Backgrid.Row.
*/
initialize: function (options) {
requireOptions(options, ["columns", "collection"]);
this.columns = options.columns;
if (!(this.columns instanceof Backbone.Collection)) {
this.columns = new Columns(this.columns);
}
this.row = options.row || Row;
this.rows = this.collection.map(function (model) {
var row = new this.row({
columns: this.columns,
model: model
});
return row;
}, this);
var collection = this.collection;
this.listenTo(collection, "add", this.insertRow);
this.listenTo(collection, "remove", this.removeRow);
this.listenTo(collection, "sort", this.refresh);
this.listenTo(collection, "reset", this.refresh);
},
/**
This method can be called either directly or as a callback to a
[Backbone.Collecton#add](http://backbonejs.org/#Collection-add) event.
When called directly, it accepts a model or an array of models and an
option hash just like
[Backbone.Collection#add](http://backbonejs.org/#Collection-add) and
delegates to it. Once the model is added, a new row is inserted into the
body and automatically rendered.
When called as a callback of an `add` event, splices a new row into the
body and renders it.
@param {Backbone.Model} model The model to render as a row.
@param {Backbone.Collection} collection When called directly, this
parameter is actually the options to
[Backbone.Collection#add](http://backbonejs.org/#Collection-add).
@param {Object} options When called directly, this must be null.
See:
- [Backbone.Collection#add](http://backbonejs.org/#Collection-add)
*/
insertRow: function (model, collection, options) {
// insertRow() is called directly
if (!(collection instanceof Backbone.Collection) && !options) {
this.collection.add(model, (options = collection));
return;
}
options = _.extend({render: true}, options || {});
var row = new this.row({
columns: this.columns,
model: model
});
var index = collection.indexOf(model);
this.rows.splice(index, 0, row);
var $el = this.$el;
var $children = $el.children();
var $rowEl = row.render().$el;
if (options.render) {
if (index >= $children.length) {
$el.append($rowEl);
}
else {
$children.eq(index).before($rowEl);
}
}
},
/**
The method can be called either directly or as a callback to a
[Backbone.Collection#remove](http://backbonejs.org/#Collection-remove)
event.
When called directly, it accepts a model or an array of models and an
option hash just like
[Backbone.Collection#remove](http://backbonejs.org/#Collection-remove) and
delegates to it. Once the model is removed, a corresponding row is removed
from the body.
When called as a callback of a `remove` event, splices into the rows and
removes the row responsible for rendering the model.
@param {Backbone.Model} model The model to remove from the body.
@param {Backbone.Collection} collection When called directly, this
parameter is actually the options to
[Backbone.Collection#remove](http://backbonejs.org/#Collection-remove).
@param {Object} options When called directly, this must be null.
See:
- [Backbone.Collection#remove](http://backbonejs.org/#Collection-remove)
*/
removeRow: function (model, collection, options) {
// removeRow() is called directly
if (!options) {
this.collection.remove(model, (options = collection));
return;
}
if (_.isUndefined(options.render) || options.render) {
this.rows[options.index].remove();
}
this.rows.splice(options.index, 1);
},
/**
Reinitialize all the rows inside the body and re-render them.
@chainable
*/
refresh: function () {
var self = this;
_.each(self.rows, function (row) {
row.remove();
});
self.rows = self.collection.map(function (model) {
var row = new self.row({
columns: self.columns,
model: model
});
return row;
});
self.render();
Backbone.trigger("backgrid:refresh");
return self;
},
/**
Renders all the rows inside this body.
*/
render: function () {
this.$el.empty();
var fragment = document.createDocumentFragment();
for (var i = 0; i < this.rows.length; i++) {
var row = this.rows[i];
fragment.appendChild(row.render().el);
}
this.el.appendChild(fragment);
return this;
},
/**
Clean up this body and it's rows.
@chainable
*/
remove: function () {
for (var i = 0; i < this.rows.length; i++) {
var row = this.rows[i];
row.remove.apply(row, arguments);
}
return Backbone.View.prototype.remove.apply(this, arguments);
}
});
/*
backgrid
http://github.com/wyuenho/backgrid
Copyright (c) 2013 Jimmy Yuen Ho Wong
Licensed under the MIT @license.
*/
/**
A Footer is a generic class that only defines a default tag `tfoot` and
number of required parameters in the initializer.
@abstract
@class Backgrid.Footer
@extends Backbone.View
*/
var Footer = Backgrid.Footer = Backbone.View.extend({
/** @property */
tagName: "tfoot",
/**
Initializer.
@param {Object} options
@param {*} options.parent The parent view class of this footer.
@param {Backbone.Collection.<Backgrid.Column>|Array.<Backgrid.Column>|Array.<Object>} options.columns
Column metadata.
@param {Backbone.Collection} options.collection
@throws {TypeError} If options.columns or options.collection is undefined.
*/
initialize: function (options) {
requireOptions(options, ["columns", "collection"]);
this.parent = options.parent;
this.columns = options.columns;
if (!(this.columns instanceof Backbone.Collection)) {
this.columns = new Backgrid.Columns(this.columns);
}
}
});
/*
backgrid
http://github.com/wyuenho/backgrid
Copyright (c) 2013 Jimmy Yuen Ho Wong
Licensed under the MIT @license.
*/
/**
Grid represents a data grid that has a header, body and an optional footer.
By default, a Grid treats each model in a collection as a row, and each
attribute in a model as a column. To render a grid you must provide a list of
column metadata and a collection to the Grid constructor. Just like any
Backbone.View class, the grid is rendered as a DOM node fragment when you
call render().
var grid = Backgrid.Grid({
columns: [{ name: "id", label: "ID", type: "string" },
// ...
],
collections: books
});
$("#table-container").append(grid.render().el);
Optionally, if you want to customize the rendering of the grid's header and
footer, you may choose to extend Backgrid.Header and Backgrid.Footer, and
then supply that class or an instance of that class to the Grid constructor.
See the documentation for Header and Footer for further details.
var grid = Backgrid.Grid({
columns: [{ name: "id", label: "ID", type: "string" }],
collections: books,
header: Backgrid.Header.extend({
//...
}),
footer: Backgrid.Paginator
});
Finally, if you want to override how the rows are rendered in the table body,
you can supply a Body subclass as the `body` attribute that uses a different
Row class.
@class Backgrid.Grid
@extends Backbone.View
See:
- Backgrid.Column
- Backgrid.Header
- Backgrid.Body
- Backgrid.Row
- Backgrid.Footer
*/
var Grid = Backgrid.Grid = Backbone.View.extend({
/** @property */
tagName: "table",
/** @property */
className: "backgrid",
/** @property */
header: Header,
/** @property */
body: Body,
/** @property */
footer: null,
/**
Initializes a Grid instance.
@param {Object} options
@param {Backbone.Collection.<Backgrid.Column>|Array.<Backgrid.Column>|Array.<Object>} options.columns Column metadata.
@param {Backbone.Collection} options.collection The collection of tabular model data to display.
@param {Backgrid.Header} [options.header=Backgrid.Header] An optional Header class to override the default.
@param {Backgrid.Body} [options.body=Backgrid.Body] An optional Body class to override the default.
@param {Backgrid.Row} [options.row=Backgrid.Row] An optional Row class to override the default.
@param {Backgrid.Footer} [options.footer=Backgrid.Footer] An optional Footer class.
*/
initialize: function (options) {
requireOptions(options, ["columns", "collection"]);
// Convert the list of column objects here first so the subviews don't have
// to.
if (!(options.columns instanceof Backbone.Collection)) {
options.columns = new Columns(options.columns);
}
this.columns = options.columns;
this.header = options.header || this.header;
this.header = new this.header(options);
this.body = options.body || this.body;
this.body = new this.body(options);
this.footer = options.footer || this.footer;
if (this.footer) {
this.footer = new this.footer(options);
}
this.listenTo(this.columns, "reset", function () {
this.header = new (this.header.remove().constructor)(options);
this.body = new (this.body.remove().constructor)(options);
if (this.footer) this.footer = new (this.footer.remove().constructor)(options);
this.render();
});
},
/**
Delegates to Backgrid.Body#insertRow.
*/
insertRow: function (model, collection, options) {
return this.body.insertRow(model, collection, options);
},
/**
Delegates to Backgrid.Body#removeRow.
*/
removeRow: function (model, collection, options) {
return this.body.removeRow(model, collection, options);
},
/**
Delegates to Backgrid.Columns#add for adding a column. Subviews can listen
to the `add` event from their internal `columns` if rerendering needs to
happen.
@param {Object} [options] Options for `Backgrid.Columns#add`.
@param {boolean} [options.render=true] Whether to render the column
immediately after insertion.
@chainable
*/
insertColumn: function (column, options) {
var self = this;
options = options || {render: true};
self.columns.add(column, options);
return self;
},
/**
Delegates to Backgrid.Columns#remove for removing a column. Subviews can
listen to the `remove` event from the internal `columns` if rerendering
needs to happen.
@param {Object} [options] Options for `Backgrid.Columns#remove`.
@chainable
*/
removeColumn: function (column, options) {
var self = this;
self.columns.remove(column, options);
return self;
},
/**
Renders the grid's header, then footer, then finally the body.
*/
render: function () {
this.$el.empty();
this.$el.append(this.header.render().$el);
if (this.footer) {
this.$el.append(this.footer.render().$el);
}
this.$el.append(this.body.render().$el);
/**
Backbone event. Fired when the grid has been successfully rendered.
@event rendered
*/
this.trigger("rendered");
return this;
},
/**
Clean up this grid and its subviews.
@chainable
*/
remove: function () {
this.header.remove.apply(this.header, arguments);
this.body.remove.apply(this.body, arguments);
this.footer && this.footer.remove.apply(this.footer, arguments);
return Backbone.View.prototype.remove.apply(this, arguments);
}
});
}(this, $, _, Backbone));
| BobbieBel/cdnjs | ajax/libs/backgrid.js/0.1.3/backgrid.js | JavaScript | mit | 62,121 |
// { dg-do assemble }
// { dg-options "-pedantic -Wno-deprecated" }
// This code snippet should be rejected with -pedantic
// Based on a test case by Louidor Erez <s3824888@techst02.technion.ac.il>
template<class T>
class Vector {
public:
typedef T* iterator;
};
template<class T>
void f()
{
Vector<T>::iterator i = 0; // { dg-error "typename" "typename" } missing typename
} // { dg-error "expected" "expected" { target *-*-* } 16 }
| selmentdev/selment-toolchain | source/gcc-latest/gcc/testsuite/g++.old-deja/g++.other/typename1.C | C++ | gpl-3.0 | 442 |
// 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.
// catch ret inside try region
// note: this is NOT the test case
// after vswhidbey:5875 is fixed, intry will be outside the outer try block
using System;
namespace hello
{
class Class1
{
private static TestUtil.TestLog testLog;
static Class1()
{
// Create test writer object to hold expected output
System.IO.StringWriter expectedOut = new System.IO.StringWriter();
// Write expected output to string writer object
expectedOut.WriteLine("1234");
expectedOut.WriteLine("test2");
expectedOut.WriteLine("end outer catch test2");
expectedOut.WriteLine("1234");
// Create and initialize test log object
testLog = new TestUtil.TestLog(expectedOut);
}
static public int Main(string[] args)
{
//Start recording
testLog.StartRecording();
int i = 1234;
Console.WriteLine(i);
goto begin2;
begin:
String s = "test1";
begin2:
s = "test2";
intry:
try
{
Console.WriteLine(s);
throw new Exception();
}
catch
{
try
{
if (i == 3) goto intry; // catch ret
if (i >= 0) goto incatch;
if (i < 0) goto begin; // catch ret
}
catch
{
if (i != 0) goto incatch;
Console.WriteLine("end inner catch");
}
Console.WriteLine("unreached");
incatch:
Console.WriteLine("end outer catch " + s);
}
Console.WriteLine(i);
// stop recoding
testLog.StopRecording();
return testLog.VerifyOutput();
}
}
}
| dpodder/coreclr | tests/src/JIT/Methodical/eh/leaves/oponerror.cs | C# | mit | 2,172 |
// 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;
using System.Runtime.CompilerServices;
public class BringUpTest
{
const int Pass = 100;
const int Fail = -1;
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static double DblAddConst(double x) { return x+1; }
public static int Main()
{
double y = DblAddConst(13d);
Console.WriteLine(y);
if (System.Math.Abs(y-14d) <= Double.Epsilon) return Pass;
else return Fail;
}
}
| Godin/coreclr | tests/src/JIT/CodeGenBringUpTests/DblAddConst.cs | C# | mit | 663 |
// 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 System;
using System.Collections.Generic;
using System.Composition;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
{
[ExportWorkspaceServiceFactory(typeof(VisualStudioRuleSetManager), ServiceLayer.Host), Shared]
internal sealed class VisualStudioRuleSetManagerFactory : IWorkspaceServiceFactory
{
private readonly IServiceProvider _serviceProvider;
private readonly IForegroundNotificationService _foregroundNotificationService;
private readonly IAsynchronousOperationListener _listener;
[ImportingConstructor]
public VisualStudioRuleSetManagerFactory(
SVsServiceProvider serviceProvider,
IForegroundNotificationService foregroundNotificationService,
[ImportMany] IEnumerable<Lazy<IAsynchronousOperationListener, FeatureMetadata>> asyncListeners)
{
_serviceProvider = serviceProvider;
_foregroundNotificationService = foregroundNotificationService;
_listener = new AggregateAsynchronousOperationListener(asyncListeners, FeatureAttribute.RuleSetEditor);
}
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
{
IVsFileChangeEx fileChangeService = (IVsFileChangeEx)_serviceProvider.GetService(typeof(SVsFileChangeEx));
return new VisualStudioRuleSetManager(fileChangeService, _foregroundNotificationService, _listener);
}
}
}
| mmitche/roslyn | src/VisualStudio/Core/Def/Implementation/ProjectSystem/RuleSets/VisualStudioRuleSetManagerFactory.cs | C# | apache-2.0 | 1,917 |
// Code generated by "stringer -type=ValueType valuetype.go"; DO NOT EDIT.
package schema
import "fmt"
const _ValueType_name = "TypeInvalidTypeBoolTypeIntTypeFloatTypeStringTypeListTypeMapTypeSettypeObject"
var _ValueType_index = [...]uint8{0, 11, 19, 26, 35, 45, 53, 60, 67, 77}
func (i ValueType) String() string {
if i < 0 || i >= ValueType(len(_ValueType_index)-1) {
return fmt.Sprintf("ValueType(%d)", i)
}
return _ValueType_name[_ValueType_index[i]:_ValueType_index[i+1]]
}
| thiagocaiubi/terraform-provider-azurerm | vendor/github.com/hashicorp/terraform/helper/schema/valuetype_string.go | GO | mpl-2.0 | 490 |
/*
Copyright 2017 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 lister-gen
package v1
import (
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/tools/cache"
api "k8s.io/kubernetes/pkg/api"
v1 "k8s.io/kubernetes/pkg/api/v1"
)
// EndpointsLister helps list Endpoints.
type EndpointsLister interface {
// List lists all Endpoints in the indexer.
List(selector labels.Selector) (ret []*v1.Endpoints, err error)
// Endpoints returns an object that can list and get Endpoints.
Endpoints(namespace string) EndpointsNamespaceLister
EndpointsListerExpansion
}
// endpointsLister implements the EndpointsLister interface.
type endpointsLister struct {
indexer cache.Indexer
}
// NewEndpointsLister returns a new EndpointsLister.
func NewEndpointsLister(indexer cache.Indexer) EndpointsLister {
return &endpointsLister{indexer: indexer}
}
// List lists all Endpoints in the indexer.
func (s *endpointsLister) List(selector labels.Selector) (ret []*v1.Endpoints, err error) {
err = cache.ListAll(s.indexer, selector, func(m interface{}) {
ret = append(ret, m.(*v1.Endpoints))
})
return ret, err
}
// Endpoints returns an object that can list and get Endpoints.
func (s *endpointsLister) Endpoints(namespace string) EndpointsNamespaceLister {
return endpointsNamespaceLister{indexer: s.indexer, namespace: namespace}
}
// EndpointsNamespaceLister helps list and get Endpoints.
type EndpointsNamespaceLister interface {
// List lists all Endpoints in the indexer for a given namespace.
List(selector labels.Selector) (ret []*v1.Endpoints, err error)
// Get retrieves the Endpoints from the indexer for a given namespace and name.
Get(name string) (*v1.Endpoints, error)
EndpointsNamespaceListerExpansion
}
// endpointsNamespaceLister implements the EndpointsNamespaceLister
// interface.
type endpointsNamespaceLister struct {
indexer cache.Indexer
namespace string
}
// List lists all Endpoints in the indexer for a given namespace.
func (s endpointsNamespaceLister) List(selector labels.Selector) (ret []*v1.Endpoints, err error) {
err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {
ret = append(ret, m.(*v1.Endpoints))
})
return ret, err
}
// Get retrieves the Endpoints from the indexer for a given namespace and name.
func (s endpointsNamespaceLister) Get(name string) (*v1.Endpoints, error) {
obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name)
if err != nil {
return nil, err
}
if !exists {
return nil, errors.NewNotFound(api.Resource("endpoints"), name)
}
return obj.(*v1.Endpoints), nil
}
| mikegrass/minikube | vendor/k8s.io/kubernetes/pkg/client/listers/core/v1/endpoints.go | GO | apache-2.0 | 3,176 |
<?php
/*
* This file is part of the Assetic package, an OpenSky project.
*
* (c) 2010-2013 OpenSky Project Inc
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Assetic\Filter;
use Assetic\Asset\AssetInterface;
use Assetic\Exception\FilterException;
/**
* Loads LESS files.
*
* @link http://lesscss.org/
* @author Kris Wallsmith <kris.wallsmith@gmail.com>
*/
class LessFilter extends BaseNodeFilter
{
private $nodeBin;
private $compress;
/**
* Load Paths
*
* A list of paths which less will search for includes.
*
* @var array
*/
protected $loadPaths = array();
/**
* Constructor.
*
* @param string $nodeBin The path to the node binary
* @param array $nodePaths An array of node paths
*/
public function __construct($nodeBin = '/usr/bin/node', array $nodePaths = array())
{
$this->nodeBin = $nodeBin;
$this->setNodePaths($nodePaths);
}
public function setCompress($compress)
{
$this->compress = $compress;
}
/**
* Adds a path where less will search for includes
*
* @param string $path Load path (absolute)
*/
public function addLoadPath($path)
{
$this->loadPaths[] = $path;
}
public function filterLoad(AssetInterface $asset)
{
static $format = <<<'EOF'
var less = require('less');
var sys = require(process.binding('natives').util ? 'util' : 'sys');
new(less.Parser)(%s).parse(%s, function(e, tree) {
if (e) {
less.writeError(e);
process.exit(2);
}
try {
sys.print(tree.toCSS(%s));
} catch (e) {
less.writeError(e);
process.exit(3);
}
});
EOF;
$root = $asset->getSourceRoot();
$path = $asset->getSourcePath();
// parser options
$parserOptions = array();
if ($root && $path) {
$parserOptions['paths'] = array(dirname($root.'/'.$path));
$parserOptions['filename'] = basename($path);
}
foreach ($this->loadPaths as $loadPath) {
$parserOptions['paths'][] = $loadPath;
}
// tree options
$treeOptions = array();
if (null !== $this->compress) {
$treeOptions['compress'] = $this->compress;
}
$pb = $this->createProcessBuilder();
$pb->inheritEnvironmentVariables();
$pb->add($this->nodeBin)->add($input = tempnam(sys_get_temp_dir(), 'assetic_less'));
file_put_contents($input, sprintf($format,
json_encode($parserOptions),
json_encode($asset->getContent()),
json_encode($treeOptions)
));
$proc = $pb->getProcess();
$code = $proc->run();
unlink($input);
if (0 !== $code) {
throw FilterException::fromProcess($proc)->setInput($asset->getContent());
}
$asset->setContent($proc->getOutput());
}
public function filterDump(AssetInterface $asset)
{
}
}
| nandy-andy/performance-blog | vendors/assetic/Assetic/Filter/LessFilter.php | PHP | gpl-2.0 | 3,106 |
/*
* Copyright (C) 2007 The Guava 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 com.google.common.collect;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nullable;
/**
* GWT emulation of {@code HashBiMap} that just delegates to two HashMaps.
*
* @author Mike Bostock
*/
public final class HashBiMap<K, V> extends AbstractBiMap<K, V> {
/**
* Returns a new, empty {@code HashBiMap} with the default initial capacity
* (16).
*/
public static <K, V> HashBiMap<K, V> create() {
return new HashBiMap<K, V>();
}
/**
* Constructs a new, empty bimap with the specified expected size.
*
* @param expectedSize the expected number of entries
* @throws IllegalArgumentException if the specified expected size is
* negative
*/
public static <K, V> HashBiMap<K, V> create(int expectedSize) {
return new HashBiMap<K, V>(expectedSize);
}
/**
* Constructs a new bimap containing initial values from {@code map}. The
* bimap is created with an initial capacity sufficient to hold the mappings
* in the specified map.
*/
public static <K, V> HashBiMap<K, V> create(
Map<? extends K, ? extends V> map) {
HashBiMap<K, V> bimap = create(map.size());
bimap.putAll(map);
return bimap;
}
private HashBiMap() {
super(new HashMap<K, V>(), new HashMap<V, K>());
}
private HashBiMap(int expectedSize) {
super(
Maps.<K, V>newHashMapWithExpectedSize(expectedSize),
Maps.<V, K>newHashMapWithExpectedSize(expectedSize));
}
// Override these two methods to show that keys and values may be null
@Override public V put(@Nullable K key, @Nullable V value) {
return super.put(key, value);
}
@Override public V forcePut(@Nullable K key, @Nullable V value) {
return super.forcePut(key, value);
}
}
| congdepeng/java-guava-lib-demo | guava-libraries/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/HashBiMap.java | Java | apache-2.0 | 2,365 |
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("react"));
else if(typeof define === 'function' && define.amd)
define(["react"], factory);
else if(typeof exports === 'object')
exports["Slider"] = factory(require("react"));
else
root["Slider"] = factory(root["React"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_4__) {
return /******/ (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] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = 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;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(1);
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _react = __webpack_require__(4);
var _react2 = _interopRequireDefault(_react);
var _innerSlider = __webpack_require__(5);
var _objectAssign = __webpack_require__(23);
var _objectAssign2 = _interopRequireDefault(_objectAssign);
var _json2mq = __webpack_require__(2);
var _json2mq2 = _interopRequireDefault(_json2mq);
var _reactResponsiveMixin = __webpack_require__(26);
var _reactResponsiveMixin2 = _interopRequireDefault(_reactResponsiveMixin);
var _defaultProps = __webpack_require__(9);
var _defaultProps2 = _interopRequireDefault(_defaultProps);
var Slider = _react2['default'].createClass({
displayName: 'Slider',
mixins: [_reactResponsiveMixin2['default']],
getInitialState: function getInitialState() {
return {
breakpoint: null
};
},
componentDidMount: function componentDidMount() {
var _this = this;
if (this.props.responsive) {
var breakpoints = this.props.responsive.map(function (breakpt) {
return breakpt.breakpoint;
});
breakpoints.sort(function (x, y) {
return x - y;
});
breakpoints.forEach(function (breakpoint, index) {
var bQuery;
if (index === 0) {
bQuery = (0, _json2mq2['default'])({ minWidth: 0, maxWidth: breakpoint });
} else {
bQuery = (0, _json2mq2['default'])({ minWidth: breakpoints[index - 1], maxWidth: breakpoint });
}
_this.media(bQuery, function () {
_this.setState({ breakpoint: breakpoint });
});
});
// Register media query for full screen. Need to support resize from small to large
var query = (0, _json2mq2['default'])({ minWidth: breakpoints.slice(-1)[0] });
this.media(query, function () {
_this.setState({ breakpoint: null });
});
}
},
render: function render() {
var _this2 = this;
var settings;
var newProps;
if (this.state.breakpoint) {
newProps = this.props.responsive.filter(function (resp) {
return resp.breakpoint === _this2.state.breakpoint;
});
settings = newProps[0].settings === 'unslick' ? 'unslick' : (0, _objectAssign2['default'])({}, this.props, newProps[0].settings);
} else {
settings = (0, _objectAssign2['default'])({}, _defaultProps2['default'], this.props);
}
if (settings === 'unslick') {
// if 'unslick' responsive breakpoint setting used, just return the <Slider> tag nested HTML
return _react2['default'].createElement(
'div',
null,
this.props.children
);
} else {
return _react2['default'].createElement(
_innerSlider.InnerSlider,
settings,
this.props.children
);
}
}
});
module.exports = Slider;
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
var camel2hyphen = __webpack_require__(3);
var isDimension = function (feature) {
var re = /[height|width]$/;
return re.test(feature);
};
var obj2mq = function (obj) {
var mq = '';
var features = Object.keys(obj);
features.forEach(function (feature, index) {
var value = obj[feature];
feature = camel2hyphen(feature);
// Add px to dimension features
if (isDimension(feature) && typeof value === 'number') {
value = value + 'px';
}
if (value === true) {
mq += feature;
} else if (value === false) {
mq += 'not ' + feature;
} else {
mq += '(' + feature + ': ' + value + ')';
}
if (index < features.length-1) {
mq += ' and '
}
});
return mq;
};
var json2mq = function (query) {
var mq = '';
if (typeof query === 'string') {
return query;
}
// Handling array of media queries
if (query instanceof Array) {
query.forEach(function (q, index) {
mq += obj2mq(q);
if (index < query.length-1) {
mq += ', '
}
});
return mq;
}
// Handling single media query
return obj2mq(query);
};
module.exports = json2mq;
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
var camel2hyphen = function (str) {
return str
.replace(/[A-Z]/g, function (match) {
return '-' + match.toLowerCase();
})
.toLowerCase();
};
module.exports = camel2hyphen;
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
module.exports = __WEBPACK_EXTERNAL_MODULE_4__;
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _react = __webpack_require__(4);
var _react2 = _interopRequireDefault(_react);
var _mixinsEventHandlers = __webpack_require__(!(function webpackMissingModule() { var e = new Error("Cannot find module \"./mixins/event-handlers\""); e.code = 'MODULE_NOT_FOUND'; throw e; }()));
var _mixinsEventHandlers2 = _interopRequireDefault(_mixinsEventHandlers);
var _mixinsHelpers = __webpack_require__(!(function webpackMissingModule() { var e = new Error("Cannot find module \"./mixins/helpers\""); e.code = 'MODULE_NOT_FOUND'; throw e; }()));
var _mixinsHelpers2 = _interopRequireDefault(_mixinsHelpers);
var _initialState = __webpack_require__(8);
var _initialState2 = _interopRequireDefault(_initialState);
var _defaultProps = __webpack_require__(9);
var _defaultProps2 = _interopRequireDefault(_defaultProps);
var _classnames = __webpack_require__(10);
var _classnames2 = _interopRequireDefault(_classnames);
var _track = __webpack_require__(11);
var _dots = __webpack_require__(24);
var _arrows = __webpack_require__(25);
var InnerSlider = _react2['default'].createClass({
displayName: 'InnerSlider',
mixins: [_mixinsHelpers2['default'], _mixinsEventHandlers2['default']],
getInitialState: function getInitialState() {
return _initialState2['default'];
},
getDefaultProps: function getDefaultProps() {
return _defaultProps2['default'];
},
componentWillMount: function componentWillMount() {
if (this.props.init) {
this.props.init();
}
this.setState({
mounted: true
});
var lazyLoadedList = [];
for (var i = 0; i < this.props.children.length; i++) {
if (i >= this.state.currentSlide && i < this.state.currentSlide + this.props.slidesToShow) {
lazyLoadedList.push(i);
}
}
if (this.props.lazyLoad && this.state.lazyLoadedList.length === 0) {
this.setState({
lazyLoadedList: lazyLoadedList
});
}
},
componentDidMount: function componentDidMount() {
// Hack for autoplay -- Inspect Later
this.initialize(this.props);
this.adaptHeight();
},
componentDidUpdate: function componentDidUpdate() {
this.adaptHeight();
},
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
this.initialize(nextProps);
},
render: function render() {
var className = (0, _classnames2['default'])('slick-initialized', 'slick-slider', this.props.className);
var trackProps = {
fade: this.props.fade,
cssEase: this.props.cssEase,
speed: this.props.speed,
infinite: this.props.infinite,
centerMode: this.props.centerMode,
currentSlide: this.state.currentSlide,
lazyLoad: this.props.lazyLoad,
lazyLoadedList: this.state.lazyLoadedList,
rtl: this.props.rtl,
slideWidth: this.state.slideWidth,
slidesToShow: this.props.slidesToShow,
slideCount: this.state.slideCount,
trackStyle: this.state.trackStyle,
variableWidth: this.props.variableWidth
};
var dots;
if (this.props.dots === true && this.state.slideCount > this.props.slidesToShow) {
var dotProps = {
dotsClass: this.props.dotsClass,
slideCount: this.state.slideCount,
slidesToShow: this.props.slidesToShow,
currentSlide: this.state.currentSlide,
slidesToScroll: this.props.slidesToScroll,
clickHandler: this.changeSlide
};
dots = _react2['default'].createElement(_dots.Dots, dotProps);
}
var prevArrow, nextArrow;
var arrowProps = {
infinite: this.props.infinite,
centerMode: this.props.centerMode,
currentSlide: this.state.currentSlide,
slideCount: this.state.slideCount,
slidesToShow: this.props.slidesToShow,
prevArrow: this.props.prevArrow,
nextArrow: this.props.nextArrow,
clickHandler: this.changeSlide
};
if (this.props.arrows) {
prevArrow = _react2['default'].createElement(_arrows.PrevArrow, arrowProps);
nextArrow = _react2['default'].createElement(_arrows.NextArrow, arrowProps);
}
return _react2['default'].createElement(
'div',
{ className: className },
_react2['default'].createElement(
'div',
{
ref: 'list',
className: 'slick-list',
onMouseDown: this.swipeStart,
onMouseMove: this.state.dragging ? this.swipeMove : null,
onMouseUp: this.swipeEnd,
onMouseLeave: this.state.dragging ? this.swipeEnd : null,
onTouchStart: this.swipeStart,
onTouchMove: this.state.dragging ? this.swipeMove : null,
onTouchEnd: this.swipeEnd,
onTouchCancel: this.state.dragging ? this.swipeEnd : null },
_react2['default'].createElement(
_track.Track,
_extends({ ref: 'track' }, trackProps),
this.props.children
)
),
prevArrow,
nextArrow,
dots
);
}
});
exports.InnerSlider = InnerSlider;
/***/ },
/* 6 */,
/* 7 */,
/* 8 */
/***/ function(module, exports, __webpack_require__) {
var initialState = {
animating: false,
dragging: false,
autoPlayTimer: null,
currentDirection: 0,
currentLeft: null,
currentSlide: 0,
direction: 1,
// listWidth: null,
// listHeight: null,
// loadIndex: 0,
slideCount: null,
slideWidth: null,
// sliding: false,
// slideOffset: 0,
swipeLeft: null,
touchObject: {
startX: 0,
startY: 0,
curX: 0,
curY: 0
},
lazyLoadedList: [],
// added for react
initialized: false,
edgeDragged: false,
swiped: false, // used by swipeEvent. differentites between touch and swipe.
trackStyle: {},
trackWidth: 0
// Removed
// transformsEnabled: false,
// $nextArrow: null,
// $prevArrow: null,
// $dots: null,
// $list: null,
// $slideTrack: null,
// $slides: null,
};
module.exports = initialState;
/***/ },
/* 9 */
/***/ function(module, exports, __webpack_require__) {
var defaultProps = {
className: '',
// accessibility: true,
adaptiveHeight: false,
arrows: true,
autoplay: false,
autoplaySpeed: 3000,
centerMode: false,
centerPadding: '50px',
cssEase: 'ease',
dots: false,
dotsClass: 'slick-dots',
draggable: true,
easing: 'linear',
edgeFriction: 0.35,
fade: false,
focusOnSelect: false,
infinite: true,
initialSlide: 0,
lazyLoad: false,
responsive: null,
rtl: false,
slide: 'div',
slidesToShow: 1,
slidesToScroll: 1,
speed: 500,
swipe: true,
swipeToSlide: false,
touchMove: true,
touchThreshold: 5,
useCSS: true,
variableWidth: false,
vertical: false,
// waitForAnimate: true,
afterChange: null,
beforeChange: null,
edgeEvent: null,
init: null,
swipeEvent: null,
// nextArrow, prevArrow are react componets
nextArrow: null,
prevArrow: null
};
module.exports = defaultProps;
/***/ },
/* 10 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
Copyright (c) 2015 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
function classNames () {
'use strict';
var classes = '';
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
if (!arg) continue;
var argType = typeof arg;
if ('string' === argType || 'number' === argType) {
classes += ' ' + arg;
} else if (Array.isArray(arg)) {
classes += ' ' + classNames.apply(null, arg);
} else if ('object' === argType) {
for (var key in arg) {
if (arg.hasOwnProperty(key) && arg[key]) {
classes += ' ' + key;
}
}
}
}
return classes.substr(1);
}
// safely export classNames for node / browserify
if (typeof module !== 'undefined' && module.exports) {
module.exports = classNames;
}
/* global define */
// safely export classNames for RequireJS
if (true) {
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function() {
return classNames;
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
}
/***/ },
/* 11 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _react = __webpack_require__(4);
var _react2 = _interopRequireDefault(_react);
var _reactLibCloneWithProps = __webpack_require__(12);
var _reactLibCloneWithProps2 = _interopRequireDefault(_reactLibCloneWithProps);
var _objectAssign = __webpack_require__(23);
var _objectAssign2 = _interopRequireDefault(_objectAssign);
var _classnames = __webpack_require__(10);
var _classnames2 = _interopRequireDefault(_classnames);
var getSlideClasses = function getSlideClasses(spec) {
var slickActive, slickCenter, slickCloned;
var centerOffset, index;
if (spec.rtl) {
index = spec.slideCount - 1 - spec.index;
console.log();
} else {
index = spec.index;
}
slickCloned = index < 0 || index >= spec.slideCount;
if (spec.centerMode) {
centerOffset = Math.floor(spec.slidesToShow / 2);
slickCenter = spec.currentSlide === index;
if (index > spec.currentSlide - centerOffset - 1 && index <= spec.currentSlide + centerOffset) {
slickActive = true;
}
} else {
slickActive = spec.currentSlide <= index && index < spec.currentSlide + spec.slidesToShow;
}
return (0, _classnames2['default'])({
'slick-slide': true,
'slick-active': slickActive,
'slick-center': slickCenter,
'slick-cloned': slickCloned
});
};
var getSlideStyle = function getSlideStyle(spec) {
var style = {};
if (spec.variableWidth === undefined || spec.variableWidth === false) {
style.width = spec.slideWidth;
}
if (spec.fade) {
style.position = 'relative';
style.left = -spec.index * spec.slideWidth;
style.opacity = spec.currentSlide === spec.index ? 1 : 0;
style.transition = 'opacity ' + spec.speed + 'ms ' + spec.cssEase;
style.WebkitTransition = 'opacity ' + spec.speed + 'ms ' + spec.cssEase;
}
return style;
};
var renderSlides = function renderSlides(spec) {
var key;
var slides = [];
var preCloneSlides = [];
var postCloneSlides = [];
var count = _react2['default'].Children.count(spec.children);
var child;
_react2['default'].Children.forEach(spec.children, function (elem, index) {
if (!spec.lazyLoad | (spec.lazyLoad && spec.lazyLoadedList.indexOf(index) >= 0)) {
child = elem;
} else {
child = _react2['default'].createElement('div', null);
}
var childStyle = getSlideStyle((0, _objectAssign2['default'])({}, spec, { index: index }));
slides.push((0, _reactLibCloneWithProps2['default'])(child, {
key: index,
'data-index': index,
className: getSlideClasses((0, _objectAssign2['default'])({ index: index }, spec)),
style: childStyle
}));
// variableWidth doesn't wrap properly.
if (spec.infinite && spec.fade === false) {
var infiniteCount = spec.variableWidth ? spec.slidesToShow + 1 : spec.slidesToShow;
if (index >= count - infiniteCount) {
key = -(count - index);
preCloneSlides.push((0, _reactLibCloneWithProps2['default'])(child, {
key: key,
'data-index': key,
className: getSlideClasses((0, _objectAssign2['default'])({ index: key }, spec)),
style: childStyle
}));
}
if (index < infiniteCount) {
key = count + index;
postCloneSlides.push((0, _reactLibCloneWithProps2['default'])(child, {
key: key,
'data-index': key,
className: getSlideClasses((0, _objectAssign2['default'])({ index: key }, spec)),
style: childStyle
}));
}
}
});
if (spec.rtl) {
return preCloneSlides.concat(slides, postCloneSlides).reverse();
} else {
return preCloneSlides.concat(slides, postCloneSlides);
}
};
var Track = _react2['default'].createClass({
displayName: 'Track',
render: function render() {
var slides = renderSlides(this.props);
return _react2['default'].createElement(
'div',
{ className: 'slick-track', style: this.props.trackStyle },
slides
);
}
});
exports.Track = Track;
/***/ },
/* 12 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, 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.
*
* @typechecks static-only
* @providesModule cloneWithProps
*/
'use strict';
var ReactElement = __webpack_require__(13);
var ReactPropTransferer = __webpack_require__(20);
var keyOf = __webpack_require__(22);
var warning = __webpack_require__(14);
var CHILDREN_PROP = keyOf({children: null});
/**
* Sometimes you want to change the props of a child passed to you. Usually
* this is to add a CSS class.
*
* @param {ReactElement} child child element you'd like to clone
* @param {object} props props you'd like to modify. className and style will be
* merged automatically.
* @return {ReactElement} a clone of child with props merged in.
*/
function cloneWithProps(child, props) {
if ("production" !== (undefined)) {
("production" !== (undefined) ? warning(
!child.ref,
'You are calling cloneWithProps() on a child with a ref. This is ' +
'dangerous because you\'re creating a new child which will not be ' +
'added as a ref to its parent.'
) : null);
}
var newProps = ReactPropTransferer.mergeProps(props, child.props);
// Use `child.props.children` if it is provided.
if (!newProps.hasOwnProperty(CHILDREN_PROP) &&
child.props.hasOwnProperty(CHILDREN_PROP)) {
newProps.children = child.props.children;
}
// The current API doesn't retain _owner and _context, which is why this
// doesn't use ReactElement.cloneAndReplaceProps.
return ReactElement.createElement(child.type, newProps);
}
module.exports = cloneWithProps;
/***/ },
/* 13 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2014-2015, Facebook, 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.
*
* @providesModule ReactElement
*/
'use strict';
var ReactContext = __webpack_require__(16);
var ReactCurrentOwner = __webpack_require__(19);
var assign = __webpack_require__(17);
var warning = __webpack_require__(14);
var RESERVED_PROPS = {
key: true,
ref: true
};
/**
* Warn for mutations.
*
* @internal
* @param {object} object
* @param {string} key
*/
function defineWarningProperty(object, key) {
Object.defineProperty(object, key, {
configurable: false,
enumerable: true,
get: function() {
if (!this._store) {
return null;
}
return this._store[key];
},
set: function(value) {
("production" !== (undefined) ? warning(
false,
'Don\'t set the %s property of the React element. Instead, ' +
'specify the correct value when initially creating the element.',
key
) : null);
this._store[key] = value;
}
});
}
/**
* This is updated to true if the membrane is successfully created.
*/
var useMutationMembrane = false;
/**
* Warn for mutations.
*
* @internal
* @param {object} element
*/
function defineMutationMembrane(prototype) {
try {
var pseudoFrozenProperties = {
props: true
};
for (var key in pseudoFrozenProperties) {
defineWarningProperty(prototype, key);
}
useMutationMembrane = true;
} catch (x) {
// IE will fail on defineProperty
}
}
/**
* Base constructor for all React elements. This is only used to make this
* work with a dynamic instanceof check. Nothing should live on this prototype.
*
* @param {*} type
* @param {string|object} ref
* @param {*} key
* @param {*} props
* @internal
*/
var ReactElement = function(type, key, ref, owner, context, props) {
// Built-in properties that belong on the element
this.type = type;
this.key = key;
this.ref = ref;
// Record the component responsible for creating this element.
this._owner = owner;
// TODO: Deprecate withContext, and then the context becomes accessible
// through the owner.
this._context = context;
if ("production" !== (undefined)) {
// The validation flag and props are currently mutative. We put them on
// an external backing store so that we can freeze the whole object.
// This can be replaced with a WeakMap once they are implemented in
// commonly used development environments.
this._store = {props: props, originalProps: assign({}, props)};
// To make comparing ReactElements easier for testing purposes, we make
// the validation flag non-enumerable (where possible, which should
// include every environment we run tests in), so the test framework
// ignores it.
try {
Object.defineProperty(this._store, 'validated', {
configurable: false,
enumerable: false,
writable: true
});
} catch (x) {
}
this._store.validated = false;
// We're not allowed to set props directly on the object so we early
// return and rely on the prototype membrane to forward to the backing
// store.
if (useMutationMembrane) {
Object.freeze(this);
return;
}
}
this.props = props;
};
// We intentionally don't expose the function on the constructor property.
// ReactElement should be indistinguishable from a plain object.
ReactElement.prototype = {
_isReactElement: true
};
if ("production" !== (undefined)) {
defineMutationMembrane(ReactElement.prototype);
}
ReactElement.createElement = function(type, config, children) {
var propName;
// Reserved names are extracted
var props = {};
var key = null;
var ref = null;
if (config != null) {
ref = config.ref === undefined ? null : config.ref;
key = config.key === undefined ? null : '' + config.key;
// Remaining properties are added to a new props object
for (propName in config) {
if (config.hasOwnProperty(propName) &&
!RESERVED_PROPS.hasOwnProperty(propName)) {
props[propName] = config[propName];
}
}
}
// Children can be more than one argument, and those are transferred onto
// the newly allocated props object.
var childrenLength = arguments.length - 2;
if (childrenLength === 1) {
props.children = children;
} else if (childrenLength > 1) {
var childArray = Array(childrenLength);
for (var i = 0; i < childrenLength; i++) {
childArray[i] = arguments[i + 2];
}
props.children = childArray;
}
// Resolve default props
if (type && type.defaultProps) {
var defaultProps = type.defaultProps;
for (propName in defaultProps) {
if (typeof props[propName] === 'undefined') {
props[propName] = defaultProps[propName];
}
}
}
return new ReactElement(
type,
key,
ref,
ReactCurrentOwner.current,
ReactContext.current,
props
);
};
ReactElement.createFactory = function(type) {
var factory = ReactElement.createElement.bind(null, type);
// Expose the type on the factory and the prototype so that it can be
// easily accessed on elements. E.g. <Foo />.type === Foo.type.
// This should not be named `constructor` since this may not be the function
// that created the element, and it may not even be a constructor.
// Legacy hook TODO: Warn if this is accessed
factory.type = type;
return factory;
};
ReactElement.cloneAndReplaceProps = function(oldElement, newProps) {
var newElement = new ReactElement(
oldElement.type,
oldElement.key,
oldElement.ref,
oldElement._owner,
oldElement._context,
newProps
);
if ("production" !== (undefined)) {
// If the key on the original is valid, then the clone is valid
newElement._store.validated = oldElement._store.validated;
}
return newElement;
};
ReactElement.cloneElement = function(element, config, children) {
var propName;
// Original props are copied
var props = assign({}, element.props);
// Reserved names are extracted
var key = element.key;
var ref = element.ref;
// Owner will be preserved, unless ref is overridden
var owner = element._owner;
if (config != null) {
if (config.ref !== undefined) {
// Silently steal the ref from the parent.
ref = config.ref;
owner = ReactCurrentOwner.current;
}
if (config.key !== undefined) {
key = '' + config.key;
}
// Remaining properties override existing props
for (propName in config) {
if (config.hasOwnProperty(propName) &&
!RESERVED_PROPS.hasOwnProperty(propName)) {
props[propName] = config[propName];
}
}
}
// Children can be more than one argument, and those are transferred onto
// the newly allocated props object.
var childrenLength = arguments.length - 2;
if (childrenLength === 1) {
props.children = children;
} else if (childrenLength > 1) {
var childArray = Array(childrenLength);
for (var i = 0; i < childrenLength; i++) {
childArray[i] = arguments[i + 2];
}
props.children = childArray;
}
return new ReactElement(
element.type,
key,
ref,
owner,
element._context,
props
);
};
/**
* @param {?object} object
* @return {boolean} True if `object` is a valid component.
* @final
*/
ReactElement.isValidElement = function(object) {
// ReactTestUtils is often used outside of beforeEach where as React is
// within it. This leads to two different instances of React on the same
// page. To identify a element from a different React instance we use
// a flag instead of an instanceof check.
var isElement = !!(object && object._isReactElement);
// if (isElement && !(object instanceof ReactElement)) {
// This is an indicator that you're using multiple versions of React at the
// same time. This will screw with ownership and stuff. Fix it, please.
// TODO: We could possibly warn here.
// }
return isElement;
};
module.exports = ReactElement;
/***/ },
/* 14 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2014-2015, Facebook, 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.
*
* @providesModule warning
*/
"use strict";
var emptyFunction = __webpack_require__(15);
/**
* Similar to invariant but only logs a warning if the condition is not met.
* This can be used to log issues in development environments in critical
* paths. Removing the logging code for production environments will keep the
* same logic and follow the same code paths.
*/
var warning = emptyFunction;
if ("production" !== (undefined)) {
warning = function(condition, format ) {for (var args=[],$__0=2,$__1=arguments.length;$__0<$__1;$__0++) args.push(arguments[$__0]);
if (format === undefined) {
throw new Error(
'`warning(condition, format, ...args)` requires a warning ' +
'message argument'
);
}
if (format.length < 10 || /^[s\W]*$/.test(format)) {
throw new Error(
'The warning format should be able to uniquely identify this ' +
'warning. Please, use a more descriptive format than: ' + format
);
}
if (format.indexOf('Failed Composite propType: ') === 0) {
return; // Ignore CompositeComponent proptype check.
}
if (!condition) {
var argIndex = 0;
var message = 'Warning: ' + format.replace(/%s/g, function() {return args[argIndex++];});
console.warn(message);
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch(x) {}
}
};
}
module.exports = warning;
/***/ },
/* 15 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, 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.
*
* @providesModule emptyFunction
*/
function makeEmptyFunction(arg) {
return function() {
return arg;
};
}
/**
* This function accepts and discards inputs; it has no side effects. This is
* primarily useful idiomatically for overridable function endpoints which
* always need to be callable, since JS lacks a null-call idiom ala Cocoa.
*/
function emptyFunction() {}
emptyFunction.thatReturns = makeEmptyFunction;
emptyFunction.thatReturnsFalse = makeEmptyFunction(false);
emptyFunction.thatReturnsTrue = makeEmptyFunction(true);
emptyFunction.thatReturnsNull = makeEmptyFunction(null);
emptyFunction.thatReturnsThis = function() { return this; };
emptyFunction.thatReturnsArgument = function(arg) { return arg; };
module.exports = emptyFunction;
/***/ },
/* 16 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, 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.
*
* @providesModule ReactContext
*/
'use strict';
var assign = __webpack_require__(17);
var emptyObject = __webpack_require__(18);
var warning = __webpack_require__(14);
var didWarn = false;
/**
* Keeps track of the current context.
*
* The context is automatically passed down the component ownership hierarchy
* and is accessible via `this.context` on ReactCompositeComponents.
*/
var ReactContext = {
/**
* @internal
* @type {object}
*/
current: emptyObject,
/**
* Temporarily extends the current context while executing scopedCallback.
*
* A typical use case might look like
*
* render: function() {
* var children = ReactContext.withContext({foo: 'foo'}, () => (
*
* ));
* return <div>{children}</div>;
* }
*
* @param {object} newContext New context to merge into the existing context
* @param {function} scopedCallback Callback to run with the new context
* @return {ReactComponent|array<ReactComponent>}
*/
withContext: function(newContext, scopedCallback) {
if ("production" !== (undefined)) {
("production" !== (undefined) ? warning(
didWarn,
'withContext is deprecated and will be removed in a future version. ' +
'Use a wrapper component with getChildContext instead.'
) : null);
didWarn = true;
}
var result;
var previousContext = ReactContext.current;
ReactContext.current = assign({}, previousContext, newContext);
try {
result = scopedCallback();
} finally {
ReactContext.current = previousContext;
}
return result;
}
};
module.exports = ReactContext;
/***/ },
/* 17 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2014-2015, Facebook, 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.
*
* @providesModule Object.assign
*/
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign
'use strict';
function assign(target, sources) {
if (target == null) {
throw new TypeError('Object.assign target cannot be null or undefined');
}
var to = Object(target);
var hasOwnProperty = Object.prototype.hasOwnProperty;
for (var nextIndex = 1; nextIndex < arguments.length; nextIndex++) {
var nextSource = arguments[nextIndex];
if (nextSource == null) {
continue;
}
var from = Object(nextSource);
// We don't currently support accessors nor proxies. Therefore this
// copy cannot throw. If we ever supported this then we must handle
// exceptions and side-effects. We don't support symbols so they won't
// be transferred.
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
}
return to;
}
module.exports = assign;
/***/ },
/* 18 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, 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.
*
* @providesModule emptyObject
*/
"use strict";
var emptyObject = {};
if ("production" !== (undefined)) {
Object.freeze(emptyObject);
}
module.exports = emptyObject;
/***/ },
/* 19 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, 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.
*
* @providesModule ReactCurrentOwner
*/
'use strict';
/**
* Keeps track of the current owner.
*
* The current owner is the component who should own any components that are
* currently being constructed.
*
* The depth indicate how many composite components are above this render level.
*/
var ReactCurrentOwner = {
/**
* @internal
* @type {ReactComponent}
*/
current: null
};
module.exports = ReactCurrentOwner;
/***/ },
/* 20 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, 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.
*
* @providesModule ReactPropTransferer
*/
'use strict';
var assign = __webpack_require__(17);
var emptyFunction = __webpack_require__(15);
var joinClasses = __webpack_require__(21);
/**
* Creates a transfer strategy that will merge prop values using the supplied
* `mergeStrategy`. If a prop was previously unset, this just sets it.
*
* @param {function} mergeStrategy
* @return {function}
*/
function createTransferStrategy(mergeStrategy) {
return function(props, key, value) {
if (!props.hasOwnProperty(key)) {
props[key] = value;
} else {
props[key] = mergeStrategy(props[key], value);
}
};
}
var transferStrategyMerge = createTransferStrategy(function(a, b) {
// `merge` overrides the first object's (`props[key]` above) keys using the
// second object's (`value`) keys. An object's style's existing `propA` would
// get overridden. Flip the order here.
return assign({}, b, a);
});
/**
* Transfer strategies dictate how props are transferred by `transferPropsTo`.
* NOTE: if you add any more exceptions to this list you should be sure to
* update `cloneWithProps()` accordingly.
*/
var TransferStrategies = {
/**
* Never transfer `children`.
*/
children: emptyFunction,
/**
* Transfer the `className` prop by merging them.
*/
className: createTransferStrategy(joinClasses),
/**
* Transfer the `style` prop (which is an object) by merging them.
*/
style: transferStrategyMerge
};
/**
* Mutates the first argument by transferring the properties from the second
* argument.
*
* @param {object} props
* @param {object} newProps
* @return {object}
*/
function transferInto(props, newProps) {
for (var thisKey in newProps) {
if (!newProps.hasOwnProperty(thisKey)) {
continue;
}
var transferStrategy = TransferStrategies[thisKey];
if (transferStrategy && TransferStrategies.hasOwnProperty(thisKey)) {
transferStrategy(props, thisKey, newProps[thisKey]);
} else if (!props.hasOwnProperty(thisKey)) {
props[thisKey] = newProps[thisKey];
}
}
return props;
}
/**
* ReactPropTransferer are capable of transferring props to another component
* using a `transferPropsTo` method.
*
* @class ReactPropTransferer
*/
var ReactPropTransferer = {
/**
* Merge two props objects using TransferStrategies.
*
* @param {object} oldProps original props (they take precedence)
* @param {object} newProps new props to merge in
* @return {object} a new object containing both sets of props merged.
*/
mergeProps: function(oldProps, newProps) {
return transferInto(assign({}, oldProps), newProps);
}
};
module.exports = ReactPropTransferer;
/***/ },
/* 21 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, 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.
*
* @providesModule joinClasses
* @typechecks static-only
*/
'use strict';
/**
* Combines multiple className strings into one.
* http://jsperf.com/joinclasses-args-vs-array
*
* @param {...?string} classes
* @return {string}
*/
function joinClasses(className/*, ... */) {
if (!className) {
className = '';
}
var nextClass;
var argLength = arguments.length;
if (argLength > 1) {
for (var ii = 1; ii < argLength; ii++) {
nextClass = arguments[ii];
if (nextClass) {
className = (className ? className + ' ' : '') + nextClass;
}
}
}
return className;
}
module.exports = joinClasses;
/***/ },
/* 22 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, 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.
*
* @providesModule keyOf
*/
/**
* Allows extraction of a minified key. Let's the build system minify keys
* without loosing the ability to dynamically use key strings as values
* themselves. Pass in an object with a single key/val pair and it will return
* you the string key of that single record. Suppose you want to grab the
* value for a key 'className' inside of an object. Key/val minification may
* have aliased that key to be 'xa12'. keyOf({className: null}) will return
* 'xa12' in that case. Resolve keys you want to use once at startup time, then
* reuse those resolutions.
*/
var keyOf = function(oneKeyObj) {
var key;
for (key in oneKeyObj) {
if (!oneKeyObj.hasOwnProperty(key)) {
continue;
}
return key;
}
return null;
};
module.exports = keyOf;
/***/ },
/* 23 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
function ToObject(val) {
if (val == null) {
throw new TypeError('Object.assign cannot be called with null or undefined');
}
return Object(val);
}
module.exports = Object.assign || function (target, source) {
var from;
var keys;
var to = ToObject(target);
for (var s = 1; s < arguments.length; s++) {
from = arguments[s];
keys = Object.keys(Object(from));
for (var i = 0; i < keys.length; i++) {
to[keys[i]] = from[keys[i]];
}
}
return to;
};
/***/ },
/* 24 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _react = __webpack_require__(4);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(10);
var _classnames2 = _interopRequireDefault(_classnames);
var getDotCount = function getDotCount(spec) {
var dots;
dots = Math.ceil(spec.slideCount / spec.slidesToScroll);
return dots;
};
var Dots = _react2['default'].createClass({
displayName: 'Dots',
clickHandler: function clickHandler(options, e) {
// In Autoplay the focus stays on clicked button even after transition
// to next slide. That only goes away by click somewhere outside
e.preventDefault();
this.props.clickHandler(options);
},
render: function render() {
var _this = this;
var dotCount = getDotCount({
slideCount: this.props.slideCount,
slidesToScroll: this.props.slidesToScroll
});
var dots = Array.apply(null, { length: dotCount }).map(function (x, i) {
var className = (0, _classnames2['default'])({
'slick-active': _this.props.currentSlide === i * _this.props.slidesToScroll
});
var dotOptions = {
message: 'dots',
index: i,
slidesToScroll: _this.props.slidesToScroll,
currentSlide: _this.props.currentSlide
};
return _react2['default'].createElement(
'li',
{ key: i, className: className },
_react2['default'].createElement(
'button',
{ onClick: _this.clickHandler.bind(_this, dotOptions) },
i
)
);
});
return _react2['default'].createElement(
'ul',
{ className: this.props.dotsClass, style: { display: 'block' } },
dots
);
}
});
exports.Dots = Dots;
/***/ },
/* 25 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _react = __webpack_require__(4);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(10);
var _classnames2 = _interopRequireDefault(_classnames);
var PrevArrow = _react2['default'].createClass({
displayName: 'PrevArrow',
clickHandler: function clickHandler(options, e) {
e.preventDefault();
this.props.clickHandler(options, e);
},
render: function render() {
var prevClasses = { 'slick-prev': true };
var prevHandler = this.clickHandler.bind(this, { message: 'previous' });
if (!this.props.infinite && (this.props.currentSlide === 0 || this.props.slideCount <= this.props.slidesToShow)) {
prevClasses['slick-disabled'] = true;
prevHandler = null;
}
var prevArrowProps = {
key: '0',
ref: 'previous',
'data-role': 'none',
className: (0, _classnames2['default'])(prevClasses),
style: { display: 'block' },
onClick: prevHandler
};
var prevArrow;
if (this.props.prevArrow) {
prevArrow = _react2['default'].createElement(this.props.prevArrow, prevArrowProps);
} else {
prevArrow = _react2['default'].createElement(
'button',
_extends({ key: '0', type: 'button' }, prevArrowProps),
' Previous'
);
}
return prevArrow;
}
});
exports.PrevArrow = PrevArrow;
var NextArrow = _react2['default'].createClass({
displayName: 'NextArrow',
clickHandler: function clickHandler(options, e) {
e.preventDefault();
this.props.clickHandler(options, e);
},
render: function render() {
var nextClasses = { 'slick-next': true };
var nextHandler = this.clickHandler.bind(this, { message: 'next' });
if (!this.props.infinite) {
if (this.props.centerMode && this.props.currentSlide >= this.props.slideCount - 1) {
nextClasses['slick-disabled'] = true;
nextHandler = null;
} else {
if (this.props.currentSlide >= this.props.slideCount - this.props.slidesToShow) {
nextClasses['slick-disabled'] = true;
nextHandler = null;
}
}
if (this.props.slideCount <= this.props.slidesToShow) {
nextClasses['slick-disabled'] = true;
nextHandler = null;
}
}
var nextArrowProps = {
key: '1',
ref: 'next',
'data-role': 'none',
className: (0, _classnames2['default'])(nextClasses),
style: { display: 'block' },
onClick: nextHandler
};
var nextArrow;
if (this.props.nextArrow) {
nextArrow = _react2['default'].createElement(this.props.nextArrow, nextArrowProps);
} else {
nextArrow = _react2['default'].createElement(
'button',
_extends({ key: '1', type: 'button' }, nextArrowProps),
' Next'
);
}
return nextArrow;
}
});
exports.NextArrow = NextArrow;
/***/ },
/* 26 */
/***/ function(module, exports, __webpack_require__) {
var canUseDOM = __webpack_require__(27);
var enquire = canUseDOM && __webpack_require__(28);
var json2mq = __webpack_require__(2);
var ResponsiveMixin = {
media: function (query, handler) {
query = json2mq(query);
if (typeof handler === 'function') {
handler = {
match: handler
};
}
enquire.register(query, handler);
// Queue the handlers to unregister them at unmount
if (! this._responsiveMediaHandlers) {
this._responsiveMediaHandlers = [];
}
this._responsiveMediaHandlers.push({query: query, handler: handler});
},
componentWillUnmount: function () {
this._responsiveMediaHandlers.forEach(function(obj) {
enquire.unregister(obj.query, obj.handler);
});
}
};
module.exports = ResponsiveMixin;
/***/ },
/* 27 */
/***/ function(module, exports, __webpack_require__) {
var canUseDOM = !!(
typeof window !== 'undefined' &&
window.document &&
window.document.createElement
);
module.exports = canUseDOM;
/***/ },
/* 28 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_RESULT__;/*!
* enquire.js v2.1.1 - Awesome Media Queries in JavaScript
* Copyright (c) 2014 Nick Williams - http://wicky.nillia.ms/enquire.js
* License: MIT (http://www.opensource.org/licenses/mit-license.php)
*/
;(function (name, context, factory) {
var matchMedia = window.matchMedia;
if (typeof module !== 'undefined' && module.exports) {
module.exports = factory(matchMedia);
}
else if (true) {
!(__WEBPACK_AMD_DEFINE_RESULT__ = function() {
return (context[name] = factory(matchMedia));
}.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
}
else {
context[name] = factory(matchMedia);
}
}('enquire', this, function (matchMedia) {
'use strict';
/*jshint unused:false */
/**
* Helper function for iterating over a collection
*
* @param collection
* @param fn
*/
function each(collection, fn) {
var i = 0,
length = collection.length,
cont;
for(i; i < length; i++) {
cont = fn(collection[i], i);
if(cont === false) {
break; //allow early exit
}
}
}
/**
* Helper function for determining whether target object is an array
*
* @param target the object under test
* @return {Boolean} true if array, false otherwise
*/
function isArray(target) {
return Object.prototype.toString.apply(target) === '[object Array]';
}
/**
* Helper function for determining whether target object is a function
*
* @param target the object under test
* @return {Boolean} true if function, false otherwise
*/
function isFunction(target) {
return typeof target === 'function';
}
/**
* Delegate to handle a media query being matched and unmatched.
*
* @param {object} options
* @param {function} options.match callback for when the media query is matched
* @param {function} [options.unmatch] callback for when the media query is unmatched
* @param {function} [options.setup] one-time callback triggered the first time a query is matched
* @param {boolean} [options.deferSetup=false] should the setup callback be run immediately, rather than first time query is matched?
* @constructor
*/
function QueryHandler(options) {
this.options = options;
!options.deferSetup && this.setup();
}
QueryHandler.prototype = {
/**
* coordinates setup of the handler
*
* @function
*/
setup : function() {
if(this.options.setup) {
this.options.setup();
}
this.initialised = true;
},
/**
* coordinates setup and triggering of the handler
*
* @function
*/
on : function() {
!this.initialised && this.setup();
this.options.match && this.options.match();
},
/**
* coordinates the unmatch event for the handler
*
* @function
*/
off : function() {
this.options.unmatch && this.options.unmatch();
},
/**
* called when a handler is to be destroyed.
* delegates to the destroy or unmatch callbacks, depending on availability.
*
* @function
*/
destroy : function() {
this.options.destroy ? this.options.destroy() : this.off();
},
/**
* determines equality by reference.
* if object is supplied compare options, if function, compare match callback
*
* @function
* @param {object || function} [target] the target for comparison
*/
equals : function(target) {
return this.options === target || this.options.match === target;
}
};
/**
* Represents a single media query, manages it's state and registered handlers for this query
*
* @constructor
* @param {string} query the media query string
* @param {boolean} [isUnconditional=false] whether the media query should run regardless of whether the conditions are met. Primarily for helping older browsers deal with mobile-first design
*/
function MediaQuery(query, isUnconditional) {
this.query = query;
this.isUnconditional = isUnconditional;
this.handlers = [];
this.mql = matchMedia(query);
var self = this;
this.listener = function(mql) {
self.mql = mql;
self.assess();
};
this.mql.addListener(this.listener);
}
MediaQuery.prototype = {
/**
* add a handler for this query, triggering if already active
*
* @param {object} handler
* @param {function} handler.match callback for when query is activated
* @param {function} [handler.unmatch] callback for when query is deactivated
* @param {function} [handler.setup] callback for immediate execution when a query handler is registered
* @param {boolean} [handler.deferSetup=false] should the setup callback be deferred until the first time the handler is matched?
*/
addHandler : function(handler) {
var qh = new QueryHandler(handler);
this.handlers.push(qh);
this.matches() && qh.on();
},
/**
* removes the given handler from the collection, and calls it's destroy methods
*
* @param {object || function} handler the handler to remove
*/
removeHandler : function(handler) {
var handlers = this.handlers;
each(handlers, function(h, i) {
if(h.equals(handler)) {
h.destroy();
return !handlers.splice(i,1); //remove from array and exit each early
}
});
},
/**
* Determine whether the media query should be considered a match
*
* @return {Boolean} true if media query can be considered a match, false otherwise
*/
matches : function() {
return this.mql.matches || this.isUnconditional;
},
/**
* Clears all handlers and unbinds events
*/
clear : function() {
each(this.handlers, function(handler) {
handler.destroy();
});
this.mql.removeListener(this.listener);
this.handlers.length = 0; //clear array
},
/*
* Assesses the query, turning on all handlers if it matches, turning them off if it doesn't match
*/
assess : function() {
var action = this.matches() ? 'on' : 'off';
each(this.handlers, function(handler) {
handler[action]();
});
}
};
/**
* Allows for registration of query handlers.
* Manages the query handler's state and is responsible for wiring up browser events
*
* @constructor
*/
function MediaQueryDispatch () {
if(!matchMedia) {
throw new Error('matchMedia not present, legacy browsers require a polyfill');
}
this.queries = {};
this.browserIsIncapable = !matchMedia('only all').matches;
}
MediaQueryDispatch.prototype = {
/**
* Registers a handler for the given media query
*
* @param {string} q the media query
* @param {object || Array || Function} options either a single query handler object, a function, or an array of query handlers
* @param {function} options.match fired when query matched
* @param {function} [options.unmatch] fired when a query is no longer matched
* @param {function} [options.setup] fired when handler first triggered
* @param {boolean} [options.deferSetup=false] whether setup should be run immediately or deferred until query is first matched
* @param {boolean} [shouldDegrade=false] whether this particular media query should always run on incapable browsers
*/
register : function(q, options, shouldDegrade) {
var queries = this.queries,
isUnconditional = shouldDegrade && this.browserIsIncapable;
if(!queries[q]) {
queries[q] = new MediaQuery(q, isUnconditional);
}
//normalise to object in an array
if(isFunction(options)) {
options = { match : options };
}
if(!isArray(options)) {
options = [options];
}
each(options, function(handler) {
queries[q].addHandler(handler);
});
return this;
},
/**
* unregisters a query and all it's handlers, or a specific handler for a query
*
* @param {string} q the media query to target
* @param {object || function} [handler] specific handler to unregister
*/
unregister : function(q, handler) {
var query = this.queries[q];
if(query) {
if(handler) {
query.removeHandler(handler);
}
else {
query.clear();
delete this.queries[q];
}
}
return this;
}
};
return new MediaQueryDispatch();
}));
/***/ }
/******/ ])
});
; | maruilian11/cdnjs | ajax/libs/react-slick/0.6.0/react-slick.js | JavaScript | mit | 61,015 |
/*!
* Bootstrap-select v1.6.3 (http://silviomoreto.github.io/bootstrap-select)
*
* Copyright 2013-2015 bootstrap-select
* Licensed under MIT (https://github.com/silviomoreto/bootstrap-select/blob/master/LICENSE)
*/
(function ($) {
$.fn.selectpicker.defaults = {
noneSelectedText: 'Niets geselecteerd',
noneResultsText: 'Geen resultaten gevonden voor {0}',
countSelectedText: '{0} van {1} geselecteerd',
maxOptionsText: ['Limiet bereikt ({n} {var} max)', 'Groep limiet bereikt ({n} {var} max)', ['items', 'item']],
multipleSeparator: ', '
};
})(jQuery);
| jhonrsalcedo/sitio | wp-content/themes/viviendas/assets/libraries/bootstrap-select/dist/js/i18n/defaults-nl_NL.js | JavaScript | gpl-2.0 | 582 |
package com.bumptech.glide.gifdecoder;
import java.util.ArrayList;
import java.util.List;
public class GifHeader {
public int[] gct = null;
/**
* Global status code of GIF data parsing
*/
public int status = GifDecoder.STATUS_OK;
public int frameCount = 0;
public GifFrame currentFrame;
public List<GifFrame> frames = new ArrayList<GifFrame>();
// logical screen size
public int width; // full image width
public int height; // full image height
public boolean gctFlag; // 1 : global color table flag
// 2-4 : color resolution
// 5 : gct sort flag
public int gctSize; // 6-8 : gct size
public int bgIndex; // background color index
public int pixelAspect; // pixel aspect ratio
//TODO: this is set both during reading the header and while decoding frames...
public int bgColor;
public boolean isTransparent;
public int loopCount;
}
| heymind/iosched | third_party/gif_decoder/src/main/java/com/bumptech/glide/gifdecoder/GifHeader.java | Java | apache-2.0 | 924 |
import {has, isArray} from "./util"
import {SourceLocation} from "./locutil"
// A second optional argument can be given to further configure
// the parser process. These options are recognized:
export const defaultOptions = {
// `ecmaVersion` indicates the ECMAScript version to parse. Must
// be either 3, or 5, or 6. This influences support for strict
// mode, the set of reserved words, support for getters and
// setters and other features. The default is 6.
ecmaVersion: 6,
// Source type ("script" or "module") for different semantics
sourceType: "script",
// `onInsertedSemicolon` can be a callback that will be called
// when a semicolon is automatically inserted. It will be passed
// th position of the comma as an offset, and if `locations` is
// enabled, it is given the location as a `{line, column}` object
// as second argument.
onInsertedSemicolon: null,
// `onTrailingComma` is similar to `onInsertedSemicolon`, but for
// trailing commas.
onTrailingComma: null,
// By default, reserved words are only enforced if ecmaVersion >= 5.
// Set `allowReserved` to a boolean value to explicitly turn this on
// an off. When this option has the value "never", reserved words
// and keywords can also not be used as property names.
allowReserved: null,
// When enabled, a return at the top level is not considered an
// error.
allowReturnOutsideFunction: false,
// When enabled, import/export statements are not constrained to
// appearing at the top of the program.
allowImportExportEverywhere: false,
// When enabled, hashbang directive in the beginning of file
// is allowed and treated as a line comment.
allowHashBang: false,
// When `locations` is on, `loc` properties holding objects with
// `start` and `end` properties in `{line, column}` form (with
// line being 1-based and column 0-based) will be attached to the
// nodes.
locations: false,
// A function can be passed as `onToken` option, which will
// cause Acorn to call that function with object in the same
// format as tokens returned from `tokenizer().getToken()`. Note
// that you are not allowed to call the parser from the
// callback—that will corrupt its internal state.
onToken: null,
// A function can be passed as `onComment` option, which will
// cause Acorn to call that function with `(block, text, start,
// end)` parameters whenever a comment is skipped. `block` is a
// boolean indicating whether this is a block (`/* */`) comment,
// `text` is the content of the comment, and `start` and `end` are
// character offsets that denote the start and end of the comment.
// When the `locations` option is on, two more parameters are
// passed, the full `{line, column}` locations of the start and
// end of the comments. Note that you are not allowed to call the
// parser from the callback—that will corrupt its internal state.
onComment: null,
// Nodes have their start and end characters offsets recorded in
// `start` and `end` properties (directly on the node, rather than
// the `loc` object, which holds line/column data. To also add a
// [semi-standardized][range] `range` property holding a `[start,
// end]` array with the same numbers, set the `ranges` option to
// `true`.
//
// [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
ranges: false,
// It is possible to parse multiple files into a single AST by
// passing the tree produced by parsing the first file as
// `program` option in subsequent parses. This will add the
// toplevel forms of the parsed file to the `Program` (top) node
// of an existing parse tree.
program: null,
// When `locations` is on, you can pass this to record the source
// file in every node's `loc` object.
sourceFile: null,
// This value, if given, is stored in every node, whether
// `locations` is on or off.
directSourceFile: null,
// When enabled, parenthesized expressions are represented by
// (non-standard) ParenthesizedExpression nodes
preserveParens: false,
plugins: {}
}
// Interpret and default an options object
export function getOptions(opts) {
let options = {}
for (let opt in defaultOptions)
options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]
if (options.allowReserved == null)
options.allowReserved = options.ecmaVersion < 5
if (isArray(options.onToken)) {
let tokens = options.onToken
options.onToken = (token) => tokens.push(token)
}
if (isArray(options.onComment))
options.onComment = pushComment(options, options.onComment)
return options
}
function pushComment(options, array) {
return function (block, text, start, end, startLoc, endLoc) {
let comment = {
type: block ? 'Block' : 'Line',
value: text,
start: start,
end: end
}
if (options.locations)
comment.loc = new SourceLocation(this, startLoc, endLoc)
if (options.ranges)
comment.range = [start, end]
array.push(comment)
}
}
| hellokidder/js-studying | 微信小程序/wxtest/node_modules/acorn-jsx/node_modules/acorn/src/options.js | JavaScript | mit | 5,026 |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.CodeAnalysis.Editor.Implementation.BraceMatching
{
internal struct BraceCharacterAndKind
{
public char Character { get; }
public int Kind { get; }
public BraceCharacterAndKind(char character, int kind)
: this()
{
this.Character = character;
this.Kind = kind;
}
}
}
| mmitche/roslyn | src/EditorFeatures/Core/Implementation/BraceMatching/BraceCharacterAndKind.cs | C# | apache-2.0 | 539 |
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package language_test
import (
"fmt"
"net/http"
"golang.org/x/text/language"
)
func ExampleCanonType() {
p := func(id string) {
fmt.Printf("Default(%s) -> %s\n", id, language.Make(id))
fmt.Printf("BCP47(%s) -> %s\n", id, language.BCP47.Make(id))
fmt.Printf("Macro(%s) -> %s\n", id, language.Macro.Make(id))
fmt.Printf("All(%s) -> %s\n", id, language.All.Make(id))
}
p("en-Latn")
p("sh")
p("zh-cmn")
p("bjd")
p("iw-Latn-fonipa-u-cu-usd")
// Output:
// Default(en-Latn) -> en-Latn
// BCP47(en-Latn) -> en
// Macro(en-Latn) -> en-Latn
// All(en-Latn) -> en
// Default(sh) -> sr-Latn
// BCP47(sh) -> sh
// Macro(sh) -> sh
// All(sh) -> sr-Latn
// Default(zh-cmn) -> cmn
// BCP47(zh-cmn) -> cmn
// Macro(zh-cmn) -> zh
// All(zh-cmn) -> zh
// Default(bjd) -> drl
// BCP47(bjd) -> drl
// Macro(bjd) -> bjd
// All(bjd) -> drl
// Default(iw-Latn-fonipa-u-cu-usd) -> he-Latn-fonipa-u-cu-usd
// BCP47(iw-Latn-fonipa-u-cu-usd) -> he-Latn-fonipa-u-cu-usd
// Macro(iw-Latn-fonipa-u-cu-usd) -> iw-Latn-fonipa-u-cu-usd
// All(iw-Latn-fonipa-u-cu-usd) -> he-Latn-fonipa-u-cu-usd
}
func ExampleTag_Base() {
fmt.Println(language.Make("und").Base())
fmt.Println(language.Make("und-US").Base())
fmt.Println(language.Make("und-NL").Base())
fmt.Println(language.Make("und-419").Base()) // Latin America
fmt.Println(language.Make("und-ZZ").Base())
// Output:
// en Low
// en High
// nl High
// es Low
// en Low
}
func ExampleTag_Script() {
en := language.Make("en")
sr := language.Make("sr")
sr_Latn := language.Make("sr_Latn")
fmt.Println(en.Script())
fmt.Println(sr.Script())
// Was a script explicitly specified?
_, c := sr.Script()
fmt.Println(c == language.Exact)
_, c = sr_Latn.Script()
fmt.Println(c == language.Exact)
// Output:
// Latn High
// Cyrl Low
// false
// true
}
func ExampleTag_Region() {
ru := language.Make("ru")
en := language.Make("en")
fmt.Println(ru.Region())
fmt.Println(en.Region())
// Output:
// RU Low
// US Low
}
func ExampleRegion_TLD() {
us := language.MustParseRegion("US")
gb := language.MustParseRegion("GB")
uk := language.MustParseRegion("UK")
bu := language.MustParseRegion("BU")
fmt.Println(us.TLD())
fmt.Println(gb.TLD())
fmt.Println(uk.TLD())
fmt.Println(bu.TLD())
fmt.Println(us.Canonicalize().TLD())
fmt.Println(gb.Canonicalize().TLD())
fmt.Println(uk.Canonicalize().TLD())
fmt.Println(bu.Canonicalize().TLD())
// Output:
// US <nil>
// UK <nil>
// UK <nil>
// ZZ language: region is not a valid ccTLD
// US <nil>
// UK <nil>
// UK <nil>
// MM <nil>
}
func ExampleCompose() {
nl, _ := language.ParseBase("nl")
us, _ := language.ParseRegion("US")
de := language.Make("de-1901-u-co-phonebk")
jp := language.Make("ja-JP")
fi := language.Make("fi-x-ing")
u, _ := language.ParseExtension("u-nu-arabic")
x, _ := language.ParseExtension("x-piglatin")
// Combine a base language and region.
fmt.Println(language.Compose(nl, us))
// Combine a base language and extension.
fmt.Println(language.Compose(nl, x))
// Replace the region.
fmt.Println(language.Compose(jp, us))
// Combine several tags.
fmt.Println(language.Compose(us, nl, u))
// Replace the base language of a tag.
fmt.Println(language.Compose(de, nl))
fmt.Println(language.Compose(de, nl, u))
// Remove the base language.
fmt.Println(language.Compose(de, language.Base{}))
// Remove all variants.
fmt.Println(language.Compose(de, []language.Variant{}))
// Remove all extensions.
fmt.Println(language.Compose(de, []language.Extension{}))
fmt.Println(language.Compose(fi, []language.Extension{}))
// Remove all variants and extensions.
fmt.Println(language.Compose(de.Raw()))
// An error is gobbled or returned if non-nil.
fmt.Println(language.Compose(language.ParseRegion("ZA")))
fmt.Println(language.Compose(language.ParseRegion("HH")))
// Compose uses the same Default canonicalization as Make.
fmt.Println(language.Compose(language.Raw.Parse("en-Latn-UK")))
// Call compose on a different CanonType for different results.
fmt.Println(language.All.Compose(language.Raw.Parse("en-Latn-UK")))
// Output:
// nl-US <nil>
// nl-x-piglatin <nil>
// ja-US <nil>
// nl-US-u-nu-arabic <nil>
// nl-1901-u-co-phonebk <nil>
// nl-1901-u-nu-arabic <nil>
// und-1901-u-co-phonebk <nil>
// de-u-co-phonebk <nil>
// de-1901 <nil>
// fi <nil>
// de <nil>
// und-ZA <nil>
// und language: subtag "HH" is well-formed but unknown
// en-Latn-GB <nil>
// en-GB <nil>
}
func ExampleParse_errors() {
for _, s := range []string{"Foo", "Bar", "Foobar"} {
_, err := language.Parse(s)
if err != nil {
if inv, ok := err.(language.ValueError); ok {
fmt.Println(inv.Subtag())
} else {
fmt.Println(s)
}
}
}
for _, s := range []string{"en", "aa-Uuuu", "AC", "ac-u"} {
_, err := language.Parse(s)
switch e := err.(type) {
case language.ValueError:
fmt.Printf("%s: culprit %q\n", s, e.Subtag())
case nil:
// No error.
default:
// A syntax error.
fmt.Printf("%s: ill-formed\n", s)
}
}
// Output:
// foo
// Foobar
// aa-Uuuu: culprit "Uuuu"
// AC: culprit "ac"
// ac-u: ill-formed
}
func ExampleParent() {
p := func(tag string) {
fmt.Printf("parent(%v): %v\n", tag, language.Make(tag).Parent())
}
p("zh-CN")
// Australian English inherits from World English.
p("en-AU")
// If the tag has a different maximized script from its parent, a tag with
// this maximized script is inserted. This allows different language tags
// which have the same base language and script in common to inherit from
// a common set of settings.
p("zh-HK")
// If the maximized script of the parent is not identical, CLDR will skip
// inheriting from it, as it means there will not be many entries in common
// and inheriting from it is nonsensical.
p("zh-Hant")
// The parent of a tag with variants and extensions is the tag with all
// variants and extensions removed.
p("de-1994-u-co-phonebk")
// Remove default script.
p("de-Latn-LU")
// Output:
// parent(zh-CN): zh
// parent(en-AU): en-001
// parent(zh-HK): zh-Hant
// parent(zh-Hant): und
// parent(de-1994-u-co-phonebk): de
// parent(de-Latn-LU): de
}
// ExampleMatcher_bestMatch gives some examples of getting the best match of
// a set of tags to any of the tags of given set.
func ExampleMatcher() {
// This is the set of tags from which we want to pick the best match. These
// can be, for example, the supported languages for some package.
tags := []language.Tag{
language.English,
language.BritishEnglish,
language.French,
language.Afrikaans,
language.BrazilianPortuguese,
language.EuropeanPortuguese,
language.Croatian,
language.SimplifiedChinese,
language.Raw.Make("iw-IL"),
language.Raw.Make("iw"),
language.Raw.Make("he"),
}
m := language.NewMatcher(tags)
// A simple match.
fmt.Println(m.Match(language.Make("fr")))
// Australian English is closer to British than American English.
fmt.Println(m.Match(language.Make("en-AU")))
// Default to the first tag passed to the Matcher if there is no match.
fmt.Println(m.Match(language.Make("ar")))
// Get the default tag.
fmt.Println(m.Match())
fmt.Println("----")
// Someone specifying sr-Latn is probably fine with getting Croatian.
fmt.Println(m.Match(language.Make("sr-Latn")))
// We match SimplifiedChinese, but with Low confidence.
fmt.Println(m.Match(language.TraditionalChinese))
// Serbian in Latin script is a closer match to Croatian than Traditional
// Chinese to Simplified Chinese.
fmt.Println(m.Match(language.TraditionalChinese, language.Make("sr-Latn")))
fmt.Println("----")
// In case a multiple variants of a language are available, the most spoken
// variant is typically returned.
fmt.Println(m.Match(language.Portuguese))
// Pick the first value passed to Match in case of a tie.
fmt.Println(m.Match(language.Dutch, language.Make("fr-BE"), language.Make("af-NA")))
fmt.Println(m.Match(language.Dutch, language.Make("af-NA"), language.Make("fr-BE")))
fmt.Println("----")
// If a Matcher is initialized with a language and it's deprecated version,
// it will distinguish between them.
fmt.Println(m.Match(language.Raw.Make("iw")))
// However, for non-exact matches, it will treat deprecated versions as
// equivalent and consider other factors first.
fmt.Println(m.Match(language.Raw.Make("he-IL")))
fmt.Println("----")
// User settings passed to the Unicode extension are ignored for matching
// and preserved in the returned tag.
fmt.Println(m.Match(language.Make("de-u-co-phonebk"), language.Make("fr-u-cu-frf")))
// Even if the matching language is different.
fmt.Println(m.Match(language.Make("de-u-co-phonebk"), language.Make("br-u-cu-frf")))
// If there is no matching language, the options of the first preferred tag are used.
fmt.Println(m.Match(language.Make("de-u-co-phonebk")))
// Output:
// fr 2 Exact
// en-GB 1 High
// en 0 No
// en 0 No
// ----
// hr 6 High
// zh-Hans 7 Low
// hr 6 High
// ----
// pt-BR 4 High
// fr 2 High
// af 3 High
// ----
// iw 9 Exact
// he 10 Exact
// ----
// fr-u-cu-frf 2 Exact
// fr-u-cu-frf 2 High
// en-u-co-phonebk 0 No
// TODO: "he" should be "he-u-rg-IL High"
}
func ExampleMatchStrings() {
// languages supported by this service:
matcher := language.NewMatcher([]language.Tag{
language.English, language.Dutch, language.German,
})
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
lang, _ := r.Cookie("lang")
tag, _ := language.MatchStrings(matcher, lang.String(), r.Header.Get("Accept-Language"))
fmt.Println("User language:", tag)
})
}
func ExampleComprehends() {
// Various levels of comprehensibility.
fmt.Println(language.Comprehends(language.English, language.English))
fmt.Println(language.Comprehends(language.AmericanEnglish, language.BritishEnglish))
// An explicit Und results in no match.
fmt.Println(language.Comprehends(language.English, language.Und))
fmt.Println("----")
// There is usually no mutual comprehensibility between different scripts.
fmt.Println(language.Comprehends(language.Make("en-Dsrt"), language.English))
// One exception is for Traditional versus Simplified Chinese, albeit with
// a low confidence.
fmt.Println(language.Comprehends(language.TraditionalChinese, language.SimplifiedChinese))
fmt.Println("----")
// A Swiss German speaker will often understand High German.
fmt.Println(language.Comprehends(language.Make("gsw"), language.Make("de")))
// The converse is not generally the case.
fmt.Println(language.Comprehends(language.Make("de"), language.Make("gsw")))
// Output:
// Exact
// High
// No
// ----
// No
// Low
// ----
// High
// No
}
func ExampleTag_values() {
us := language.MustParseRegion("US")
en := language.MustParseBase("en")
lang, _, region := language.AmericanEnglish.Raw()
fmt.Println(lang == en, region == us)
lang, _, region = language.BritishEnglish.Raw()
fmt.Println(lang == en, region == us)
// Tags can be compared for exact equivalence using '=='.
en_us, _ := language.Compose(en, us)
fmt.Println(en_us == language.AmericanEnglish)
// Output:
// true true
// true false
// true
}
| kettle11/wabi | wabi/vendor/golang.org/x/text/language/examples_test.go | GO | mit | 11,347 |
function thisIsAFunctionWithAVeryLongNameAndWayTooManyParameters(thisIsTheFirstParameter, andThisOneIsRelatedToIt, butNotThisOne, andNeitherThis, inFactThereArentThatManyParameters) {
throw null;
}
| lokiiart/upali-mobile | www/frontend/node_modules/babel-plugin-syntax-trailing-function-commas/test/fixtures/trailing-function-commas/declaration/expected.js | JavaScript | gpl-3.0 | 200 |
<?php
/**
* CFileValidator class file.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @link http://www.yiiframework.com/
* @copyright Copyright © 2008-2011 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
/**
* CFileValidator verifies if an attribute is receiving a valid uploaded file.
*
* It uses the model class and attribute name to retrieve the information
* about the uploaded file. It then checks if a file is uploaded successfully,
* if the file size is within the limit and if the file type is allowed.
*
* This validator will attempt to fetch uploaded data if attribute is not
* previously set. Please note that this cannot be done if input is tabular:
* <pre>
* foreach($models as $i=>$model)
* $model->attribute = CUploadedFile::getInstance($model, "[$i]attribute");
* </pre>
* Please note that you must use {@link CUploadedFile::getInstances} for multiple
* file uploads.
*
* When using CFileValidator with an active record, the following code is often used:
* <pre>
* if($model->save())
* {
* // single upload
* $model->attribute->saveAs($path);
* // multiple upload
* foreach($model->attribute as $file)
* $file->saveAs($path);
* }
* </pre>
*
* You can use {@link CFileValidator} to validate the file attribute.
*
* In addition to the {@link message} property for setting a custom error message,
* CFileValidator has a few custom error messages you can set that correspond to different
* validation scenarios. When the file is too large, you may use the {@link tooLarge} property
* to define a custom error message. Similarly for {@link tooSmall}, {@link wrongType} and
* {@link tooMany}. The messages may contain additional placeholders that will be replaced
* with the actual content. In addition to the "{attribute}" placeholder, recognized by all
* validators (see {@link CValidator}), CFileValidator allows for the following placeholders
* to be specified:
* <ul>
* <li>{file}: replaced with the name of the file.</li>
* <li>{limit}: when using {@link tooLarge}, replaced with {@link maxSize};
* when using {@link tooSmall}, replaced with {@link minSize}; and when using {@link tooMany}
* replaced with {@link maxFiles}.</li>
* <li>{extensions}: when using {@link wrongType}, it will be replaced with the allowed extensions.</li>
* </ul>
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @package system.validators
* @since 1.0
*/
class CFileValidator extends CValidator
{
/**
* @var boolean whether the attribute requires a file to be uploaded or not.
* Defaults to false, meaning a file is required to be uploaded.
*/
public $allowEmpty=false;
/**
* @var mixed a list of file name extensions that are allowed to be uploaded.
* This can be either an array or a string consisting of file extension names
* separated by space or comma (e.g. "gif, jpg").
* Extension names are case-insensitive. Defaults to null, meaning all file name
* extensions are allowed.
*/
public $types;
/**
* @var mixed a list of MIME-types of the file that are allowed to be uploaded.
* This can be either an array or a string consisting of MIME-types separated
* by space or comma (e.g. "image/gif, image/jpeg"). MIME-types are
* case-insensitive. Defaults to null, meaning all MIME-types are allowed.
* In order to use this property fileinfo PECL extension should be installed.
* @since 1.1.11
*/
public $mimeTypes;
/**
* @var integer the minimum number of bytes required for the uploaded file.
* Defaults to null, meaning no limit.
* @see tooSmall
*/
public $minSize;
/**
* @var integer the maximum number of bytes required for the uploaded file.
* Defaults to null, meaning no limit.
* Note, the size limit is also affected by 'upload_max_filesize' INI setting
* and the 'MAX_FILE_SIZE' hidden field value.
* @see tooLarge
*/
public $maxSize;
/**
* @var string the error message used when the uploaded file is too large.
* @see maxSize
*/
public $tooLarge;
/**
* @var string the error message used when the uploaded file is too small.
* @see minSize
*/
public $tooSmall;
/**
* @var string the error message used when the uploaded file has an extension name
* that is not listed among {@link types}.
*/
public $wrongType;
/**
* @var string the error message used when the uploaded file has a MIME-type
* that is not listed among {@link mimeTypes}. In order to use this property
* fileinfo PECL extension should be installed.
* @since 1.1.11
*/
public $wrongMimeType;
/**
* @var integer the maximum file count the given attribute can hold.
* It defaults to 1, meaning single file upload. By defining a higher number,
* multiple uploads become possible.
*/
public $maxFiles=1;
/**
* @var string the error message used if the count of multiple uploads exceeds
* limit.
*/
public $tooMany;
/**
* @var boolean whether attributes listed with this validator should be considered safe for massive assignment.
* For this validator it defaults to false.
* @since 1.1.12
*/
public $safe=false;
/**
* Set the attribute and then validates using {@link validateFile}.
* If there is any error, the error message is added to the object.
* @param CModel $object the object being validated
* @param string $attribute the attribute being validated
*/
protected function validateAttribute($object, $attribute)
{
if($this->maxFiles > 1)
{
$files=$object->$attribute;
if(!is_array($files) || !isset($files[0]) || !$files[0] instanceof CUploadedFile)
$files = CUploadedFile::getInstances($object, $attribute);
if(array()===$files)
return $this->emptyAttribute($object, $attribute);
if(count($files) > $this->maxFiles)
{
$message=$this->tooMany!==null?$this->tooMany : Yii::t('yii', '{attribute} cannot accept more than {limit} files.');
$this->addError($object, $attribute, $message, array('{attribute}'=>$attribute, '{limit}'=>$this->maxFiles));
}
else
foreach($files as $file)
$this->validateFile($object, $attribute, $file);
}
else
{
$file = $object->$attribute;
if(!$file instanceof CUploadedFile)
{
$file = CUploadedFile::getInstance($object, $attribute);
if(null===$file)
return $this->emptyAttribute($object, $attribute);
}
$this->validateFile($object, $attribute, $file);
}
}
/**
* Internally validates a file object.
* @param CModel $object the object being validated
* @param string $attribute the attribute being validated
* @param CUploadedFile $file uploaded file passed to check against a set of rules
*/
protected function validateFile($object, $attribute, $file)
{
if(null===$file || ($error=$file->getError())==UPLOAD_ERR_NO_FILE)
return $this->emptyAttribute($object, $attribute);
elseif($error==UPLOAD_ERR_INI_SIZE || $error==UPLOAD_ERR_FORM_SIZE || $this->maxSize!==null && $file->getSize()>$this->maxSize)
{
$message=$this->tooLarge!==null?$this->tooLarge : Yii::t('yii','The file "{file}" is too large. Its size cannot exceed {limit} bytes.');
$this->addError($object,$attribute,$message,array('{file}'=>$file->getName(), '{limit}'=>$this->getSizeLimit()));
}
elseif($error==UPLOAD_ERR_PARTIAL)
throw new CException(Yii::t('yii','The file "{file}" was only partially uploaded.',array('{file}'=>$file->getName())));
elseif($error==UPLOAD_ERR_NO_TMP_DIR)
throw new CException(Yii::t('yii','Missing the temporary folder to store the uploaded file "{file}".',array('{file}'=>$file->getName())));
elseif($error==UPLOAD_ERR_CANT_WRITE)
throw new CException(Yii::t('yii','Failed to write the uploaded file "{file}" to disk.',array('{file}'=>$file->getName())));
elseif(defined('UPLOAD_ERR_EXTENSION') && $error==UPLOAD_ERR_EXTENSION) // available for PHP 5.2.0 or above
throw new CException(Yii::t('yii','File upload was stopped by extension.'));
if($this->minSize!==null && $file->getSize()<$this->minSize)
{
$message=$this->tooSmall!==null?$this->tooSmall : Yii::t('yii','The file "{file}" is too small. Its size cannot be smaller than {limit} bytes.');
$this->addError($object,$attribute,$message,array('{file}'=>$file->getName(), '{limit}'=>$this->minSize));
}
if($this->types!==null)
{
if(is_string($this->types))
$types=preg_split('/[\s,]+/',strtolower($this->types),-1,PREG_SPLIT_NO_EMPTY);
else
$types=$this->types;
if(!in_array(strtolower($file->getExtensionName()),$types))
{
$message=$this->wrongType!==null?$this->wrongType : Yii::t('yii','The file "{file}" cannot be uploaded. Only files with these extensions are allowed: {extensions}.');
$this->addError($object,$attribute,$message,array('{file}'=>$file->getName(), '{extensions}'=>implode(', ',$types)));
}
}
if($this->mimeTypes!==null)
{
if(function_exists('finfo_open'))
{
$mimeType=false;
if($info=finfo_open(defined('FILEINFO_MIME_TYPE') ? FILEINFO_MIME_TYPE : FILEINFO_MIME))
$mimeType=finfo_file($info,$file->getTempName());
}
elseif(function_exists('mime_content_type'))
$mimeType=mime_content_type($file->getTempName());
else
throw new CException(Yii::t('yii','In order to use MIME-type validation provided by CFileValidator fileinfo PECL extension should be installed.'));
if(is_string($this->mimeTypes))
$mimeTypes=preg_split('/[\s,]+/',strtolower($this->mimeTypes),-1,PREG_SPLIT_NO_EMPTY);
else
$mimeTypes=$this->mimeTypes;
if($mimeType===false || !in_array(strtolower($mimeType),$mimeTypes))
{
$message=$this->wrongMimeType!==null?$this->wrongMimeType : Yii::t('yii','The file "{file}" cannot be uploaded. Only files of these MIME-types are allowed: {mimeTypes}.');
$this->addError($object,$attribute,$message,array('{file}'=>$file->getName(), '{mimeTypes}'=>implode(', ',$mimeTypes)));
}
}
}
/**
* Raises an error to inform end user about blank attribute.
* @param CModel $object the object being validated
* @param string $attribute the attribute being validated
*/
protected function emptyAttribute($object, $attribute)
{
if(!$this->allowEmpty)
{
$message=$this->message!==null?$this->message : Yii::t('yii','{attribute} cannot be blank.');
$this->addError($object,$attribute,$message);
}
}
/**
* Returns the maximum size allowed for uploaded files.
* This is determined based on three factors:
* <ul>
* <li>'upload_max_filesize' in php.ini</li>
* <li>'MAX_FILE_SIZE' hidden field</li>
* <li>{@link maxSize}</li>
* </ul>
*
* @return integer the size limit for uploaded files.
*/
protected function getSizeLimit()
{
$limit=ini_get('upload_max_filesize');
$limit=$this->sizeToBytes($limit);
if($this->maxSize!==null && $limit>0 && $this->maxSize<$limit)
$limit=$this->maxSize;
if(isset($_POST['MAX_FILE_SIZE']) && $_POST['MAX_FILE_SIZE']>0 && $_POST['MAX_FILE_SIZE']<$limit)
$limit=$_POST['MAX_FILE_SIZE'];
return $limit;
}
/**
* Converts php.ini style size to bytes. Examples of size strings are: 150, 1g, 500k, 5M (size suffix
* is case insensitive). If you pass here the number with a fractional part, then everything after
* the decimal point will be ignored (php.ini values common behavior). For example 1.5G value would be
* treated as 1G and 1073741824 number will be returned as a result. This method is public
* (was private before) since 1.1.11.
*
* @param string $sizeStr the size string to convert.
* @return integer the byte count in the given size string.
* @since 1.1.11
*/
public function sizeToBytes($sizeStr)
{
// get the latest character
switch (strtolower(substr($sizeStr, -1)))
{
case 'm': return (int)$sizeStr * 1048576; // 1024 * 1024
case 'k': return (int)$sizeStr * 1024; // 1024
case 'g': return (int)$sizeStr * 1073741824; // 1024 * 1024 * 1024
default: return (int)$sizeStr; // do nothing
}
}
} | thu0ng91/yanyen | yii/validators/CFileValidator.php | PHP | bsd-2-clause | 11,916 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Reflection.Metadata
{
public enum ImportDefinitionKind
{
ImportNamespace = 1,
ImportAssemblyNamespace = 2,
ImportType = 3,
ImportXmlNamespace = 4,
ImportAssemblyReferenceAlias = 5,
AliasAssemblyReference = 6,
AliasNamespace = 7,
AliasAssemblyNamespace = 8,
AliasType = 9
}
}
| shahid-pk/corefx | src/System.Reflection.Metadata/src/System/Reflection/Metadata/PortablePdb/ImportDefinitionKind.cs | C# | mit | 580 |
/*
Copyright 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.
*/
// Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: k8s.io/kubernetes/vendor/k8s.io/api/apiserverinternal/v1alpha1/generated.proto
package v1alpha1
import (
fmt "fmt"
io "io"
proto "github.com/gogo/protobuf/proto"
math "math"
math_bits "math/bits"
reflect "reflect"
strings "strings"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package
func (m *ServerStorageVersion) Reset() { *m = ServerStorageVersion{} }
func (*ServerStorageVersion) ProtoMessage() {}
func (*ServerStorageVersion) Descriptor() ([]byte, []int) {
return fileDescriptor_a3903ff5e3cc7a03, []int{0}
}
func (m *ServerStorageVersion) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *ServerStorageVersion) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
func (m *ServerStorageVersion) XXX_Merge(src proto.Message) {
xxx_messageInfo_ServerStorageVersion.Merge(m, src)
}
func (m *ServerStorageVersion) XXX_Size() int {
return m.Size()
}
func (m *ServerStorageVersion) XXX_DiscardUnknown() {
xxx_messageInfo_ServerStorageVersion.DiscardUnknown(m)
}
var xxx_messageInfo_ServerStorageVersion proto.InternalMessageInfo
func (m *StorageVersion) Reset() { *m = StorageVersion{} }
func (*StorageVersion) ProtoMessage() {}
func (*StorageVersion) Descriptor() ([]byte, []int) {
return fileDescriptor_a3903ff5e3cc7a03, []int{1}
}
func (m *StorageVersion) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *StorageVersion) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
func (m *StorageVersion) XXX_Merge(src proto.Message) {
xxx_messageInfo_StorageVersion.Merge(m, src)
}
func (m *StorageVersion) XXX_Size() int {
return m.Size()
}
func (m *StorageVersion) XXX_DiscardUnknown() {
xxx_messageInfo_StorageVersion.DiscardUnknown(m)
}
var xxx_messageInfo_StorageVersion proto.InternalMessageInfo
func (m *StorageVersionCondition) Reset() { *m = StorageVersionCondition{} }
func (*StorageVersionCondition) ProtoMessage() {}
func (*StorageVersionCondition) Descriptor() ([]byte, []int) {
return fileDescriptor_a3903ff5e3cc7a03, []int{2}
}
func (m *StorageVersionCondition) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *StorageVersionCondition) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
func (m *StorageVersionCondition) XXX_Merge(src proto.Message) {
xxx_messageInfo_StorageVersionCondition.Merge(m, src)
}
func (m *StorageVersionCondition) XXX_Size() int {
return m.Size()
}
func (m *StorageVersionCondition) XXX_DiscardUnknown() {
xxx_messageInfo_StorageVersionCondition.DiscardUnknown(m)
}
var xxx_messageInfo_StorageVersionCondition proto.InternalMessageInfo
func (m *StorageVersionList) Reset() { *m = StorageVersionList{} }
func (*StorageVersionList) ProtoMessage() {}
func (*StorageVersionList) Descriptor() ([]byte, []int) {
return fileDescriptor_a3903ff5e3cc7a03, []int{3}
}
func (m *StorageVersionList) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *StorageVersionList) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
func (m *StorageVersionList) XXX_Merge(src proto.Message) {
xxx_messageInfo_StorageVersionList.Merge(m, src)
}
func (m *StorageVersionList) XXX_Size() int {
return m.Size()
}
func (m *StorageVersionList) XXX_DiscardUnknown() {
xxx_messageInfo_StorageVersionList.DiscardUnknown(m)
}
var xxx_messageInfo_StorageVersionList proto.InternalMessageInfo
func (m *StorageVersionSpec) Reset() { *m = StorageVersionSpec{} }
func (*StorageVersionSpec) ProtoMessage() {}
func (*StorageVersionSpec) Descriptor() ([]byte, []int) {
return fileDescriptor_a3903ff5e3cc7a03, []int{4}
}
func (m *StorageVersionSpec) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *StorageVersionSpec) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
func (m *StorageVersionSpec) XXX_Merge(src proto.Message) {
xxx_messageInfo_StorageVersionSpec.Merge(m, src)
}
func (m *StorageVersionSpec) XXX_Size() int {
return m.Size()
}
func (m *StorageVersionSpec) XXX_DiscardUnknown() {
xxx_messageInfo_StorageVersionSpec.DiscardUnknown(m)
}
var xxx_messageInfo_StorageVersionSpec proto.InternalMessageInfo
func (m *StorageVersionStatus) Reset() { *m = StorageVersionStatus{} }
func (*StorageVersionStatus) ProtoMessage() {}
func (*StorageVersionStatus) Descriptor() ([]byte, []int) {
return fileDescriptor_a3903ff5e3cc7a03, []int{5}
}
func (m *StorageVersionStatus) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *StorageVersionStatus) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
func (m *StorageVersionStatus) XXX_Merge(src proto.Message) {
xxx_messageInfo_StorageVersionStatus.Merge(m, src)
}
func (m *StorageVersionStatus) XXX_Size() int {
return m.Size()
}
func (m *StorageVersionStatus) XXX_DiscardUnknown() {
xxx_messageInfo_StorageVersionStatus.DiscardUnknown(m)
}
var xxx_messageInfo_StorageVersionStatus proto.InternalMessageInfo
func init() {
proto.RegisterType((*ServerStorageVersion)(nil), "k8s.io.api.apiserverinternal.v1alpha1.ServerStorageVersion")
proto.RegisterType((*StorageVersion)(nil), "k8s.io.api.apiserverinternal.v1alpha1.StorageVersion")
proto.RegisterType((*StorageVersionCondition)(nil), "k8s.io.api.apiserverinternal.v1alpha1.StorageVersionCondition")
proto.RegisterType((*StorageVersionList)(nil), "k8s.io.api.apiserverinternal.v1alpha1.StorageVersionList")
proto.RegisterType((*StorageVersionSpec)(nil), "k8s.io.api.apiserverinternal.v1alpha1.StorageVersionSpec")
proto.RegisterType((*StorageVersionStatus)(nil), "k8s.io.api.apiserverinternal.v1alpha1.StorageVersionStatus")
}
func init() {
proto.RegisterFile("k8s.io/kubernetes/vendor/k8s.io/api/apiserverinternal/v1alpha1/generated.proto", fileDescriptor_a3903ff5e3cc7a03)
}
var fileDescriptor_a3903ff5e3cc7a03 = []byte{
// 763 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x54, 0x4f, 0x4f, 0x13, 0x41,
0x14, 0xef, 0xd2, 0x52, 0x60, 0xaa, 0x54, 0x46, 0x08, 0xb5, 0x26, 0x5b, 0x6c, 0xa2, 0x41, 0x8d,
0xbb, 0xd2, 0x88, 0x91, 0x98, 0x68, 0x58, 0x20, 0x06, 0x03, 0x62, 0x06, 0xe2, 0x01, 0x3d, 0x38,
0xdd, 0x1d, 0xb7, 0x6b, 0xbb, 0x3b, 0x9b, 0x9d, 0x69, 0x13, 0x2e, 0xc6, 0x8f, 0xe0, 0x07, 0xf1,
0xe8, 0x87, 0xe0, 0x64, 0xb8, 0x98, 0x90, 0x98, 0x34, 0xb2, 0x7e, 0x0b, 0x4e, 0x66, 0x66, 0x77,
0x5b, 0xb6, 0x2d, 0xb1, 0xe1, 0xb0, 0xc9, 0xce, 0x7b, 0xef, 0xf7, 0x7b, 0x7f, 0xe6, 0x37, 0x0f,
0xbc, 0x69, 0x3e, 0x63, 0x9a, 0x43, 0xf5, 0x66, 0xbb, 0x4e, 0x02, 0x8f, 0x70, 0xc2, 0xf4, 0x0e,
0xf1, 0x2c, 0x1a, 0xe8, 0xb1, 0x03, 0xfb, 0x8e, 0xf8, 0x18, 0x09, 0x3a, 0x24, 0x70, 0x3c, 0x4e,
0x02, 0x0f, 0xb7, 0xf4, 0xce, 0x0a, 0x6e, 0xf9, 0x0d, 0xbc, 0xa2, 0xdb, 0xc4, 0x23, 0x01, 0xe6,
0xc4, 0xd2, 0xfc, 0x80, 0x72, 0x0a, 0xef, 0x46, 0x30, 0x0d, 0xfb, 0x8e, 0x36, 0x04, 0xd3, 0x12,
0x58, 0xf9, 0x91, 0xed, 0xf0, 0x46, 0xbb, 0xae, 0x99, 0xd4, 0xd5, 0x6d, 0x6a, 0x53, 0x5d, 0xa2,
0xeb, 0xed, 0x4f, 0xf2, 0x24, 0x0f, 0xf2, 0x2f, 0x62, 0x2d, 0x3f, 0xe9, 0x17, 0xe3, 0x62, 0xb3,
0xe1, 0x78, 0x24, 0x38, 0xd2, 0xfd, 0xa6, 0x2d, 0x2b, 0xd3, 0x5d, 0xc2, 0xb1, 0xde, 0x19, 0xaa,
0xa5, 0xac, 0x5f, 0x86, 0x0a, 0xda, 0x1e, 0x77, 0x5c, 0x32, 0x04, 0x78, 0xfa, 0x3f, 0x00, 0x33,
0x1b, 0xc4, 0xc5, 0x83, 0xb8, 0xea, 0x2f, 0x05, 0xcc, 0xef, 0xcb, 0x4e, 0xf7, 0x39, 0x0d, 0xb0,
0x4d, 0xde, 0x91, 0x80, 0x39, 0xd4, 0x83, 0xab, 0xa0, 0x80, 0x7d, 0x27, 0x72, 0x6d, 0x6f, 0x96,
0x94, 0x25, 0x65, 0x79, 0xc6, 0xb8, 0x79, 0xdc, 0xad, 0x64, 0xc2, 0x6e, 0xa5, 0xb0, 0xfe, 0x76,
0x3b, 0x71, 0xa1, 0x8b, 0x71, 0x70, 0x1d, 0x14, 0x89, 0x67, 0x52, 0xcb, 0xf1, 0xec, 0x98, 0xa9,
0x34, 0x21, 0xa1, 0x8b, 0x31, 0xb4, 0xb8, 0x95, 0x76, 0xa3, 0xc1, 0x78, 0xb8, 0x01, 0xe6, 0x2c,
0x62, 0x52, 0x0b, 0xd7, 0x5b, 0x49, 0x35, 0xac, 0x94, 0x5d, 0xca, 0x2e, 0xcf, 0x18, 0x0b, 0x61,
0xb7, 0x32, 0xb7, 0x39, 0xe8, 0x44, 0xc3, 0xf1, 0xd5, 0x1f, 0x13, 0x60, 0x76, 0xa0, 0xa3, 0x8f,
0x60, 0x5a, 0x8c, 0xdb, 0xc2, 0x1c, 0xcb, 0x76, 0x0a, 0xb5, 0xc7, 0x5a, 0xff, 0xca, 0x7b, 0x53,
0xd3, 0xfc, 0xa6, 0x2d, 0xef, 0x5f, 0x13, 0xd1, 0x5a, 0x67, 0x45, 0xdb, 0xab, 0x7f, 0x26, 0x26,
0xdf, 0x25, 0x1c, 0x1b, 0x30, 0xee, 0x02, 0xf4, 0x6d, 0xa8, 0xc7, 0x0a, 0xdf, 0x83, 0x1c, 0xf3,
0x89, 0x29, 0x3b, 0x2e, 0xd4, 0xd6, 0xb4, 0xb1, 0x04, 0xa5, 0xa5, 0xcb, 0xdc, 0xf7, 0x89, 0x69,
0x5c, 0x8b, 0xd3, 0xe4, 0xc4, 0x09, 0x49, 0x52, 0x68, 0x82, 0x3c, 0xe3, 0x98, 0xb7, 0xc5, 0x2c,
0x04, 0xfd, 0xf3, 0xab, 0xd1, 0x4b, 0x0a, 0x63, 0x36, 0x4e, 0x90, 0x8f, 0xce, 0x28, 0xa6, 0xae,
0x7e, 0xcf, 0x82, 0xc5, 0x34, 0x60, 0x83, 0x7a, 0x96, 0xc3, 0xc5, 0xfc, 0x5e, 0x82, 0x1c, 0x3f,
0xf2, 0x49, 0x2c, 0x85, 0x87, 0x49, 0x89, 0x07, 0x47, 0x3e, 0x39, 0xef, 0x56, 0x6e, 0x5f, 0x02,
0x13, 0x6e, 0x24, 0x81, 0x70, 0xad, 0xd7, 0x41, 0x24, 0x89, 0x3b, 0xe9, 0x22, 0xce, 0xbb, 0x95,
0x62, 0x0f, 0x96, 0xae, 0x0b, 0xbe, 0x06, 0x90, 0xd6, 0x65, 0x87, 0xd6, 0xab, 0x48, 0xc1, 0x42,
0x59, 0x62, 0x10, 0x59, 0xa3, 0x1c, 0xd3, 0xc0, 0xbd, 0xa1, 0x08, 0x34, 0x02, 0x05, 0x3b, 0x00,
0xb6, 0x30, 0xe3, 0x07, 0x01, 0xf6, 0x58, 0x54, 0xa2, 0xe3, 0x92, 0x52, 0x4e, 0x0e, 0xf5, 0xc1,
0x78, 0x8a, 0x10, 0x88, 0x7e, 0xde, 0x9d, 0x21, 0x36, 0x34, 0x22, 0x03, 0xbc, 0x07, 0xf2, 0x01,
0xc1, 0x8c, 0x7a, 0xa5, 0x49, 0xd9, 0x7e, 0xef, 0x0e, 0x90, 0xb4, 0xa2, 0xd8, 0x0b, 0xef, 0x83,
0x29, 0x97, 0x30, 0x86, 0x6d, 0x52, 0xca, 0xcb, 0xc0, 0x62, 0x1c, 0x38, 0xb5, 0x1b, 0x99, 0x51,
0xe2, 0xaf, 0xfe, 0x54, 0x00, 0x4c, 0xcf, 0x7d, 0xc7, 0x61, 0x1c, 0x7e, 0x18, 0x52, 0xba, 0x36,
0x5e, 0x5f, 0x02, 0x2d, 0x75, 0x7e, 0x23, 0x4e, 0x39, 0x9d, 0x58, 0x2e, 0xa8, 0xfc, 0x10, 0x4c,
0x3a, 0x9c, 0xb8, 0xe2, 0x16, 0xb3, 0xcb, 0x85, 0xda, 0xea, 0x95, 0x74, 0x68, 0x5c, 0x8f, 0x33,
0x4c, 0x6e, 0x0b, 0x2e, 0x14, 0x51, 0x56, 0xe7, 0x07, 0xfb, 0x11, 0x0f, 0xa0, 0xfa, 0x7b, 0x02,
0xcc, 0x8f, 0x92, 0x31, 0xfc, 0x02, 0x8a, 0x2c, 0x65, 0x67, 0x25, 0x45, 0x16, 0x35, 0xf6, 0xe3,
0x18, 0xb1, 0xfa, 0xfa, 0xab, 0x2a, 0x6d, 0x67, 0x68, 0x30, 0x19, 0xdc, 0x03, 0x0b, 0x26, 0x75,
0x5d, 0xea, 0x6d, 0x8d, 0xdc, 0x79, 0xb7, 0xc2, 0x6e, 0x65, 0x61, 0x63, 0x54, 0x00, 0x1a, 0x8d,
0x83, 0x01, 0x00, 0x66, 0xf2, 0x04, 0xa2, 0xa5, 0x57, 0xa8, 0xbd, 0xb8, 0xd2, 0x80, 0x7b, 0x2f,
0xa9, 0xbf, 0xb3, 0x7a, 0x26, 0x86, 0x2e, 0x64, 0x31, 0xb4, 0xe3, 0x33, 0x35, 0x73, 0x72, 0xa6,
0x66, 0x4e, 0xcf, 0xd4, 0xcc, 0xd7, 0x50, 0x55, 0x8e, 0x43, 0x55, 0x39, 0x09, 0x55, 0xe5, 0x34,
0x54, 0x95, 0x3f, 0xa1, 0xaa, 0x7c, 0xfb, 0xab, 0x66, 0x0e, 0xa7, 0x93, 0x3c, 0xff, 0x02, 0x00,
0x00, 0xff, 0xff, 0xa1, 0x5f, 0xcf, 0x37, 0x78, 0x07, 0x00, 0x00,
}
func (m *ServerStorageVersion) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *ServerStorageVersion) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *ServerStorageVersion) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.DecodableVersions) > 0 {
for iNdEx := len(m.DecodableVersions) - 1; iNdEx >= 0; iNdEx-- {
i -= len(m.DecodableVersions[iNdEx])
copy(dAtA[i:], m.DecodableVersions[iNdEx])
i = encodeVarintGenerated(dAtA, i, uint64(len(m.DecodableVersions[iNdEx])))
i--
dAtA[i] = 0x1a
}
}
i -= len(m.EncodingVersion)
copy(dAtA[i:], m.EncodingVersion)
i = encodeVarintGenerated(dAtA, i, uint64(len(m.EncodingVersion)))
i--
dAtA[i] = 0x12
i -= len(m.APIServerID)
copy(dAtA[i:], m.APIServerID)
i = encodeVarintGenerated(dAtA, i, uint64(len(m.APIServerID)))
i--
dAtA[i] = 0xa
return len(dAtA) - i, nil
}
func (m *StorageVersion) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *StorageVersion) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *StorageVersion) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
{
size, err := m.Status.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintGenerated(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x1a
{
size, err := m.Spec.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintGenerated(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
{
size, err := m.ObjectMeta.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintGenerated(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
return len(dAtA) - i, nil
}
func (m *StorageVersionCondition) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *StorageVersionCondition) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *StorageVersionCondition) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
i -= len(m.Message)
copy(dAtA[i:], m.Message)
i = encodeVarintGenerated(dAtA, i, uint64(len(m.Message)))
i--
dAtA[i] = 0x32
i -= len(m.Reason)
copy(dAtA[i:], m.Reason)
i = encodeVarintGenerated(dAtA, i, uint64(len(m.Reason)))
i--
dAtA[i] = 0x2a
{
size, err := m.LastTransitionTime.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintGenerated(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x22
i = encodeVarintGenerated(dAtA, i, uint64(m.ObservedGeneration))
i--
dAtA[i] = 0x18
i -= len(m.Status)
copy(dAtA[i:], m.Status)
i = encodeVarintGenerated(dAtA, i, uint64(len(m.Status)))
i--
dAtA[i] = 0x12
i -= len(m.Type)
copy(dAtA[i:], m.Type)
i = encodeVarintGenerated(dAtA, i, uint64(len(m.Type)))
i--
dAtA[i] = 0xa
return len(dAtA) - i, nil
}
func (m *StorageVersionList) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *StorageVersionList) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *StorageVersionList) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Items) > 0 {
for iNdEx := len(m.Items) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.Items[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintGenerated(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
}
}
{
size, err := m.ListMeta.MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintGenerated(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
return len(dAtA) - i, nil
}
func (m *StorageVersionSpec) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *StorageVersionSpec) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *StorageVersionSpec) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
return len(dAtA) - i, nil
}
func (m *StorageVersionStatus) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *StorageVersionStatus) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *StorageVersionStatus) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Conditions) > 0 {
for iNdEx := len(m.Conditions) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.Conditions[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintGenerated(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x1a
}
}
if m.CommonEncodingVersion != nil {
i -= len(*m.CommonEncodingVersion)
copy(dAtA[i:], *m.CommonEncodingVersion)
i = encodeVarintGenerated(dAtA, i, uint64(len(*m.CommonEncodingVersion)))
i--
dAtA[i] = 0x12
}
if len(m.StorageVersions) > 0 {
for iNdEx := len(m.StorageVersions) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.StorageVersions[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintGenerated(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
}
}
return len(dAtA) - i, nil
}
func encodeVarintGenerated(dAtA []byte, offset int, v uint64) int {
offset -= sovGenerated(v)
base := offset
for v >= 1<<7 {
dAtA[offset] = uint8(v&0x7f | 0x80)
v >>= 7
offset++
}
dAtA[offset] = uint8(v)
return base
}
func (m *ServerStorageVersion) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.APIServerID)
n += 1 + l + sovGenerated(uint64(l))
l = len(m.EncodingVersion)
n += 1 + l + sovGenerated(uint64(l))
if len(m.DecodableVersions) > 0 {
for _, s := range m.DecodableVersions {
l = len(s)
n += 1 + l + sovGenerated(uint64(l))
}
}
return n
}
func (m *StorageVersion) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = m.ObjectMeta.Size()
n += 1 + l + sovGenerated(uint64(l))
l = m.Spec.Size()
n += 1 + l + sovGenerated(uint64(l))
l = m.Status.Size()
n += 1 + l + sovGenerated(uint64(l))
return n
}
func (m *StorageVersionCondition) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Type)
n += 1 + l + sovGenerated(uint64(l))
l = len(m.Status)
n += 1 + l + sovGenerated(uint64(l))
n += 1 + sovGenerated(uint64(m.ObservedGeneration))
l = m.LastTransitionTime.Size()
n += 1 + l + sovGenerated(uint64(l))
l = len(m.Reason)
n += 1 + l + sovGenerated(uint64(l))
l = len(m.Message)
n += 1 + l + sovGenerated(uint64(l))
return n
}
func (m *StorageVersionList) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = m.ListMeta.Size()
n += 1 + l + sovGenerated(uint64(l))
if len(m.Items) > 0 {
for _, e := range m.Items {
l = e.Size()
n += 1 + l + sovGenerated(uint64(l))
}
}
return n
}
func (m *StorageVersionSpec) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
return n
}
func (m *StorageVersionStatus) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if len(m.StorageVersions) > 0 {
for _, e := range m.StorageVersions {
l = e.Size()
n += 1 + l + sovGenerated(uint64(l))
}
}
if m.CommonEncodingVersion != nil {
l = len(*m.CommonEncodingVersion)
n += 1 + l + sovGenerated(uint64(l))
}
if len(m.Conditions) > 0 {
for _, e := range m.Conditions {
l = e.Size()
n += 1 + l + sovGenerated(uint64(l))
}
}
return n
}
func sovGenerated(x uint64) (n int) {
return (math_bits.Len64(x|1) + 6) / 7
}
func sozGenerated(x uint64) (n int) {
return sovGenerated(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func (this *ServerStorageVersion) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&ServerStorageVersion{`,
`APIServerID:` + fmt.Sprintf("%v", this.APIServerID) + `,`,
`EncodingVersion:` + fmt.Sprintf("%v", this.EncodingVersion) + `,`,
`DecodableVersions:` + fmt.Sprintf("%v", this.DecodableVersions) + `,`,
`}`,
}, "")
return s
}
func (this *StorageVersion) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&StorageVersion{`,
`ObjectMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ObjectMeta), "ObjectMeta", "v1.ObjectMeta", 1), `&`, ``, 1) + `,`,
`Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "StorageVersionSpec", "StorageVersionSpec", 1), `&`, ``, 1) + `,`,
`Status:` + strings.Replace(strings.Replace(this.Status.String(), "StorageVersionStatus", "StorageVersionStatus", 1), `&`, ``, 1) + `,`,
`}`,
}, "")
return s
}
func (this *StorageVersionCondition) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&StorageVersionCondition{`,
`Type:` + fmt.Sprintf("%v", this.Type) + `,`,
`Status:` + fmt.Sprintf("%v", this.Status) + `,`,
`ObservedGeneration:` + fmt.Sprintf("%v", this.ObservedGeneration) + `,`,
`LastTransitionTime:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.LastTransitionTime), "Time", "v1.Time", 1), `&`, ``, 1) + `,`,
`Reason:` + fmt.Sprintf("%v", this.Reason) + `,`,
`Message:` + fmt.Sprintf("%v", this.Message) + `,`,
`}`,
}, "")
return s
}
func (this *StorageVersionList) String() string {
if this == nil {
return "nil"
}
repeatedStringForItems := "[]StorageVersion{"
for _, f := range this.Items {
repeatedStringForItems += strings.Replace(strings.Replace(f.String(), "StorageVersion", "StorageVersion", 1), `&`, ``, 1) + ","
}
repeatedStringForItems += "}"
s := strings.Join([]string{`&StorageVersionList{`,
`ListMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ListMeta), "ListMeta", "v1.ListMeta", 1), `&`, ``, 1) + `,`,
`Items:` + repeatedStringForItems + `,`,
`}`,
}, "")
return s
}
func (this *StorageVersionSpec) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&StorageVersionSpec{`,
`}`,
}, "")
return s
}
func (this *StorageVersionStatus) String() string {
if this == nil {
return "nil"
}
repeatedStringForStorageVersions := "[]ServerStorageVersion{"
for _, f := range this.StorageVersions {
repeatedStringForStorageVersions += strings.Replace(strings.Replace(f.String(), "ServerStorageVersion", "ServerStorageVersion", 1), `&`, ``, 1) + ","
}
repeatedStringForStorageVersions += "}"
repeatedStringForConditions := "[]StorageVersionCondition{"
for _, f := range this.Conditions {
repeatedStringForConditions += strings.Replace(strings.Replace(f.String(), "StorageVersionCondition", "StorageVersionCondition", 1), `&`, ``, 1) + ","
}
repeatedStringForConditions += "}"
s := strings.Join([]string{`&StorageVersionStatus{`,
`StorageVersions:` + repeatedStringForStorageVersions + `,`,
`CommonEncodingVersion:` + valueToStringGenerated(this.CommonEncodingVersion) + `,`,
`Conditions:` + repeatedStringForConditions + `,`,
`}`,
}, "")
return s
}
func valueToStringGenerated(v interface{}) string {
rv := reflect.ValueOf(v)
if rv.IsNil() {
return "nil"
}
pv := reflect.Indirect(rv).Interface()
return fmt.Sprintf("*%v", pv)
}
func (m *ServerStorageVersion) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenerated
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: ServerStorageVersion: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: ServerStorageVersion: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field APIServerID", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenerated
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthGenerated
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthGenerated
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.APIServerID = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field EncodingVersion", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenerated
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthGenerated
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthGenerated
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.EncodingVersion = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field DecodableVersions", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenerated
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthGenerated
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthGenerated
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.DecodableVersions = append(m.DecodableVersions, string(dAtA[iNdEx:postIndex]))
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipGenerated(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthGenerated
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *StorageVersion) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenerated
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: StorageVersion: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: StorageVersion: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ObjectMeta", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenerated
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthGenerated
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthGenerated
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.ObjectMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Spec", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenerated
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthGenerated
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthGenerated
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.Spec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenerated
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthGenerated
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthGenerated
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.Status.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipGenerated(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthGenerated
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *StorageVersionCondition) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenerated
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: StorageVersionCondition: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: StorageVersionCondition: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenerated
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthGenerated
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthGenerated
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Type = StorageVersionConditionType(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenerated
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthGenerated
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthGenerated
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Status = ConditionStatus(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 3:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field ObservedGeneration", wireType)
}
m.ObservedGeneration = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenerated
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.ObservedGeneration |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 4:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field LastTransitionTime", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenerated
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthGenerated
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthGenerated
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.LastTransitionTime.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 5:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Reason", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenerated
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthGenerated
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthGenerated
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Reason = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 6:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Message", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenerated
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthGenerated
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthGenerated
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Message = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipGenerated(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthGenerated
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *StorageVersionList) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenerated
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: StorageVersionList: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: StorageVersionList: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ListMeta", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenerated
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthGenerated
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthGenerated
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.ListMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Items", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenerated
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthGenerated
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthGenerated
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Items = append(m.Items, StorageVersion{})
if err := m.Items[len(m.Items)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipGenerated(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthGenerated
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *StorageVersionSpec) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenerated
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: StorageVersionSpec: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: StorageVersionSpec: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
default:
iNdEx = preIndex
skippy, err := skipGenerated(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthGenerated
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *StorageVersionStatus) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenerated
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: StorageVersionStatus: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: StorageVersionStatus: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field StorageVersions", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenerated
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthGenerated
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthGenerated
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.StorageVersions = append(m.StorageVersions, ServerStorageVersion{})
if err := m.StorageVersions[len(m.StorageVersions)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field CommonEncodingVersion", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenerated
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthGenerated
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthGenerated
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
s := string(dAtA[iNdEx:postIndex])
m.CommonEncodingVersion = &s
iNdEx = postIndex
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Conditions", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenerated
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthGenerated
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthGenerated
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Conditions = append(m.Conditions, StorageVersionCondition{})
if err := m.Conditions[len(m.Conditions)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipGenerated(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthGenerated
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func skipGenerated(dAtA []byte) (n int, err error) {
l := len(dAtA)
iNdEx := 0
depth := 0
for iNdEx < l {
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowGenerated
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
wireType := int(wire & 0x7)
switch wireType {
case 0:
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowGenerated
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
iNdEx++
if dAtA[iNdEx-1] < 0x80 {
break
}
}
case 1:
iNdEx += 8
case 2:
var length int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowGenerated
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
length |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if length < 0 {
return 0, ErrInvalidLengthGenerated
}
iNdEx += length
case 3:
depth++
case 4:
if depth == 0 {
return 0, ErrUnexpectedEndOfGroupGenerated
}
depth--
case 5:
iNdEx += 4
default:
return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
}
if iNdEx < 0 {
return 0, ErrInvalidLengthGenerated
}
if depth == 0 {
return iNdEx, nil
}
}
return 0, io.ErrUnexpectedEOF
}
var (
ErrInvalidLengthGenerated = fmt.Errorf("proto: negative length found during unmarshaling")
ErrIntOverflowGenerated = fmt.Errorf("proto: integer overflow")
ErrUnexpectedEndOfGroupGenerated = fmt.Errorf("proto: unexpected end of group")
)
| grafana/loki | vendor/k8s.io/api/apiserverinternal/v1alpha1/generated.pb.go | GO | agpl-3.0 | 45,028 |
/**
* Copyright 2013-2015, Facebook, 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.
*
* @typechecks
* @providesModule ReactCSSTransitionGroupChild
*/
'use strict';
var React = require('./React');
var ReactDOM = require('./ReactDOM');
var CSSCore = require('fbjs/lib/CSSCore');
var ReactTransitionEvents = require('./ReactTransitionEvents');
var onlyChild = require('./onlyChild');
// We don't remove the element from the DOM until we receive an animationend or
// transitionend event. If the user screws up and forgets to add an animation
// their node will be stuck in the DOM forever, so we detect if an animation
// does not start and if it doesn't, we just call the end listener immediately.
var TICK = 17;
var ReactCSSTransitionGroupChild = React.createClass({
displayName: 'ReactCSSTransitionGroupChild',
propTypes: {
name: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.shape({
enter: React.PropTypes.string,
leave: React.PropTypes.string,
active: React.PropTypes.string
}), React.PropTypes.shape({
enter: React.PropTypes.string,
enterActive: React.PropTypes.string,
leave: React.PropTypes.string,
leaveActive: React.PropTypes.string,
appear: React.PropTypes.string,
appearActive: React.PropTypes.string
})]).isRequired,
// Once we require timeouts to be specified, we can remove the
// boolean flags (appear etc.) and just accept a number
// or a bool for the timeout flags (appearTimeout etc.)
appear: React.PropTypes.bool,
enter: React.PropTypes.bool,
leave: React.PropTypes.bool,
appearTimeout: React.PropTypes.number,
enterTimeout: React.PropTypes.number,
leaveTimeout: React.PropTypes.number
},
transition: function (animationType, finishCallback, userSpecifiedDelay) {
var node = ReactDOM.findDOMNode(this);
if (!node) {
if (finishCallback) {
finishCallback();
}
return;
}
var className = this.props.name[animationType] || this.props.name + '-' + animationType;
var activeClassName = this.props.name[animationType + 'Active'] || className + '-active';
var timeout = null;
var endListener = function (e) {
if (e && e.target !== node) {
return;
}
clearTimeout(timeout);
CSSCore.removeClass(node, className);
CSSCore.removeClass(node, activeClassName);
ReactTransitionEvents.removeEndEventListener(node, endListener);
// Usually this optional callback is used for informing an owner of
// a leave animation and telling it to remove the child.
if (finishCallback) {
finishCallback();
}
};
CSSCore.addClass(node, className);
// Need to do this to actually trigger a transition.
this.queueClass(activeClassName);
// If the user specified a timeout delay.
if (userSpecifiedDelay) {
// Clean-up the animation after the specified delay
timeout = setTimeout(endListener, userSpecifiedDelay);
this.transitionTimeouts.push(timeout);
} else {
// DEPRECATED: this listener will be removed in a future version of react
ReactTransitionEvents.addEndEventListener(node, endListener);
}
},
queueClass: function (className) {
this.classNameQueue.push(className);
if (!this.timeout) {
this.timeout = setTimeout(this.flushClassNameQueue, TICK);
}
},
flushClassNameQueue: function () {
if (this.isMounted()) {
this.classNameQueue.forEach(CSSCore.addClass.bind(CSSCore, ReactDOM.findDOMNode(this)));
}
this.classNameQueue.length = 0;
this.timeout = null;
},
componentWillMount: function () {
this.classNameQueue = [];
this.transitionTimeouts = [];
},
componentWillUnmount: function () {
if (this.timeout) {
clearTimeout(this.timeout);
}
this.transitionTimeouts.forEach(function (timeout) {
clearTimeout(timeout);
});
},
componentWillAppear: function (done) {
if (this.props.appear) {
this.transition('appear', done, this.props.appearTimeout);
} else {
done();
}
},
componentWillEnter: function (done) {
if (this.props.enter) {
this.transition('enter', done, this.props.enterTimeout);
} else {
done();
}
},
componentWillLeave: function (done) {
if (this.props.leave) {
this.transition('leave', done, this.props.leaveTimeout);
} else {
done();
}
},
render: function () {
return onlyChild(this.props.children);
}
});
module.exports = ReactCSSTransitionGroupChild; | emineKoc/WiseWit | wisewit_front_end/node_modules/react/lib/ReactCSSTransitionGroupChild.js | JavaScript | gpl-3.0 | 4,805 |
var _ = require('lodash');
/**
* formats variables for handlebars in multi-post contexts.
* If extraValues are available, they are merged in the final value
* @return {Object} containing page variables
*/
function formatPageResponse(result) {
var response = {
posts: result.posts,
pagination: result.meta.pagination
};
_.each(result.data, function (data, name) {
if (data.meta) {
// Move pagination to be a top level key
response[name] = data;
response[name].pagination = data.meta.pagination;
delete response[name].meta;
} else {
// This is a single object, don't wrap it in an array
response[name] = data[0];
}
});
return response;
}
/**
* similar to formatPageResponse, but for single post pages
* @return {Object} containing page variables
*/
function formatResponse(post) {
return {
post: post
};
}
module.exports = {
channel: formatPageResponse,
single: formatResponse
};
| norsasono/openshift-ghost-starter | node_modules/ghost/core/server/controllers/frontend/format-response.js | JavaScript | mit | 1,048 |
package dns
import "github.com/jen20/riviera/azure"
type DeleteRecordSet struct {
Name string `json:"-"`
ResourceGroupName string `json:"-"`
ZoneName string `json:"-"`
RecordSetType string `json:"-"`
}
func (command DeleteRecordSet) APIInfo() azure.APIInfo {
return azure.APIInfo{
APIVersion: apiVersion,
Method: "DELETE",
URLPathFunc: dnsRecordSetDefaultURLPathFunc(command.ResourceGroupName, command.ZoneName, command.RecordSetType, command.Name),
ResponseTypeFunc: func() interface{} {
return nil
},
}
}
| TStraub-rms/terraform | vendor/github.com/jen20/riviera/dns/delete_dns_recordset.go | GO | mpl-2.0 | 561 |
package main
func main() {
c := make(chan int, 1);
c <- 0;
if <-c != 0 { panic(0) }
}
| SanDisk-Open-Source/SSD_Dashboard | uefi/gcc/gcc-4.6.3/gcc/testsuite/go.go-torture/execute/chan-1.go | GO | gpl-2.0 | 93 |
/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package priorities
import (
"reflect"
"testing"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/kubernetes/pkg/api/v1"
schedulerapi "k8s.io/kubernetes/plugin/pkg/scheduler/api"
"k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache"
)
func TestBalancedResourceAllocation(t *testing.T) {
labels1 := map[string]string{
"foo": "bar",
"baz": "blah",
}
labels2 := map[string]string{
"bar": "foo",
"baz": "blah",
}
machine1Spec := v1.PodSpec{
NodeName: "machine1",
}
machine2Spec := v1.PodSpec{
NodeName: "machine2",
}
noResources := v1.PodSpec{
Containers: []v1.Container{},
}
cpuOnly := v1.PodSpec{
NodeName: "machine1",
Containers: []v1.Container{
{
Resources: v1.ResourceRequirements{
Requests: v1.ResourceList{
"cpu": resource.MustParse("1000m"),
"memory": resource.MustParse("0"),
},
},
},
{
Resources: v1.ResourceRequirements{
Requests: v1.ResourceList{
"cpu": resource.MustParse("2000m"),
"memory": resource.MustParse("0"),
},
},
},
},
}
cpuOnly2 := cpuOnly
cpuOnly2.NodeName = "machine2"
cpuAndMemory := v1.PodSpec{
NodeName: "machine2",
Containers: []v1.Container{
{
Resources: v1.ResourceRequirements{
Requests: v1.ResourceList{
"cpu": resource.MustParse("1000m"),
"memory": resource.MustParse("2000"),
},
},
},
{
Resources: v1.ResourceRequirements{
Requests: v1.ResourceList{
"cpu": resource.MustParse("2000m"),
"memory": resource.MustParse("3000"),
},
},
},
},
}
tests := []struct {
pod *v1.Pod
pods []*v1.Pod
nodes []*v1.Node
expectedList schedulerapi.HostPriorityList
test string
}{
{
/*
Node1 scores (remaining resources) on 0-10 scale
CPU Fraction: 0 / 4000 = 0%
Memory Fraction: 0 / 10000 = 0%
Node1 Score: 10 - (0-0)*10 = 10
Node2 scores (remaining resources) on 0-10 scale
CPU Fraction: 0 / 4000 = 0 %
Memory Fraction: 0 / 10000 = 0%
Node2 Score: 10 - (0-0)*10 = 10
*/
pod: &v1.Pod{Spec: noResources},
nodes: []*v1.Node{makeNode("machine1", 4000, 10000), makeNode("machine2", 4000, 10000)},
expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 10}, {Host: "machine2", Score: 10}},
test: "nothing scheduled, nothing requested",
},
{
/*
Node1 scores on 0-10 scale
CPU Fraction: 3000 / 4000= 75%
Memory Fraction: 5000 / 10000 = 50%
Node1 Score: 10 - (0.75-0.5)*10 = 7
Node2 scores on 0-10 scale
CPU Fraction: 3000 / 6000= 50%
Memory Fraction: 5000/10000 = 50%
Node2 Score: 10 - (0.5-0.5)*10 = 10
*/
pod: &v1.Pod{Spec: cpuAndMemory},
nodes: []*v1.Node{makeNode("machine1", 4000, 10000), makeNode("machine2", 6000, 10000)},
expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 7}, {Host: "machine2", Score: 10}},
test: "nothing scheduled, resources requested, differently sized machines",
},
{
/*
Node1 scores on 0-10 scale
CPU Fraction: 0 / 4000= 0%
Memory Fraction: 0 / 10000 = 0%
Node1 Score: 10 - (0-0)*10 = 10
Node2 scores on 0-10 scale
CPU Fraction: 0 / 4000= 0%
Memory Fraction: 0 / 10000 = 0%
Node2 Score: 10 - (0-0)*10 = 10
*/
pod: &v1.Pod{Spec: noResources},
nodes: []*v1.Node{makeNode("machine1", 4000, 10000), makeNode("machine2", 4000, 10000)},
expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 10}, {Host: "machine2", Score: 10}},
test: "no resources requested, pods scheduled",
pods: []*v1.Pod{
{Spec: machine1Spec, ObjectMeta: metav1.ObjectMeta{Labels: labels2}},
{Spec: machine1Spec, ObjectMeta: metav1.ObjectMeta{Labels: labels1}},
{Spec: machine2Spec, ObjectMeta: metav1.ObjectMeta{Labels: labels1}},
{Spec: machine2Spec, ObjectMeta: metav1.ObjectMeta{Labels: labels1}},
},
},
{
/*
Node1 scores on 0-10 scale
CPU Fraction: 6000 / 10000 = 60%
Memory Fraction: 0 / 20000 = 0%
Node1 Score: 10 - (0.6-0)*10 = 4
Node2 scores on 0-10 scale
CPU Fraction: 6000 / 10000 = 60%
Memory Fraction: 5000 / 20000 = 25%
Node2 Score: 10 - (0.6-0.25)*10 = 6
*/
pod: &v1.Pod{Spec: noResources},
nodes: []*v1.Node{makeNode("machine1", 10000, 20000), makeNode("machine2", 10000, 20000)},
expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 4}, {Host: "machine2", Score: 6}},
test: "no resources requested, pods scheduled with resources",
pods: []*v1.Pod{
{Spec: cpuOnly, ObjectMeta: metav1.ObjectMeta{Labels: labels2}},
{Spec: cpuOnly, ObjectMeta: metav1.ObjectMeta{Labels: labels1}},
{Spec: cpuOnly2, ObjectMeta: metav1.ObjectMeta{Labels: labels1}},
{Spec: cpuAndMemory, ObjectMeta: metav1.ObjectMeta{Labels: labels1}},
},
},
{
/*
Node1 scores on 0-10 scale
CPU Fraction: 6000 / 10000 = 60%
Memory Fraction: 5000 / 20000 = 25%
Node1 Score: 10 - (0.6-0.25)*10 = 6
Node2 scores on 0-10 scale
CPU Fraction: 6000 / 10000 = 60%
Memory Fraction: 10000 / 20000 = 50%
Node2 Score: 10 - (0.6-0.5)*10 = 9
*/
pod: &v1.Pod{Spec: cpuAndMemory},
nodes: []*v1.Node{makeNode("machine1", 10000, 20000), makeNode("machine2", 10000, 20000)},
expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 6}, {Host: "machine2", Score: 9}},
test: "resources requested, pods scheduled with resources",
pods: []*v1.Pod{
{Spec: cpuOnly},
{Spec: cpuAndMemory},
},
},
{
/*
Node1 scores on 0-10 scale
CPU Fraction: 6000 / 10000 = 60%
Memory Fraction: 5000 / 20000 = 25%
Node1 Score: 10 - (0.6-0.25)*10 = 6
Node2 scores on 0-10 scale
CPU Fraction: 6000 / 10000 = 60%
Memory Fraction: 10000 / 50000 = 20%
Node2 Score: 10 - (0.6-0.2)*10 = 6
*/
pod: &v1.Pod{Spec: cpuAndMemory},
nodes: []*v1.Node{makeNode("machine1", 10000, 20000), makeNode("machine2", 10000, 50000)},
expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 6}, {Host: "machine2", Score: 6}},
test: "resources requested, pods scheduled with resources, differently sized machines",
pods: []*v1.Pod{
{Spec: cpuOnly},
{Spec: cpuAndMemory},
},
},
{
/*
Node1 scores on 0-10 scale
CPU Fraction: 6000 / 4000 > 100% ==> Score := 0
Memory Fraction: 0 / 10000 = 0
Node1 Score: 0
Node2 scores on 0-10 scale
CPU Fraction: 6000 / 4000 > 100% ==> Score := 0
Memory Fraction 5000 / 10000 = 50%
Node2 Score: 0
*/
pod: &v1.Pod{Spec: cpuOnly},
nodes: []*v1.Node{makeNode("machine1", 4000, 10000), makeNode("machine2", 4000, 10000)},
expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 0}, {Host: "machine2", Score: 0}},
test: "requested resources exceed node capacity",
pods: []*v1.Pod{
{Spec: cpuOnly},
{Spec: cpuAndMemory},
},
},
{
pod: &v1.Pod{Spec: noResources},
nodes: []*v1.Node{makeNode("machine1", 0, 0), makeNode("machine2", 0, 0)},
expectedList: []schedulerapi.HostPriority{{Host: "machine1", Score: 0}, {Host: "machine2", Score: 0}},
test: "zero node resources, pods scheduled with resources",
pods: []*v1.Pod{
{Spec: cpuOnly},
{Spec: cpuAndMemory},
},
},
}
for _, test := range tests {
nodeNameToInfo := schedulercache.CreateNodeNameToInfoMap(test.pods, test.nodes)
list, err := priorityFunction(BalancedResourceAllocationMap, nil)(test.pod, nodeNameToInfo, test.nodes)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if !reflect.DeepEqual(test.expectedList, list) {
t.Errorf("%s: expected %#v, got %#v", test.test, test.expectedList, list)
}
}
}
| wanghaoran1988/origin | vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/priorities/balanced_resource_allocation_test.go | GO | apache-2.0 | 8,474 |
'use strict';
var times = require('../times');
var moment = require('moment');
function init (ctx) {
var translate = ctx.language.translate;
var basal = {
name: 'basal'
, label: 'Basal Profile'
, pluginType: 'pill-minor'
};
basal.setProperties = function setProperties (sbx) {
if (hasRequiredInfo(sbx)) {
var profile = sbx.data.profile;
var current = profile.getTempBasal(sbx.time);
var tempMark = '';
tempMark += current.treatment ? 'T' : '';
tempMark += current.combobolustreatment ? 'C' : '';
tempMark += tempMark ? ': ' : '';
sbx.offerProperty('basal', function setBasal() {
return {
display: tempMark + current.totalbasal.toFixed(3) + 'U'
, current: current
};
});
}
};
function hasRequiredInfo (sbx) {
if (!sbx.data.profile) { return false; }
if (!sbx.data.profile.hasData()) {
console.warn('For the Basal plugin to function you need a treatment profile');
return false;
}
if (!sbx.data.profile.getBasal()) {
console.warn('For the Basal plugin to function you need a basal profile');
return false;
}
return true;
}
basal.updateVisualisation = function updateVisualisation (sbx) {
if (!hasRequiredInfo(sbx)) {
return;
}
var profile = sbx.data.profile;
var prop = sbx.properties.basal;
var basalValue = prop && prop.current;
var tzMessage = profile.getTimezone() ? profile.getTimezone() : 'Timezone not set in profile';
var info = [{label: translate('Current basal'), value: prop.display}
, {label: translate('Sensitivity'), value: profile.getSensitivity(sbx.time) + ' ' + sbx.settings.units + ' / U'}
, {label: translate('Current Carb Ratio'), value: '1 U / ' + profile.getCarbRatio(sbx.time) + 'g'}
, {label: translate('Basal timezone'), value: tzMessage}
, {label: '------------', value: ''}
, {label: translate('Active profile'), value: profile.activeProfileToTime(sbx.time)}
];
var tempText, remaining;
if (basalValue.treatment) {
tempText = basalValue.treatment.percent ? (basalValue.treatment.percent > 0 ? '+' : '') + basalValue.treatment.percent + '%' :
!isNaN(basalValue.treatment.absolute) ? basalValue.treatment.absolute + 'U/h' : '';
remaining = parseInt(basalValue.treatment.duration - times.msecs(sbx.time - basalValue.treatment.mills).mins);
info.push({label: '------------', value: ''});
info.push({label: translate('Active temp basal'), value: tempText});
info.push({label: translate('Active temp basal start'), value: new Date(basalValue.treatment.mills).toLocaleString()});
info.push({label: translate('Active temp basal duration'), value: parseInt(basalValue.treatment.duration) + ' ' + translate('mins')});
info.push({label: translate('Active temp basal remaining'), value: remaining + ' ' + translate('mins')});
info.push({label: translate('Basal profile value'), value: basalValue.basal.toFixed(3) + ' U'});
}
if (basalValue.combobolustreatment) {
tempText = (basalValue.combobolustreatment.relative ? '+' + basalValue.combobolustreatment.relative + 'U/h' : '');
remaining = parseInt(basalValue.combobolustreatment.duration - times.msecs(sbx.time - basalValue.combobolustreatment.mills).mins);
info.push({label: '------------', value: ''});
info.push({label: translate('Active combo bolus'), value: tempText});
info.push({label: translate('Active combo bolus start'), value: new Date(basalValue.combobolustreatment.mills).toLocaleString()});
info.push({label: translate('Active combo bolus duration'), value: parseInt(basalValue.combobolustreatment.duration) + ' ' + translate('mins')});
info.push({label: translate('Active combo bolus remaining'), value: remaining + ' ' + translate('mins')});
}
sbx.pluginBase.updatePillText(basal, {
value: prop.display
, label: translate('BASAL')
, info: info
});
};
function basalMessage(slots, sbx) {
var basalValue = sbx.data.profile.getTempBasal(sbx.time);
var response = 'Unable to determine current basal';
var preamble = '';
if (basalValue.treatment) {
preamble = (slots && slots.pwd && slots.pwd.value) ? translate('alexaPreamble3person', {
params: [
slots.pwd.value
]
}) : translate('alexaPreamble');
var minutesLeft = moment(basalValue.treatment.endmills).from(moment(sbx.time));
response = translate('alexaBasalTemp', {
params: [
preamble,
basalValue.totalbasal,
minutesLeft
]
});
} else {
preamble = (slots && slots.pwd && slots.pwd.value) ? translate('alexaPreamble3person', {
params: [
slots.pwd.value
]
}) : translate('alexaPreamble');
response = translate('alexaBasal', {
params: [
preamble,
basalValue.totalbasal
]
});
}
return response;
}
function alexaRollupCurrentBasalHandler (slots, sbx, callback) {
callback(null, {results: basalMessage(slots, sbx), priority: 1});
}
function alexaCurrentBasalhandler (next, slots, sbx) {
next('Current Basal', basalMessage(slots, sbx));
}
basal.alexa = {
rollupHandlers: [{
rollupGroup: 'Status'
, rollupName: 'current basal'
, rollupHandler: alexaRollupCurrentBasalHandler
}],
intentHandlers: [{
intent: 'MetricNow'
, routableSlot:'metric'
, slots:['basal', 'current basal']
, intentHandler: alexaCurrentBasalhandler
}]
};
return basal;
}
module.exports = init;
| GarthDB/cgm-remote-monitor | lib/plugins/basalprofile.js | JavaScript | agpl-3.0 | 5,961 |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Form\Util;
use Symfony\Component\PropertyAccess\PropertyPathIteratorInterface as BasePropertyPathIteratorInterface;
/**
* Alias for {@link \Symfony\Component\PropertyAccess\PropertyPathIteratorInterface}.
*
* @author Bernhard Schussek <bschussek@gmail.com>
*
* @deprecated deprecated since version 2.2, to be removed in 2.3. Use
* {@link \Symfony\Component\PropertyAccess\PropertyPathIterator}
* instead.
*/
interface PropertyPathIteratorInterface extends BasePropertyPathIteratorInterface
{
}
| nandy-andy/performance-blog | vendors/silex/symfony/form/Symfony/Component/Form/Util/PropertyPathIteratorInterface.php | PHP | gpl-2.0 | 794 |
<?php
/**
* @file
* Contains database additions to drupal-8.bare.standard.php.gz for testing the
* upgrade path of https://www.drupal.org/node/507488.
*/
use Drupal\Core\Database\Database;
$connection = Database::getConnection();
// Structure of a custom block with visibility settings.
$block_configs[] = \Drupal\Component\Serialization\Yaml::decode(file_get_contents(__DIR__ . '/block.block.testfor2569529.yml'));
foreach ($block_configs as $block_config) {
$connection->insert('config')
->fields([
'collection',
'name',
'data',
])
->values([
'collection' => '',
'name' => 'block.block.' . $block_config['id'],
'data' => serialize($block_config),
])
->execute();
}
// Update the config entity query "index".
$existing_blocks = $connection->select('key_value')
->fields('key_value', ['value'])
->condition('collection', 'config.entity.key_store.block')
->condition('name', 'theme:seven')
->execute()
->fetchField();
$existing_blocks = unserialize($existing_blocks);
$connection->update('key_value')
->fields([
'value' => serialize(array_merge($existing_blocks, ['block.block.seven_secondary_local_tasks']))
])
->condition('collection', 'config.entity.key_store.block')
->condition('name', 'theme:seven')
->execute();
| nrackleff/capstone | web/core/modules/system/tests/fixtures/update/drupal-8.seven-secondary-local-tasks-block-2569529.php | PHP | gpl-2.0 | 1,321 |
module GitStyleBinary
module Commands
class Help
# not loving this syntax, but works for now
GitStyleBinary.command do
short_desc "get help for a specific command"
run do |command|
# this is slightly ugly b/c it has to muck around in the internals to
# get information about commands other than itself. This isn't a
# typical case
self.class.send :define_method, :educate_about_command do |name|
load_all_commands
if GitStyleBinary.known_commands.has_key?(name)
cmd = GitStyleBinary.known_commands[name]
cmd.process_parser!
cmd.parser.educate
else
puts "Unknown command '#{name}'"
end
end
if command.argv.size > 0
command.argv.first == "help" ? educate : educate_about_command(command.argv.first)
else
educate
end
end
end
end
end
end
| tyok/dotfiles | bin/yadr/lib/git-style-binaries-0.1.11/lib/git-style-binary/commands/help.rb | Ruby | bsd-2-clause | 998 |
var baseIndexOf = require('./_baseIndexOf'),
toInteger = require('./toInteger');
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* Gets the index at which the first occurrence of `value` is found in `array`
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons. If `fromIndex` is negative, it's used as the
* offset from the end of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} [fromIndex=0] The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.indexOf([1, 2, 1, 2], 2);
* // => 1
*
* // Search from the `fromIndex`.
* _.indexOf([1, 2, 1, 2], 2, 2);
* // => 3
*/
function indexOf(array, value, fromIndex) {
var length = array ? array.length : 0;
if (!length) {
return -1;
}
var index = fromIndex == null ? 0 : toInteger(fromIndex);
if (index < 0) {
index = nativeMax(length + index, 0);
}
return baseIndexOf(array, value, index);
}
module.exports = indexOf;
| ElvisLouis/code | work/project/Edison/elvis/work/js/node_modules/async/node_modules/lodash/indexOf.js | JavaScript | gpl-2.0 | 1,232 |
<?php
/**
* @file
* Contains \Drupal\views\Plugin\views\sort\Broken.
*/
namespace Drupal\views\Plugin\views\sort;
use Drupal\views\Plugin\views\BrokenHandlerTrait;
/**
* A special handler to take the place of missing or broken handlers.
*
* @ingroup views_sort_handlers
*
* @ViewsSort("broken")
*/
class Broken extends SortPluginBase {
use BrokenHandlerTrait;
}
| komejo/d8demo-dev | web/core/modules/views/src/Plugin/views/sort/Broken.php | PHP | mit | 378 |
(function(){
if (
(typeof self === 'undefined' || !self.Prism) &&
(typeof global === 'undefined' || !global.Prism)
) {
return;
}
var options = {
classMap: {}
};
Prism.plugins.customClass = {
map: function map(cm) {
options.classMap = cm;
},
prefix: function prefix(string) {
options.prefixString = string;
}
}
Prism.hooks.add('wrap', function (env) {
if (!options.classMap && !options.prefixString) {
return;
}
env.classes = env.classes.map(function(c) {
return (options.prefixString || '') + (options.classMap[c] || c);
});
});
})();
| ihmcrobotics/ihmc-realtime | websitedocs/website/node_modules/prismjs/plugins/custom-class/prism-custom-class.js | JavaScript | apache-2.0 | 559 |
// PR c++/28385
// instantiating op() with void()() was making the compiler think that 'fcn'
// was const, so it could eliminate the call.
// { dg-do run }
extern "C" void abort (void);
int barcnt = 0;
class Foo {
public:
template<typename T>
void operator()(const T& fcn) {
fcn();
}
};
void bar() {
barcnt++;
}
int main() {
Foo myFoo;
myFoo(bar);
myFoo(&bar);
if (barcnt != 2)
abort ();
return 0;
}
| SanDisk-Open-Source/SSD_Dashboard | uefi/gcc/gcc-4.6.3/gcc/testsuite/g++.dg/template/const1.C | C++ | gpl-2.0 | 442 |
// +build go1.6,!go1.7
/*
* Copyright 2016, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
package transport
import (
"net"
"golang.org/x/net/context"
)
// dialContext connects to the address on the named network.
func dialContext(ctx context.Context, network, address string) (net.Conn, error) {
return (&net.Dialer{Cancel: ctx.Done()}).Dial(network, address)
}
| ae6rt/decap | web/vendor/google.golang.org/grpc/transport/go16.go | GO | mit | 1,869 |