repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
derekchiang/keystone
|
keystone/contrib/federation/controllers.py
|
11029
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# 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.
"""Extensions supporting Federation."""
from keystone.common import controller
from keystone.common import dependency
from keystone.common import wsgi
from keystone import config
from keystone.contrib.federation import utils
from keystone import exception
CONF = config.CONF
class _ControllerBase(controller.V3Controller):
"""Base behaviors for federation controllers.
Two new class parameters:
* `_mutable_parameters` - set of parameters that can be changed by users.
Usually used by cls.check_immutable_params()
* `_public_parameters` - set of parameters that are exposed to the user.
Usually used by cls.filter_params()
"""
@classmethod
def check_immutable_params(cls, ref):
"""Raise exception when disallowed parameter is in ref.
Check whether the ref dictionary representing a request has only
mutable parameters included. If not, raise an exception. This method
checks only root-level keys from a ref dictionary.
:param ref: a dictionary representing deserialized request to be
stored
:raises: :class:`keystone.exception.ImmutableAttributeError`
"""
ref_keys = set(ref.keys())
blocked_keys = ref_keys.difference(cls._mutable_parameters)
if not blocked_keys:
#No immutable parameters changed
return
exception_args = {'target': cls.__name__,
'attribute': blocked_keys.pop()}
raise exception.ImmutableAttributeError(**exception_args)
@classmethod
def filter_params(cls, ref):
"""Remove unspecified parameters from the dictionary.
This function removes unspecified parameters from the dictionary. See
check_immutable_parameters for corresponding function that raises
exceptions. This method checks only root-level keys from a ref
dictionary.
:param ref: a dictionary representing deserialized response to be
serialized
"""
ref_keys = set(ref.keys())
blocked_keys = ref_keys - cls._public_parameters
for blocked_param in blocked_keys:
del ref[blocked_param]
return ref
@classmethod
def base_url(cls, path=None):
"""Construct a path and pass it to V3Controller.base_url method."""
path = '/OS-FEDERATION/' + cls.collection_name
return controller.V3Controller.base_url(path=path)
@dependency.requires('federation_api')
class IdentityProvider(_ControllerBase):
"""Identity Provider representation."""
collection_name = 'identity_providers'
member_name = 'identity_provider'
_mutable_parameters = frozenset(['description', 'enabled'])
_public_parameters = frozenset(['id', 'enabled', 'description', 'links'])
@classmethod
def _add_related_links(cls, ref):
"""Add URLs for entities related with Identity Provider.
Add URLs pointing to:
- protocols tied to the Identity Provider
"""
ref.setdefault('links', {})
base_path = ref['links'].get('self')
if base_path is None:
base_path = '/'.join([IdentityProvider.base_url(), ref['id']])
for name in ['protocols']:
ref['links'][name] = '/'.join([base_path, name])
@classmethod
def _add_self_referential_link(cls, ref):
id = ref.get('id')
self_path = '/'.join([cls.base_url(), id])
ref.setdefault('links', {})
ref['links']['self'] = self_path
@classmethod
def wrap_member(cls, context, ref):
cls._add_self_referential_link(ref)
cls._add_related_links(ref)
ref = cls.filter_params(ref)
return {cls.member_name: ref}
#TODO(marek-denis): Implement, when mapping engine is ready
def _delete_tokens_issued_by_idp(self, idp_id):
"""Delete tokens created upon authentication from an IdP
After the IdP is deregistered, users authenticating via such IdP should
no longer be allowed to use federated services. Thus, delete all the
tokens issued upon authentication from IdP with idp_id id
:param idp_id: id of Identity Provider for which related tokens should
be removed.
"""
raise exception.NotImplemented()
@controller.protected()
def create_identity_provider(self, context, idp_id, identity_provider):
identity_provider = self._normalize_dict(identity_provider)
identity_provider.setdefault('enabled', False)
IdentityProvider.check_immutable_params(identity_provider)
idp_ref = self.federation_api.create_idp(idp_id, identity_provider)
response = IdentityProvider.wrap_member(context, idp_ref)
return wsgi.render_response(body=response, status=('201', 'Created'))
@controller.protected()
def list_identity_providers(self, context):
ref = self.federation_api.list_idps()
ref = [self.filter_params(x) for x in ref]
return IdentityProvider.wrap_collection(context, ref)
@controller.protected()
def get_identity_provider(self, context, idp_id):
ref = self.federation_api.get_idp(idp_id)
return IdentityProvider.wrap_member(context, ref)
@controller.protected()
def delete_identity_provider(self, context, idp_id):
self.federation_api.delete_idp(idp_id)
@controller.protected()
def update_identity_provider(self, context, idp_id, identity_provider):
identity_provider = self._normalize_dict(identity_provider)
IdentityProvider.check_immutable_params(identity_provider)
idp_ref = self.federation_api.update_idp(idp_id, identity_provider)
return IdentityProvider.wrap_member(context, idp_ref)
@dependency.requires('federation_api')
class FederationProtocol(_ControllerBase):
"""A federation protocol representation.
See IdentityProvider docstring for explanation on _mutable_parameters
and _public_parameters class attributes.
"""
collection_name = 'protocols'
member_name = 'protocol'
_public_parameters = frozenset(['id', 'mapping_id', 'links'])
_mutable_parameters = frozenset(['mapping_id'])
@classmethod
def _add_self_referential_link(cls, ref):
"""Add 'links' entry to the response dictionary.
Calls IdentityProvider.base_url() class method, as it constructs
proper URL along with the 'identity providers' part included.
:param ref: response dictionary
"""
ref.setdefault('links', {})
base_path = ref['links'].get('identity_provider')
if base_path is None:
base_path = [IdentityProvider.base_url(), ref['idp_id']]
base_path = '/'.join(base_path)
self_path = [base_path, 'protocols', ref['id']]
self_path = '/'.join(self_path)
ref['links']['self'] = self_path
@classmethod
def _add_related_links(cls, ref):
"""Add new entries to the 'links' subdictionary in the response.
Adds 'identity_provider' key with URL pointing to related identity
provider as a value.
:param ref: response dictionary
"""
ref.setdefault('links', {})
base_path = '/'.join([IdentityProvider.base_url(), ref['idp_id']])
ref['links']['identity_provider'] = base_path
@classmethod
def wrap_member(cls, context, ref):
cls._add_related_links(ref)
cls._add_self_referential_link(ref)
ref = cls.filter_params(ref)
return {cls.member_name: ref}
@controller.protected()
def create_protocol(self, context, idp_id, protocol_id, protocol):
ref = self._normalize_dict(protocol)
FederationProtocol.check_immutable_params(ref)
ref = self.federation_api.create_protocol(idp_id, protocol_id, ref)
response = FederationProtocol.wrap_member(context, ref)
return wsgi.render_response(body=response, status=('201', 'Created'))
@controller.protected()
def update_protocol(self, context, idp_id, protocol_id, protocol):
ref = self._normalize_dict(protocol)
FederationProtocol.check_immutable_params(ref)
ref = self.federation_api.update_protocol(idp_id, protocol_id,
protocol)
return FederationProtocol.wrap_member(context, ref)
@controller.protected()
def get_protocol(self, context, idp_id, protocol_id):
ref = self.federation_api.get_protocol(idp_id, protocol_id)
return FederationProtocol.wrap_member(context, ref)
@controller.protected()
def list_protocols(self, context, idp_id):
protocols_ref = self.federation_api.list_protocols(idp_id)
protocols = list(protocols_ref)
return FederationProtocol.wrap_collection(context, protocols)
@controller.protected()
def delete_protocol(self, context, idp_id, protocol_id):
self.federation_api.delete_protocol(idp_id, protocol_id)
@dependency.requires('federation_api')
class MappingController(_ControllerBase):
collection_name = 'mappings'
member_name = 'mapping'
@controller.protected()
def create_mapping(self, context, mapping_id, mapping):
ref = self._normalize_dict(mapping)
utils.validate_mapping_structure(ref)
mapping_ref = self.federation_api.create_mapping(mapping_id, ref)
response = MappingController.wrap_member(context, mapping_ref)
return wsgi.render_response(body=response, status=('201', 'Created'))
@controller.protected()
def list_mappings(self, context):
ref = self.federation_api.list_mappings()
return MappingController.wrap_collection(context, ref)
@controller.protected()
def get_mapping(self, context, mapping_id):
ref = self.federation_api.get_mapping(mapping_id)
return MappingController.wrap_member(context, ref)
@controller.protected()
def delete_mapping(self, context, mapping_id):
self.federation_api.delete_mapping(mapping_id)
@controller.protected()
def update_mapping(self, context, mapping_id, mapping):
mapping = self._normalize_dict(mapping)
utils.validate_mapping_structure(mapping)
mapping_ref = self.federation_api.update_mapping(mapping_id, mapping)
return MappingController.wrap_member(context, mapping_ref)
|
apache-2.0
|
manuelkasiske/openshift-golang-template
|
example-golang-dep/cmd/server/grunt/clean.js
|
115
|
module.exports = function (grunt, options) {
'use strict';
return {
build: ['build/*']
};
};
|
apache-2.0
|
afs/rdf-delta
|
rdf-patch/src/main/java/org/seaborne/patch/binary/thrift/RDF_Decimal.java
|
15157
|
/**
* Autogenerated by Thrift Compiler (0.13.0)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package org.seaborne.patch.binary.thrift;
@SuppressWarnings("all")
@javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.13.0)", date = "2021-08-10")
public class RDF_Decimal implements org.apache.thrift.TBase<RDF_Decimal, RDF_Decimal._Fields>, java.io.Serializable, Cloneable, Comparable<RDF_Decimal> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("RDF_Decimal");
private static final org.apache.thrift.protocol.TField VALUE_FIELD_DESC = new org.apache.thrift.protocol.TField("value", org.apache.thrift.protocol.TType.I64, (short)1);
private static final org.apache.thrift.protocol.TField SCALE_FIELD_DESC = new org.apache.thrift.protocol.TField("scale", org.apache.thrift.protocol.TType.I32, (short)2);
private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new RDF_DecimalStandardSchemeFactory();
private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new RDF_DecimalTupleSchemeFactory();
public long value; // required
public int scale; // required
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
VALUE((short)1, "value"),
SCALE((short)2, "scale");
private static final java.util.Map<java.lang.String, _Fields> byName = new java.util.HashMap<java.lang.String, _Fields>();
static {
for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
@org.apache.thrift.annotation.Nullable
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // VALUE
return VALUE;
case 2: // SCALE
return SCALE;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
@org.apache.thrift.annotation.Nullable
public static _Fields findByName(java.lang.String name) {
return byName.get(name);
}
private final short _thriftId;
private final java.lang.String _fieldName;
_Fields(short thriftId, java.lang.String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public java.lang.String getFieldName() {
return _fieldName;
}
}
// isset id assignments
private static final int __VALUE_ISSET_ID = 0;
private static final int __SCALE_ISSET_ID = 1;
private byte __isset_bitfield = 0;
public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.VALUE, new org.apache.thrift.meta_data.FieldMetaData("value", org.apache.thrift.TFieldRequirementType.REQUIRED,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64)));
tmpMap.put(_Fields.SCALE, new org.apache.thrift.meta_data.FieldMetaData("scale", org.apache.thrift.TFieldRequirementType.REQUIRED,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32)));
metaDataMap = java.util.Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(RDF_Decimal.class, metaDataMap);
}
public RDF_Decimal() {
}
public RDF_Decimal(
long value,
int scale)
{
this();
this.value = value;
setValueIsSet(true);
this.scale = scale;
setScaleIsSet(true);
}
/**
* Performs a deep copy on <i>other</i>.
*/
public RDF_Decimal(RDF_Decimal other) {
__isset_bitfield = other.__isset_bitfield;
this.value = other.value;
this.scale = other.scale;
}
public RDF_Decimal deepCopy() {
return new RDF_Decimal(this);
}
@Override
public void clear() {
setValueIsSet(false);
this.value = 0;
setScaleIsSet(false);
this.scale = 0;
}
public long getValue() {
return this.value;
}
public RDF_Decimal setValue(long value) {
this.value = value;
setValueIsSet(true);
return this;
}
public void unsetValue() {
__isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __VALUE_ISSET_ID);
}
/** Returns true if field value is set (has been assigned a value) and false otherwise */
public boolean isSetValue() {
return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __VALUE_ISSET_ID);
}
public void setValueIsSet(boolean value) {
__isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __VALUE_ISSET_ID, value);
}
public int getScale() {
return this.scale;
}
public RDF_Decimal setScale(int scale) {
this.scale = scale;
setScaleIsSet(true);
return this;
}
public void unsetScale() {
__isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __SCALE_ISSET_ID);
}
/** Returns true if field scale is set (has been assigned a value) and false otherwise */
public boolean isSetScale() {
return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __SCALE_ISSET_ID);
}
public void setScaleIsSet(boolean value) {
__isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __SCALE_ISSET_ID, value);
}
public void setFieldValue(_Fields field, @org.apache.thrift.annotation.Nullable java.lang.Object value) {
switch (field) {
case VALUE:
if (value == null) {
unsetValue();
} else {
setValue((java.lang.Long)value);
}
break;
case SCALE:
if (value == null) {
unsetScale();
} else {
setScale((java.lang.Integer)value);
}
break;
}
}
@org.apache.thrift.annotation.Nullable
public java.lang.Object getFieldValue(_Fields field) {
switch (field) {
case VALUE:
return getValue();
case SCALE:
return getScale();
}
throw new java.lang.IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
public boolean isSet(_Fields field) {
if (field == null) {
throw new java.lang.IllegalArgumentException();
}
switch (field) {
case VALUE:
return isSetValue();
case SCALE:
return isSetScale();
}
throw new java.lang.IllegalStateException();
}
@Override
public boolean equals(java.lang.Object that) {
if (that == null)
return false;
if (that instanceof RDF_Decimal)
return this.equals((RDF_Decimal)that);
return false;
}
public boolean equals(RDF_Decimal that) {
if (that == null)
return false;
if (this == that)
return true;
boolean this_present_value = true;
boolean that_present_value = true;
if (this_present_value || that_present_value) {
if (!(this_present_value && that_present_value))
return false;
if (this.value != that.value)
return false;
}
boolean this_present_scale = true;
boolean that_present_scale = true;
if (this_present_scale || that_present_scale) {
if (!(this_present_scale && that_present_scale))
return false;
if (this.scale != that.scale)
return false;
}
return true;
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = hashCode * 8191 + org.apache.thrift.TBaseHelper.hashCode(value);
hashCode = hashCode * 8191 + scale;
return hashCode;
}
@Override
public int compareTo(RDF_Decimal other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = java.lang.Boolean.valueOf(isSetValue()).compareTo(other.isSetValue());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetValue()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.value, other.value);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = java.lang.Boolean.valueOf(isSetScale()).compareTo(other.isSetScale());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetScale()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.scale, other.scale);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
@org.apache.thrift.annotation.Nullable
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
scheme(iprot).read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
scheme(oprot).write(oprot, this);
}
@Override
public java.lang.String toString() {
java.lang.StringBuilder sb = new java.lang.StringBuilder("RDF_Decimal(");
boolean first = true;
sb.append("value:");
sb.append(this.value);
first = false;
if (!first) sb.append(", ");
sb.append("scale:");
sb.append(this.scale);
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// alas, we cannot check 'value' because it's a primitive and you chose the non-beans generator.
// alas, we cannot check 'scale' because it's a primitive and you chose the non-beans generator.
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException {
try {
// it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
__isset_bitfield = 0;
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class RDF_DecimalStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
public RDF_DecimalStandardScheme getScheme() {
return new RDF_DecimalStandardScheme();
}
}
private static class RDF_DecimalStandardScheme extends org.apache.thrift.scheme.StandardScheme<RDF_Decimal> {
public void read(org.apache.thrift.protocol.TProtocol iprot, RDF_Decimal struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // VALUE
if (schemeField.type == org.apache.thrift.protocol.TType.I64) {
struct.value = iprot.readI64();
struct.setValueIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 2: // SCALE
if (schemeField.type == org.apache.thrift.protocol.TType.I32) {
struct.scale = iprot.readI32();
struct.setScaleIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
if (!struct.isSetValue()) {
throw new org.apache.thrift.protocol.TProtocolException("Required field 'value' was not found in serialized data! Struct: " + toString());
}
if (!struct.isSetScale()) {
throw new org.apache.thrift.protocol.TProtocolException("Required field 'scale' was not found in serialized data! Struct: " + toString());
}
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, RDF_Decimal struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
oprot.writeFieldBegin(VALUE_FIELD_DESC);
oprot.writeI64(struct.value);
oprot.writeFieldEnd();
oprot.writeFieldBegin(SCALE_FIELD_DESC);
oprot.writeI32(struct.scale);
oprot.writeFieldEnd();
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class RDF_DecimalTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
public RDF_DecimalTupleScheme getScheme() {
return new RDF_DecimalTupleScheme();
}
}
private static class RDF_DecimalTupleScheme extends org.apache.thrift.scheme.TupleScheme<RDF_Decimal> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, RDF_Decimal struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
oprot.writeI64(struct.value);
oprot.writeI32(struct.scale);
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, RDF_Decimal struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
struct.value = iprot.readI64();
struct.setValueIsSet(true);
struct.scale = iprot.readI32();
struct.setScaleIsSet(true);
}
}
private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) {
return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();
}
}
|
apache-2.0
|
pskpretty/routeOptimizerApplication
|
src/main/java/com/qut/routeOptimizerApplication/service/opta/vehiclerouting/domain/ouput/JsonVehicleRoutingSolution.java
|
1620
|
package com.qut.routeOptimizerApplication.service.opta.vehiclerouting.domain.ouput;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
import com.qut.routeOptimizerApplication.service.opta.vehiclerouting.domain.JsonCustomer;
@XmlRootElement
public class JsonVehicleRoutingSolution {
protected String name;
protected List<JsonCustomer> customerList;
protected List<JsonVehicleRoute> vehicleRouteList;
protected Boolean feasible;
protected String distance;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<JsonCustomer> getCustomerList() {
return customerList;
}
public void setCustomerList(List<JsonCustomer> customerList) {
this.customerList = customerList;
}
public List<JsonVehicleRoute> getVehicleRouteList() {
return vehicleRouteList;
}
public void setVehicleRouteList(List<JsonVehicleRoute> vehicleRouteList) {
this.vehicleRouteList = vehicleRouteList;
}
public Boolean getFeasible() {
return feasible;
}
public void setFeasible(Boolean feasible) {
this.feasible = feasible;
}
public String getDistance() {
return distance;
}
public void setDistance(String distance) {
this.distance = distance;
}
@Override
public String toString() {
return "JsonVehicleRoutingSolution [name=" + name + ", customerList=" + customerList + ", vehicleRouteList="
+ vehicleRouteList + ", feasible=" + feasible + ", distance=" + distance + "]";
}
}
|
apache-2.0
|
zoozooll/MyExercise
|
meep/MeepStore2/src/com/oregonscientific/meep/store2/DetailFragment.java
|
24629
|
package com.oregonscientific.meep.store2;
import java.util.ArrayList;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.oregonscientific.meep.store2.PaymentFragment.UpdateStatusListener;
import com.oregonscientific.meep.store2.adapter.ListAdapterShelf;
import com.oregonscientific.meep.store2.ctrl.AppInstallationCtrl;
import com.oregonscientific.meep.store2.ctrl.EbookCtrl;
import com.oregonscientific.meep.store2.ctrl.RestRequest.PurchaseItemListener;
import com.oregonscientific.meep.store2.ctrl.StoreItemDownloadCtrl;
import com.oregonscientific.meep.store2.global.MeepStoreApplication;
import com.oregonscientific.meep.store2.global.MeepStoreLog;
import com.oregonscientific.meep.store2.object.DownloadStoreItem;
import com.oregonscientific.meep.store2.object.MeepStoreItem;
import com.oregonscientific.meep.store2.object.PurchaseFeedback;
public class DetailFragment extends DialogFragment {
public static MeepStoreItem getStoreItem() {
return storeItem;
}
public static void setStoreItem(MeepStoreItem item) {
storeItem = item;
}
public static String getPackageNameOfItem()
{
String pkgName = null;
if(storeItem!=null)
{
pkgName = storeItem.getPackageName();
}
return pkgName;
}
private static MeepStoreItem storeItem;
private String prefix;
// ListAdapterScreenshot adapter;
// HorizontalListView listview;
HorizontalScrollView hs;
LinearLayout imageList;
Drawable drawable;
PaymentFragment paymentFragment;
PopUpDialogFragment popupFragment;
ScreenShotFragment shotFragment;
// ImageThreadLoader imageLoader;
// ImageThreadLoader imageShotLoader;
MeepStoreApplication mApp;
ProgressBar progressBar;
Button button;
ArrayList<String> screenShots = new ArrayList<String>();
AppInstallationCtrl.PakageListener mPackageListener = null;
private final int NO_NETWORK = 3;
private final int LOADING = 4;
private final int TIMEOUT = 5;
private final int SUCCESS_MESSAGE = 6;
private final int INSTALLING = 7;
private final int WAITING = 8;
private final int DOWNLOADING = 9;
private final int NOT_ENOUGH_SPACE = 10;
private final int EBOOK_DOWNLOAD_SUCCESS = 11;
private final int AWAITING_APPROVAL = 12;
private final int INSTALL = 14;
public interface ReloadItem {
public void reloadAllItems();
public void updateItemStatus(String action, String packetname, String id);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(STYLE_NO_FRAME, android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
// prefix = this.getResources().getString(R.string.prefix);
mApp = (MeepStoreApplication) this.getActivity().getApplicationContext();
// imageLoader = mApp.getImageLoader();
// imageShotLoader = mApp.getImageShotLoader();
}
@Override
public void onStart() {
super.onStart();
initStoreItemDownloadListener();
initPackageListener();
}
// @Override
// public void onStop() {
// super.onStop();
//
// if (mApp.getAppCtrl() != null) {
// mApp.getAppCtrl().removePackageListener(mPackageListener);
// }
// if (mApp.getStoreDownloadCtrl() != null) {
// mApp.getStoreDownloadCtrl().removeDownloadListeners(mDownloadListener);
// }
// }
public static DetailFragment newInstance(MeepStoreItem storeItem) {
DetailFragment.storeItem = storeItem;
DetailFragment myDialogFragment = new DetailFragment();
return myDialogFragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.layout_details, container, false);
hs = (HorizontalScrollView) v.findViewById(R.id.horizontalScrollView);
imageList = (LinearLayout) v.findViewById(R.id.imagesLinear);
TextView name = (TextView) v.findViewById(R.id.textName);
TextView info = (TextView) v.findViewById(R.id.textInfo);
TextView size = (TextView) v.findViewById(R.id.textSize);
TextView description = (TextView) v.findViewById(R.id.description);
button = (Button) v.findViewById(R.id.button);
progressBar = (ProgressBar) v.findViewById(R.id.progressBarDownload);
ImageView recommend = (ImageView) v.findViewById(R.id.recommend);
final ImageView image;
final ImageView imageblock;
View icon;
boolean isEbook = false;
if (storeItem.getItemType().equals(MeepStoreItem.TYPE_EBOOK)) {
isEbook = true;
}
// content isnot ebook
if (!isEbook) {
icon = v.findViewById(R.id.icon);
image = (ImageView) v.findViewById(R.id.image);
imageblock = (ImageView) v.findViewById(R.id.imageblock);
imageblock.setBackgroundResource(R.drawable.meep_market_description_block);
mApp.getImageDownloader().download(mApp.getLoginInfo().url_prefix
+ storeItem.getIconUrl(), 75, 75, image);
// Bitmap cachedImage = null;
// try {
// prefix = mApp.getLoginInfo().url_prefix;
// cachedImage =
// imageLoader.loadImage(prefix+storeItem.getIconUrl(), new
// ImageLoadedListener() {
// public void imageLoaded(Bitmap imageBitmap) {
// imageblock.setBackgroundResource(R.drawable.meep_market_description_block);
// image.setImageBitmap(imageBitmap);
// //notifyDataSetChanged();
// }
// });
// } catch (MalformedURLException e) {
// Log.e("APPSTATUS", "Bad remote image URL: " + e.toString());
// }
//
// if( cachedImage != null ) {
// imageblock.setBackgroundResource(R.drawable.meep_market_description_block);
// image.setImageBitmap(cachedImage);
// }else{
// imageblock.setBackgroundResource(R.drawable.meep_market_description_block_dummy);
// }
} else {
// content is ebook
icon = v.findViewById(R.id.icon2);
image = (ImageView) v.findViewById(R.id.imagebook);
imageblock = (ImageView) v.findViewById(R.id.imageblockbook);
imageblock.setBackgroundResource(R.drawable.meep_market_book_block);
mApp.getImageDownloader().download(mApp.getLoginInfo().url_prefix
+ storeItem.getIconUrl(), 75, 75, image);
// Bitmap cachedImage = null;
// try {
// prefix = mApp.getLoginInfo().url_prefix;
// cachedImage = imageLoader.loadImage(prefix +
// storeItem.getIconUrl(),
// new ImageLoadedListener() {
// public void imageLoaded(Bitmap imageBitmap) {
// imageblock.setBackgroundResource(R.drawable.meep_market_book_block);
// image.setImageBitmap(imageBitmap);
// // notifyDataSetChanged();
// }
// });
// } catch (MalformedURLException e) {
// Log.e("APPSTATUS", "Bad remote image URL: " + e.toString());
// }
//
// if (cachedImage != null) {
// imageblock.setBackgroundResource(R.drawable.meep_market_book_block);
// image.setImageBitmap(cachedImage);
// } else {
// imageblock.setBackgroundResource(R.drawable.meep_market_book_block_dummy);
// }
}
icon.setVisibility(View.VISIBLE);
// BADGE
setBadge(storeItem, v, isEbook);
// common
name.setText(storeItem.getName());
info.setText(storeItem.getDeveloper());
size.setText(storeItem.getSize() + "MB");
description.setText(storeItem.getDescription());
// Action
button.setOnClickListener((new View.OnClickListener() {
@Override
public void onClick(View pV) {
// show detail
paymentFragment = PaymentFragment.newInstance(storeItem);
paymentFragment.show(getFragmentManager(), "dialog");
paymentFragment.setUpdateStatusListener(new UpdateStatusListener() {
@Override
public void awaiting() {
handler.sendEmptyMessage(AWAITING_APPROVAL);
}
@Override
public void waiting() {
handler.sendEmptyMessage(WAITING);
}
});
}
}));
if (storeItem.getItemAction().equals(MeepStoreItem.ACTION_NORMAL)) {
button.setBackgroundResource(R.drawable.btn_item_description_coins);
button.setText(Integer.toString(storeItem.getPrice()));
button.setPadding(100, 0, 0, 0);
} else if (storeItem.getItemAction().equals(MeepStoreItem.ACTION_FREE)) {
button.setBackgroundResource(R.drawable.btn_item_description_free);
button.setText(R.string.free);
button.setPadding(30, 0, 0, 0);
} else if (storeItem.getItemAction().equals(MeepStoreItem.ACTION_GET_IT)) {
button.setBackgroundResource(R.drawable.btn_item_description_get);
button.setText(R.string.getit);
button.setPadding(30, 0, 0, 0);
} else if (storeItem.getItemAction().equals(MeepStoreItem.ACTION_INSTALLED)) {
showButtonUninstall();
} else if (storeItem.getItemAction().equals(MeepStoreItem.ACTION_PURCHASED)) {
if (storeItem.isRecovery()) {
button.setText(R.string.recover);
}
showButtonInstall();
} else if (storeItem.getItemAction().equals(MeepStoreItem.ACTION_DOWNLOADING)) {
showProgressBar();
} else if (storeItem.getItemAction().equals(MeepStoreItem.ACTION_PENDING_TO_DOWNLOAD)) {
showButtonQueuing();
} else if (storeItem.getItemAction().equals(MeepStoreItem.ACTION_PENDING)) {
showButtonAwaitingApproval();
} else if (storeItem.getItemAction().equals(MeepStoreItem.ACTION_INSTALLING)) {
showButtonInstalling();
} else if (storeItem.getItemAction().equals(MeepStoreItem.ACTION_EBOOK_DOWNLOADED)) {
showButtonSuccess();
} else if (storeItem.getItemAction().equals(MeepStoreItem.ACTION_BLOCKED)) {
showTextBlocked();
} else {
button.setVisibility(View.GONE);
}
// Recommend
if (storeItem.getRecommends() != null) {
if (storeItem.getRecommends().equals(MeepStoreItem.RECOMMEND_RECOMMENDS)) {
recommend.setImageResource(R.drawable.meep_store_gold);
} else if (storeItem.getRecommends().equals(MeepStoreItem.RECOMMEND_FRIENDLY)) {
recommend.setImageResource(R.drawable.meep_store_silver);
} else if (storeItem.getRecommends().equals(MeepStoreItem.RECOMMEND_LIKES)) {
recommend.setImageResource(R.drawable.meep_store_broze);
} else {
recommend.setVisibility(View.INVISIBLE);
}
} else {
recommend.setVisibility(View.INVISIBLE);
}
// screenshot
if (storeItem.getScreenShotUrls() == null
&& storeItem.getScreenShotUrls().length == 0) {
} else {
screenShots.clear();
for (String url : storeItem.getScreenShotUrls()) {
screenShots.add(url);
addFlowChildren(url);
}
}
return v;
}
public void popupScreenshot(int index) {
try {
if (shotFragment == null) {
shotFragment = ScreenShotFragment.newInstance(ScreenShotFragment.SCREENSHOT, index, screenShots);
shotFragment.show(getFragmentManager(), "dialog");
} else {
ScreenShotFragment.setPictureIndex(index);
shotFragment.loadImage();
shotFragment.show(getFragmentManager(), "dialog");
}
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
public void addFlowChildren(final String url) {
View view = ((LayoutInflater) this.getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.item_screenshot, null);
final ImageView image;
image = (ImageView) view.findViewById(R.id.image);
mApp.getImageDownloader().download(mApp.getLoginInfo().url_prefix + url, 200, 200, image);
// mApp.getImageDownloader().download(mApp.getLoginInfo().url_prefix +
// url, image);
// Bitmap cachedImage = null;
// try {
// prefix = mApp.getLoginInfo().url_prefix;
// cachedImage = imageShotLoader.loadImage(prefix + url, new
// ImageLoadedListener() {
// public void imageLoaded(final Bitmap imageBitmap) {
// image.setImageBitmap(imageBitmap);
// MeepStoreLog.logcatMessage("APPSTATUS", "screenshot loaded" + url);
// notifyDataSetChanged();
// }
// });
// } catch (MalformedURLException e) {
// Log.e("APPSTATUS", "Bad remote image URL: " + e.toString());
// }
// if (cachedImage != null) {
// image.setImageBitmap(cachedImage);
// } else {
// }
image.setOnClickListener((new View.OnClickListener() {
@Override
public void onClick(View pV) {
popupScreenshot(screenShots.lastIndexOf(url));
}
}));
int w = 196;
int h = 110;
// add view and set padding
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(w, h);
lp.setMargins(0, 0, 20, 0);
imageList.addView(view, lp);
}
public void setBadge(MeepStoreItem item, View view, boolean isEbook) {
ImageView badge;
// BADGE
if (!isEbook) {
badge = (ImageView) view.findViewById(R.id.badge);
} else {
badge = (ImageView) view.findViewById(R.id.badgebook);
}
if (item.getBadge().equals(MeepStoreItem.BADGE_ACCESSORY)) {
badge.setImageResource(R.drawable.meep_accessary);
} else if (item.getBadge().equals(MeepStoreItem.BADGE_BESTSELLER)) {
badge.setImageResource(R.drawable.meep_bestseller);
} else if (item.getBadge().equals(MeepStoreItem.BADGE_HOTITEM)) {
badge.setImageResource(R.drawable.meep_hotitem);
} else if (item.getBadge().equals(MeepStoreItem.BADGE_SALE)) {
badge.setImageResource(R.drawable.meep_sale);
} else if (item.getBadge().equals(MeepStoreItem.BADGE_SDCARD)) {
badge.setImageResource(R.drawable.meep_sdcard);
} else {
badge.setVisibility(View.GONE);
}
}
public Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
try {
switch (msg.what) {
case EBOOK_DOWNLOAD_SUCCESS:
showButtonSuccess();
break;
case NO_NETWORK:
popupFragment = PopUpDialogFragment.newInstance(PopUpDialogFragment.NO_NETWORK);
if (getFragmentManager() != null)
popupFragment.show(getFragmentManager(), "dialog");
break;
case LOADING:
popupFragment = PopUpDialogFragment.newInstance(PopUpDialogFragment.LOADING);
if (getFragmentManager() != null)
popupFragment.show(getFragmentManager(), "dialog");
break;
case TIMEOUT:
popupFragment = PopUpDialogFragment.newInstance(PopUpDialogFragment.TIMEOUT);
if (getFragmentManager() != null)
popupFragment.show(getFragmentManager(), "dialog");
break;
case SUCCESS_MESSAGE:
popupFragment = PopUpDialogFragment.newInstance(PopUpDialogFragment.COMMON_MESSAGE);
if (getFragmentManager() != null)
popupFragment.show(getFragmentManager(), "dialog");
break;
case INSTALLING:
showButtonInstalling();
break;
case WAITING:
showButtonQueuing();
break;
case DOWNLOADING:
showProgressBar();
break;
case AWAITING_APPROVAL:
showButtonAwaitingApproval();
break;
case NOT_ENOUGH_SPACE:
popupFragment = PopUpDialogFragment.newInstance(PopUpDialogFragment.NOT_ENOUGH_SPACE);
if (getFragmentManager() != null)
popupFragment.show(getFragmentManager(), "dialog");
break;
case INSTALL:
showButtonInstall();
break;
default:
break;
}
} catch (Exception e) {
MeepStoreLog.logcatMessage("test", "parent/current fragment has been closed");
}
}
};
public Handler getHandler() {
return handler;
}
public void showProgressBar() {
progressBar.setVisibility(View.VISIBLE);
button.setVisibility(View.GONE);
updateShelf(MeepStoreItem.ACTION_DOWNLOADING, storeItem.getPackageName(), storeItem.getItemId());
}
public void showUnclickableButton() {
progressBar.setVisibility(View.GONE);
button.setVisibility(View.VISIBLE);
button.setPadding(0, 0, 0, 0);
button.setClickable(false);
button.setBackgroundColor(Color.TRANSPARENT);
}
public void showCommonButton() {
progressBar.setVisibility(View.GONE);
button.setVisibility(View.VISIBLE);
button.setPadding(0, 0, 0, 0);
button.setBackgroundResource(R.drawable.btn_item_description_blank);
}
public void showButtonInstalling() {
showUnclickableButton();
button.setText(R.string.installing);
updateShelf(MeepStoreItem.ACTION_INSTALLING, storeItem.getPackageName(), storeItem.getItemId());
}
public void showButtonQueuing() {
showUnclickableButton();
button.setText(R.string.queuing_for_downloading);
updateShelf(MeepStoreItem.ACTION_PENDING_TO_DOWNLOAD, storeItem.getPackageName(), storeItem.getItemId());
}
public void showButtonAwaitingApproval() {
showUnclickableButton();
button.setText(R.string.awaiting);
updateShelf(MeepStoreItem.ACTION_PENDING, storeItem.getPackageName(), storeItem.getItemId());
}
public void showButtonSuccess() {
// showUnclickableButton();
// button.setText(R.string.ebook_success);
showCommonButton();
button.setText(R.string.uninstall2);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
EbookCtrl.removeEbook(storeItem);
storeItem.setItemAction(MeepStoreItem.ACTION_PURCHASED);
showButtonInstall();
updateShelf(MeepStoreItem.ACTION_PURCHASED, storeItem.getPackageName(), storeItem.getItemId());
}
});
updateShelf(MeepStoreItem.ACTION_EBOOK_DOWNLOADED, storeItem.getPackageName(), storeItem.getItemId());
}
public void updateShelf(String action, String packageName, String id) {
if (getActivity() instanceof GenericStoreActivity) {
try {
((GenericStoreActivity) getActivity()).updateItemStatus(action, packageName, id);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void showButtonInstall() {
if (button != null) {
showCommonButton();
button.setText(R.string.install);
button.setOnClickListener((new View.OnClickListener() {
@Override
public void onClick(View pV) {
if (mApp.isNetworkAvailable(getActivity())) {
// loading
handler.sendEmptyMessage(LOADING);
pV.setEnabled(false);
mApp.getRestRequest().purchaseStoreItem(storeItem.getItemId(), mApp.getUserToken());
mApp.getRestRequest().setPurchaseItemListener(new PurchaseItemListener() {
@Override
public void onPurchaseReceived(
PurchaseFeedback feedback) {
if (popupFragment != null) {
popupFragment.dismiss();
}
if (feedback != null) {
switch (feedback.getCode()) {
case 200:
if (feedback.getUrl() != null) {
DownloadStoreItem downloadItem = new DownloadStoreItem(feedback.getItem_id(), feedback.getName(), feedback.getType(), feedback.getImage(), feedback.getUrl(), "", feedback.getPackage_name());
mApp.getStoreDownloadCtrl().addStoreDownloadItem(downloadItem);
}
if (mApp.isItemDownloading(storeItem.getItemId())) {
storeItem.setItemAction(MeepStoreItem.ACTION_DOWNLOADING);
showProgressBar();
} else {
storeItem.setItemAction(MeepStoreItem.ACTION_PENDING_TO_DOWNLOAD);
showButtonQueuing();
}
break;
case 999:
handler.sendEmptyMessage(TIMEOUT);
break;
default:
break;
}
button.setEnabled(true);
} else {
handler.sendEmptyMessage(TIMEOUT);
}
button.setEnabled(true);
}
});
} else {
// no network
handler.sendEmptyMessage(NO_NETWORK);
}
}
}));
}
}
public void showButtonUninstall() {
showCommonButton();
button.setText(R.string.uninstall);
button.setOnClickListener((new View.OnClickListener() {
@Override
public void onClick(View pV) {
AppInstallationCtrl.uninstallApp(getActivity(), storeItem.getPackageName());
}
}));
}
public void showTextBlocked() {
showUnclickableButton();
button.setTextSize(20);
button.setGravity(Gravity.LEFT);
button.setText(R.string.not_allow_to_downlaod);
}
StoreItemDownloadCtrl.DownloadListener mDownloadListener = null;
private void initStoreItemDownloadListener() {
mDownloadListener = new StoreItemDownloadCtrl.DownloadListener() {
@Override
public void onDownloadProgress(String id, int percentage) {
updateDownloadStatus(id, percentage);
}
@Override
public void onDownloadCompleted(boolean downloadAborted,
DownloadStoreItem item) {
if (!downloadAborted)
updateDownloadCompleted(item);
else {
handler.sendEmptyMessage(INSTALL);
}
}
@Override
public void onNoSpace() {
handler.sendEmptyMessage(NOT_ENOUGH_SPACE);
}
};
mApp.getStoreDownloadCtrl().addDownloadListeners(mDownloadListener);
}
private void updateDownloadStatus(String id, int progress) {
MeepStoreLog.logcatMessage("APPSTATUS", "id:" + id + ",progress:" + progress);
if (storeItem.getItemId().equals(id)) {
// show progressbar
handler.sendEmptyMessage(DOWNLOADING);
if (!storeItem.getItemAction().equals(MeepStoreItem.ACTION_DOWNLOADING)) {
storeItem.setItemAction(MeepStoreItem.ACTION_DOWNLOADING);
// updateShelf(MeepStoreItem.ACTION_DOWNLOADING, null, id
// ,progress);
}
storeItem.setProgress(progress);
if (progressBar != null) {
progressBar.setProgress(progress);
}
}
// else
// {
//
// if(progress ==1)
// {
// updateShelf(MeepStoreItem.ACTION_DOWNLOADING, null, id,progress);
// }
// }
}
private void updateDownloadCompleted(DownloadStoreItem item) {
String id = item.getId();
String type = item.getType();
MeepStoreLog.logcatMessage("APPSTATUS", "complete id:" + id);
if (storeItem.getItemId().equals(id)) {
if (progressBar != null) {
progressBar.setProgress(100);
}
handler.sendEmptyMessage(INSTALLING);
if (type != null) {
if (type.equals(MeepStoreItem.TYPE_EBOOK)) {
storeItem.setItemAction(MeepStoreItem.ACTION_EBOOK_DOWNLOADED);
handler.sendEmptyMessage(EBOOK_DOWNLOAD_SUCCESS);
// updateShelf(MeepStoreItem.ACTION_EBOOK_DOWNLOADED, null,
// id,-1);
} else {
storeItem.setItemAction(MeepStoreItem.ACTION_INSTALLING);
// updateShelf(MeepStoreItem.ACTION_INSTALLING, null,
// id,100);
}
}
}
}
public void initPackageListener() {
mPackageListener = new AppInstallationCtrl.PakageListener() {
@Override
public void onpackageReplaced(String packageName) {
// AppInstallationCtrl.removeApk(packageName);
// TODO Auto-generated method stub
MeepStoreLog.logcatMessage("storedownload", "package replace 2");
MeepStoreLog.logcatMessage("APPSTATUS", "replace app " + packageName);
}
@Override
public void onpackageRemoved(String packageName) {
// TODO Auto-generated method stub
MeepStoreLog.logcatMessage("storedownload", "package remove 2");
MeepStoreLog.logcatMessage("APPSTATUS", "remove app " + packageName);
if (storeItem != null && packageName != null) {
if (packageName.equals(storeItem.getPackageName())) {
storeItem.setItemAction(MeepStoreItem.ACTION_PURCHASED);
if (storeItem.isRecovery() && button != null) {
button.setText(R.string.recover);
}
showButtonInstall();
}
}
// updateShelf(MeepStoreItem.ACTION_PURCHASED,packageName,null,-1);
}
@Override
public void onpackageAdded(String packageName) {
// AppInstallationCtrl.removeApk(packageName);
MeepStoreLog.logcatMessage("storedownload", "package add 2");
// TODO Auto-generated method stub
MeepStoreLog.logcatMessage("APPSTATUS", "add app " + packageName);
if (storeItem != null && packageName != null) {
if (packageName.equals(storeItem.getPackageName())) {
storeItem.setItemAction(MeepStoreItem.ACTION_INSTALLED);
showButtonUninstall();
}
}
// updateShelf(MeepStoreItem.ACTION_INSTALLED,packageName,null,-1);
}
};
MeepStoreLog.logcatMessage("AppCtrl", "detail");
mApp.getAppCtrl().addPackageListener(mPackageListener);
}
@Override
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
try {
if (getActivity() instanceof GenericStoreActivity) {
ListAdapterShelf listAdapterShelf = ((GenericStoreActivity) getActivity()).getShelfListAdapter();
listAdapterShelf.enableItemButton();
}
super.onDismiss(dialog);
} catch (Exception e) {
MeepStoreLog.LogMsg("current activity has been closed");
}
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
MeepStoreLog.logcatMessage("AppCtrl", "remove detail");
if (mApp.getAppCtrl() != null) {
mApp.getAppCtrl().removePackageListener(mPackageListener);
}
if (mApp.getStoreDownloadCtrl() != null) {
mApp.getStoreDownloadCtrl().removeDownloadListeners(mDownloadListener);
}
}
}
|
apache-2.0
|
googleapis/google-api-java-client-services
|
clients/google-api-services-cloudtasks/v2beta2/1.31.0/com/google/api/services/cloudtasks/v2beta2/model/Queue.java
|
18027
|
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.cloudtasks.v2beta2.model;
/**
* A queue is a container of related tasks. Queues are configured to manage how those tasks are
* dispatched. Configurable properties include rate limits, retry options, target types, and others.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Cloud Tasks API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class Queue extends com.google.api.client.json.GenericJson {
/**
* App Engine HTTP target. An App Engine queue is a queue that has an AppEngineHttpTarget.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private AppEngineHttpTarget appEngineHttpTarget;
/**
* Caller-specified and required in CreateQueue, after which it becomes output only. The queue
* name. The queue name must have the following format:
* `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` * `PROJECT_ID` can contain letters
* ([A-Za-z]), numbers ([0-9]), hyphens (-), colons (:), or periods (.). For more information, see
* [Identifying projects](https://cloud.google.com/resource-manager/docs/creating-managing-
* projects#identifying_projects) * `LOCATION_ID` is the canonical ID for the queue's location.
* The list of available locations can be obtained by calling ListLocations. For more information,
* see https://cloud.google.com/about/locations/. * `QUEUE_ID` can contain letters ([A-Za-z]),
* numbers ([0-9]), or hyphens (-). The maximum length is 100 characters.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/**
* Pull target. A pull queue is a queue that has a PullTarget.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private PullTarget pullTarget;
/**
* Output only. The last time this queue was purged. All tasks that were created before this time
* were purged. A queue can be purged using PurgeQueue, the [App Engine Task Queue SDK, or the
* Cloud Console](https://cloud.google.com/appengine/docs/standard/python/taskqueue/push/deleting-
* tasks-and-queues#purging_all_tasks_from_a_queue). Purge time will be truncated to the nearest
* microsecond. Purge time will be unset if the queue has never been purged.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private String purgeTime;
/**
* Rate limits for task dispatches. rate_limits and retry_config are related because they both
* control task attempts however they control how tasks are attempted in different ways: *
* rate_limits controls the total rate of dispatches from a queue (i.e. all traffic dispatched
* from the queue, regardless of whether the dispatch is from a first attempt or a retry). *
* retry_config controls what happens to particular a task after its first attempt fails. That is,
* retry_config controls task retries (the second attempt, third attempt, etc).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private RateLimits rateLimits;
/**
* Settings that determine the retry behavior. * For tasks created using Cloud Tasks: the queue-
* level retry settings apply to all tasks in the queue that were created using Cloud Tasks. Retry
* settings cannot be set on individual tasks. * For tasks created using the App Engine SDK: the
* queue-level retry settings apply to all tasks in the queue which do not have retry settings
* explicitly set on the task and were created by the App Engine SDK. See [App Engine
* documentation](https://cloud.google.com/appengine/docs/standard/python/taskqueue/push/retrying-
* tasks).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private RetryConfig retryConfig;
/**
* Output only. The state of the queue. `state` can only be changed by called PauseQueue,
* ResumeQueue, or uploading
* [queue.yaml/xml](https://cloud.google.com/appengine/docs/python/config/queueref). UpdateQueue
* cannot be used to change `state`.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String state;
/**
* Output only. The realtime, informational statistics for a queue. In order to receive the
* statistics the caller should include this field in the FieldMask.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private QueueStats stats;
/**
* The maximum amount of time that a task will be retained in this queue. Queues created by Cloud
* Tasks have a default `task_ttl` of 31 days. After a task has lived for `task_ttl`, the task
* will be deleted regardless of whether it was dispatched or not. The `task_ttl` for queues
* created via queue.yaml/xml is equal to the maximum duration because there is a [storage
* quota](https://cloud.google.com/appengine/quotas#Task_Queue) for these queues. To view the
* maximum valid duration, see the documentation for Duration.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private String taskTtl;
/**
* The task tombstone time to live (TTL). After a task is deleted or completed, the task's
* tombstone is retained for the length of time specified by `tombstone_ttl`. The tombstone is
* used by task de-duplication; another task with the same name can't be created until the
* tombstone has expired. For more information about task de-duplication, see the documentation
* for CreateTaskRequest. Queues created by Cloud Tasks have a default `tombstone_ttl` of 1 hour.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private String tombstoneTtl;
/**
* App Engine HTTP target. An App Engine queue is a queue that has an AppEngineHttpTarget.
* @return value or {@code null} for none
*/
public AppEngineHttpTarget getAppEngineHttpTarget() {
return appEngineHttpTarget;
}
/**
* App Engine HTTP target. An App Engine queue is a queue that has an AppEngineHttpTarget.
* @param appEngineHttpTarget appEngineHttpTarget or {@code null} for none
*/
public Queue setAppEngineHttpTarget(AppEngineHttpTarget appEngineHttpTarget) {
this.appEngineHttpTarget = appEngineHttpTarget;
return this;
}
/**
* Caller-specified and required in CreateQueue, after which it becomes output only. The queue
* name. The queue name must have the following format:
* `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` * `PROJECT_ID` can contain letters
* ([A-Za-z]), numbers ([0-9]), hyphens (-), colons (:), or periods (.). For more information, see
* [Identifying projects](https://cloud.google.com/resource-manager/docs/creating-managing-
* projects#identifying_projects) * `LOCATION_ID` is the canonical ID for the queue's location.
* The list of available locations can be obtained by calling ListLocations. For more information,
* see https://cloud.google.com/about/locations/. * `QUEUE_ID` can contain letters ([A-Za-z]),
* numbers ([0-9]), or hyphens (-). The maximum length is 100 characters.
* @return value or {@code null} for none
*/
public java.lang.String getName() {
return name;
}
/**
* Caller-specified and required in CreateQueue, after which it becomes output only. The queue
* name. The queue name must have the following format:
* `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` * `PROJECT_ID` can contain letters
* ([A-Za-z]), numbers ([0-9]), hyphens (-), colons (:), or periods (.). For more information, see
* [Identifying projects](https://cloud.google.com/resource-manager/docs/creating-managing-
* projects#identifying_projects) * `LOCATION_ID` is the canonical ID for the queue's location.
* The list of available locations can be obtained by calling ListLocations. For more information,
* see https://cloud.google.com/about/locations/. * `QUEUE_ID` can contain letters ([A-Za-z]),
* numbers ([0-9]), or hyphens (-). The maximum length is 100 characters.
* @param name name or {@code null} for none
*/
public Queue setName(java.lang.String name) {
this.name = name;
return this;
}
/**
* Pull target. A pull queue is a queue that has a PullTarget.
* @return value or {@code null} for none
*/
public PullTarget getPullTarget() {
return pullTarget;
}
/**
* Pull target. A pull queue is a queue that has a PullTarget.
* @param pullTarget pullTarget or {@code null} for none
*/
public Queue setPullTarget(PullTarget pullTarget) {
this.pullTarget = pullTarget;
return this;
}
/**
* Output only. The last time this queue was purged. All tasks that were created before this time
* were purged. A queue can be purged using PurgeQueue, the [App Engine Task Queue SDK, or the
* Cloud Console](https://cloud.google.com/appengine/docs/standard/python/taskqueue/push/deleting-
* tasks-and-queues#purging_all_tasks_from_a_queue). Purge time will be truncated to the nearest
* microsecond. Purge time will be unset if the queue has never been purged.
* @return value or {@code null} for none
*/
public String getPurgeTime() {
return purgeTime;
}
/**
* Output only. The last time this queue was purged. All tasks that were created before this time
* were purged. A queue can be purged using PurgeQueue, the [App Engine Task Queue SDK, or the
* Cloud Console](https://cloud.google.com/appengine/docs/standard/python/taskqueue/push/deleting-
* tasks-and-queues#purging_all_tasks_from_a_queue). Purge time will be truncated to the nearest
* microsecond. Purge time will be unset if the queue has never been purged.
* @param purgeTime purgeTime or {@code null} for none
*/
public Queue setPurgeTime(String purgeTime) {
this.purgeTime = purgeTime;
return this;
}
/**
* Rate limits for task dispatches. rate_limits and retry_config are related because they both
* control task attempts however they control how tasks are attempted in different ways: *
* rate_limits controls the total rate of dispatches from a queue (i.e. all traffic dispatched
* from the queue, regardless of whether the dispatch is from a first attempt or a retry). *
* retry_config controls what happens to particular a task after its first attempt fails. That is,
* retry_config controls task retries (the second attempt, third attempt, etc).
* @return value or {@code null} for none
*/
public RateLimits getRateLimits() {
return rateLimits;
}
/**
* Rate limits for task dispatches. rate_limits and retry_config are related because they both
* control task attempts however they control how tasks are attempted in different ways: *
* rate_limits controls the total rate of dispatches from a queue (i.e. all traffic dispatched
* from the queue, regardless of whether the dispatch is from a first attempt or a retry). *
* retry_config controls what happens to particular a task after its first attempt fails. That is,
* retry_config controls task retries (the second attempt, third attempt, etc).
* @param rateLimits rateLimits or {@code null} for none
*/
public Queue setRateLimits(RateLimits rateLimits) {
this.rateLimits = rateLimits;
return this;
}
/**
* Settings that determine the retry behavior. * For tasks created using Cloud Tasks: the queue-
* level retry settings apply to all tasks in the queue that were created using Cloud Tasks. Retry
* settings cannot be set on individual tasks. * For tasks created using the App Engine SDK: the
* queue-level retry settings apply to all tasks in the queue which do not have retry settings
* explicitly set on the task and were created by the App Engine SDK. See [App Engine
* documentation](https://cloud.google.com/appengine/docs/standard/python/taskqueue/push/retrying-
* tasks).
* @return value or {@code null} for none
*/
public RetryConfig getRetryConfig() {
return retryConfig;
}
/**
* Settings that determine the retry behavior. * For tasks created using Cloud Tasks: the queue-
* level retry settings apply to all tasks in the queue that were created using Cloud Tasks. Retry
* settings cannot be set on individual tasks. * For tasks created using the App Engine SDK: the
* queue-level retry settings apply to all tasks in the queue which do not have retry settings
* explicitly set on the task and were created by the App Engine SDK. See [App Engine
* documentation](https://cloud.google.com/appengine/docs/standard/python/taskqueue/push/retrying-
* tasks).
* @param retryConfig retryConfig or {@code null} for none
*/
public Queue setRetryConfig(RetryConfig retryConfig) {
this.retryConfig = retryConfig;
return this;
}
/**
* Output only. The state of the queue. `state` can only be changed by called PauseQueue,
* ResumeQueue, or uploading
* [queue.yaml/xml](https://cloud.google.com/appengine/docs/python/config/queueref). UpdateQueue
* cannot be used to change `state`.
* @return value or {@code null} for none
*/
public java.lang.String getState() {
return state;
}
/**
* Output only. The state of the queue. `state` can only be changed by called PauseQueue,
* ResumeQueue, or uploading
* [queue.yaml/xml](https://cloud.google.com/appengine/docs/python/config/queueref). UpdateQueue
* cannot be used to change `state`.
* @param state state or {@code null} for none
*/
public Queue setState(java.lang.String state) {
this.state = state;
return this;
}
/**
* Output only. The realtime, informational statistics for a queue. In order to receive the
* statistics the caller should include this field in the FieldMask.
* @return value or {@code null} for none
*/
public QueueStats getStats() {
return stats;
}
/**
* Output only. The realtime, informational statistics for a queue. In order to receive the
* statistics the caller should include this field in the FieldMask.
* @param stats stats or {@code null} for none
*/
public Queue setStats(QueueStats stats) {
this.stats = stats;
return this;
}
/**
* The maximum amount of time that a task will be retained in this queue. Queues created by Cloud
* Tasks have a default `task_ttl` of 31 days. After a task has lived for `task_ttl`, the task
* will be deleted regardless of whether it was dispatched or not. The `task_ttl` for queues
* created via queue.yaml/xml is equal to the maximum duration because there is a [storage
* quota](https://cloud.google.com/appengine/quotas#Task_Queue) for these queues. To view the
* maximum valid duration, see the documentation for Duration.
* @return value or {@code null} for none
*/
public String getTaskTtl() {
return taskTtl;
}
/**
* The maximum amount of time that a task will be retained in this queue. Queues created by Cloud
* Tasks have a default `task_ttl` of 31 days. After a task has lived for `task_ttl`, the task
* will be deleted regardless of whether it was dispatched or not. The `task_ttl` for queues
* created via queue.yaml/xml is equal to the maximum duration because there is a [storage
* quota](https://cloud.google.com/appengine/quotas#Task_Queue) for these queues. To view the
* maximum valid duration, see the documentation for Duration.
* @param taskTtl taskTtl or {@code null} for none
*/
public Queue setTaskTtl(String taskTtl) {
this.taskTtl = taskTtl;
return this;
}
/**
* The task tombstone time to live (TTL). After a task is deleted or completed, the task's
* tombstone is retained for the length of time specified by `tombstone_ttl`. The tombstone is
* used by task de-duplication; another task with the same name can't be created until the
* tombstone has expired. For more information about task de-duplication, see the documentation
* for CreateTaskRequest. Queues created by Cloud Tasks have a default `tombstone_ttl` of 1 hour.
* @return value or {@code null} for none
*/
public String getTombstoneTtl() {
return tombstoneTtl;
}
/**
* The task tombstone time to live (TTL). After a task is deleted or completed, the task's
* tombstone is retained for the length of time specified by `tombstone_ttl`. The tombstone is
* used by task de-duplication; another task with the same name can't be created until the
* tombstone has expired. For more information about task de-duplication, see the documentation
* for CreateTaskRequest. Queues created by Cloud Tasks have a default `tombstone_ttl` of 1 hour.
* @param tombstoneTtl tombstoneTtl or {@code null} for none
*/
public Queue setTombstoneTtl(String tombstoneTtl) {
this.tombstoneTtl = tombstoneTtl;
return this;
}
@Override
public Queue set(String fieldName, Object value) {
return (Queue) super.set(fieldName, value);
}
@Override
public Queue clone() {
return (Queue) super.clone();
}
}
|
apache-2.0
|
Alachisoft/NCache
|
Src/NCCache/Caching/AllowedOperationType.cs
|
845
|
// Copyright (c) 2021 Alachisoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License
namespace Alachisoft.NCache.Caching
{
public enum AllowedOperationType
{
AtomicRead = 1,
AtomicWrite = 2,
BulkRead = 3,
BulkWrite = 4,
InternalCommand = 5,
ClusterRead = 6
}
}
|
apache-2.0
|
caicloud/cyclone
|
web/src/components/workflow/component/add/CreateWorkflow.js
|
5267
|
import { Steps, Button, Form } from 'antd';
import Graph from './Graph';
import BasicInfo from './BasicInfo';
import styles from '../index.module.less';
import classNames from 'classnames/bind';
import PropTypes from 'prop-types';
import { tranformStage } from '@/lib/util';
import { inject, observer } from 'mobx-react';
const styleCls = classNames.bind(styles);
const Step = Steps.Step;
@inject('workflow')
@observer
class App extends React.Component {
static propTypes = {
setFieldValue: PropTypes.func,
values: PropTypes.object,
handleDepend: PropTypes.func,
handleSubmit: PropTypes.func,
submitting: PropTypes.bool,
setSubmitting: PropTypes.func,
saveStagePostition: PropTypes.func,
workFlowInfo: PropTypes.object,
workflow: PropTypes.object,
workflowName: PropTypes.string,
project: PropTypes.string,
validateForm: PropTypes.func,
setTouched: PropTypes.func,
history: PropTypes.object,
};
constructor(props) {
super(props);
const { workFlowInfo } = props;
this.state = {
current: 0,
graph: _.isEmpty(workFlowInfo)
? {}
: tranformStage(
_.get(workFlowInfo, 'spec.stages'),
_.get(workFlowInfo, 'metadata.annotations.stagePosition')
),
};
}
componentDidUpdate(prevProps) {
const { submitting, setSubmitting } = this.props;
if (!submitting && submitting !== prevProps.submitting) {
setSubmitting(submitting);
}
}
next = update => {
const {
workflow: { updateWorkflow, workflowDetail },
values,
workflowName,
project,
validateForm,
setTouched,
} = this.props;
validateForm().then(error => {
if (_.isEmpty(error)) {
const current = this.state.current + 1;
this.setState({ current });
if (update) {
const detail = _.get(workflowDetail, workflowName);
const prevDes = _.get(detail, 'metadata.annotations.description');
const des = _.get(values, 'metadata.annotations.description');
if (prevDes !== des) {
const workflowData = {
metadata: {
name: workflowName,
annotations: { description: des },
},
..._.pick(detail, 'spec.stages'),
};
updateWorkflow(project, workflowName, workflowData);
}
}
} else {
setTouched({ 'metadata.name': true });
}
});
};
prev = update => {
const current = this.state.current - 1;
this.setState({ current });
};
// cancel create workflow
cancel = () => {
this.props.history.goBack();
};
saveGraph = graphData => {
this.setState({ graph: graphData });
};
getStepContent = current => {
const {
setFieldValue,
values,
handleDepend,
saveStagePostition,
workFlowInfo,
project,
workflowName,
validateForm,
setTouched,
} = this.props;
const { graph } = this.state;
const update = !_.isEmpty(workFlowInfo);
switch (current) {
case 0: {
return <BasicInfo update={update} values={values} />;
}
case 1: {
return (
<Graph
setFieldValue={setFieldValue}
values={values}
initialGraph={graph}
update={update}
project={project}
workflowName={workflowName}
setStageDepned={handleDepend}
updateStagePosition={saveStagePostition}
saveGraphWhenUnmount={this.saveGraph}
validateForm={validateForm}
setTouched={setTouched}
/>
);
}
default: {
return null;
}
}
};
render() {
const { current } = this.state;
const { handleSubmit, workflowName } = this.props;
const update = !!workflowName;
const steps = [
{
title: `${intl.get('workflow.basicInfo')}`,
content: <BasicInfo />,
},
{
title: `${intl.get('workflow.task')}`,
content: <Graph />,
},
];
return (
<Form>
<Steps current={current} size="small">
{steps.map((item, i) => (
<Step key={i} title={item.title} />
))}
</Steps>
<div
className={styleCls('steps-content', {
graph: current === 1,
})}
>
{this.getStepContent(current)}
</div>
<div className="steps-action">
{current < steps.length - 1 && (
<Button type="primary" onClick={() => this.next(update)}>
{intl.get('next')}
</Button>
)}
{current === steps.length - 1 && !update && (
<Button type="primary" onClick={handleSubmit}>
{intl.get('confirm')}
</Button>
)}
{current > 0 && (
<Button style={{ marginLeft: 8 }} onClick={() => this.prev()}>
{intl.get('prev')}
</Button>
)}
{
<Button style={{ marginLeft: 8 }} onClick={() => this.cancel()}>
{intl.get('cancel')}
</Button>
}
</div>
</Form>
);
}
}
export default App;
|
apache-2.0
|
wingsofovnia/reppy
|
reppy-core/src/main/java/com/github/wingsofovnia/reppy/api/SequenceRepository.java
|
514
|
package com.github.wingsofovnia.reppy.api;
import java.io.Serializable;
import java.util.Optional;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.stream.Stream;
public interface SequenceRepository<T, ID extends Serializable> extends Repository<T> {
Optional<T> get(ID index);
Stream<T> getAll();
void remove(ID index);
@Override
default Spliterator<T> spliterator() {
return Spliterators.spliterator(iterator(), size(), Spliterator.ORDERED);
}
}
|
apache-2.0
|
akiellor/selenium
|
javascript/atoms/events.js
|
13006
|
// Copyright 2010 WebDriver committers
// Copyright 2010 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.
/**
* @fileoverview Functions to do with firing and simulating events.
*
*/
goog.provide('bot.events');
goog.require('bot.dom');
goog.require('goog.dom');
goog.require('goog.events.EventType');
goog.require('goog.userAgent');
/**
* Enumeration of mouse buttons that can be pressed.
*
* @enum {number}
*/
bot.events.Button = {
NONE: null, // So that we can move a mouse without a button being down
LEFT: (goog.userAgent.IE ? 1 : 0),
MIDDLE: (goog.userAgent.IE ? 4 : 1),
RIGHT: (goog.userAgent.IE ? 2 : 2)
};
/**
* The related target field is only useful for mouseover, mouseout, dragenter
* and dragexit events. We use this array to see if the relatedTarget field
* needs to be assigned a value.
*
* https://developer.mozilla.org/en/DOM/event.relatedTarget
* @private
* @const
*/
bot.events.RELATED_TARGET_EVENTS_ = [
goog.events.EventType.DRAGSTART,
'dragexit', /** goog.events.EventType.DRAGEXIT, */
goog.events.EventType.MOUSEOVER,
goog.events.EventType.MOUSEOUT
];
/**
* @typedef {{x: (number|undefined),
* y: (number|undefined),
* button: (bot.events.Button|undefined),
* bubble: (boolean|undefined),
* alt: (boolean|undefined),
* control: (boolean|undefined),
* shift: (boolean|undefined),
* meta: (boolean|undefined),
* related: (Element|undefined)}}
*/
bot.events.MouseArgs;
/**
* Initialize a new mouse event. The opt_args can be used to pass in extra
* parameters that might be needed, though the function attempts to guess some
* valid default values. Extra arguments are specified as properties of the
* object passed in as "opt_args" and can be:
*
* <dl>
* <dt>x</dt>
* <dd>The x value relative to the client viewport.</dd>
* <dt>y</dt>
* <dd>The y value relative to the client viewport.</dd>
* <dt>button</dt>
* <dd>The mouse button (from {@code bot.events.button}). Defaults to LEFT</dd>
* <dt>bubble</dt>
* <dd>Can the event bubble? Defaults to true</dd>
* <dt>alt</dt>
* <dd>Is the "Alt" key pressed. Defaults to false</dd>
* <dt>control</dt>
* <dd>Is the "Alt" key pressed. Defaults to false</dd>
* <dt>shift</dt>
* <dd>Is the "Alt" key pressed. Defaults to false</dd>
* <dt>meta</dt>
* <dd>Is the "Alt" key pressed. Defaults to false</dd>
* <dt>related</dt>
* <dd>The related target. Defaults to null</dd>
* </dl>
*
* @param {!Element} element The element on which the event will be fired.
* @param {!goog.events.EventType} type One of the goog.events.EventType values.
* @param {!bot.events.MouseArgs=} opt_args See above.
* @return {!Event} An initialized mouse event, with fields populated from
* opt_args.
* @private
*/
bot.events.newMouseEvent_ = function(element, type, opt_args) {
var doc = goog.dom.getOwnerDocument(element);
var win = goog.dom.getWindow(doc);
var pos = goog.style.getClientPosition(element);
var args = opt_args || {};
// Use string indexes so we can be compiled aggressively
var x = (args['x'] || 0) + pos.x;
var y = (args['y'] || 0) + pos.y;
var button = args['button'] || bot.events.Button.LEFT;
var canBubble = args['bubble'] || true;
// Only useful for mouseover, mouseout, dragenter and dragexit
// https://developer.mozilla.org/en/DOM/event.relatedTarget
var relatedTarget = null;
if (goog.array.contains(bot.events.RELATED_TARGET_EVENTS_, type)) {
relatedTarget = args['related'] || null;
}
var alt = !!args['alt'];
var control = !!args['control'];
var shift = !!args['shift'];
var meta = !!args['meta'];
var event;
// IE path first
if (element['fireEvent'] && doc && doc['createEventObject']) {
event = doc.createEventObject();
event.altKey = alt;
event.controlKey = control;
event.metaKey = meta;
event.shiftKey = shift;
// NOTE: ie8 does a strange thing with the coordinates passed in the event:
// - if offset{X,Y} coordinates are specified, they are also used for
// client{X,Y}, event if client{X,Y} are also specified.
// - if only client{X,Y} are specified, they are also used for offset{x,y}
// Thus, for ie8, it is impossible to set both offset and client
// and have them be correct when they come out on the other side.
event.clientX = x;
event.clientY = y;
event.button = button;
event.relatedTarget = relatedTarget;
} else {
event = doc.createEvent('MouseEvents');
if (event['initMouseEvent']) {
// see http://developer.mozilla.org/en/docs/DOM:event.button and
// http://developer.mozilla.org/en/docs/DOM:event.initMouseEvent
// for button ternary logic logic.
// screenX=0 and screenY=0 are ignored
event.initMouseEvent(type, canBubble, true, win, 1, 0, 0, x, y,
control, alt, shift, meta, button, relatedTarget);
} else {
// You're in a strange and bad place here.
event.initEvent(type, canBubble, true);
event.shiftKey = shift;
event.metaKey = meta;
event.altKey = alt;
event.ctrlKey = control;
event.button = button;
}
}
return event;
};
/**
* Data structure representing keyboard event arguments that may be
* passed to the fire function.
*
* @typedef {{keyCode: (number|undefined),
* charCode: (number|undefined),
* alt: (boolean|undefined),
* ctrl: (boolean|undefined),
* shift: (boolean|undefined),
* meta: (boolean|undefined)}}
*/
bot.events.KeyboardArgs;
/**
* Initialize a new keyboard event.
*
* @param {!Element} element The element on which the event will be fired.
* @param {!goog.events.EventType} type The type of keyboard event being sent,
* should be KEYPRESS, KEYDOWN, or KEYUP.
* @param {!bot.events.KeyboardArgs=} opt_args See above.
* @return {!Event} An initialized keyboard event, with fields populated from
* opt_args.
* @private
*/
bot.events.newKeyEvent_ = function(element, type, opt_args) {
var doc = goog.dom.getOwnerDocument(element);
var win = goog.dom.getWindow(doc);
var args = opt_args || {};
var keyCode = args['keyCode'] || 0;
var charCode = args['charCode'] || 0;
var alt = !!args['alt'];
var control = !!args['ctrl'];
var shift = !!args['shift'];
var meta = !!args['meta'];
var event;
if (goog.userAgent.GECKO) {
event = doc.createEvent('KeyboardEvent');
event.initKeyEvent(type,
/* bubbles= */ true,
/* cancelable= */true,
/* view= */ win,
control,
alt,
shift,
meta,
keyCode,
charCode);
} else if (goog.userAgent.IE) {
event = doc.createEventObject();
event.keyCode = keyCode;
event.altKey = alt;
event.ctrlKey = control;
event.metaKey = meta;
event.shiftKey = shift;
} else { // For both WebKit and Opera.
event = doc.createEvent('Events');
event.initEvent(type, true, true);
event.charCode = charCode;
event.keyCode = keyCode;
event.altKey = alt;
event.ctrlKey = control;
event.metaKey = meta;
event.shiftKey = shift;
}
return event;
};
/**
* Data structure representing arguments that may be passed to the fire
* function.
*
* @typedef {{bubble: (boolean|undefined),
* alt: (boolean|undefined),
* control: (boolean|undefined),
* shift: (boolean|undefined),
* meta: (boolean|undefined)}}
*/
bot.events.HtmlArgs;
/**
* Initialize a new HTML event. The opt_args can be used to pass in extra
* parameters that might be needed, though the function attempts to guess some
* valid default values. Extra arguments are specified as properties of the
* object passed in as "opt_args" and can be:
*
* <dl>
* <dt>bubble</dt>
* <dd>Can the event bubble? Defaults to true</dd>
* <dt>alt</dt>
* <dd>Is the "Alt" key pressed. Defaults to false</dd>
* <dt>control</dt>
* <dd>Is the "Alt" key pressed. Defaults to false</dd>
* <dt>shift</dt>
* <dd>Is the "Alt" key pressed. Defaults to false</dd>
* <dt>meta</dt>
* <dd>Is the "Alt" key pressed. Defaults to false</dd>
* </dl>
*
* @param {!Element} element The element on which the event will be fired.
* @param {!goog.events.EventType} type One of the goog.events.EventType values.
* @param {!bot.events.HtmlArgs=} opt_args See above.
* @return {!Event} An initialized event object, with fields populated from
* opt_args.
* @private
*/
bot.events.newHtmlEvent_ = function(element, type, opt_args) {
var doc = goog.dom.getOwnerDocument(element);
var win = goog.dom.getWindow(doc);
var args = opt_args || {};
var canBubble = args['bubble'] !== false;
var alt = !!args['alt'];
var control = !!args['control'];
var shift = !!args['shift'];
var meta = !!args['meta'];
var event;
if (element['fireEvent'] && doc && doc['createEventObject']) {
event = doc.createEventObject();
event.altKey = alt;
event.ctrl = control;
event.metaKey = meta;
event.shiftKey = shift;
} else {
event = doc.createEvent('HTMLEvents');
event.initEvent(type, canBubble, true);
event.shiftKey = shift;
event.metaKey = meta;
event.altKey = alt;
event.ctrlKey = control;
}
return event;
};
/**
* Maps symbolic names to functions used to initialize the event.
*
* @type {!Object.<goog.events.EventType,
* function(!Element, !goog.events.EventType, ...): !Event>}
* @private
* @const
*/
bot.events.INIT_FUNCTIONS_ = {};
bot.events.INIT_FUNCTIONS_[goog.events.EventType.CLICK] =
bot.events.newMouseEvent_;
bot.events.INIT_FUNCTIONS_[goog.events.EventType.KEYDOWN] =
bot.events.newKeyEvent_;
bot.events.INIT_FUNCTIONS_[goog.events.EventType.KEYPRESS] =
bot.events.newKeyEvent_;
bot.events.INIT_FUNCTIONS_[goog.events.EventType.KEYUP] =
bot.events.newKeyEvent_;
bot.events.INIT_FUNCTIONS_[goog.events.EventType.MOUSEDOWN] =
bot.events.newMouseEvent_;
bot.events.INIT_FUNCTIONS_[goog.events.EventType.MOUSEMOVE] =
bot.events.newMouseEvent_;
bot.events.INIT_FUNCTIONS_[goog.events.EventType.MOUSEOUT] =
bot.events.newMouseEvent_;
bot.events.INIT_FUNCTIONS_[goog.events.EventType.MOUSEOVER] =
bot.events.newMouseEvent_;
bot.events.INIT_FUNCTIONS_[goog.events.EventType.MOUSEUP] =
bot.events.newMouseEvent_;
/**
* Dispatch the event in a browser-safe way.
*
* @param {!Element} target The element on which this event will fire.
* @param {!goog.events.EventType} type The type of event to fire.
* @param {!Object} event The initialized event.
* @return {boolean} Whether the event fired successfully or was cancelled.
* @private
*/
bot.events.dispatchEvent_ = function(target, type, event) {
// Amusingly, fireEvent is native code on IE 7-, so we can't just use
// goog.isFunction
if (goog.isFunction(target['fireEvent']) ||
goog.isObject(target['fireEvent'])) {
// when we go this route, window.event is never set to contain the
// event we have just created. ideally we could just slide it in
// as follows in the try-block below, but this normally doesn't
// work. This is why I try to avoid this code path, which is only
// required if we need to set attributes on the event (e.g.,
// clientX).
try {
var doc = goog.dom.getOwnerDocument(target);
var win = goog.dom.getWindow(doc);
win.event = event;
} catch (e) {
// work around for http://jira.openqa.org/browse/SEL-280 -- make
// the event available somewhere:
}
return target.fireEvent('on' + type, event);
} else {
return target.dispatchEvent((/**@type {Event} */event));
}
};
/**
* Fire a named event on a particular element.
*
* @param {!Element} target The element on which to fire the event.
* @param {!goog.events.EventType} type The type of event.
* @param {!(bot.events.MouseArgs|bot.events.HtmlArgs|
* bot.events.KeyboardArgs)=} opt_args Arguments, used to initialize
* the event.
* @return {boolean} Whether the event fired successfully or was cancelled.
*/
bot.events.fire = function(target, type, opt_args) {
var init = bot.events.INIT_FUNCTIONS_[type] || bot.events.newHtmlEvent_;
var event = init(target, type, opt_args);
return bot.events.dispatchEvent_(target, type, event);
};
|
apache-2.0
|
craigbr/mon-api
|
src/test/java/com/hpcloud/mon/integration/NotificationMethodIntegrationTest.java
|
4712
|
package com.hpcloud.mon.integration;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.fail;
import java.nio.charset.Charset;
import javax.ws.rs.core.MediaType;
import org.skife.jdbi.v2.DBI;
import org.skife.jdbi.v2.Handle;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.google.common.io.Resources;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.hpcloud.mon.MonApiConfiguration;
import com.hpcloud.mon.MonApiModule;
import com.hpcloud.mon.app.command.CreateNotificationMethodCommand;
import com.hpcloud.mon.domain.exception.EntityNotFoundException;
import com.hpcloud.mon.domain.model.notificationmethod.NotificationMethod;
import com.hpcloud.mon.domain.model.notificationmethod.NotificationMethodRepository;
import com.hpcloud.mon.domain.model.notificationmethod.NotificationMethodType;
import com.hpcloud.mon.infrastructure.persistence.NotificationMethodRepositoryImpl;
import com.hpcloud.mon.resource.AbstractMonApiResourceTest;
import com.hpcloud.mon.resource.NotificationMethodResource;
import com.sun.jersey.api.client.ClientResponse;
@Test(groups = "integration")
public class NotificationMethodIntegrationTest extends AbstractMonApiResourceTest {
private static final String TENANT_ID = "notification-method-test";
private DBI db;
private NotificationMethod notificationMethod;
private NotificationMethodRepository repo;
@Override
protected void setupResources() throws Exception {
super.setupResources();
Handle handle = db.open();
handle.execute("truncate table notification_method");
handle.execute("insert into notification_method (id, tenant_id, name, type, address, created_at, updated_at) values ('29387234', 'notification-method-test', 'MySMS', 'SMS', '8675309', NOW(), NOW())");
db.close(handle);
repo = new NotificationMethodRepositoryImpl(db);
addResources(new NotificationMethodResource(repo));
}
@BeforeTest
protected void beforeTest() throws Exception {
MonApiConfiguration config = getConfiguration("config-test.yml", MonApiConfiguration.class);
Injector injector = Guice.createInjector(new MonApiModule(environment, config));
db = injector.getInstance(DBI.class);
Handle handle = db.open();
handle.execute(Resources.toString(
NotificationMethodRepositoryImpl.class.getResource("notification_method.sql"),
Charset.defaultCharset()));
handle.close();
// Fixtures
notificationMethod = new NotificationMethod("123", "Joe's SMS", NotificationMethodType.SMS,
"8675309");
}
public void shouldCreate() throws Exception {
ClientResponse response = client().resource("/v2.0/notification-methods")
.header("X-Tenant-Id", TENANT_ID)
.type(MediaType.APPLICATION_JSON)
.post(
ClientResponse.class,
new CreateNotificationMethodCommand(notificationMethod.getName(),
notificationMethod.getType(), notificationMethod.getAddress()));
NotificationMethod newNotificationMethod = response.getEntity(NotificationMethod.class);
String location = response.getHeaders().get("Location").get(0);
assertEquals(response.getStatus(), 201);
assertEquals(location, "/v2.0/notification-methods/" + newNotificationMethod.getId());
assertEquals(newNotificationMethod.getName(), notificationMethod.getName());
assertEquals(newNotificationMethod.getAddress(), notificationMethod.getAddress());
assertEquals(repo.findById(TENANT_ID, newNotificationMethod.getId()), newNotificationMethod);
}
public void shouldConflict() throws Exception {
ClientResponse response = client().resource("/v2.0/notification-methods")
.header("X-Tenant-Id", TENANT_ID)
.type(MediaType.APPLICATION_JSON)
.post(ClientResponse.class,
new CreateNotificationMethodCommand("MySMS", NotificationMethodType.SMS, "8675309"));
assertEquals(response.getStatus(), 409);
}
public void shouldDelete() {
NotificationMethod newMethod = repo.create(TENANT_ID, notificationMethod.getName(),
notificationMethod.getType(), notificationMethod.getAddress());
assertNotNull(repo.findById(TENANT_ID, newMethod.getId()));
ClientResponse response = client().resource("/v2.0/notification-methods/" + newMethod.getId())
.header("X-Tenant-Id", TENANT_ID)
.delete(ClientResponse.class);
assertEquals(response.getStatus(), 204);
try {
assertNull(repo.findById(TENANT_ID, newMethod.getId()));
fail();
} catch (EntityNotFoundException expected) {
}
}
}
|
apache-2.0
|
road-framework/ROADDesigner
|
au.edu.swin.ict.road.designer.diagram/src/au/edu/swin/ict/road/designer/smc/diagram/edit/commands/ContractRoleAIDCreateCommand.java
|
2497
|
package au.edu.swin.ict.road.designer.smc.diagram.edit.commands;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.gmf.runtime.common.core.command.CommandResult;
import org.eclipse.gmf.runtime.emf.type.core.commands.EditElementCommand;
import org.eclipse.gmf.runtime.emf.type.core.requests.CreateRelationshipRequest;
import au.edu.swin.ict.road.designer.smc.Contract;
import au.edu.swin.ict.road.designer.smc.Role;
import au.edu.swin.ict.road.designer.smc.diagram.edit.policies.SmcBaseItemSemanticEditPolicy;
/**
* @generated
*/
public class ContractRoleAIDCreateCommand extends EditElementCommand {
/**
* @generated
*/
private final EObject source;
/**
* @generated
*/
private final EObject target;
/**
* @generated
*/
public ContractRoleAIDCreateCommand(CreateRelationshipRequest request,
EObject source, EObject target) {
super(request.getLabel(), null, request);
this.source = source;
this.target = target;
}
/**
* @generated
*/
public boolean canExecute() {
if (source == null && target == null) {
return false;
}
if (source != null && false == source instanceof Contract) {
return false;
}
if (target != null && false == target instanceof Role) {
return false;
}
if (getSource() == null) {
return true; // link creation is in progress; source is not defined yet
}
// target may be null here but it's possible to check constraint
return SmcBaseItemSemanticEditPolicy.LinkConstraints
.canCreateContractRoleAID_4001(getSource(), getTarget());
}
/**
* @generated
*/
protected CommandResult doExecuteWithResult(IProgressMonitor monitor,
IAdaptable info) throws ExecutionException {
if (!canExecute()) {
throw new ExecutionException(
"Invalid arguments in create link command"); //$NON-NLS-1$
}
if (getSource() != null && getTarget() != null) {
getSource().setRoleAID(getTarget());
}
return CommandResult.newOKCommandResult();
}
/**
* @generated
*/
protected void setElementToEdit(EObject element) {
throw new UnsupportedOperationException();
}
/**
* @generated
*/
protected Contract getSource() {
return (Contract) source;
}
/**
* @generated
*/
protected Role getTarget() {
return (Role) target;
}
}
|
apache-2.0
|
nla/bamboo
|
ui/src/bamboo/crawl/Serieses.java
|
2067
|
package bamboo.crawl;
import java.util.List;
import bamboo.AuthHelper;
import bamboo.core.NotFoundException;
import bamboo.util.Pager;
public class Serieses {
private final SeriesDAO dao;
public Serieses(SeriesDAO seriesDAO) {
this.dao = seriesDAO;
}
public Series getOrNull(long id) {
return dao.findCrawlSeriesById(id);
}
/**
* Retrieve a series's metadata.
*
* @throws NotFoundException if the crawl doesn't exist
*/
public Series get(long id) {
return NotFoundException.check(getOrNull(id), "series", id);
}
public Pager<SeriesDAO.CrawlSeriesWithCount> paginate(long page) {
return new Pager<>(page, dao.countCrawlSeries(), dao::paginateCrawlSeries);
}
public Pager<SeriesDAO.CrawlSeriesWithCount> paginateForAgencyId(long agencyId, long page) {
return new Pager<>(page, dao.countCrawlSeriesForAgencyId(agencyId), (limit, offset) -> dao.paginateCrawlSeriesForAgencyId(agencyId, limit, offset));
}
public long create(Series series) {
return dao.createCrawlSeries(series.getName(), series.getPath(), series.getDescription(), AuthHelper.currentUser(), series.getAgencyId());
}
public void update(long seriesId, Series series, List<Long> collectionIds) {
String path = series.getPath() == null ? null : series.getPath().toString();
int rows1 = dao.updateCrawlSeries(seriesId, series.getName(), path, series.getDescription(), AuthHelper.currentUser());
if (rows1 > 0) {
dao.removeCrawlSeriesFromAllCollections(seriesId);
dao.addCrawlSeriesToCollections(seriesId, collectionIds);
}
int rows = rows1;
if (rows == 0) {
throw new NotFoundException("series", seriesId);
}
}
public List<Series> listAll() {
return dao.listCrawlSeries();
}
public List<Series> listImportable() {
return dao.listImportableCrawlSeries();
}
public void recalculateWarcStats() {
dao.recalculateWarcStats();
}
}
|
apache-2.0
|
Klamann/maps4cim
|
maps4cim-gui/src/main/java/de/nx42/maps4cim/gui/window/RenderWindow.java
|
8694
|
/**
* maps4cim - a real world map generator for CiM 2
* Copyright 2013 Sebastian Straub
*
* 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 de.nx42.maps4cim.gui.window;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.util.ResourceBundle;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.WindowConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.xml.bind.JAXBException;
import ch.qos.logback.classic.LoggerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.nx42.maps4cim.MapGenerator;
import de.nx42.maps4cim.ResourceLoader;
import de.nx42.maps4cim.config.Config;
import de.nx42.maps4cim.gui.util.Components;
import de.nx42.maps4cim.gui.util.Fonts;
import de.nx42.maps4cim.gui.util.TextAreaLogAppender;
import de.nx42.maps4cim.util.Serializer;
public class RenderWindow extends JFrame {
private static final ResourceBundle MESSAGES = ResourceLoader.getMessages();
private static final Logger log = LoggerFactory.getLogger(RenderWindow.class);
private static final long serialVersionUID = -1913557466280155872L;
private JPanel contentPane;
private JButton btnDone;
private JButton btnSaveLog;
private JTextPane logView;
private JProgressBar progressBar;
private boolean working = false;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
RenderWindow frame = new RenderWindow();
frame.setVisible(true);
} catch (Exception e) {
log.error("Error while creating RenderWindow", e);
}
}
});
}
/**
* Create the frame.
*/
public RenderWindow() {
super();
setTitle(MESSAGES.getString("RenderWindow.this.title")); //$NON-NLS-1$
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setBounds(115, 115, 500, 400);
setMinimumSize(new Dimension(400, 180));
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
Components.setIconImages(this);
progressBar = new JProgressBar(0, 100);
btnDone = new JButton(MESSAGES.getString("RenderWindow.btnDone.text")); //$NON-NLS-1$
btnDone.setToolTipText(MESSAGES.getString("RenderWindow.btnDone.toolTipText")); //$NON-NLS-1$
btnDone.addActionListener(btnDoneAction);
logView = new JTextPane();
logView.setFont(Fonts.select(logView.getFont(), "Tahoma", "Geneva", "Arial"));
logView.setEditable(false);
JScrollPane scrollPane = new JScrollPane(logView);
scrollPane.setBorder(null);
btnSaveLog = new JButton(MESSAGES.getString("RenderWindow.btnSaveLog.text")); //$NON-NLS-1$
btnSaveLog.setToolTipText(MESSAGES.getString("RenderWindow.btnSaveLog.toolTipText")); //$NON-NLS-1$
btnSaveLog.addActionListener(btnSaveLogAction);
GroupLayout gl_contentPane = new GroupLayout(contentPane);
gl_contentPane.setHorizontalGroup(
gl_contentPane.createParallelGroup(Alignment.TRAILING)
.addGroup(gl_contentPane.createSequentialGroup()
.addContainerGap()
.addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING)
.addComponent(scrollPane, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 454, Short.MAX_VALUE)
.addComponent(progressBar, GroupLayout.DEFAULT_SIZE, 454, Short.MAX_VALUE)
.addGroup(gl_contentPane.createSequentialGroup()
.addComponent(btnSaveLog)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(btnDone, GroupLayout.PREFERRED_SIZE, 80, GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
gl_contentPane.setVerticalGroup(
gl_contentPane.createParallelGroup(Alignment.TRAILING)
.addGroup(gl_contentPane.createSequentialGroup()
.addContainerGap()
.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 259, Short.MAX_VALUE)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(progressBar, GroupLayout.PREFERRED_SIZE, 26, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
.addComponent(btnDone)
.addComponent(btnSaveLog))
.addContainerGap())
);
contentPane.setLayout(gl_contentPane);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
cancelMapGenerator();
}
});
addLogAppender();
}
// action listeners
protected ActionListener btnDoneAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
cancelMapGenerator();
if(working) {
finishWork(false);
} else {
dispose();
}
}
};
protected ActionListener btnSaveLogAction = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Document doc = logView.getStyledDocument();
try {
String eventlog = doc.getText(0, doc.getLength());
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
StringSelection strSel = new StringSelection(eventlog);
clipboard.setContents(strSel, null);
// log.debug("the log has been copied to clipboard");
} catch (BadLocationException e1) {
log.error("Could not copy log to clipboard", e);
}
}
};
// application logic
Thread mapGenerator;
private Config config = null;
public void runMapGenerator(final Config conf, final File dest) {
config = conf;
if(mapGenerator != null) {
mapGenerator.interrupt();
}
mapGenerator = new Thread(new Runnable() {
@Override
public void run() {
boolean success = MapGenerator.execute(conf, dest);
mapGeneratorFinished(success);
}
});
mapGenerator.start();
startWork();
}
@SuppressWarnings("deprecation")
protected void cancelMapGenerator() {
if(mapGenerator != null && mapGenerator.isAlive()) {
log.warn("Operation aborted by user request.");
mapGenerator.interrupt();
// Show no mercy
if(mapGenerator.isAlive()) {
mapGenerator.stop();
}
mapGenerator = null;
}
}
protected void mapGeneratorFinished() {
mapGeneratorFinished(true);
}
protected void mapGeneratorFinished(final boolean success) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
finishWork(success);
}
});
autoSaveConfig();
}
protected void startWork() {
working = true;
progressBar.setValue(0);
progressBar.setIndeterminate(true);
}
protected void finishWork(boolean success) {
working = false;
progressBar.setIndeterminate(false);
progressBar.setValue(success ? 100 : 0);
btnDone.setText("Done");
}
protected void autoSaveConfig() {
File serialized = new File(ResourceLoader.getAppDir(), "config-last.xml");
try {
Serializer.serialize(Config.class, config, serialized);
} catch (JAXBException e) {
log.error("Could not auto-save config in appdata", e);
}
}
protected void addLogAppender() {
TextAreaLogAppender tap = new TextAreaLogAppender(logView);
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
ch.qos.logback.classic.Logger logbackLogger = lc.getLogger(Logger.ROOT_LOGGER_NAME);
logbackLogger.addAppender(tap);
// Logger.getRootLogger().addAppender(tap);
}
}
|
apache-2.0
|
aspnet/AspNetCore
|
src/DataProtection/DataProtection/test/AuthenticatedEncryption/ManagedAuthenticatedEncryptorFactoryTest.cs
|
1798
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel;
using Microsoft.AspNetCore.DataProtection.Cng;
using Microsoft.AspNetCore.DataProtection.KeyManagement;
using Microsoft.AspNetCore.DataProtection.Managed;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using Xunit;
namespace Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption
{
public class ManagedAuthenticatedEncryptorFactoryTest
{
[Fact]
public void CreateEncrptorInstance_UnknownDescriptorType_ReturnsNull()
{
// Arrange
var key = new Mock<IKey>();
key.Setup(k => k.Descriptor).Returns(new Mock<IAuthenticatedEncryptorDescriptor>().Object);
var factory = new ManagedAuthenticatedEncryptorFactory(NullLoggerFactory.Instance);
// Act
var encryptor = factory.CreateEncryptorInstance(key.Object);
// Assert
Assert.Null(encryptor);
}
[Fact]
public void CreateEncrptorInstance_ExpectedDescriptorType_ReturnsEncryptor()
{
// Arrange
var descriptor = new ManagedAuthenticatedEncryptorConfiguration().CreateNewDescriptor();
var key = new Mock<IKey>();
key.Setup(k => k.Descriptor).Returns(descriptor);
var factory = new ManagedAuthenticatedEncryptorFactory(NullLoggerFactory.Instance);
// Act
var encryptor = factory.CreateEncryptorInstance(key.Object);
// Assert
Assert.NotNull(encryptor);
Assert.IsType<ManagedAuthenticatedEncryptor>(encryptor);
}
}
}
|
apache-2.0
|
google/model-viewer
|
packages/model-viewer/src/features/scene-graph/api.ts
|
9511
|
/* @license
* Copyright 2020 Google LLC. 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.
*/
import {AlphaMode, MagFilter, MinFilter, WrapMode} from '../../three-components/gltf-instance/gltf-2.0.js';
/**
* All constructs in a 3DOM scene graph have a corresponding string name.
* This is similar in spirit to the concept of a "tag name" in HTML, and exists
* in support of looking up 3DOM elements by type.
*/
export declare interface ThreeDOMElementMap {
'model': Model;
'material': Material;
'pbr-metallic-roughness': PBRMetallicRoughness;
'sampler': Sampler;
'image': Image;
'texture': Texture;
'texture-info': TextureInfo;
}
/**
* A Model is the root element of a 3DOM scene graph. It gives scripts access
* to the sub-elements found without the graph.
*/
export declare interface Model {
/**
* An ordered set of unique Materials found in this model. The Materials
* correspond to the listing of materials in the glTF, with the possible
* addition of a default material at the end.
*/
readonly materials: Readonly<Material[]>;
/**
* Gets a material(s) by name.
* @param name the name of the material to return.
* @returns the first material to whose name matches `name`
*/
getMaterialByName(name: string): Material|null;
/**
* Creates a new material variant from an existing material.
* @param originalMaterialIndex index of the material to clone the variant
* from.
* @param materialName the name of the new material
* @param variantName the name of the variant
* @param activateVariant activates this material variant, i.e. the variant
* material is rendered, not the existing material.
* @returns returns a clone of the original material, returns `null` if the
* material instance for this variant already exists.
*/
createMaterialInstanceForVariant(
originalMaterialIndex: number, newMaterialName: string,
variantName: string, activateVariant: boolean): Material|null;
/**
* Adds a variant name to the model.
* @param variantName
*/
createVariant(variantName: string): void;
/**
* Adds an existing material to a variant name.
* @param materialIndex
* @param targetVariantName
*/
setMaterialToVariant(materialIndex: number, targetVariantName: string): void;
/**
* Removes the variant name from the model.
* @param variantName the variant to remove.
*/
deleteVariant(variantName: string): void;
}
/**
* A Material gives the script access to modify a single, unique material found
* in a model's scene graph.
*
* @see https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#reference-material
*/
export declare interface Material {
/**
* The name of the material, if any.
*/
name: string;
readonly normalTexture: TextureInfo|null;
readonly occlusionTexture: TextureInfo|null;
readonly emissiveTexture: TextureInfo|null;
readonly emissiveFactor: Readonly<RGB>;
setEmissiveFactor(rgb: RGB): void;
setAlphaCutoff(cutoff: number): void;
getAlphaCutoff(): number;
setDoubleSided(doubleSided: boolean): void;
getDoubleSided(): boolean;
setAlphaMode(alphaMode: AlphaMode): void;
getAlphaMode(): AlphaMode;
/**
* The PBRMetallicRoughness configuration of the material.
*/
readonly pbrMetallicRoughness: PBRMetallicRoughness;
/**
* Asynchronously loads the underlying material resource if it's currently
* unloaded, otherwise the method is a noop.
*/
ensureLoaded(): void;
/**
* Returns true if the material participates in the variant.
* @param name the variant name.
*/
hasVariant(name: string): boolean;
/**
* Returns true if the material is loaded.
*/
readonly isLoaded: boolean;
/**
* Returns true if the material is participating in scene renders.
*/
readonly isActive: boolean;
/**
* Returns the glTF index of this material.
*/
readonly index: number;
}
/**
* The PBRMetallicRoughness encodes the PBR properties of a material
*
* @see https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#reference-pbrmetallicroughness
*/
export declare interface PBRMetallicRoughness {
/**
* The base color factor of the material, represented as RGBA values
*/
readonly baseColorFactor: Readonly<RGBA>;
/**
* Metalness factor of the material, represented as number between 0 and 1
*/
readonly metallicFactor: number;
/**
* Roughness factor of the material, represented as number between 0 and 1
*/
readonly roughnessFactor: number;
/**
* A texture reference, associating an image with color information and
* a sampler for describing base color factor for a UV coordinate space.
*/
readonly baseColorTexture: TextureInfo|null;
/**
* A texture reference, associating an image with color information and
* a sampler for describing metalness (B channel) and roughness (G channel)
* for a UV coordinate space.
*/
readonly metallicRoughnessTexture: TextureInfo|null;
/**
* Changes the base color factor of the material to the given value.
*/
setBaseColorFactor(rgba: RGBA): void;
/**
* Changes the metalness factor of the material to the given value.
*/
setMetallicFactor(value: number): void;
/**
* Changes the roughness factor of the material to the given value.
*/
setRoughnessFactor(value: number): void;
}
/**
* A TextureInfo is a pointer to a specific Texture in use on a Material
*
* @see https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#reference-textureinfo
*/
export declare interface TextureInfo {
/**
* The Texture being referenced by this TextureInfo
*/
readonly texture: Texture|null;
/**
* Sets a texture on the texture info, or removes the texture if argument is
* null.
*/
setTexture(texture: Texture|null): void;
}
/**
* A Texture pairs an Image and a Sampler for use in a Material
*
* @see https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#reference-texture
*/
export declare interface Texture {
/**
* The name of the texture, if any.
*/
readonly name: string;
/**
* The Sampler for this Texture
*/
readonly sampler: Sampler;
/**
* The source Image for this Texture
*/
readonly source: Image;
}
/**
* A Sampler describes how to filter and wrap textures
*
* @see https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#reference-sampler
*/
export declare interface Sampler {
/**
* The name of the sampler, if any.
*/
readonly name: string;
/**
* @see https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#samplerminfilter
*/
readonly minFilter: MinFilter;
/**
* @see https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#samplermagfilter
*/
readonly magFilter: MagFilter;
/**
* @see https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#samplerwraps
*/
readonly wrapS: WrapMode;
/**
* @see https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#samplerwrapt
*/
readonly wrapT: WrapMode;
/**
* Configure the minFilter value of the Sampler.
*/
setMinFilter(filter: MinFilter): void;
/**
* Configure the magFilter value of the Sampler.
*/
setMagFilter(filter: MagFilter): void;
/**
* Configure the S (U) wrap mode of the Sampler.
*/
setWrapS(mode: WrapMode): void;
/**
* Configure the T (V) wrap mode of the Sampler.
*/
setWrapT(mode: WrapMode): void;
}
/**
* An Image represents an embedded or external image used to provide texture
* color data.
*
* @see https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#reference-image
*/
export declare interface Image {
/**
* The name of the image, if any.
*/
readonly name: string;
/**
* The type is 'external' if the image has a configured URI. Otherwise, it is
* considered to be 'embedded'. Note: this distinction is only implied by the
* glTF spec, and is made explicit here for convenience.
*/
readonly type: 'embedded'|'external';
/**
* The URI of the image, if it is external.
*/
readonly uri?: string;
/**
* The bufferView of the image, if it is embedded.
*/
readonly bufferView?: number
/**
* Configure the URI of the image. If a URI is specified for an otherwise
* embedded image, the URI will take precedence over an embedded buffer.
*/
setURI(uri: string): Promise<void>;
/**
* A method to create an object URL of this image at the desired
* resolution. Especially useful for KTX2 textures which are GPU compressed,
* and so are unreadable on the CPU without a method like this.
*/
createThumbnail(width: number, height: number): Promise<string>;
}
/**
* An RGBA-encoded color, with channels represented as floating point values
* from [0,1].
*/
export declare type RGBA = [number, number, number, number];
export declare type RGB = [number, number, number];
|
apache-2.0
|
haocs/azure-powershell
|
src/ServiceManagement/Services/Commands.Test/Properties/AssemblyInfo.cs
|
1456
|
using System.Reflection;
using System.Runtime.InteropServices;
using Xunit;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Microsoft.WindowsAzure.Commands.Test")]
[assembly: AssemblyCompany(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCompany)]
[assembly: AssemblyProduct(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyProduct)]
[assembly: AssemblyCopyright(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCopyright)]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("88accda2-ccb3-4813-8141-5d1a2640f93d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.2.3")]
[assembly: AssemblyFileVersion("1.2.3")]
[assembly: CollectionBehavior(DisableTestParallelization = true)]
|
apache-2.0
|
letsencrypt/letsencrypt
|
certbot/compat/misc.py
|
5439
|
"""
This compat module handles various platform specific calls that do not fall into one
particular category.
"""
import os
import select
import sys
import errno
import ctypes
import stat
from certbot import errors
UNPRIVILEGED_SUBCOMMANDS_ALLOWED = [
'certificates', 'enhance', 'revoke', 'delete',
'register', 'unregister', 'config_changes', 'plugins']
def raise_for_non_administrative_windows_rights(subcommand):
"""
On Windows, raise if current shell does not have the administrative rights.
Do nothing on Linux.
:param str subcommand: The subcommand (like 'certonly') passed to the certbot client.
:raises .errors.Error: If the provided subcommand must be run on a shell with
administrative rights, and current shell does not have these rights.
"""
# Why not simply try ctypes.windll.shell32.IsUserAnAdmin() and catch AttributeError ?
# Because windll exists only on a Windows runtime, and static code analysis engines
# do not like at all non existent objects when run from Linux (even if we handle properly
# all the cases in the code).
# So we access windll only by reflection to trick theses engines.
if hasattr(ctypes, 'windll') and subcommand not in UNPRIVILEGED_SUBCOMMANDS_ALLOWED:
windll = getattr(ctypes, 'windll')
if windll.shell32.IsUserAnAdmin() == 0:
raise errors.Error(
'Error, "{0}" subcommand must be run on a shell with administrative rights.'
.format(subcommand))
def os_geteuid():
"""
Get current user uid
:returns: The current user uid.
:rtype: int
"""
try:
# Linux specific
return os.geteuid()
except AttributeError:
# Windows specific
return 0
def os_rename(src, dst):
"""
Rename a file to a destination path and handles situations where the destination exists.
:param str src: The current file path.
:param str dst: The new file path.
"""
try:
os.rename(src, dst)
except OSError as err:
# Windows specific, renaming a file on an existing path is not possible.
# On Python 3, the best fallback with atomic capabilities we have is os.replace.
if err.errno != errno.EEXIST:
# Every other error is a legitimate exception.
raise
if not hasattr(os, 'replace'): # pragma: no cover
# We should never go on this line. Either we are on Linux and os.rename has succeeded,
# either we are on Windows, and only Python >= 3.4 is supported where os.replace is
# available.
raise RuntimeError('Error: tried to run os_rename on Python < 3.3. '
'Certbot supports only Python 3.4 >= on Windows.')
getattr(os, 'replace')(src, dst)
def readline_with_timeout(timeout, prompt):
"""
Read user input to return the first line entered, or raise after specified timeout.
:param float timeout: The timeout in seconds given to the user.
:param str prompt: The prompt message to display to the user.
:returns: The first line entered by the user.
:rtype: str
"""
try:
# Linux specific
#
# Call to select can only be done like this on UNIX
rlist, _, _ = select.select([sys.stdin], [], [], timeout)
if not rlist:
raise errors.Error(
"Timed out waiting for answer to prompt '{0}'".format(prompt))
return rlist[0].readline()
except OSError:
# Windows specific
#
# No way with select to make a timeout to the user input on Windows,
# as select only supports socket in this case.
# So no timeout on Windows for now.
return sys.stdin.readline()
def compare_file_modes(mode1, mode2):
"""Return true if the two modes can be considered as equals for this platform"""
if os.name != 'nt':
# Linux specific: standard compare
return oct(stat.S_IMODE(mode1)) == oct(stat.S_IMODE(mode2))
# Windows specific: most of mode bits are ignored on Windows. Only check user R/W rights.
return (stat.S_IMODE(mode1) & stat.S_IREAD == stat.S_IMODE(mode2) & stat.S_IREAD
and stat.S_IMODE(mode1) & stat.S_IWRITE == stat.S_IMODE(mode2) & stat.S_IWRITE)
WINDOWS_DEFAULT_FOLDERS = {
'config': 'C:\\Certbot',
'work': 'C:\\Certbot\\lib',
'logs': 'C:\\Certbot\\log',
}
LINUX_DEFAULT_FOLDERS = {
'config': '/etc/letsencrypt',
'work': '/var/lib/letsencrypt',
'logs': '/var/log/letsencrypt',
}
def get_default_folder(folder_type):
"""
Return the relevant default folder for the current OS
:param str folder_type: The type of folder to retrieve (config, work or logs)
:returns: The relevant default folder.
:rtype: str
"""
if os.name != 'nt':
# Linux specific
return LINUX_DEFAULT_FOLDERS[folder_type]
# Windows specific
return WINDOWS_DEFAULT_FOLDERS[folder_type]
def underscores_for_unsupported_characters_in_path(path):
# type: (str) -> str
"""
Replace unsupported characters in path for current OS by underscores.
:param str path: the path to normalize
:return: the normalized path
:rtype: str
"""
if os.name != 'nt':
# Linux specific
return path
# Windows specific
drive, tail = os.path.splitdrive(path)
return drive + tail.replace(':', '_')
|
apache-2.0
|
pcmoritz/ray-1
|
rllib/evaluation/tests/test_trajectory_view_api.py
|
18090
|
import copy
import gym
from gym.spaces import Box, Discrete
import numpy as np
import unittest
import ray
from ray import tune
from ray.rllib.agents.callbacks import DefaultCallbacks
import ray.rllib.agents.dqn as dqn
import ray.rllib.agents.ppo as ppo
from ray.rllib.examples.env.debug_counter_env import MultiAgentDebugCounterEnv
from ray.rllib.examples.env.multi_agent import MultiAgentCartPole
from ray.rllib.evaluation.rollout_worker import RolloutWorker
from ray.rllib.examples.policy.episode_env_aware_policy import \
EpisodeEnvAwareAttentionPolicy, EpisodeEnvAwareLSTMPolicy
from ray.rllib.models.tf.attention_net import GTrXLNet
from ray.rllib.policy.rnn_sequencing import pad_batch_to_sequences_of_same_size
from ray.rllib.policy.sample_batch import DEFAULT_POLICY_ID, SampleBatch
from ray.rllib.policy.view_requirement import ViewRequirement
from ray.rllib.utils.annotations import override
from ray.rllib.utils.test_utils import framework_iterator, check
class MyCallbacks(DefaultCallbacks):
@override(DefaultCallbacks)
def on_learn_on_batch(self, *, policy, train_batch, result, **kwargs):
assert train_batch.count == 201
assert sum(train_batch["seq_lens"]) == 201
for k, v in train_batch.items():
if k == "state_in_0":
assert len(v) == len(train_batch["seq_lens"])
else:
assert len(v) == 201
current = None
for o in train_batch[SampleBatch.OBS]:
if current:
assert o == current + 1
current = o
if o == 15:
current = None
class TestTrajectoryViewAPI(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
ray.init()
@classmethod
def tearDownClass(cls) -> None:
ray.shutdown()
def test_traj_view_normal_case(self):
"""Tests, whether Model and Policy return the correct ViewRequirements.
"""
config = dqn.DEFAULT_CONFIG.copy()
config["num_envs_per_worker"] = 10
config["rollout_fragment_length"] = 4
for _ in framework_iterator(config):
trainer = dqn.DQNTrainer(
config,
env="ray.rllib.examples.env.debug_counter_env.DebugCounterEnv")
policy = trainer.get_policy()
view_req_model = policy.model.view_requirements
view_req_policy = policy.view_requirements
assert len(view_req_model) == 1, view_req_model
assert len(view_req_policy) == 8, view_req_policy
for key in [
SampleBatch.OBS,
SampleBatch.ACTIONS,
SampleBatch.REWARDS,
SampleBatch.DONES,
SampleBatch.NEXT_OBS,
SampleBatch.EPS_ID,
SampleBatch.AGENT_INDEX,
"weights",
]:
assert key in view_req_policy
# None of the view cols has a special underlying data_col,
# except next-obs.
if key != SampleBatch.NEXT_OBS:
assert view_req_policy[key].data_col is None
else:
assert view_req_policy[key].data_col == SampleBatch.OBS
assert view_req_policy[key].shift == 1
rollout_worker = trainer.workers.local_worker()
sample_batch = rollout_worker.sample()
expected_count = \
config["num_envs_per_worker"] * \
config["rollout_fragment_length"]
assert sample_batch.count == expected_count
for v in sample_batch.values():
assert len(v) == expected_count
trainer.stop()
def test_traj_view_lstm_prev_actions_and_rewards(self):
"""Tests, whether Policy/Model return correct LSTM ViewRequirements.
"""
config = ppo.DEFAULT_CONFIG.copy()
config["model"] = config["model"].copy()
# Activate LSTM + prev-action + rewards.
config["model"]["use_lstm"] = True
config["model"]["lstm_use_prev_action"] = True
config["model"]["lstm_use_prev_reward"] = True
for _ in framework_iterator(config):
trainer = ppo.PPOTrainer(config, env="CartPole-v0")
policy = trainer.get_policy()
view_req_model = policy.model.view_requirements
view_req_policy = policy.view_requirements
# 7=obs, prev-a + r, 2x state-in, 2x state-out.
assert len(view_req_model) == 7, view_req_model
assert len(view_req_policy) == 19, view_req_policy
for key in [
SampleBatch.OBS, SampleBatch.ACTIONS, SampleBatch.REWARDS,
SampleBatch.DONES, SampleBatch.NEXT_OBS,
SampleBatch.VF_PREDS, SampleBatch.PREV_ACTIONS,
SampleBatch.PREV_REWARDS, "advantages", "value_targets",
SampleBatch.ACTION_DIST_INPUTS, SampleBatch.ACTION_LOGP
]:
assert key in view_req_policy
if key == SampleBatch.PREV_ACTIONS:
assert view_req_policy[key].data_col == SampleBatch.ACTIONS
assert view_req_policy[key].shift == -1
elif key == SampleBatch.PREV_REWARDS:
assert view_req_policy[key].data_col == SampleBatch.REWARDS
assert view_req_policy[key].shift == -1
elif key not in [
SampleBatch.NEXT_OBS, SampleBatch.PREV_ACTIONS,
SampleBatch.PREV_REWARDS
]:
assert view_req_policy[key].data_col is None
else:
assert view_req_policy[key].data_col == SampleBatch.OBS
assert view_req_policy[key].shift == 1
trainer.stop()
def test_traj_view_attention_net(self):
config = ppo.DEFAULT_CONFIG.copy()
# Setup attention net.
config["model"] = config["model"].copy()
config["model"]["max_seq_len"] = 50
config["model"]["custom_model"] = GTrXLNet
config["model"]["custom_model_config"] = {
"num_transformer_units": 1,
"attention_dim": 64,
"num_heads": 2,
"memory_inference": 50,
"memory_training": 50,
"head_dim": 32,
"ff_hidden_dim": 32,
}
# Test with odd batch numbers.
config["train_batch_size"] = 1031
config["sgd_minibatch_size"] = 201
config["num_sgd_iter"] = 5
config["num_workers"] = 0
config["callbacks"] = MyCallbacks
config["env_config"] = {
"config": {
"start_at_t": 1
}
} # first obs is [1.0]
for _ in framework_iterator(config, frameworks="tf2"):
trainer = ppo.PPOTrainer(
config,
env="ray.rllib.examples.env.debug_counter_env.DebugCounterEnv",
)
rw = trainer.workers.local_worker()
sample = rw.sample()
assert sample.count == config["rollout_fragment_length"]
results = trainer.train()
assert results["train_batch_size"] == config["train_batch_size"]
trainer.stop()
def test_traj_view_next_action(self):
action_space = Discrete(2)
rollout_worker_w_api = RolloutWorker(
env_creator=lambda _: gym.make("CartPole-v0"),
policy_config=ppo.DEFAULT_CONFIG,
rollout_fragment_length=200,
policy_spec=ppo.PPOTorchPolicy,
policy_mapping_fn=None,
num_envs=1,
)
# Add the next action to the view reqs of the policy.
# This should be visible then in postprocessing and train batches.
rollout_worker_w_api.policy_map[DEFAULT_POLICY_ID].view_requirements[
"next_actions"] = ViewRequirement(
SampleBatch.ACTIONS, shift=1, space=action_space)
# Make sure, we have DONEs as well.
rollout_worker_w_api.policy_map[DEFAULT_POLICY_ID].view_requirements[
"dones"] = ViewRequirement()
batch = rollout_worker_w_api.sample()
self.assertTrue("next_actions" in batch)
expected_a_ = None # expected next action
for i in range(len(batch["actions"])):
a, d, a_ = batch["actions"][i], batch["dones"][i], \
batch["next_actions"][i]
if not d and expected_a_ is not None:
check(a, expected_a_)
elif d:
check(a_, 0)
expected_a_ = None
continue
expected_a_ = a_
def test_traj_view_lstm_functionality(self):
action_space = Box(-float("inf"), float("inf"), shape=(3, ))
obs_space = Box(float("-inf"), float("inf"), (4, ))
max_seq_len = 50
rollout_fragment_length = 200
assert rollout_fragment_length % max_seq_len == 0
policies = {
"pol0": (EpisodeEnvAwareLSTMPolicy, obs_space, action_space, {}),
}
def policy_fn(agent_id, episode, **kwargs):
return "pol0"
config = {
"multiagent": {
"policies": policies,
"policy_mapping_fn": policy_fn,
},
"model": {
"use_lstm": True,
"max_seq_len": max_seq_len,
},
},
rollout_worker_w_api = RolloutWorker(
env_creator=lambda _: MultiAgentDebugCounterEnv({"num_agents": 4}),
policy_config=config,
rollout_fragment_length=rollout_fragment_length,
policy_spec=policies,
policy_mapping_fn=policy_fn,
num_envs=1,
)
rollout_worker_wo_api = RolloutWorker(
env_creator=lambda _: MultiAgentDebugCounterEnv({"num_agents": 4}),
policy_config=config,
rollout_fragment_length=rollout_fragment_length,
policy_spec=policies,
policy_mapping_fn=policy_fn,
num_envs=1,
)
for iteration in range(20):
result = rollout_worker_w_api.sample()
check(result.count, rollout_fragment_length)
pol_batch_w = result.policy_batches["pol0"]
assert pol_batch_w.count >= rollout_fragment_length
analyze_rnn_batch(pol_batch_w, max_seq_len)
result = rollout_worker_wo_api.sample()
pol_batch_wo = result.policy_batches["pol0"]
check(pol_batch_w, pol_batch_wo)
def test_traj_view_attention_functionality(self):
action_space = Box(-float("inf"), float("inf"), shape=(3, ))
obs_space = Box(float("-inf"), float("inf"), (4, ))
max_seq_len = 50
rollout_fragment_length = 201
policies = {
"pol0": (EpisodeEnvAwareAttentionPolicy, obs_space, action_space,
{}),
}
def policy_fn(agent_id, episode, **kwargs):
return "pol0"
config = {
"multiagent": {
"policies": policies,
"policy_mapping_fn": policy_fn,
},
"model": {
"max_seq_len": max_seq_len,
},
},
rollout_worker_w_api = RolloutWorker(
env_creator=lambda _: MultiAgentDebugCounterEnv({"num_agents": 4}),
policy_config=config,
rollout_fragment_length=rollout_fragment_length,
policy_spec=policies,
policy_mapping_fn=policy_fn,
num_envs=1,
)
batch = rollout_worker_w_api.sample()
print(batch)
def test_counting_by_agent_steps(self):
"""Test whether a PPOTrainer can be built with all frameworks."""
config = copy.deepcopy(ppo.DEFAULT_CONFIG)
action_space = Discrete(2)
obs_space = Box(float("-inf"), float("inf"), (4, ), dtype=np.float32)
config["num_workers"] = 2
config["num_sgd_iter"] = 2
config["framework"] = "torch"
config["rollout_fragment_length"] = 21
config["train_batch_size"] = 147
config["multiagent"] = {
"policies": {
"p0": (None, obs_space, action_space, {}),
"p1": (None, obs_space, action_space, {}),
},
"policy_mapping_fn": lambda aid, **kwargs: "p{}".format(aid),
"count_steps_by": "agent_steps",
}
tune.register_env(
"ma_cartpole", lambda _: MultiAgentCartPole({"num_agents": 2}))
num_iterations = 2
trainer = ppo.PPOTrainer(config=config, env="ma_cartpole")
results = None
for i in range(num_iterations):
results = trainer.train()
self.assertGreater(results["agent_timesteps_total"],
num_iterations * config["train_batch_size"])
self.assertLess(results["agent_timesteps_total"],
(num_iterations + 1) * config["train_batch_size"])
trainer.stop()
def analyze_rnn_batch(batch, max_seq_len):
count = batch.count
# Check prev_reward/action, next_obs consistency.
for idx in range(count):
# If timestep tracked by batch, good.
if "t" in batch:
ts = batch["t"][idx]
# Else, ts
else:
ts = batch["obs"][idx][3]
obs_t = batch["obs"][idx]
a_t = batch["actions"][idx]
r_t = batch["rewards"][idx]
state_in_0 = batch["state_in_0"][idx]
state_in_1 = batch["state_in_1"][idx]
# Check postprocessing outputs.
if "2xobs" in batch:
postprocessed_col_t = batch["2xobs"][idx]
assert (obs_t == postprocessed_col_t / 2.0).all()
# Check state-in/out and next-obs values.
if idx > 0:
next_obs_t_m_1 = batch["new_obs"][idx - 1]
state_out_0_t_m_1 = batch["state_out_0"][idx - 1]
state_out_1_t_m_1 = batch["state_out_1"][idx - 1]
# Same trajectory as for t-1 -> Should be able to match.
if (batch[SampleBatch.AGENT_INDEX][idx] ==
batch[SampleBatch.AGENT_INDEX][idx - 1]
and batch[SampleBatch.EPS_ID][idx] ==
batch[SampleBatch.EPS_ID][idx - 1]):
assert batch["unroll_id"][idx - 1] == batch["unroll_id"][idx]
assert (obs_t == next_obs_t_m_1).all()
assert (state_in_0 == state_out_0_t_m_1).all()
assert (state_in_1 == state_out_1_t_m_1).all()
# Different trajectory.
else:
assert batch["unroll_id"][idx - 1] != batch["unroll_id"][idx]
assert not (obs_t == next_obs_t_m_1).all()
assert not (state_in_0 == state_out_0_t_m_1).all()
assert not (state_in_1 == state_out_1_t_m_1).all()
# Check initial 0-internal states.
if ts == 0:
assert (state_in_0 == 0.0).all()
assert (state_in_1 == 0.0).all()
# Check initial 0-internal states (at ts=0).
if ts == 0:
assert (state_in_0 == 0.0).all()
assert (state_in_1 == 0.0).all()
# Check prev. a/r values.
if idx < count - 1:
prev_actions_t_p_1 = batch["prev_actions"][idx + 1]
prev_rewards_t_p_1 = batch["prev_rewards"][idx + 1]
# Same trajectory as for t+1 -> Should be able to match.
if batch[SampleBatch.AGENT_INDEX][idx] == \
batch[SampleBatch.AGENT_INDEX][idx + 1] and \
batch[SampleBatch.EPS_ID][idx] == \
batch[SampleBatch.EPS_ID][idx + 1]:
assert (a_t == prev_actions_t_p_1).all()
assert r_t == prev_rewards_t_p_1
# Different (new) trajectory. Assume t-1 (prev-a/r) to be
# always 0.0s. [3]=ts
elif ts == 0:
assert (prev_actions_t_p_1 == 0).all()
assert prev_rewards_t_p_1 == 0.0
pad_batch_to_sequences_of_same_size(
batch,
max_seq_len=max_seq_len,
shuffle=False,
batch_divisibility_req=1)
# Check after seq-len 0-padding.
cursor = 0
for i, seq_len in enumerate(batch["seq_lens"]):
state_in_0 = batch["state_in_0"][i]
state_in_1 = batch["state_in_1"][i]
for j in range(seq_len):
k = cursor + j
ts = batch["t"][k]
obs_t = batch["obs"][k]
a_t = batch["actions"][k]
r_t = batch["rewards"][k]
# Check postprocessing outputs.
if "2xobs" in batch:
postprocessed_col_t = batch["2xobs"][k]
assert (obs_t == postprocessed_col_t / 2.0).all()
# Check state-in/out and next-obs values.
if j > 0:
next_obs_t_m_1 = batch["new_obs"][k - 1]
# state_out_0_t_m_1 = batch["state_out_0"][k - 1]
# state_out_1_t_m_1 = batch["state_out_1"][k - 1]
# Always same trajectory as for t-1.
assert batch["unroll_id"][k - 1] == batch["unroll_id"][k]
assert (obs_t == next_obs_t_m_1).all()
# assert (state_in_0 == state_out_0_t_m_1).all())
# assert (state_in_1 == state_out_1_t_m_1).all())
# Check initial 0-internal states.
elif ts == 0:
assert (state_in_0 == 0.0).all()
assert (state_in_1 == 0.0).all()
for j in range(seq_len, max_seq_len):
k = cursor + j
obs_t = batch["obs"][k]
a_t = batch["actions"][k]
r_t = batch["rewards"][k]
assert (obs_t == 0.0).all()
assert (a_t == 0.0).all()
assert (r_t == 0.0).all()
cursor += max_seq_len
if __name__ == "__main__":
import pytest
import sys
sys.exit(pytest.main(["-v", __file__]))
|
apache-2.0
|
jmsalcido/my-flights
|
project/src/main/java/com/nearsoft/myflights/connectors/util/FSFlightConnectorUtil.java
|
3970
|
package com.nearsoft.myflights.connectors.util;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import com.nearsoft.myflights.model.Flight;
import com.nearsoft.myflights.model.FlightDetail;
import com.nearsoft.myflights.model.fs.FSAirline;
import com.nearsoft.myflights.model.fs.FSConnection;
import com.nearsoft.myflights.model.fs.FSFlight;
import com.nearsoft.myflights.model.fs.FSFlightLeg;
public class FSFlightConnectorUtil {
/**
* create a Flight object from a FSFlight object parsed from JSON
* @param fsFlight
* @param fsAirlines
* @param date
* @return
*/
public static Flight createFlightFromFSFlight(FSFlight fsFlight,
Map<String, String> fsAirlines, Date date) {
Flight flight = new Flight();
flight.setDate(date);
flight.setDepartureAirport(fsFlight.getDepartureAirportFsCode());
flight.setArrivalAirport(fsFlight.getArrivalAirportFsCode());
flight.setTravelTime(fsFlight.getFlightDurationMinutes());
flight.setFlightType(fsFlight.getFlightType()
.equalsIgnoreCase("DIRECT") ? Flight.NON_STOP
: Flight.CONNECTION);
List<FSFlightLeg> fsFlightDetails = fsFlight.getFlightLegs();
flight.setFlightDetails(new ArrayList<FlightDetail>());
StringBuilder sb = new StringBuilder();
for (FSFlightLeg fsFlightLeg : fsFlightDetails) {
FlightDetail flightDetail = createFlightDetailFromFSFlightLeg(fsFlightLeg, fsAirlines);
flight.getFlightDetails().add(flightDetail);
sb.append(flightDetail.getFlightNumber());
}
// Id is set at last because is the concatenation of all the flight numbers
flight.setId(Long.parseLong(sb.toString()));
return flight;
}
/**
* return a FSConnection object from a JSON String
* @param gson
* @param json
* @return
*/
public static FSConnection getFSConnectionFromJson(Gson gson, String json) {
return gson.fromJson(json, FSConnection.class);
}
/**
* create a FlightDetail object from a FSFlightLeg object parsed from JSON
* @param flightLeg
* @param fsAirlines
* @return
*/
public static FlightDetail createFlightDetailFromFSFlightLeg(
FSFlightLeg flightLeg, Map<String, String> fsAirlines) {
FlightDetail flightDetail = new FlightDetail();
flightDetail.setArrivalAirport(flightLeg.getArrivalAirportFsCode());
flightDetail.setDepartureAirport(flightLeg.getDepartureAirportFsCode());
String departureTime = FlightConnectorUtil.removeCharacters(flightLeg.getDepartureTime());
String arrivalTime = FlightConnectorUtil.removeCharacters(flightLeg.getArrivalTime());
flightDetail.setDepartureTime(departureTime);
flightDetail.setArrivalTime(arrivalTime);
flightDetail.setTravelTime(flightLeg.getFlightDurationMinutes());
String airline_code = flightLeg.getCarrierFsCode();
String airline_name = fsAirlines.get(airline_code);
flightDetail.setAirlineName(airline_name);
flightDetail.setAirlineCode(airline_code);
flightDetail.setFlightNumber(flightLeg.getFlightNumber());
return flightDetail;
}
/**
* convert a FSAirline list into a Map<String, String> where the key is the code value of the airline and the value is the airline name
* @param fsAirlines
* @return
*/
public static Map<String, String> convertFSAirlinesListToMap(
List<FSAirline> fsAirlines) {
Map<String, String> airlinesMap = new HashMap<>();
for (FSAirline fsAirline : fsAirlines) {
airlinesMap.put(fsAirline.getFs(), fsAirline.getName());
}
return airlinesMap;
}
}
|
apache-2.0
|
asheshsaraf/ecommerce-simple
|
sm-core/src/main/java/com/salesmanager/core/business/search/service/SearchService.java
|
1738
|
package com.salesmanager.core.business.search.service;
import com.salesmanager.core.business.catalog.product.model.Product;
import com.salesmanager.core.business.generic.exception.ServiceException;
import com.salesmanager.core.business.merchant.model.MerchantStore;
import com.salesmanager.core.business.search.model.SearchKeywords;
import com.salesmanager.core.business.search.model.SearchResponse;
public interface SearchService {
/**
* The indexing service for products. The index service must be invoked when a product is
* created or updated
* @param store
* @param product
* @throws ServiceException
*/
void index(MerchantStore store, Product product) throws ServiceException;
/**
* Deletes an index in the appropriate language. Must be invoked when a product is deleted
* @param store
* @param product
* @throws ServiceException
*/
void deleteIndex(MerchantStore store, Product product)
throws ServiceException;
/**
* Similar keywords based on a a series of characters. Used in the auto-complete
* functionality
* @param collectionName
* @param jsonString
* @param entriesCount
* @return
* @throws ServiceException
*/
SearchKeywords searchForKeywords(String collectionName,
String jsonString, int entriesCount) throws ServiceException;
/**
* Search products based on user entry
* @param store
* @param languageCode
* @param jsonString
* @param entriesCount
* @param startIndex
* @throws ServiceException
*/
SearchResponse search(MerchantStore store, String languageCode, String jsonString,
int entriesCount, int startIndex) throws ServiceException;
/**
* Initializes search service in order to avoid lazy initialization
*/
void initService();
}
|
apache-2.0
|
1986webdeveloper/Code-Examples
|
Magento/customize-order-status/api/set_deliverydate_api.php
|
2508
|
<?php
// MAKE A CONNECTION WITH DATABASE
$con = mysqli_connect('HOST','USER_NAME','PASSWORD') or die(mysql_error()); // DB connection
$db = mysqli_select_db($con, 'DATABASE_NAME');
function sign($method, $url, $data, $consumerSecret, $tokenSecret)
{
$url = urlEncodeAsZend($url);
$data = urlEncodeAsZend(http_build_query($data, '', '&'));
$data = implode('&', [$method, $url, $data]);
$secret = implode('&', [$consumerSecret, $tokenSecret]);
return base64_encode(hash_hmac('sha1', $data, $secret, true));
}
function urlEncodeAsZend($value)
{
$encoded = rawurlencode($value);
$encoded = str_replace('%7E', '~', $encoded);
return $encoded;
}
// REPLACE WITH YOUR ACTUAL DATA OBTAINED WHILE CREATING NEW INTEGRATION
$consumerKey = $_POST['consumerKey'];
$consumerSecret = $_POST['consumerSecret'];
$accessToken = $_POST['accessToken'];
$accessTokenSecret = $_POST['accessTokenSecret'];
$method = 'GET';
$url = 'http://eatfully.com/index.php/rest/V1/orders/'.$_POST['id'];
$data = [
'oauth_consumer_key' => $consumerKey,
'oauth_nonce' => md5(uniqid(rand(), true)),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => time(),
'oauth_token' => $accessToken,
'oauth_version' => '1.0',
];
$data['oauth_signature'] = sign($method, $url, $data, $consumerSecret, $accessTokenSecret);
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
CURLOPT_HTTPHEADER => [
'Authorization: OAuth ' . http_build_query($data, '', ',')
]
]);
$result = curl_exec($curl);
curl_close($curl);
$result = json_decode($result);
// IF SUCCESS THEN DISPLAY STATUSES OTHERWISE PRINT MESSAGE FOR UNAUTHORIZED.
if($result->message == ''){
if($_POST['expected_delivery_date'] != '' || $_POST['actual_delivery_date'] != ''){
$expected = '';
if($_POST['expected_delivery_date'] != ''){
$expected .= "`expected_delivery_date` = '".$_POST['expected_delivery_date']."'";
}
$actual = '';
if($_POST['actual_delivery_date'] != ''){
$actual .= "`actual_delivery_date` = '".$_POST['actual_delivery_date']."'";
}
$comma = '';
if($_POST['expected_delivery_date'] != '' && $_POST['actual_delivery_date'] != ''){
$comma .= ',';
}
$set_deliverydate_sql = mysqli_query($con, "UPDATE `mgwl_sales_order` SET ".$expected.$comma.$actual." where entity_id='".$_POST['id']."'");
echo "Date updated successfully.";
} else {
echo "Please provide appropriate data.";
}
} else {
echo "you are not authorized to do this operation.";
}
?>
|
apache-2.0
|
vsch/idea-multimarkdown
|
src/test/java/com/vladsch/md/nav/testUtil/MdEnhLightPlatformCodeInsightFixtureSpecTestCase.java
|
1128
|
// Copyright (c) 2015-2020 Vladimir Schneider <vladimir.schneider@gmail.com> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.testUtil;
import com.vladsch.flexmark.util.data.DataHolder;
import com.vladsch.md.nav.testUtil.cases.MdEnhCodeInsightFixtureSpecTestCase;
import com.vladsch.plugin.test.util.cases.CodeInsightFixtureSpecTestCase;
import org.jetbrains.annotations.Nullable;
import java.util.HashMap;
import java.util.Map;
public abstract class MdEnhLightPlatformCodeInsightFixtureSpecTestCase extends MdLightPlatformCodeInsightFixtureSpecTestCase implements MdEnhCodeInsightFixtureSpecTestCase {
final private static Map<String, DataHolder> optionsMap = new HashMap<>();
static {
optionsMap.putAll(MdEnhCodeInsightFixtureSpecTestCase.getOptionsMap());
}
public MdEnhLightPlatformCodeInsightFixtureSpecTestCase(@Nullable Map<String, ? extends DataHolder> optionMap, @Nullable DataHolder... defaultOptions) {
super(CodeInsightFixtureSpecTestCase.optionsMaps(optionsMap, optionMap), defaultOptions);
}
}
|
apache-2.0
|
gina-alaska/sandy-utils
|
lib/processing_framework/compress_helper.rb
|
688
|
module ProcessingFramework
module CompressHelper
include ShellOutHelper
def uncompress(file)
filename = case File.extname(file)
when '.gz'
shell_out!("gunzip #{file}", live_stream: false)
File.basename(file, '.gz')
when '.bz2'
shell_out!("bunzip2 #{file}", live_stream: false)
File.basename(file, '.bz2')
else
file
end
filename
end
def gzip!(file)
shell_out!("gzip #{file}", live_stream: false, clean_environment: true)
"#{file}.gz"
end
def bzip2!(file)
shell_out!("bzip2 #{file}", live_stream: false,clean_environment: true)
"#{file}.bz2"
end
end
end
|
apache-2.0
|
newbiet/zstack
|
plugin/nfsPrimaryStorage/src/main/java/org/zstack/storage/primary/nfs/NfsPrimaryStorageKVMBackend.java
|
53272
|
package org.zstack.storage.primary.nfs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.zstack.core.CoreGlobalProperty;
import org.zstack.core.cloudbus.CloudBus;
import org.zstack.core.cloudbus.CloudBusCallBack;
import org.zstack.core.cloudbus.CloudBusListCallBack;
import org.zstack.core.db.DatabaseFacade;
import org.zstack.core.db.SimpleQuery;
import org.zstack.core.db.SimpleQuery.Op;
import org.zstack.core.errorcode.ErrorFacade;
import org.zstack.core.timeout.ApiTimeoutManager;
import org.zstack.header.core.*;
import org.zstack.header.core.workflow.*;
import org.zstack.header.errorcode.OperationFailureException;
import org.zstack.core.workflow.*;
import org.zstack.header.errorcode.ErrorCode;
import org.zstack.header.host.*;
import org.zstack.header.image.ImageInventory;
import org.zstack.header.message.MessageReply;
import org.zstack.header.storage.backup.BackupStorageInventory;
import org.zstack.header.storage.backup.BackupStorageType;
import org.zstack.header.storage.backup.BackupStorageVO;
import org.zstack.header.storage.primary.CreateTemplateFromVolumeSnapshotOnPrimaryStorageMsg.SnapshotDownloadInfo;
import org.zstack.header.storage.primary.*;
import org.zstack.header.storage.snapshot.VolumeSnapshotInventory;
import org.zstack.header.vm.VmInstanceState;
import org.zstack.header.vm.VmInstanceVO;
import org.zstack.header.vm.VmInstanceVO_;
import org.zstack.header.volume.VolumeInventory;
import org.zstack.identity.AccountManager;
import org.zstack.kvm.KVMAgentCommands.AgentResponse;
import org.zstack.kvm.*;
import org.zstack.storage.primary.PrimaryStorageBase.PhysicalCapacityUsage;
import org.zstack.storage.primary.PrimaryStorageCapacityUpdater;
import org.zstack.storage.primary.nfs.NfsPrimaryStorageKVMBackendCommands.*;
import org.zstack.utils.Bucket;
import org.zstack.utils.CollectionUtils;
import org.zstack.utils.Utils;
import org.zstack.utils.function.Function;
import org.zstack.utils.gson.JSONObjectUtil;
import org.zstack.utils.logging.CLogger;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.Callable;
public class NfsPrimaryStorageKVMBackend implements NfsPrimaryStorageBackend,
KVMHostConnectExtensionPoint, HostConnectionReestablishExtensionPoint {
private static final CLogger logger = Utils.getLogger(NfsPrimaryStorageKVMBackend.class);
@Autowired
private DatabaseFacade dbf;
@Autowired
private ApiTimeoutManager timeoutMgr;
@Autowired
private CloudBus bus;
@Autowired
private AccountManager acntMgr;
@Autowired
private ErrorFacade errf;
@Autowired
private NfsPrimaryStorageFactory nfsFactory;
@Autowired
private NfsPrimaryStorageManager nfsMgr;
public static final String MOUNT_PRIMARY_STORAGE_PATH = "/nfsprimarystorage/mount";
public static final String UNMOUNT_PRIMARY_STORAGE_PATH = "/nfsprimarystorage/unmount";
public static final String CREATE_EMPTY_VOLUME_PATH = "/nfsprimarystorage/createemptyvolume";
public static final String GET_CAPACITY_PATH = "/nfsprimarystorage/getcapacity";
public static final String DELETE_PATH = "/nfsprimarystorage/delete";
public static final String CHECK_BITS_PATH = "/nfsprimarystorage/checkbits";
public static final String MOVE_BITS_PATH = "/nfsprimarystorage/movebits";
public static final String MERGE_SNAPSHOT_PATH = "/nfsprimarystorage/mergesnapshot";
public static final String REBASE_MERGE_SNAPSHOT_PATH = "/nfsprimarystorage/rebaseandmergesnapshot";
public static final String REVERT_VOLUME_FROM_SNAPSHOT_PATH = "/nfsprimarystorage/revertvolumefromsnapshot";
public static final String CREATE_TEMPLATE_FROM_VOLUME_PATH = "/nfsprimarystorage/sftp/createtemplatefromvolume";
public static final String OFFLINE_SNAPSHOT_MERGE = "/nfsprimarystorage/offlinesnapshotmerge";
public static final String REMOUNT_PATH = "/nfsprimarystorage/remount";
//////////////// For unit test //////////////////////////
private boolean syncGetCapacity = false;
public static final String SYNC_GET_CAPACITY_PATH = "/nfsprimarystorage/syncgetcapacity";
//////////////// End for unit test //////////////////////
private static final String QCOW3_QEMU_IMG_VERSION = "2.0.0";
private void mount(PrimaryStorageInventory inv, String hostUuid) {
MountCmd cmd = new MountCmd();
cmd.setUrl(inv.getUrl());
cmd.setMountPath(inv.getMountPath());
cmd.setUuid(inv.getUuid());
cmd.setOptions(NfsSystemTags.MOUNT_OPTIONS.getTokenByResourceUuid(inv.getUuid(), NfsSystemTags.MOUNT_OPTIONS_TOKEN));
KVMHostSyncHttpCallMsg msg = new KVMHostSyncHttpCallMsg();
msg.setCommand(cmd);
msg.setPath(MOUNT_PRIMARY_STORAGE_PATH);
msg.setHostUuid(hostUuid);
msg.setNoStatusCheck(true);
bus.makeTargetServiceIdByResourceUuid(msg, HostConstant.SERVICE_ID, hostUuid);
MessageReply reply = bus.call(msg);
if (!reply.isSuccess()) {
throw new OperationFailureException(reply.getError());
}
MountAgentResponse rsp = ((KVMHostSyncHttpCallReply)reply).toResponse(MountAgentResponse.class);
if (!rsp.isSuccess()) {
throw new OperationFailureException(errf.stringToOperationError(rsp.getError()));
}
new PrimaryStorageCapacityUpdater(inv.getUuid()).update(
rsp.getTotalCapacity(), rsp.getAvailableCapacity(), rsp.getTotalCapacity(), rsp.getAvailableCapacity()
);
logger.debug(String.format(
"Successfully mounted nfs primary storage[uuid:%s] on kvm host[uuid:%s]",
inv.getUuid(), hostUuid));
}
@Override
public void attachToCluster(PrimaryStorageInventory inv, String clusterUuid) throws NfsPrimaryStorageException {
if (!CoreGlobalProperty.UNIT_TEST_ON) {
checkQemuImgVersionInOtherClusters(inv, clusterUuid);
}
SimpleQuery<HostVO> query = dbf.createQuery(HostVO.class);
query.select(HostVO_.uuid);
query.add(HostVO_.state, Op.NOT_IN, HostState.PreMaintenance, HostState.Maintenance);
query.add(HostVO_.status, Op.EQ, HostStatus.Connected);
query.add(HostVO_.clusterUuid, Op.EQ, clusterUuid);
List<String> hostUuids = query.listValue();
for (String huuid : hostUuids) {
mount(inv, huuid);
}
}
private void checkQemuImgVersionInOtherClusters(final PrimaryStorageInventory inv, String clusterUuid) {
SimpleQuery<HostVO> hq = dbf.createQuery(HostVO.class);
hq.select(HostVO_.uuid);
hq.add(HostVO_.clusterUuid, Op.EQ, clusterUuid);
List<String> huuidsInCluster = hq.listValue();
if (huuidsInCluster.isEmpty()) {
return;
}
Map<String, List<String>> qtags = KVMSystemTags.QEMU_IMG_VERSION.getTags(huuidsInCluster);
if (qtags.isEmpty()) {
// the hosts may be still in Connecting
return;
}
List<String> huuidsAttachedPrimaryStorage = new Callable<List<String>>() {
@Override
@Transactional(readOnly = true)
public List<String> call() {
String sql = "select h.uuid from HostVO h, PrimaryStorageClusterRefVO ref where h.clusterUuid = ref.clusterUuid and ref.primaryStorageUuid = :psUuid";
TypedQuery<String> q = dbf.getEntityManager().createQuery(sql, String.class);
q.setParameter("psUuid", inv.getUuid());
return q.getResultList();
}
}.call();
if (huuidsAttachedPrimaryStorage.isEmpty()) {
return;
}
String versionInCluster = KVMSystemTags.QEMU_IMG_VERSION.getTokenByTag(qtags.values().iterator().next().get(0), KVMSystemTags.QEMU_IMG_VERSION_TOKEN);
qtags = KVMSystemTags.QEMU_IMG_VERSION.getTags(huuidsAttachedPrimaryStorage);
for (Entry<String, List<String>> e : qtags.entrySet()) {
String otherVersion = KVMSystemTags.QEMU_IMG_VERSION.getTokenByTag(e.getValue().get(0), KVMSystemTags.QEMU_IMG_VERSION_TOKEN);
if ((versionInCluster.compareTo(QCOW3_QEMU_IMG_VERSION) >= 0 && otherVersion.compareTo(QCOW3_QEMU_IMG_VERSION) < 0) ||
(versionInCluster.compareTo(QCOW3_QEMU_IMG_VERSION) < 0 && otherVersion.compareTo(QCOW3_QEMU_IMG_VERSION) >= 0)) {
String err = String.format(
"unable to attach a primary storage[uuid:%s, name:%s] to cluster[uuid:%s]. Kvm host in the cluster has qemu-img "
+ "with version[%s]; but the primary storage has attached to another cluster that has kvm host which has qemu-img with "
+ "version[%s]. qemu-img version greater than %s is incompatible with versions less than %s, this will causes volume snapshot operation "
+ "to fail. Please avoid attaching a primary storage to clusters that have different Linux distributions, in order to prevent qemu-img version mismatch",
inv.getUuid(), inv.getName(), clusterUuid, versionInCluster, otherVersion, QCOW3_QEMU_IMG_VERSION, QCOW3_QEMU_IMG_VERSION
);
throw new OperationFailureException(errf.stringToOperationError(err));
}
}
}
private void unmount(PrimaryStorageInventory inv, String hostUuid) {
UnmountCmd cmd = new UnmountCmd();
cmd.setUuid(inv.getUuid());
cmd.setMountPath(inv.getMountPath());
cmd.setUrl(inv.getUrl());
KVMHostSyncHttpCallMsg msg = new KVMHostSyncHttpCallMsg();
msg.setCommand(cmd);
msg.setPath(UNMOUNT_PRIMARY_STORAGE_PATH);
msg.setHostUuid(hostUuid);
bus.makeTargetServiceIdByResourceUuid(msg, HostConstant.SERVICE_ID, hostUuid);
MessageReply reply = bus.call(msg);
if (!reply.isSuccess()) {
throw new OperationFailureException(reply.getError());
}
AgentResponse rsp = ((KVMHostSyncHttpCallReply)reply).toResponse(AgentResponse.class);
if (!rsp.isSuccess()) {
String err = String.format("Unable to unmount nfs primary storage[uuid:%s] on kvm host[uuid:%s], because %s", inv.getUuid(), hostUuid, rsp.getError());
logger.warn(err);
} else {
String info = String.format("Successfully unmount nfs primary storage[uuid:%s] on kvm host[uuid:%s]", inv.getUuid(), hostUuid);
logger.debug(info);
}
}
@Override
public void detachFromCluster(PrimaryStorageInventory inv, String clusterUuid) throws NfsPrimaryStorageException {
SimpleQuery<HostVO> query = dbf.createQuery(HostVO.class);
query.select(HostVO_.uuid);
query.add(HostVO_.status, Op.EQ, HostStatus.Connected);
query.add(HostVO_.clusterUuid, Op.EQ, clusterUuid);
List<String> hostUuids = query.listValue();
for (String huuid : hostUuids) {
unmount(inv, huuid);
}
}
@Override
public HypervisorType getHypervisorType() {
return HypervisorType.valueOf(KVMConstant.KVM_HYPERVISOR_TYPE);
}
@Override
public void getPhysicalCapacity(PrimaryStorageInventory inv, final ReturnValueCompletion<PhysicalCapacityUsage> completion) {
final HostInventory host = nfsFactory.getConnectedHostForOperation(inv);
GetCapacityCmd cmd = new GetCapacityCmd();
cmd.setMountPath(inv.getMountPath());
cmd.setUuid(inv.getUuid());
KVMHostAsyncHttpCallMsg msg = new KVMHostAsyncHttpCallMsg();
msg.setHostUuid(host.getUuid());
msg.setPath(GET_CAPACITY_PATH);
msg.setCommand(cmd);
msg.setCommandTimeout(timeoutMgr.getTimeout(cmd.getClass(), "5m"));
bus.makeTargetServiceIdByResourceUuid(msg, HostConstant.SERVICE_ID, host.getUuid());
bus.send(msg, new CloudBusCallBack(completion) {
@Override
public void run(MessageReply reply) {
if (!reply.isSuccess()) {
completion.fail(reply.getError());
return;
}
KVMHostAsyncHttpCallReply r = reply.castReply();
GetCapacityResponse rsp = r.toResponse(GetCapacityResponse.class);
if (!r.isSuccess()) {
completion.fail(errf.stringToOperationError(rsp.getError()));
return;
}
PhysicalCapacityUsage usage = new PhysicalCapacityUsage();
usage.totalPhysicalSize = rsp.getTotalCapacity();
usage.availablePhysicalSize = rsp.getAvailableCapacity();
completion.success(usage);
}
});
}
@Override
public void checkIsBitsExisting(final PrimaryStorageInventory inv, final String installPath, final ReturnValueCompletion<Boolean> completion) {
HostInventory host = nfsFactory.getConnectedHostForOperation(inv);
CheckIsBitsExistingCmd cmd = new CheckIsBitsExistingCmd();
cmd.setUuid(inv.getUuid());
cmd.setInstallPath(installPath);
KVMHostAsyncHttpCallMsg msg = new KVMHostAsyncHttpCallMsg();
msg.setCommand(cmd);
msg.setCommandTimeout(timeoutMgr.getTimeout(cmd.getClass(), "5m"));
msg.setPath(CHECK_BITS_PATH);
msg.setHostUuid(host.getUuid());
bus.makeTargetServiceIdByResourceUuid(msg, HostConstant.SERVICE_ID, host.getUuid());
bus.send(msg, new CloudBusCallBack(completion) {
@Override
public void run(MessageReply reply) {
if (!reply.isSuccess()) {
completion.fail(reply.getError());
return;
}
CheckIsBitsExistingRsp rsp = ((KVMHostAsyncHttpCallReply)reply).toResponse(CheckIsBitsExistingRsp.class);
if (!rsp.isSuccess()) {
completion.fail(errf.stringToOperationError(
String.format("failed to check existence of %s on nfs primary storage[uuid:%s], %s",
installPath, inv.getUuid(), rsp.getError())
));
return;
}
nfsMgr.reportCapacityIfNeeded(inv.getUuid(), rsp);
completion.success(rsp.isExisting());
}
});
}
@Transactional(readOnly = true)
private List<PrimaryStorageInventory> getPrimaryStorageForHost(String clusterUuid) {
String sql = "select p.uuid, p.url, p.mountPath from PrimaryStorageVO p where p.type = :ptype and p.uuid in (select r.primaryStorageUuid from PrimaryStorageClusterRefVO r where r.clusterUuid = :clusterUuid)";
Query query = dbf.getEntityManager().createQuery(sql);
query.setParameter("clusterUuid", clusterUuid);
query.setParameter("ptype", NfsPrimaryStorageConstant.NFS_PRIMARY_STORAGE_TYPE);
List<Object[]> lst = query.getResultList();
List<PrimaryStorageInventory> pss = new ArrayList<PrimaryStorageInventory>();
for (Object[] objs : lst) {
PrimaryStorageInventory inv = new PrimaryStorageInventory();
inv.setUuid((String) objs[0]);
inv.setUrl((String) objs[1]);
inv.setMountPath((String) objs[2]);
pss.add(inv);
}
return pss;
}
private void checkQemuImgVersionInOtherClusters(KVMHostConnectedContext context, List<PrimaryStorageInventory> invs) {
String mine = KVMSystemTags.QEMU_IMG_VERSION.getTokenByResourceUuid(context.getInventory().getUuid(), KVMSystemTags.QEMU_IMG_VERSION_TOKEN);
final List<String> psUuids = CollectionUtils.transformToList(invs, new Function<String, PrimaryStorageInventory>() {
@Override
public String call(PrimaryStorageInventory arg) {
return arg.getUuid();
}
});
List<String> otherHostUuids = new Callable<List<String>>() {
@Override
@Transactional(readOnly = true)
public List<String> call() {
String sql = "select host.uuid from HostVO host, PrimaryStorageClusterRefVO ref where host.clusterUuid = ref.clusterUuid and ref.primaryStorageUuid in (:psUuids)";
TypedQuery<String> q = dbf.getEntityManager().createQuery(sql, String.class);
q.setParameter("psUuids", psUuids);
return q.getResultList();
}
}.call();
Map<String, List<String>> qemuTags = KVMSystemTags.QEMU_IMG_VERSION.getTags(otherHostUuids);
for (Entry<String, List<String>> e : qemuTags.entrySet()) {
String version = KVMSystemTags.QEMU_IMG_VERSION.getTokenByTag(e.getValue().get(0), KVMSystemTags.QEMU_IMG_VERSION_TOKEN);
if (
(version.compareTo(QCOW3_QEMU_IMG_VERSION) >= 0 && mine.compareTo(QCOW3_QEMU_IMG_VERSION) < 0) ||
(version.compareTo(QCOW3_QEMU_IMG_VERSION) < 0 && mine.compareTo(QCOW3_QEMU_IMG_VERSION) >= 0)
) {
String err = String.format(
"unable to attach a primary storage to cluster. Kvm host[uuid:%s, name:%s] in cluster has qemu-img "
+ "with version[%s]; but the primary storage has attached to a cluster that has kvm host[uuid:%s], which has qemu-img with "
+ "version[%s]. qemu-img version greater than %s is incompatible with versions less than %s, this will causes volume snapshot operation "
+ "to fail. Please avoid attaching a primary storage to clusters that have different Linux distributions, in order to prevent qemu-img version mismatch",
context.getInventory().getUuid(), context.getInventory().getName(), mine, e.getKey(), version, QCOW3_QEMU_IMG_VERSION, QCOW3_QEMU_IMG_VERSION
);
throw new OperationFailureException(errf.stringToOperationError(err));
}
}
}
@Override
public void instantiateVolume(final PrimaryStorageInventory pinv, final VolumeInventory volume, final ReturnValueCompletion<VolumeInventory> complete) {
String accounUuid = acntMgr.getOwnerAccountUuidOfResource(volume.getUuid());
final CreateEmptyVolumeCmd cmd = new CreateEmptyVolumeCmd();
cmd.setUuid(pinv.getUuid());
cmd.setAccountUuid(accounUuid);
cmd.setHypervisorType(KVMConstant.KVM_HYPERVISOR_TYPE);
cmd.setName(volume.getName());
cmd.setSize(volume.getSize());
cmd.setVolumeUuid(volume.getUuid());
if (volume.getRootImageUuid() != null) {
cmd.setInstallUrl(NfsPrimaryStorageKvmHelper.makeRootVolumeInstallUrl(pinv, volume));
} else {
cmd.setInstallUrl(NfsPrimaryStorageKvmHelper.makeDataVolumeInstallUrl(pinv, volume.getUuid()));
}
final HostInventory host = nfsFactory.getConnectedHostForOperation(pinv);
KVMHostAsyncHttpCallMsg msg = new KVMHostAsyncHttpCallMsg();
msg.setCommand(cmd);
msg.setPath(CREATE_EMPTY_VOLUME_PATH);
msg.setHostUuid(host.getUuid());
msg.setCommandTimeout(timeoutMgr.getTimeout(cmd.getClass(), "5m"));
bus.makeTargetServiceIdByResourceUuid(msg, HostConstant.SERVICE_ID, host.getUuid());
bus.send(msg, new CloudBusCallBack(complete) {
@Override
public void run(MessageReply reply) {
if (!reply.isSuccess()) {
complete.fail(reply.getError());
return;
}
CreateEmptyVolumeResponse rsp = ((KVMHostAsyncHttpCallReply)reply).toResponse(CreateEmptyVolumeResponse.class);
if (!rsp.isSuccess()) {
String err = String.format("unable to create empty volume[uuid:%s, name:%s] on kvm host[uuid:%s, ip:%s], because %s",
volume.getUuid(), volume.getName(), host.getUuid(), host.getManagementIp(), rsp.getError());
logger.warn(err);
complete.fail(errf.stringToOperationError(err));
return;
}
volume.setInstallPath(cmd.getInstallUrl());
nfsMgr.reportCapacityIfNeeded(pinv.getUuid(), rsp);
complete.success(volume);
}
});
}
public void setSyncGetCapacity(boolean syncGetCapacity) {
this.syncGetCapacity = syncGetCapacity;
}
@Transactional
private List<PrimaryStorageVO> getPrimaryStorageHostShouldMount(HostInventory host) {
String sql = "select p from PrimaryStorageVO p where p.type = :type and p.uuid in (select ref.primaryStorageUuid from PrimaryStorageClusterRefVO ref where ref.clusterUuid = :clusterUuid)";
TypedQuery<PrimaryStorageVO> query = dbf.getEntityManager().createQuery(sql, PrimaryStorageVO.class);
query.setParameter("type", NfsPrimaryStorageConstant.NFS_PRIMARY_STORAGE_TYPE);
query.setParameter("clusterUuid", host.getClusterUuid());
return query.getResultList();
}
@Override
public void connectionReestablished(HostInventory inv) throws HostException {
List<PrimaryStorageVO> ps = getPrimaryStorageHostShouldMount(inv);
if (ps.isEmpty()) {
return;
}
for (PrimaryStorageVO pvo : ps) {
mount(PrimaryStorageInventory.valueOf(pvo), inv.getUuid());
}
}
@Override
public HypervisorType getHypervisorTypeForReestablishExtensionPoint() {
return HypervisorType.valueOf(KVMConstant.KVM_HYPERVISOR_TYPE);
}
@Override
public void deleteImageCache(ImageCacheInventory imageCache) {
}
private void delete(final PrimaryStorageInventory pinv, final String installPath, boolean isFolder, final Completion completion) {
HostInventory host = nfsFactory.getConnectedHostForOperation(pinv);
DeleteCmd cmd = new DeleteCmd();
cmd.setFolder(isFolder);
cmd.setInstallPath(installPath);
cmd.setUuid(pinv.getUuid());
KVMHostAsyncHttpCallMsg msg = new KVMHostAsyncHttpCallMsg();
msg.setCommand(cmd);
msg.setPath(DELETE_PATH);
msg.setHostUuid(host.getUuid());
msg.setCommandTimeout(timeoutMgr.getTimeout(cmd.getClass(), "5m"));
bus.makeTargetServiceIdByResourceUuid(msg, HostConstant.SERVICE_ID, host.getUuid());
bus.send(msg, new CloudBusCallBack(completion) {
@Override
public void run(MessageReply reply) {
if (!reply.isSuccess()) {
completion.fail(reply.getError());
return;
}
DeleteResponse rsp = ((KVMHostAsyncHttpCallReply)reply).toResponse(DeleteResponse.class);
if (!rsp.isSuccess()) {
logger.warn(String.format("failed to delete bits[%s] on nfs primary storage[uuid:%s], %s, will clean up",
installPath, pinv.getUuid(), rsp.getError()));
} else {
nfsMgr.reportCapacityIfNeeded(pinv.getUuid(), rsp);
}
completion.success();
}
});
}
@Override
public void delete(final PrimaryStorageInventory pinv, final String installPath, final Completion completion) {
delete(pinv, installPath, false, completion);
}
@Override
public void deleteFolder(PrimaryStorageInventory pinv, String installPath, Completion completion) {
delete(pinv, installPath, true, completion);
}
@Override
public void revertVolumeFromSnapshot(final VolumeSnapshotInventory sinv, final VolumeInventory vol, final HostInventory host, final ReturnValueCompletion<String> completion) {
RevertVolumeFromSnapshotCmd cmd = new RevertVolumeFromSnapshotCmd();
cmd.setSnapshotInstallPath(sinv.getPrimaryStorageInstallPath());
cmd.setUuid(sinv.getPrimaryStorageUuid());
KVMHostAsyncHttpCallMsg msg = new KVMHostAsyncHttpCallMsg();
msg.setCommand(cmd);
msg.setPath(REVERT_VOLUME_FROM_SNAPSHOT_PATH);
msg.setHostUuid(host.getUuid());
msg.setCommandTimeout(timeoutMgr.getTimeout(cmd.getClass(), "5m"));
bus.makeTargetServiceIdByResourceUuid(msg, HostConstant.SERVICE_ID, host.getUuid());
bus.send(msg, new CloudBusCallBack(completion) {
@Override
public void run(MessageReply reply) {
if (!reply.isSuccess()) {
completion.fail(reply.getError());
return;
}
RevertVolumeFromSnapshotResponse rsp = ((KVMHostAsyncHttpCallReply)reply).toResponse(RevertVolumeFromSnapshotResponse.class);
if (!rsp.isSuccess()) {
completion.fail(errf.stringToOperationError(
String.format("failed to revert volume[uuid:%s] to snapshot[uuid:%s] on kvm host[uuid:%s, ip:%s], %s",
vol.getUuid(), sinv.getUuid(), host.getUuid(), host.getManagementIp(), rsp.getError())
));
return;
}
completion.success(rsp.getNewVolumeInstallPath());
}
});
}
@Override
public void createTemplateFromVolume(final PrimaryStorageInventory primaryStorage, final VolumeInventory volume, final ImageInventory image, final ReturnValueCompletion<String> completion) {
final HostInventory destHost = nfsFactory.getConnectedHostForOperation(primaryStorage);
final String installPath = NfsPrimaryStorageKvmHelper.makeTemplateFromVolumeInWorkspacePath(primaryStorage, image.getUuid());
CreateTemplateFromVolumeCmd cmd = new CreateTemplateFromVolumeCmd();
cmd.setInstallPath(installPath);
cmd.setVolumePath(volume.getInstallPath());
cmd.setUuid(primaryStorage.getUuid());
KVMHostAsyncHttpCallMsg msg = new KVMHostAsyncHttpCallMsg();
msg.setCommand(cmd);
msg.setHostUuid(destHost.getUuid());
msg.setPath(CREATE_TEMPLATE_FROM_VOLUME_PATH);
msg.setCommandTimeout(timeoutMgr.getTimeout(cmd.getClass(), "5m"));
bus.makeTargetServiceIdByResourceUuid(msg, HostConstant.SERVICE_ID, destHost.getUuid());
bus.send(msg, new CloudBusCallBack(completion) {
@Override
public void run(MessageReply reply) {
if (!reply.isSuccess()) {
completion.fail(reply.getError());
return;
}
CreateTemplateFromVolumeRsp rsp = ((KVMHostAsyncHttpCallReply)reply).toResponse(CreateTemplateFromVolumeRsp.class);
if (!rsp.isSuccess()) {
StringBuilder sb = new StringBuilder();
sb.append(String.format("failed to create template from volume, because %s", rsp.getError()));
sb.append(String.format("\ntemplate:%s", JSONObjectUtil.toJsonString(image)));
sb.append(String.format("\nvolume:%s", JSONObjectUtil.toJsonString(volume)));
sb.append(String.format("\nnfs primary storage uuid:%s", primaryStorage.getUuid()));
sb.append(String.format("\nKVM host uuid:%s, management ip:%s", destHost.getUuid(), destHost.getManagementIp()));
completion.fail(errf.stringToOperationError(sb.toString()));
return;
}
StringBuilder sb = new StringBuilder();
sb.append(String.format("successfully created template from volumes"));
sb.append(String.format("\ntemplate:%s", JSONObjectUtil.toJsonString(image)));
sb.append(String.format("\nvolume:%s", JSONObjectUtil.toJsonString(volume)));
sb.append(String.format("\nnfs primary storage uuid:%s", primaryStorage.getUuid()));
sb.append(String.format("\nKVM host uuid:%s, management ip:%s", destHost.getUuid(), destHost.getManagementIp()));
logger.debug(sb.toString());
nfsMgr.reportCapacityIfNeeded(primaryStorage.getUuid(), rsp);
completion.success(installPath);
}
});
}
private void createBitsFromVolumeSnapshot(final PrimaryStorageInventory pinv, List<SnapshotDownloadInfo> snapshots,
final String bitsUuid, final String bitsName, boolean needDownload,
final ReturnValueCompletion<CreateBitsFromSnapshotResult> completion) {
if (!needDownload) {
HostInventory host = nfsFactory.getConnectedHostForOperation(pinv);
final VolumeSnapshotInventory latest = snapshots.get(snapshots.size()-1).getSnapshot();
final String workspaceInstallPath = NfsPrimaryStorageKvmHelper.makeSnapshotWorkspacePath(pinv, bitsUuid);
MergeSnapshotCmd cmd = new MergeSnapshotCmd();
cmd.setSnapshotInstallPath(latest.getPrimaryStorageInstallPath());
cmd.setWorkspaceInstallPath(workspaceInstallPath);
cmd.setUuid(pinv.getUuid());
KVMHostAsyncHttpCallMsg msg = new KVMHostAsyncHttpCallMsg();
msg.setCommand(cmd);
msg.setCommandTimeout(timeoutMgr.getTimeout(cmd.getClass(), "5m"));
msg.setPath(MERGE_SNAPSHOT_PATH);
msg.setHostUuid(host.getUuid());
bus.makeTargetServiceIdByResourceUuid(msg, HostConstant.SERVICE_ID, host.getUuid());
bus.send(msg, new CloudBusCallBack(completion) {
@Override
public void run(MessageReply reply) {
if (!reply.isSuccess()) {
completion.fail(reply.getError());
return;
}
MergeSnapshotResponse rsp = ((KVMHostAsyncHttpCallReply)reply).toResponse(MergeSnapshotResponse.class);
if (!rsp.isSuccess()) {
completion.fail(errf.stringToOperationError(
String.format("failed to create %s[uuid:%s] from snapshot[uuid:%s] on nfs primary storage[uuid:%s], %s",
bitsName, bitsUuid, latest.getUuid(), pinv.getUuid(), rsp.getError())
));
return;
}
CreateBitsFromSnapshotResult result = new CreateBitsFromSnapshotResult();
result.setInstallPath(workspaceInstallPath);
result.setSize(rsp.getSize());
completion.success(result);
}
});
} else {
downloadAndCreateBitsFromVolumeSnapshots(pinv, snapshots, bitsName, bitsUuid, completion);
}
}
@Override
public void createTemplateFromVolumeSnapshot(final PrimaryStorageInventory pinv, List<SnapshotDownloadInfo> snapshots,
final String imageUuid, boolean needDownload,
final ReturnValueCompletion<CreateBitsFromSnapshotResult> completion) {
createBitsFromVolumeSnapshot(pinv, snapshots, imageUuid, "template", needDownload, completion);
}
@Override
public void createDataVolumeFromVolumeSnapshot(PrimaryStorageInventory pinv,
List<SnapshotDownloadInfo> infos,
String volumeUuid, boolean needDownload,
ReturnValueCompletion<CreateBitsFromSnapshotResult> completion) {
createBitsFromVolumeSnapshot(pinv, infos, volumeUuid, "volume", needDownload, completion);
}
@Override
public void moveBits(final PrimaryStorageInventory pinv, String srcPath, String destPath, final Completion completion) {
HostInventory host = nfsFactory.getConnectedHostForOperation(pinv);
MoveBitsCmd cmd = new MoveBitsCmd();
cmd.setSrcPath(srcPath);
cmd.setDestPath(destPath);
cmd.setUuid(pinv.getUuid());
KVMHostAsyncHttpCallMsg msg = new KVMHostAsyncHttpCallMsg();
msg.setCommand(cmd);
msg.setPath(MOVE_BITS_PATH);
msg.setHostUuid(host.getUuid());
msg.setCommandTimeout(timeoutMgr.getTimeout(cmd.getClass(), "5m"));
bus.makeTargetServiceIdByResourceUuid(msg, HostConstant.SERVICE_ID, host.getUuid());
bus.send(msg, new CloudBusCallBack(completion) {
@Override
public void run(MessageReply reply) {
if (!reply.isSuccess()) {
completion.fail(reply.getError());
return;
}
KVMHostAsyncHttpCallReply hreply = reply.castReply();
MoveBitsRsp rsp = hreply.toResponse(MoveBitsRsp.class);
if (!rsp.isSuccess()) {
completion.fail(errf.stringToOperationError(rsp.getError()));
return;
}
nfsMgr.reportCapacityIfNeeded(pinv.getUuid(), rsp);
completion.success();
}
});
}
@Override
public void mergeSnapshotToVolume(final PrimaryStorageInventory pinv, VolumeSnapshotInventory snapshot,
VolumeInventory volume, boolean fullRebase, final Completion completion) {
boolean offline = true;
if (volume.getVmInstanceUuid() != null) {
SimpleQuery<VmInstanceVO> q = dbf.createQuery(VmInstanceVO.class);
q.select(VmInstanceVO_.state);
q.add(VmInstanceVO_.uuid, Op.EQ, volume.getVmInstanceUuid());
VmInstanceState state = q.findValue();
offline = (state == VmInstanceState.Stopped);
}
HostInventory host = nfsFactory.getConnectedHostForOperation(pinv);
if (offline) {
OfflineMergeSnapshotCmd cmd = new OfflineMergeSnapshotCmd();
cmd.setFullRebase(fullRebase);
cmd.setSrcPath(snapshot.getPrimaryStorageInstallPath());
cmd.setDestPath(volume.getInstallPath());
cmd.setUuid(pinv.getUuid());
KVMHostAsyncHttpCallMsg msg = new KVMHostAsyncHttpCallMsg();
msg.setCommand(cmd);
msg.setPath(OFFLINE_SNAPSHOT_MERGE);
msg.setHostUuid(host.getUuid());
msg.setCommandTimeout(timeoutMgr.getTimeout(cmd.getClass(), "5m"));
bus.makeTargetServiceIdByResourceUuid(msg, HostConstant.SERVICE_ID, host.getUuid());
bus.send(msg, new CloudBusCallBack(completion) {
@Override
public void run(MessageReply reply) {
if (!reply.isSuccess()) {
completion.fail(reply.getError());
return;
}
OfflineMergeSnapshotRsp rsp = ((KVMHostAsyncHttpCallReply)reply).toResponse(OfflineMergeSnapshotRsp.class);
if (!rsp.isSuccess()) {
completion.fail(errf.stringToOperationError(rsp.getError()));
return;
}
nfsMgr.reportCapacityIfNeeded(pinv.getUuid(), rsp);
completion.success();
}
});
} else {
MergeVolumeSnapshotOnKvmMsg msg = new MergeVolumeSnapshotOnKvmMsg();
msg.setFullRebase(fullRebase);
msg.setHostUuid(host.getUuid());
msg.setFrom(snapshot);
msg.setTo(volume);
bus.makeTargetServiceIdByResourceUuid(msg, HostConstant.SERVICE_ID, host.getUuid());
bus.send(msg, new CloudBusCallBack(completion) {
@Override
public void run(MessageReply reply) {
if (reply.isSuccess()) {
completion.success();
} else {
completion.fail(reply.getError());
}
}
});
}
}
@Override
public void remount(final PrimaryStorageInventory pinv, String clusterUuid, final Completion completion) {
SimpleQuery<HostVO> q = dbf.createQuery(HostVO.class);
q.select(HostVO_.uuid);
q.add(HostVO_.clusterUuid, Op.EQ, clusterUuid);
q.add(HostVO_.status, Op.EQ, HostStatus.Connected);
final List<String> huuids = q.listValue();
if (huuids.isEmpty()) {
completion.success();
return;
}
List<KVMHostAsyncHttpCallMsg> msgs = CollectionUtils.transformToList(huuids, new Function<KVMHostAsyncHttpCallMsg, String>() {
@Override
public KVMHostAsyncHttpCallMsg call(String arg) {
RemountCmd cmd = new RemountCmd();
cmd.setUuid(pinv.getUuid());
cmd.url = pinv.getUrl();
cmd.mountPath = pinv.getMountPath();
cmd.options = NfsSystemTags.MOUNT_OPTIONS.getTokenByResourceUuid(pinv.getUuid(), NfsSystemTags.MOUNT_OPTIONS_TOKEN);
KVMHostAsyncHttpCallMsg msg = new KVMHostAsyncHttpCallMsg();
msg.setCommand(cmd);
msg.setCommandTimeout(timeoutMgr.getTimeout(cmd.getClass(), "5m"));
msg.setHostUuid(arg);
msg.setPath(REMOUNT_PATH);
bus.makeTargetServiceIdByResourceUuid(msg, HostConstant.SERVICE_ID, arg);
return msg;
}
});
bus.send(msgs, new CloudBusListCallBack(completion) {
private void reconnectHost(String huuid, ErrorCode error) {
logger.warn(String.format("failed to remount NFS primary storage[uuid:%s, name:%s] on the KVM host[uuid:%s]," +
"%s. Start a reconnect to fix the problem", pinv.getUuid(), pinv.getName(), huuid, error));
ReconnectHostMsg rmsg = new ReconnectHostMsg();
rmsg.setHostUuid(huuid);
bus.makeTargetServiceIdByResourceUuid(rmsg, HostConstant.SERVICE_ID, huuid);
bus.send(rmsg);
}
@Override
public void run(List<MessageReply> replies) {
boolean reported = false;
List<ErrorCode> errors = new ArrayList<ErrorCode>();
boolean success = false;
for (MessageReply re : replies) {
String huuid = huuids.get(replies.indexOf(re));
if (!re.isSuccess()) {
errors.add(re.getError());
reconnectHost(huuid, re.getError());
continue;
}
KVMHostAsyncHttpCallReply ar = re.castReply();
NfsPrimaryStorageAgentResponse rsp = ar.toResponse(NfsPrimaryStorageAgentResponse.class);
if (!rsp.isSuccess()) {
ErrorCode err = errf.stringToOperationError(rsp.getError());
errors.add(err);
reconnectHost(huuid, err);
continue;
}
success = true;
if (!reported) {
new PrimaryStorageCapacityUpdater(pinv.getUuid()).update(
rsp.getTotalCapacity(), rsp.getAvailableCapacity(), rsp.getTotalCapacity(), rsp.getAvailableCapacity()
);
reported = true;
}
}
if (success) {
completion.success();
} else {
completion.fail(errf.stringToOperationError(String.format("%s", errors)));
}
}
});
}
private void downloadAndCreateBitsFromVolumeSnapshots(final PrimaryStorageInventory pinv,
final List<SnapshotDownloadInfo> snapshots,
final String bitsName,
final String bitsUuid,
final ReturnValueCompletion<CreateBitsFromSnapshotResult> completion) {
final HostInventory host = nfsFactory.getConnectedHostForOperation(pinv);
FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("download-merge-snapshot-on-nfs-primary-storage-%s", pinv.getUuid()));
chain.then(new ShareFlow() {
List<String> snapshotInstallPaths = new ArrayList<String>();
String workspaceInstallPath = NfsPrimaryStorageKvmHelper.makeSnapshotWorkspacePath(pinv, bitsUuid);
long templateSize;
@Override
public void setup() {
flow(new Flow() {
String __name__ = "download-snapshot-from-backup-storage";
Map<String, Bucket> mediatorMap = new HashMap<String, Bucket>();
private Bucket findMediatorAndBackupStorage(SnapshotDownloadInfo info) {
Bucket ret = mediatorMap.get(info.getBackupStorageUuid());
if (ret == null) {
BackupStorageVO bsvo = dbf.findByUuid(info.getBackupStorageUuid(), BackupStorageVO.class);
BackupStorageInventory bsinv = BackupStorageInventory.valueOf(bsvo);
NfsPrimaryToBackupStorageMediator mediator = nfsFactory.getPrimaryToBackupStorageMediator(
BackupStorageType.valueOf(bsinv.getType()),
nfsMgr.findHypervisorTypeByImageFormatAndPrimaryStorageUuid(info.getSnapshot().getFormat(), pinv.getUuid())
);
ret = Bucket.newBucket(mediator, bsinv);
mediatorMap.put(info.getBackupStorageUuid(), ret);
}
return ret;
}
private void download(final Iterator<SnapshotDownloadInfo> it, final Completion completion1) {
if (!it.hasNext()) {
Collections.reverse(snapshotInstallPaths);
completion1.success();
return;
}
final SnapshotDownloadInfo info = it.next();
final VolumeSnapshotInventory sinv = info.getSnapshot();
Bucket bucket = findMediatorAndBackupStorage(info);
NfsPrimaryToBackupStorageMediator mediator = bucket.get(0);
final BackupStorageInventory bsinv = bucket.get(1);
final String installPath = NfsPrimaryStorageKvmHelper.makeSnapshotWorkspacePath(pinv, sinv.getUuid());
mediator.downloadBits(pinv, bsinv, info.getBackupStorageInstallPath(), installPath, new Completion(completion1) {
@Override
public void success() {
logger.debug(String.format("download volume snapshot[uuid:%s, name:%s] from backup storage[uuid:%s, %s] to nfs primary storage[uuid:%s, path:%s]",
sinv.getUuid(), sinv.getName(), bsinv.getUuid(), info.getBackupStorageInstallPath(), pinv.getUuid(), installPath));
snapshotInstallPaths.add(installPath);
download(it, completion1);
}
@Override
public void fail(ErrorCode errorCode) {
completion1.fail(errorCode);
}
});
}
@Override
public void run(final FlowTrigger trigger, Map data) {
download(snapshots.iterator(), new Completion(trigger) {
@Override
public void success() {
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
@Override
public void rollback(FlowRollback trigger, Map data) {
for (String installPath : snapshotInstallPaths) {
delete(pinv, installPath, new NopeCompletion());
}
trigger.rollback();
}
});
flow(new Flow() {
String __name__ = "merge-snapshot-on-primary-storage";
boolean mergeSuccess;
@Override
public void run(final FlowTrigger trigger, Map data) {
RebaseAndMergeSnapshotsCmd cmd = new RebaseAndMergeSnapshotsCmd();
cmd.setSnapshotInstallPaths(snapshotInstallPaths);
cmd.setWorkspaceInstallPath(workspaceInstallPath);
cmd.setUuid(pinv.getUuid());
KVMHostAsyncHttpCallMsg msg = new KVMHostAsyncHttpCallMsg();
msg.setCommand(cmd);
msg.setCommandTimeout(timeoutMgr.getTimeout(cmd.getClass(), "5m"));
msg.setPath(REBASE_MERGE_SNAPSHOT_PATH);
msg.setHostUuid(host.getUuid());
bus.makeTargetServiceIdByResourceUuid(msg, HostConstant.SERVICE_ID, host.getUuid());
bus.send(msg, new CloudBusCallBack(trigger) {
@Override
public void run(MessageReply reply) {
if (!reply.isSuccess()) {
trigger.fail(reply.getError());
return;
}
RebaseAndMergeSnapshotsResponse rsp = ((KVMHostAsyncHttpCallReply) reply).toResponse(RebaseAndMergeSnapshotsResponse.class);
if (!rsp.isSuccess()) {
trigger.fail(errf.stringToOperationError(
String.format("failed to rebase and merge snapshots for %s[uuid:%s] on nfs primary storage[uuid:%s], %s",
bitsName, bitsUuid, pinv.getUuid(), rsp.getError())
));
return;
}
nfsMgr.reportCapacityIfNeeded(pinv.getUuid(), rsp);
templateSize = rsp.getSize();
mergeSuccess = true;
trigger.next();
}
});
}
@Override
public void rollback(FlowRollback trigger, Map data) {
if (mergeSuccess) {
delete(pinv, workspaceInstallPath, new NopeCompletion());
}
trigger.rollback();
}
});
flow(new NoRollbackFlow() {
String __name__ = "delete-temporary-snapshot-in-workspace";
@Override
public void run(FlowTrigger trigger, Map data) {
for (String installPath : snapshotInstallPaths) {
delete(pinv, installPath, new NopeCompletion());
}
trigger.next();
}
});
done(new FlowDoneHandler(completion) {
@Override
public void handle(Map data) {
CreateBitsFromSnapshotResult result = new CreateBitsFromSnapshotResult();
result.setSize(templateSize);
result.setInstallPath(workspaceInstallPath);
completion.success(result);
}
});
error(new FlowErrorHandler(completion) {
@Override
public void handle(ErrorCode errCode, Map data) {
completion.fail(errCode);
}
});
}
}).start();
}
@Override
public Flow createKvmHostConnectingFlow(final KVMHostConnectedContext context) {
return new NoRollbackFlow() {
String __name__ = "remount-nfs-primary-storage";
List<PrimaryStorageInventory> invs = getPrimaryStorageForHost(context.getInventory().getClusterUuid());
@Override
public void run(final FlowTrigger trigger, Map data) {
if (invs.isEmpty()) {
trigger.next();
return;
}
if (context.isNewAddedHost() && !CoreGlobalProperty.UNIT_TEST_ON && !invs.isEmpty()) {
checkQemuImgVersionInOtherClusters(context, invs);
}
List<KVMHostAsyncHttpCallMsg> msgs = new ArrayList<KVMHostAsyncHttpCallMsg>();
for (PrimaryStorageInventory inv : invs) {
RemountCmd cmd = new RemountCmd();
cmd.mountPath = inv.getMountPath();
cmd.url = inv.getUrl();
cmd.setUuid(inv.getUuid());
cmd.options = NfsSystemTags.MOUNT_OPTIONS.getTokenByResourceUuid(inv.getUuid(), NfsSystemTags.MOUNT_OPTIONS_TOKEN);
KVMHostAsyncHttpCallMsg msg = new KVMHostAsyncHttpCallMsg();
msg.setCommand(cmd);
msg.setNoStatusCheck(true);
msg.setPath(REMOUNT_PATH);
msg.setHostUuid(context.getInventory().getUuid());
msg.setCommandTimeout(timeoutMgr.getTimeout(cmd.getClass(), "5m"));
bus.makeTargetServiceIdByResourceUuid(msg, HostConstant.SERVICE_ID, msg.getHostUuid());
msgs.add(msg);
}
bus.send(msgs, new CloudBusListCallBack(trigger) {
@Override
public void run(List<MessageReply> replies) {
for (MessageReply reply : replies) {
if (!reply.isSuccess()) {
throw new OperationFailureException(reply.getError());
}
KVMHostAsyncHttpCallReply r = reply.castReply();
NfsPrimaryStorageAgentResponse rsp = r.toResponse(NfsPrimaryStorageAgentResponse.class);
if (!rsp.isSuccess()) {
throw new OperationFailureException(errf.stringToOperationError(rsp.getError()));
}
PrimaryStorageInventory inv = invs.get(replies.indexOf(reply));
new PrimaryStorageCapacityUpdater(inv.getUuid()).update(
rsp.getTotalCapacity(), rsp.getAvailableCapacity(), rsp.getTotalCapacity(), rsp.getAvailableCapacity()
);
}
trigger.next();
}
});
}
};
}
}
|
apache-2.0
|
iamgoodman/AmazonOrdertest
|
src/com/amazonservices/mws/orders/_2013_09_01/model/ResponseMetadata.java
|
3298
|
/*******************************************************************************
* Copyright 2009-2015 Amazon Services. 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://aws.amazon.com/apache2.0
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*******************************************************************************
* Response Metadata
* API Version: 2013-09-01
* Library Version: 2015-09-24
* Generated: Fri Sep 25 20:06:20 GMT 2015
*/
package com.amazonservices.mws.orders._2013_09_01.model;
import com.amazonservices.mws.client.*;
/**
* ResponseMetadata complex type.
*
* XML schema:
*
* <pre>
* <complexType name="ResponseMetadata">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="RequestId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*/
public class ResponseMetadata extends AbstractMwsObject {
private String requestId;
/**
* Get the value of RequestId.
*
* @return The value of RequestId.
*/
public String getRequestId() {
return requestId;
}
/**
* Set the value of RequestId.
*
* @param requestId
* The new value to set.
*/
public void setRequestId(String requestId) {
this.requestId = requestId;
}
/**
* Check to see if RequestId is set.
*
* @return true if RequestId is set.
*/
public boolean isSetRequestId() {
return requestId != null;
}
/**
* Set the value of RequestId, return this.
*
* @param requestId
* The new value to set.
*
* @return This instance.
*/
public ResponseMetadata withRequestId(String requestId) {
this.requestId = requestId;
return this;
}
/**
* Read members from a MwsReader.
*
* @param r
* The reader to read from.
*/
@Override
public void readFragmentFrom(MwsReader r) {
requestId = r.read("RequestId", String.class);
}
/**
* Write members to a MwsWriter.
*
* @param w
* The writer to write to.
*/
@Override
public void writeFragmentTo(MwsWriter w) {
w.write("RequestId", requestId);
}
/**
* Write tag, xmlns and members to a MwsWriter.
*
* @param w
* The Writer to write to.
*/
@Override
public void writeTo(MwsWriter w) {
w.write("https://mws.amazonservices.com/Orders/2013-09-01", "ResponseMetadata",this);
}
/** Value constructor. */
public ResponseMetadata(String requestId) {
this.requestId = requestId;
}
/** Default constructor. */
public ResponseMetadata() {
super();
}
}
|
apache-2.0
|
erikgoe/Nigel
|
Compiler/Nigel/Linker.cpp
|
19926
|
#include "stdafx.h"
#include "Linker.h"
namespace nigel
{
Linker::Linker()
{
}
ExecutionResult Linker::onExecute( CodeBase &base )
{
std::map<u32, u16> blockBeginAddresses;//Already created blocks. Id of a block mapped to the address in hexBuffer.
std::map<u32, u16> blockEndAddresses;//Already created blocks. Id of a block mapped to the address in hexBuffer.
std::map<u32, u16> blockFinishAddresses;//Already created blocks. Id of a block mapped to the address in hexBuffer.
std::map<u32, std::list<u16>> missingBeginBlocks;//These addresses should be overwritten, if the corresponding block was created.
std::map<u32, std::list<u16>> missingEndBlocks;//These addresses should be overwritten, if the corresponding block was created.
std::map<u32, std::list<u16>> missingFinishBlocks;//These addresses should be overwritten, if the corresponding block was created.
std::map<u32, u16> conditionEnds_true;//Already created conditions. Id of a condition mapped to the address in hexBuffer.
std::map<u32, u16> conditionEnds_false;//Already created conditions. Id of a condition mapped to the address in hexBuffer.
std::map<u32, u16> missingConditionEnds_true;//These addresses should be overwritten, if the corresponding condition was finished.
std::map<u32, u16> missingConditionEnds_false;//These addresses should be overwritten, if the corresponding condition was finished.
std::map<String, u16> symbolAddresses;//Already created symbols/functions. Id of a function mapped to the address in hexBuffer.
std::map<String, std::list<u16>> missingSymbols;//These addresses should be overwritten, if the corresponding function was created.
{//Initialize the machine
base.hexBuffer.resize( 0x33 );//Insert empty space for interrupts, etc.
//Jmp to init code
base.hexBuffer[0x00] = 0x80;//jmp_rel
base.hexBuffer[0x01] = 0x29;//to init code
//<reserved for interrupt calls>
//Init, call main and then loop infinitely
base.hexBuffer[0x2B] = 0x75;//mov_const
base.hexBuffer[0x2C] = 0x07;//BR
//<reserved for main call>
base.hexBuffer[0x31] = 0x80;//jmp_rel
base.hexBuffer[0x32] = 0xFE;//to itselfe
}
{//Set address of values
u16 fastAdr = 0x80;
u16 largeAdr = 0;
bool onlyNormal = false;
for( auto &v : base.imValues )
{
if( v.second->model == MemModel::fast && !onlyNormal && v.second->address == 0 )
{
if( ( fastAdr - v.second->size / 8 ) < 0x20 )
{
generateNotification( NT::warn_toManyVariablesInFastRAM, base.srcFile );
onlyNormal = true;
}
else
{
fastAdr -= v.second->size / 8;
v.second->address = fastAdr;
}
}
if( v.second->model == MemModel::large || onlyNormal )
{
v.second->address = largeAdr;
largeAdr += v.second->size / 8;
}
}
}
//Write code to hex buffer
for( auto c : base.imCommands )
{
if( c->type == IM_Command::Type::operation )
{//Is a regular command
base.hexBuffer.push_back( static_cast< u8 >( c->operation ) );
if( c->op1 != nullptr )
{
if( c->op1->type == IM_Operator::Type::constant )
{//Write constant
base.hexBuffer.push_back( c->op1->as<IM_Constant>()->data );
}
else if( c->op1->type == IM_Operator::Type::variable )
{//Write variable
auto op = c->op1->as<IM_Variable>();
if( op->model == MemModel::fast )
base.hexBuffer.push_back( static_cast< u8 >( op->address ) );
else if( op->model == MemModel::large )
{
base.hexBuffer.push_back( static_cast< u8 >( op->address << 8 ) );
base.hexBuffer.push_back( static_cast< u8 >( op->address ) );
}
else if( op->isOnStack() )
{
base.hexBuffer.push_back( static_cast< u8 >( op->address ) );
}
}
else if( c->op1->type == IM_Operator::Type::sfr )
{//Write sfr register
base.hexBuffer.push_back( c->op1->as<IM_SFR>()->address );
}
else if( c->op1->type == IM_Operator::Type::block )
{//Write the address of a block or put into waiting queue
auto op = c->op1->as<IM_Block>();
if( op->begin )
{//To block begin
if( op->symbol != "" )
{//Function-like
if( symbolAddresses.find( op->symbol ) == symbolAddresses.end() )
{//Nothing found
missingSymbols[op->symbol].push_back( static_cast< u16 >( base.hexBuffer.size() ) );
base.hexBuffer.push_back( 0 );
base.hexBuffer.push_back( 0 );
}
else
{//Block was already created.
base.hexBuffer.push_back( static_cast< u8 >( symbolAddresses[op->symbol] << 8 ) );
base.hexBuffer.push_back( static_cast< u8 >( symbolAddresses[op->symbol] ) );
}
}
else
{//Scope-like
if( blockBeginAddresses.find( op->blockID ) == blockBeginAddresses.end() )
{//Nothing found
missingBeginBlocks[op->blockID].push_back( static_cast< u16 >( base.hexBuffer.size() ) );
base.hexBuffer.push_back( 0 );
base.hexBuffer.push_back( 0 );
}
else
{//Block was already created.
base.hexBuffer.push_back( static_cast< u8 >( blockBeginAddresses[op->blockID] << 8 ) );
base.hexBuffer.push_back( static_cast< u8 >( blockBeginAddresses[op->blockID] ) );
}
}
}
else
{
if( op->finish )
{//Finish block
if( blockFinishAddresses.find( op->blockID ) == blockFinishAddresses.end() )
{//Nothing found
missingFinishBlocks[op->blockID].push_back( static_cast< u16 >( base.hexBuffer.size() ) );
base.hexBuffer.push_back( 0 );
base.hexBuffer.push_back( 0 );
}
else
{//Block was already created.
base.hexBuffer.push_back( static_cast< u8 >( blockFinishAddresses[op->blockID] << 8 ) );
base.hexBuffer.push_back( static_cast< u8 >( blockFinishAddresses[op->blockID] ) );
}
}
else
{//To block end
if( blockEndAddresses.find( op->blockID ) == blockEndAddresses.end() )
{//Nothing found
missingEndBlocks[op->blockID].push_back( static_cast< u16 >( base.hexBuffer.size() ) );
base.hexBuffer.push_back( 0 );
base.hexBuffer.push_back( 0 );
}
else
{//Block was already created.
base.hexBuffer.push_back( static_cast< u8 >( blockEndAddresses[op->blockID] << 8 ) );
base.hexBuffer.push_back( static_cast< u8 >( blockEndAddresses[op->blockID] ) );
}
}
}
}
else if( c->op1->type == IM_Operator::Type::condition )
{//Write the address of a condition jmp
auto op = c->op1->as<IM_Condition>();
if( op->isTrue )
{//To condition true position
if( conditionEnds_true.find( op->conditionID ) == conditionEnds_true.end() )
{//Nothing found
missingConditionEnds_true[op->conditionID] = static_cast< u16 >( base.hexBuffer.size() );
base.hexBuffer.push_back( 0 );
base.hexBuffer.push_back( 0 );
}
else
{//Block was already created.
base.hexBuffer.push_back( static_cast< u8 >( conditionEnds_true[op->conditionID] << 8 ) );
base.hexBuffer.push_back( static_cast< u8 >( conditionEnds_true[op->conditionID] ) );
}
}
else
{//To condition false position
if( conditionEnds_false.find( op->conditionID ) == conditionEnds_false.end() )
{//Nothing found
missingConditionEnds_false[op->conditionID] = static_cast< u16 >( base.hexBuffer.size() );
base.hexBuffer.push_back( 0 );
base.hexBuffer.push_back( 0 );
}
else
{//Block was already created.
base.hexBuffer.push_back( static_cast< u8 >( conditionEnds_false[op->conditionID] << 8 ) );
base.hexBuffer.push_back( static_cast< u8 >( conditionEnds_false[op->conditionID] ) );
}
}
}
}
if( c->op2 != nullptr )
{
if( c->op2->type == IM_Operator::Type::constant )
{//Write constant
base.hexBuffer.push_back( c->op2->as<IM_Constant>()->data );
}
else if( c->op2->type == IM_Operator::Type::variable )
{//Write variable
auto op = c->op2->as<IM_Variable>();
if( op->model == MemModel::fast )
base.hexBuffer.push_back( static_cast< u8 >( op->address ) );
else if( op->model == MemModel::large )
{
base.hexBuffer.push_back( static_cast< u8 >( op->address << 8 ) );
base.hexBuffer.push_back( static_cast< u8 >( op->address ) );
}
else if( op->isOnStack() )
{
base.hexBuffer.push_back( static_cast< u8 >( op->address ) );
}
}
else if( c->op2->type == IM_Operator::Type::sfr )
{//Write sfr register
base.hexBuffer.push_back( c->op2->as<IM_SFR>()->address );
}
else if( c->op2->type == IM_Operator::Type::block )
{//Write the address of a block or put into waiting queue
auto op = c->op2->as<IM_Block>();
if( op->begin )
{//To block begin
if( blockBeginAddresses.find( op->blockID ) == blockBeginAddresses.end() )
{//Nothing found
missingBeginBlocks[op->blockID].push_back( static_cast<u16>( base.hexBuffer.size() ) );
base.hexBuffer.push_back( 0 );
base.hexBuffer.push_back( 0 );
}
else
{//Block was already created.
base.hexBuffer.push_back( static_cast< u8 >( blockBeginAddresses[op->blockID] << 8 ) );
base.hexBuffer.push_back( static_cast< u8 >( blockBeginAddresses[op->blockID] ) );
}
}
else
{
if( op->finish )
{//Finish block
if( blockFinishAddresses.find( op->blockID ) == blockFinishAddresses.end() )
{//Nothing found
missingFinishBlocks[op->blockID].push_back( static_cast< u16 >( base.hexBuffer.size() ) );
base.hexBuffer.push_back( 0 );
base.hexBuffer.push_back( 0 );
}
else
{//Block was already created.
base.hexBuffer.push_back( static_cast< u8 >( blockFinishAddresses[op->blockID] << 8 ) );
base.hexBuffer.push_back( static_cast< u8 >( blockFinishAddresses[op->blockID] ) );
}
}
else
{//To block end
if( blockEndAddresses.find( op->blockID ) == blockEndAddresses.end() )
{//Nothing found
missingEndBlocks[op->blockID].push_back( static_cast< u16 >( base.hexBuffer.size() ) );
base.hexBuffer.push_back( 0 );
base.hexBuffer.push_back( 0 );
}
else
{//Block was already created.
base.hexBuffer.push_back( static_cast< u8 >( blockEndAddresses[op->blockID] << 8 ) );
base.hexBuffer.push_back( static_cast< u8 >( blockEndAddresses[op->blockID] ) );
}
}
}
}
else if( c->op2->type == IM_Operator::Type::condition )
{//Write the address of a condition jmp
if( !c->op2->as<IM_Condition>()->isTrue )
missingConditionEnds_false[c->op2->as<IM_Condition>()->conditionID] = static_cast< u16 >( base.hexBuffer.size() );
else missingConditionEnds_true[c->op2->as<IM_Condition>()->conditionID] = static_cast< u16 >( base.hexBuffer.size() );
base.hexBuffer.push_back( 0 );
base.hexBuffer.push_back( 0 );
}
}
}
else if( c->type == IM_Command::Type::blockBegin )
{//Is new block
u16 address = static_cast<u16>( base.hexBuffer.size() );
blockBeginAddresses[c->id] = address;
if( missingBeginBlocks.find( c->id ) != missingBeginBlocks.end() )
{
for( auto &a : missingBeginBlocks[c->id] )
{
base.hexBuffer[a] = static_cast< u8 >( address << 8 );
base.hexBuffer[a + 1] = static_cast< u8 >( address );
}
missingBeginBlocks.erase( c->id );
}
if( c->symbol != "" )
{
if( symbolAddresses.find( c->symbol ) != symbolAddresses.end() )
{//Already defined symbol found
generateNotification( NT::err_symbolIsAlreadyDefined, std::make_shared<String>( c->symbol ), -1, base.srcFile );
}
symbolAddresses[c->symbol] = address;
if( missingSymbols.find( c->symbol ) != missingSymbols.end() )
{
for( auto &a : missingSymbols[c->symbol] )
{
base.hexBuffer[a] = static_cast< u8 >( address << 8 );
base.hexBuffer[a + 1] = static_cast< u8 >( address );
}
missingSymbols.erase( c->symbol );
}
}
if( c->symbol == "main" )
{//Main function
base.hexBuffer[0x2E] = 0x12;//call_abs
base.hexBuffer[0x2F] = static_cast< u8 >( address << 8 );
base.hexBuffer[0x30] = static_cast< u8 >( address );
}
else if( c->symbol == "interrupt0" )
{//Interrupt 0 without EA disabled
base.hexBuffer[0x03] = 0x12;//call_abs
base.hexBuffer[0x04] = static_cast< u8 >( address << 8 );
base.hexBuffer[0x05] = static_cast< u8 >( address );
base.hexBuffer[0x06] = 0x32;//reti
}
else if( c->symbol == "interrupt0_ea" )
{//Interrupt 0 with EA disabled
base.hexBuffer[0x03] = 0xC2;//clr_bit
base.hexBuffer[0x04] = 0xAF;//EA
base.hexBuffer[0x05] = 0x12;//call_abs
base.hexBuffer[0x06] = static_cast< u8 >( address << 8 );
base.hexBuffer[0x07] = static_cast< u8 >( address );
base.hexBuffer[0x08] = 0xD2;//set_bit
base.hexBuffer[0x09] = 0xAF;//EA
base.hexBuffer[0x0A] = 0x32;//reti
}
else if( c->symbol == "timer0" )
{//Timer 0 without EA disabled
base.hexBuffer[0x0B] = 0x12;//call_abs
base.hexBuffer[0x0C] = static_cast< u8 >( address << 8 );
base.hexBuffer[0x0D] = static_cast< u8 >( address );
base.hexBuffer[0x0E] = 0x32;//reti
}
else if( c->symbol == "timer0_ea" )
{//Timer 0 with EA disabled
base.hexBuffer[0x0B] = 0xC2;//clr_bit
base.hexBuffer[0x0C] = 0xAF;//EA
base.hexBuffer[0x0D] = 0x12;//call_abs
base.hexBuffer[0x0E] = static_cast< u8 >( address << 8 );
base.hexBuffer[0x0F] = static_cast< u8 >( address );
base.hexBuffer[0x10] = 0xD2;//set_bit
base.hexBuffer[0x11] = 0xAF;//EA
base.hexBuffer[0x12] = 0x32;//reti
}
else if( c->symbol == "interrupt1" )
{//Interrupt 1 without EA disabled
base.hexBuffer[0x13] = 0x12;//call_abs
base.hexBuffer[0x14] = static_cast< u8 >( address << 8 );
base.hexBuffer[0x15] = static_cast< u8 >( address );
base.hexBuffer[0x16] = 0x32;//reti
}
else if( c->symbol == "interrupt1_ea" )
{//Interrupt 1 with EA disabled
base.hexBuffer[0x13] = 0xC2;//clr_bit
base.hexBuffer[0x14] = 0xAF;//EA
base.hexBuffer[0x15] = 0x12;//call_abs
base.hexBuffer[0x16] = static_cast< u8 >( address << 8 );
base.hexBuffer[0x17] = static_cast< u8 >( address );
base.hexBuffer[0x18] = 0xD2;//set_bit
base.hexBuffer[0x19] = 0xAF;//EA
base.hexBuffer[0x1A] = 0x32;//reti
}
else if( c->symbol == "timer1" )
{//Timer 1 without EA disabled
base.hexBuffer[0x1B] = 0x12;//call_abs
base.hexBuffer[0x1C] = static_cast< u8 >( address << 8 );
base.hexBuffer[0x1D] = static_cast< u8 >( address );
base.hexBuffer[0x1E] = 0x32;//reti
}
else if( c->symbol == "timer1_ea" )
{//Timer 1 with EA disabled
base.hexBuffer[0x1B] = 0xC2;//clr_bit
base.hexBuffer[0x1C] = 0xAF;//EA
base.hexBuffer[0x1D] = 0x12;//call_abs
base.hexBuffer[0x1E] = static_cast< u8 >( address << 8 );
base.hexBuffer[0x1F] = static_cast< u8 >( address );
base.hexBuffer[0x20] = 0xD2;//set_bit
base.hexBuffer[0x21] = 0xAF;//EA
base.hexBuffer[0x22] = 0x32;//reti
}
else if( c->symbol == "serialio" )
{//Serial I/O without EA disabled
base.hexBuffer[0x23] = 0x12;//call_abs
base.hexBuffer[0x24] = static_cast< u8 >( address << 8 );
base.hexBuffer[0x25] = static_cast< u8 >( address );
base.hexBuffer[0x26] = 0x32;//reti
}
else if( c->symbol == "serialio_ea" )
{//Serial I/O with EA disabled
base.hexBuffer[0x23] = 0xC2;//clr_bit
base.hexBuffer[0x24] = 0xAF;//EA
base.hexBuffer[0x25] = 0x12;//call_abs
base.hexBuffer[0x26] = static_cast< u8 >( address << 8 );
base.hexBuffer[0x27] = static_cast< u8 >( address );
base.hexBuffer[0x28] = 0xD2;//set_bit
base.hexBuffer[0x29] = 0xAF;//EA
base.hexBuffer[0x2A] = 0x32;//reti
}
}
else if( c->type == IM_Command::Type::blockEnd )
{//End of a block
u16 address = static_cast<u16>( base.hexBuffer.size() );
blockEndAddresses[c->id] = address;
if( missingEndBlocks.find( c->id ) != missingEndBlocks.end() )
{
for( auto &a : missingEndBlocks[c->id] )
{
base.hexBuffer[a] = static_cast< u8 >( address << 8 );
base.hexBuffer[a + 1] = static_cast< u8 >( address );
}
missingEndBlocks.erase( c->id );
}
}
else if( c->type == IM_Command::Type::blockFinish )
{//Finish the block
u16 address = static_cast<u16>( base.hexBuffer.size() );
blockFinishAddresses[c->id] = address;
if( missingFinishBlocks.find( c->id ) != missingFinishBlocks.end() )
{
for( auto &a : missingFinishBlocks[c->id] )
{
base.hexBuffer[a] = static_cast< u8 >( address << 8 );
base.hexBuffer[a + 1] = static_cast< u8 >( address );
}
missingFinishBlocks.erase( c->id );
}
}
else if( c->type == IM_Command::Type::conditionEnd )
{//End of a condition
u16 address = static_cast<u16>( base.hexBuffer.size() );
conditionEnds_true[c->id] = address;
if( missingConditionEnds_true.find( c->id ) != missingConditionEnds_true.end() )
{
auto a = missingConditionEnds_true[c->id];
base.hexBuffer[a] = static_cast< u8 >( address << 8 );
base.hexBuffer[a + 1] = static_cast< u8 >( address );
missingConditionEnds_true.erase( c->id );
}
address = static_cast< u16 >( base.hexBuffer.size() ) + 2;//Add two because of false jmp
conditionEnds_false[c->id] = address;
if( missingConditionEnds_false.find( c->id ) != missingConditionEnds_false.end() )
{
auto a = missingConditionEnds_false[c->id];
base.hexBuffer[a] = static_cast< u8 >( address << 8 );
base.hexBuffer[a + 1] = static_cast< u8 >( address );
missingConditionEnds_false.erase( c->id );
}
}
}
//Error reporting
if( !missingBeginBlocks.empty() || !missingEndBlocks.empty() || !missingFinishBlocks.empty() )
{
generateNotification( NT::err_internal_blockNotFound, base.srcFile );
}
if( !missingConditionEnds_true.empty() || !missingConditionEnds_false.empty() )
{
generateNotification( NT::err_internal_conditionalNotFound, base.srcFile );
}
if( !missingSymbols.empty() )
{
generateNotification( NT::err_functionDefinitionNotFound, base.srcFile );
}
if( symbolAddresses.find( "main" ) == symbolAddresses.end() )
{
generateNotification( NT::err_mainEntryPointNotFound, base.srcFile );
}
printToFile( base.hexBuffer, *base.destFile );
return ExecutionResult::success;
}
void Linker::printToFile( const std::vector<u8>& data, fs::path file )
{
String fileStr = "";
String out;
u16 startAddr = 0;
u16 checksum = 0;
for( size_t i = 0 ; i < data.size() ; i++ )
{
out += int_to_hex( data[i] );
checksum += data[i];
if( out.size() >= 32 )
{
fileStr += ":" + int_to_hex( static_cast< u8 >( out.size() / 2 ) ) + int_to_hex( startAddr ) + "00" + out + int_to_hex( static_cast< u8 >( ~( checksum % 256 )+1 ) ) + "\r\n";
checksum = 0;
startAddr += static_cast< u16 >( out.size() / 2 );
out = "";
}
}
if( out.size() > 0 )
{
fileStr += ":" + int_to_hex( static_cast< u8 >( out.size() / 2 ) ) + int_to_hex( startAddr ) + "00" + out + int_to_hex( static_cast< u8 >( ~( checksum % 256 )+1 ) ) + "\r\n";
}
fileStr += ":00000001FF";
std::ofstream filestream( file.string(), std::ios_base::binary );
if( filestream )
{
filestream << fileStr.c_str();
filestream.close();
}
}
}
|
apache-2.0
|
potnoddle/CSharpBrew.UsageReports
|
CSharpBrew.UsageReports/Properties/AssemblyInfo.cs
|
736
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("CSharpBrew.UsageReports")]
[assembly: AssemblyDescription("A Set of content types reports.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Paul Graham")]
[assembly: AssemblyProduct("CSharpBrew.UsageReports")]
[assembly: AssemblyCopyright("Copyright ? Paul Graham 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("9f3a4ec0-97a5-47d5-91b2-3e60843d0ff1")]
[assembly: AssemblyVersion("1.0.5.24")]
[assembly: AssemblyInformationalVersion("1.0.3.1")]
[assembly: InternalsVisibleTo("UsageReports.Tests")]
|
apache-2.0
|
akbooer/openLuup
|
tests/test_chdev.lua
|
7092
|
local t = require "tests.luaunit"
-- openLuup.chdev TESTS
luup = luup or {} -- luup is not really there.
--
-- DEVICE CREATE
--
local chdev = require "openLuup.chdev"
TestChdevDevice = {} -- low-level device tests
function TestChdevDevice:setUp ()
local devType = "urn:schemas-micasaverde-com:device:HomeAutomationGateway:1"
self.devType = devType
self.d0 = chdev.create {
devNo = 0,
device_type = devType,
statevariables =
{
{ service = "myServiceId", variable = "Variable", value = "Value" },
{ service = "anotherSvId", variable = "MoreVars", value = "pi" },
}
}
end
function TestChdevDevice:tearDown ()
self.d0 = nil
end
function TestChdevDevice:test_create ()
t.assertEquals (type (self.d0), "table")
t.assertEquals (self.d0.device_type, self.devType)
local d = self.d0
-- check the values
t.assertIsNumber (d.category_num)
t.assertIsString (d.description)
t.assertIsNumber (d.device_num_parent)
t.assertIsString (d.device_type)
t.assertIsBoolean (d.embedded)
t.assertIsBoolean (d.hidden)
t.assertIsString (d.id)
t.assertIsBoolean (d.invisible)
t.assertIsString (d.ip)
t.assertIsString (d.mac)
t.assertIsString (d.pass)
t.assertIsNumber (d.room_num)
t.assertIsNumber (d.subcategory_num)
t.assertIsString (d.udn)
t.assertIsString (d.user)
-- check all the methods are present:
t.assertIsFunction (d.attr_get)
t.assertIsFunction (d.attr_set)
t.assertIsFunction (d.call_action)
t.assertIsFunction (d.is_ready)
t.assertIsFunction (d.supports_service)
t.assertIsFunction (d.variable_set)
t.assertIsFunction (d.variable_get)
t.assertIsFunction (d.version_get)
-- check the tables
t.assertIsTable (d.attributes)
t.assertIsTable (d.services)
end
function TestChdevDevice:test_create_with_file ()
local x = chdev.create {
devNo = 42,
description = "Test",
upnp_file = "D_VeraBridge.xml", -- this file is preloaded in the vfs cache
};
t.assertIsTable (x)
t.assertEquals (x.description, "Test")
t.assertEquals (x.category_num, 1)
t.assertEquals (x.device_type, "VeraBridge")
end
function TestChdevDevice:test_created_get () -- see if the ones defined initially are there
-- "myServiceId,Variable=Value \n anotherSvId,MoreVars=pi"
local a = self.d0:variable_get ("myServiceId", "Variable")
local b = self.d0:variable_get ("anotherSvId", "MoreVars")
t.assertEquals (a.value, "Value")
t.assertEquals (b.value, "pi")
end
--
-- ATTRIBUTES
--
TestChdevAttributes = {}
function TestChdevAttributes:setUp ()
local devType = "urn:schemas-micasaverde-com:device:HomeAutomationGateway:1"
self.devType = devType
self.d0 = chdev.create {
devNo = 0,
device_type = devType
}
end
function TestChdevAttributes:tearDown ()
self.d0 = nil
end
function TestChdevAttributes:test_nil_get ()
t.assertEquals (type (self.d0), "table")
local a = self.d0:attr_get "foo"
t.assertIsNil (a)
end
function TestChdevAttributes:test_set_get ()
local val = "42"
local name = "attr1"
self.d0:attr_set (name, val)
local a = self.d0:attr_get (name)
t.assertEquals (a, val)
end
function TestChdevAttributes:test_multiple_set ()
local val1 = "42"
local val2 = "BBB"
local name1 = "attr1"
local name2 = "attr2"
local tab = {[name1] = val1, [name2] = val2}
self.d0:attr_set (tab)
local a1 = self.d0:attr_get (name1)
local a2 = self.d0:attr_get (name2)
t.assertEquals (a1, val1)
t.assertEquals (a2, val2)
end
--
-- VARIABLES
--
TestChdevVariables = {}
function TestChdevVariables:setUp ()
local devType = "urn:schemas-micasaverde-com:device:HomeAutomationGateway:1"
self.devType = devType
self.d0 = chdev.create {
devNo = 0,
device_type = devType
}
end
function TestChdevVariables:tearDown ()
self.d0 = nil
end
function TestChdevVariables:test_nil_get ()
local a = self.d0:variable_get ("srv", "name")
t.assertIsNil (a)
end
function TestChdevVariables:test_set_get ()
local val = "42"
local srv = "myService"
local name = "var1"
self.d0:variable_set (srv, name, val)
local a = self.d0:variable_get (srv, name)
t.assertEquals (a.value, val)
t.assertEquals (a.name, name)
t.assertEquals (a.old, "EMPTY")
t.assertEquals (a.srv, srv)
t.assertEquals (a.dev, 0)
t.assertIsNumber (a.version)
t.assertIsNumber (a.time)
end
--
-- OTHER METHODS
--
TestChdevOtherMethods = {}
function TestChdevOtherMethods:setUp ()
local devType = "urn:schemas-micasaverde-com:device:HomeAutomationGateway:1"
self.devType = devType
self.d0 = chdev.create {
devNo = 0,
device_type = devType
}
end
function TestChdevOtherMethods:tearDown ()
self.d0 = nil
end
function TestChdevOtherMethods:test_is_ready ()
t.assertTrue (self.d0:is_ready())
end
function TestChdevOtherMethods:test_supports_service ()
local srv = "aService"
local var = "varname"
self.d0:variable_set (srv, name, val)
t.assertTrue (self.d0:supports_service (srv))
t.assertFalse (self.d0:supports_service "foo")
end
function TestChdevOtherMethods:test_version ()
local v1 = self.d0:version_get ()
t.assertIsNumber (v1)
local val = "42"
local srv = "myService"
local name = "var1"
local var = self.d0:variable_set (srv, name, val) -- change a variable
local v2 = self.d0:version_get ()
t.assertTrue (v2 > v1) -- check version number increments
t.assertEquals (var.version, v2) -- and that variable has same version
end
function TestChdevOtherMethods:test_call_action ()
local srv = "testService"
self.d0.services[srv] = {
actions = {
action1 = {
run = function (lul_device, lul_settings)
return true
end,
},
action2 = {
job = function (lul_device, lul_settings, lul_job)
return 4, 0 -- job done status
end,
},
}
}
local error, error_msg, jobNo, return_arguments = self.d0:call_action (srv, "action1", {})
t.assertEquals (error, 0)
t.assertIsNumber (jobNo)
t.assertEquals (jobNo, 0) -- this is a <run> tag, no job
t.assertIsTable (return_arguments)
error, error_msg, jobNo, return_arguments = self.d0:call_action (srv, "action2", {})
t.assertEquals (error, 0)
t.assertIsNumber (jobNo)
t.assertNotEquals (jobNo, 0) -- this is a <job> tag, so job number returned
t.assertIsTable (return_arguments)
end
function TestChdevOtherMethods:test_missing_action ()
local result
local function missing ()
return {
run = function (lul_device, lul_settings)
result = lul_settings.value
return true
end
}
end
self.d0:action_callback (missing)
local error, error_msg, jobNo, return_arguments = self.d0:call_action ("garp", "foo", {value=12345})
t.assertEquals (error, 0)
t.assertIsTable (return_arguments)
t.assertEquals (result, 12345)
end
function TestChdevOtherMethods:test_ ()
end
--------------------
if not multifile then t.LuaUnit.run "-v" end
--------------------
|
apache-2.0
|
out4b/cdif
|
lib/cdif-proxy-server.js
|
1801
|
var cp = require('child_process');
var events = require('events');
var util = require('util');
var CdifUtil = require('./cdif-util');
var CdifError = require('./error').CdifError;
function ProxyServer() {
this.server = null;
this.proxyUrl = '';
// For now this is onvif only
this.streamUrl = '';
}
util.inherits(ProxyServer, events.EventEmitter);
ProxyServer.prototype.createServer = function(path, callback) {
try {
this.server = cp.fork(path);
this.server.on('message', function(msg) {
if (msg.port) {
var port = msg.port;
var protocol = CdifUtil.getHostProtocol();
var hostIp = CdifUtil.getHostIp();
this.proxyUrl = protocol + hostIp + ':' + port;
this.emit('proxyurl', this.proxyUrl);
} else if (msg.streamUrl) {
// For now this is onvif only
this.streamUrl = msg.streamUrl;
this.emit('streamurl', this.streamUrl);
} else if (msg.error) {
this.emit('error', msg.error);
}
}.bind(this));
} catch(e) {
if (typeof(callback) === 'function') {
callback(new CdifError('proxy server create failed: ' + e.message));
}
return;
}
if (typeof(callback) === 'function') {
callback(null);
}
};
ProxyServer.prototype.killServer = function(callback) {
if (this.server) {
this.server.kill('SIGTERM');
}
if (typeof(callback) === 'function') {
callback(null);
}
};
ProxyServer.prototype.setDeviceID = function(id) {
this.server.send({deviceID: id});
};
ProxyServer.prototype.setDeviceRootUrl = function(url) {
this.server.send({deviceRootUrl: url});
};
// For now this is onvif only
ProxyServer.prototype.setDeviceStreamUrl = function(url) {
this.server.send({deviceStreamUrl: url});
};
module.exports = ProxyServer;
|
apache-2.0
|
pavel-hp/transfer
|
src/main/java/com/khokhlov/rest/model/money/MoneyRo.java
|
584
|
package com.khokhlov.rest.model.money;
import com.khokhlov.rest.model.RestObject;
import java.math.BigDecimal;
/**
* @author Khokhlov Pavel
*/
public class MoneyRo implements RestObject {
private static final long serialVersionUID = 48996516982311687L;
private BigDecimal amount;
private CurrencyRo currency;
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public CurrencyRo getCurrency() {
return currency;
}
public void setCurrency(CurrencyRo currency) {
this.currency = currency;
}
}
|
apache-2.0
|
LeonoraG/s-case-core
|
eu.scasefp7.eclipse.core.ui/src/eu/scasefp7/eclipse/core/ui/wizards/ScaseProjectNewWizard.java
|
2650
|
package eu.scasefp7.eclipse.core.ui.wizards;
import java.net.URI;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExecutableExtension;
import org.eclipse.core.runtime.QualifiedName;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.dialogs.WizardNewProjectCreationPage;
import eu.scasefp7.eclipse.core.ui.preferences.PropertyWizardPage;
import eu.scasefp7.eclipse.core.ui.preferences.internal.DomainEntry;
public class ScaseProjectNewWizard extends Wizard implements INewWizard, IExecutableExtension {
private WizardNewProjectCreationPage _pageOne;
private PropertyWizardPage _pageTwo;
private static final String PAGE_NAME = "Custom Plug-in Project Wizard";
private static final String WIZARD_NAME = "New S-Case Project";
public ScaseProjectNewWizard() {
setWindowTitle(WIZARD_NAME);
}
@Override
public void init(IWorkbench workbench, IStructuredSelection selection) {
// TODO Auto-generated method stub
}
@Override
public void addPages() {
super.addPages();
_pageOne = new WizardNewProjectCreationPage(PAGE_NAME);
_pageOne.setTitle("Create a S-Case Project");
_pageOne.setDescription("Enter project name.");
_pageTwo = new PropertyWizardPage("S-Case project domain");
_pageTwo.setTitle("Select project domain");
addPage(_pageOne);
addPage(_pageTwo);
}
@Override
public boolean performFinish() {
String name = _pageOne.getProjectName();
URI location = null;
if (!_pageOne.useDefaults()) {
location = _pageOne.getLocationURI();
} // else location == null
IResource res = ScaseProjectSupport.createProject(name, location);
int k;
org.eclipse.swt.widgets.Label domainLabel = _pageTwo.getDomainLabel();
DomainEntry de = (DomainEntry) domainLabel.getData();
if (de == null)
k = -1;
else
k = de.getId();
try {
res.setPersistentProperty(new QualifiedName("", "eu.scasefp7.eclipse.core.projectDomain"), Integer.toString(k));
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
@Override
public void setInitializationData(IConfigurationElement config,
String propertyName, Object data) throws CoreException {
// TODO Auto-generated method stub
}
}
|
apache-2.0
|
klan1/k1.lib
|
src/_common/classes.php
|
1177
|
<?php
namespace k1lib;
class K1MAGIC {
/**
*
* @var string
*/
static public $value = "98148ef8279164d12b65ec8c9ba76c7e";
/**
*
* @return string
*/
public static function get_value() {
return self::$value;
}
/**
* Set the value, please use an MD5 value here to increase security.
* @param string
*/
public static function set_value($value) {
self::$value = $value;
}
}
class LANG {
/**
*
* @var string
*/
static $lang = "en";
/**
*
* @return string
*/
public static function get_lang() {
return self::$lang;
}
/**
*
* @param string $lang
*/
public static function set_lang($lang) {
self::$lang = $lang;
}
}
class PROFILER {
static private $init = 0;
static private $finish = 0;
static private $run_time = 0;
static function start() {
self::$init = microtime(TRUE);
}
static function end() {
self::$finish = microtime(TRUE);
self::$run_time = round((microtime(TRUE) - self::$init), 5);
return self::$run_time;
}
}
|
apache-2.0
|
googleads/google-ads-java
|
google-ads-stubs-v8/src/main/java/com/google/ads/googleads/v8/enums/DayOfWeekEnum.java
|
20922
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v8/enums/day_of_week.proto
package com.google.ads.googleads.v8.enums;
/**
* <pre>
* Container for enumeration of days of the week, e.g., "Monday".
* </pre>
*
* Protobuf type {@code google.ads.googleads.v8.enums.DayOfWeekEnum}
*/
public final class DayOfWeekEnum extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v8.enums.DayOfWeekEnum)
DayOfWeekEnumOrBuilder {
private static final long serialVersionUID = 0L;
// Use DayOfWeekEnum.newBuilder() to construct.
private DayOfWeekEnum(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private DayOfWeekEnum() {
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new DayOfWeekEnum();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private DayOfWeekEnum(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownField(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v8.enums.DayOfWeekProto.internal_static_google_ads_googleads_v8_enums_DayOfWeekEnum_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v8.enums.DayOfWeekProto.internal_static_google_ads_googleads_v8_enums_DayOfWeekEnum_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v8.enums.DayOfWeekEnum.class, com.google.ads.googleads.v8.enums.DayOfWeekEnum.Builder.class);
}
/**
* <pre>
* Enumerates days of the week, e.g., "Monday".
* </pre>
*
* Protobuf enum {@code google.ads.googleads.v8.enums.DayOfWeekEnum.DayOfWeek}
*/
public enum DayOfWeek
implements com.google.protobuf.ProtocolMessageEnum {
/**
* <pre>
* Not specified.
* </pre>
*
* <code>UNSPECIFIED = 0;</code>
*/
UNSPECIFIED(0),
/**
* <pre>
* The value is unknown in this version.
* </pre>
*
* <code>UNKNOWN = 1;</code>
*/
UNKNOWN(1),
/**
* <pre>
* Monday.
* </pre>
*
* <code>MONDAY = 2;</code>
*/
MONDAY(2),
/**
* <pre>
* Tuesday.
* </pre>
*
* <code>TUESDAY = 3;</code>
*/
TUESDAY(3),
/**
* <pre>
* Wednesday.
* </pre>
*
* <code>WEDNESDAY = 4;</code>
*/
WEDNESDAY(4),
/**
* <pre>
* Thursday.
* </pre>
*
* <code>THURSDAY = 5;</code>
*/
THURSDAY(5),
/**
* <pre>
* Friday.
* </pre>
*
* <code>FRIDAY = 6;</code>
*/
FRIDAY(6),
/**
* <pre>
* Saturday.
* </pre>
*
* <code>SATURDAY = 7;</code>
*/
SATURDAY(7),
/**
* <pre>
* Sunday.
* </pre>
*
* <code>SUNDAY = 8;</code>
*/
SUNDAY(8),
UNRECOGNIZED(-1),
;
/**
* <pre>
* Not specified.
* </pre>
*
* <code>UNSPECIFIED = 0;</code>
*/
public static final int UNSPECIFIED_VALUE = 0;
/**
* <pre>
* The value is unknown in this version.
* </pre>
*
* <code>UNKNOWN = 1;</code>
*/
public static final int UNKNOWN_VALUE = 1;
/**
* <pre>
* Monday.
* </pre>
*
* <code>MONDAY = 2;</code>
*/
public static final int MONDAY_VALUE = 2;
/**
* <pre>
* Tuesday.
* </pre>
*
* <code>TUESDAY = 3;</code>
*/
public static final int TUESDAY_VALUE = 3;
/**
* <pre>
* Wednesday.
* </pre>
*
* <code>WEDNESDAY = 4;</code>
*/
public static final int WEDNESDAY_VALUE = 4;
/**
* <pre>
* Thursday.
* </pre>
*
* <code>THURSDAY = 5;</code>
*/
public static final int THURSDAY_VALUE = 5;
/**
* <pre>
* Friday.
* </pre>
*
* <code>FRIDAY = 6;</code>
*/
public static final int FRIDAY_VALUE = 6;
/**
* <pre>
* Saturday.
* </pre>
*
* <code>SATURDAY = 7;</code>
*/
public static final int SATURDAY_VALUE = 7;
/**
* <pre>
* Sunday.
* </pre>
*
* <code>SUNDAY = 8;</code>
*/
public static final int SUNDAY_VALUE = 8;
public final int getNumber() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalArgumentException(
"Can't get the number of an unknown enum value.");
}
return value;
}
/**
* @param value The numeric wire value of the corresponding enum entry.
* @return The enum associated with the given numeric wire value.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static DayOfWeek valueOf(int value) {
return forNumber(value);
}
/**
* @param value The numeric wire value of the corresponding enum entry.
* @return The enum associated with the given numeric wire value.
*/
public static DayOfWeek forNumber(int value) {
switch (value) {
case 0: return UNSPECIFIED;
case 1: return UNKNOWN;
case 2: return MONDAY;
case 3: return TUESDAY;
case 4: return WEDNESDAY;
case 5: return THURSDAY;
case 6: return FRIDAY;
case 7: return SATURDAY;
case 8: return SUNDAY;
default: return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<DayOfWeek>
internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<
DayOfWeek> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<DayOfWeek>() {
public DayOfWeek findValueByNumber(int number) {
return DayOfWeek.forNumber(number);
}
};
public final com.google.protobuf.Descriptors.EnumValueDescriptor
getValueDescriptor() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalStateException(
"Can't get the descriptor of an unrecognized enum value.");
}
return getDescriptor().getValues().get(ordinal());
}
public final com.google.protobuf.Descriptors.EnumDescriptor
getDescriptorForType() {
return getDescriptor();
}
public static final com.google.protobuf.Descriptors.EnumDescriptor
getDescriptor() {
return com.google.ads.googleads.v8.enums.DayOfWeekEnum.getDescriptor().getEnumTypes().get(0);
}
private static final DayOfWeek[] VALUES = values();
public static DayOfWeek valueOf(
com.google.protobuf.Descriptors.EnumValueDescriptor desc) {
if (desc.getType() != getDescriptor()) {
throw new java.lang.IllegalArgumentException(
"EnumValueDescriptor is not for this type.");
}
if (desc.getIndex() == -1) {
return UNRECOGNIZED;
}
return VALUES[desc.getIndex()];
}
private final int value;
private DayOfWeek(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:google.ads.googleads.v8.enums.DayOfWeekEnum.DayOfWeek)
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.ads.googleads.v8.enums.DayOfWeekEnum)) {
return super.equals(obj);
}
com.google.ads.googleads.v8.enums.DayOfWeekEnum other = (com.google.ads.googleads.v8.enums.DayOfWeekEnum) obj;
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v8.enums.DayOfWeekEnum parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v8.enums.DayOfWeekEnum parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v8.enums.DayOfWeekEnum parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v8.enums.DayOfWeekEnum parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v8.enums.DayOfWeekEnum parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v8.enums.DayOfWeekEnum parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v8.enums.DayOfWeekEnum parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v8.enums.DayOfWeekEnum parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v8.enums.DayOfWeekEnum parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v8.enums.DayOfWeekEnum parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v8.enums.DayOfWeekEnum parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v8.enums.DayOfWeekEnum parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.ads.googleads.v8.enums.DayOfWeekEnum prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* Container for enumeration of days of the week, e.g., "Monday".
* </pre>
*
* Protobuf type {@code google.ads.googleads.v8.enums.DayOfWeekEnum}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v8.enums.DayOfWeekEnum)
com.google.ads.googleads.v8.enums.DayOfWeekEnumOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v8.enums.DayOfWeekProto.internal_static_google_ads_googleads_v8_enums_DayOfWeekEnum_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v8.enums.DayOfWeekProto.internal_static_google_ads_googleads_v8_enums_DayOfWeekEnum_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v8.enums.DayOfWeekEnum.class, com.google.ads.googleads.v8.enums.DayOfWeekEnum.Builder.class);
}
// Construct using com.google.ads.googleads.v8.enums.DayOfWeekEnum.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
@java.lang.Override
public Builder clear() {
super.clear();
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v8.enums.DayOfWeekProto.internal_static_google_ads_googleads_v8_enums_DayOfWeekEnum_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v8.enums.DayOfWeekEnum getDefaultInstanceForType() {
return com.google.ads.googleads.v8.enums.DayOfWeekEnum.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v8.enums.DayOfWeekEnum build() {
com.google.ads.googleads.v8.enums.DayOfWeekEnum result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v8.enums.DayOfWeekEnum buildPartial() {
com.google.ads.googleads.v8.enums.DayOfWeekEnum result = new com.google.ads.googleads.v8.enums.DayOfWeekEnum(this);
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.ads.googleads.v8.enums.DayOfWeekEnum) {
return mergeFrom((com.google.ads.googleads.v8.enums.DayOfWeekEnum)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v8.enums.DayOfWeekEnum other) {
if (other == com.google.ads.googleads.v8.enums.DayOfWeekEnum.getDefaultInstance()) return this;
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.ads.googleads.v8.enums.DayOfWeekEnum parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.ads.googleads.v8.enums.DayOfWeekEnum) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.ads.googleads.v8.enums.DayOfWeekEnum)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v8.enums.DayOfWeekEnum)
private static final com.google.ads.googleads.v8.enums.DayOfWeekEnum DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v8.enums.DayOfWeekEnum();
}
public static com.google.ads.googleads.v8.enums.DayOfWeekEnum getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<DayOfWeekEnum>
PARSER = new com.google.protobuf.AbstractParser<DayOfWeekEnum>() {
@java.lang.Override
public DayOfWeekEnum parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new DayOfWeekEnum(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<DayOfWeekEnum> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<DayOfWeekEnum> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v8.enums.DayOfWeekEnum getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache-2.0
|
devzwy/KUtils
|
kutils/src/main/java/com/zwy/kutils/widget/loadingdialog/DialogUIUtils.java
|
27424
|
package com.zwy.kutils.widget.loadingdialog;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatDialog;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;
import com.zwy.kutils.R;
import com.zwy.kutils.widget.loadingdialog.alertdialog.ActionSheetDialog;
import com.zwy.kutils.widget.loadingdialog.alertdialog.AlertDialog;
import com.zwy.kutils.widget.loadingdialog.bean.BuildBean;
import com.zwy.kutils.widget.loadingdialog.bean.TieBean;
import com.zwy.kutils.widget.loadingdialog.listener.DialogAssigner;
import com.zwy.kutils.widget.loadingdialog.listener.DialogUIDateTimeSaveListener;
import com.zwy.kutils.widget.loadingdialog.listener.DialogUIItemListener;
import com.zwy.kutils.widget.loadingdialog.listener.DialogUIListener;
import com.zwy.kutils.widget.loadingdialog.utils.ToolUtils;
import java.util.List;
public class DialogUIUtils {
/**
* 全局上下文
*/
public static Context appContext;
/**
* 如果有使用到showTost...相关的方法使用之前需要初始化该方法
*/
public static void init(Context appContext) {
DialogUIUtils.appContext = appContext;
}
/**
* 关闭弹出框
*/
public static void dismiss(DialogInterface... dialogs) {
if (dialogs != null && dialogs.length > 0) {
for (DialogInterface dialog : dialogs) {
if (dialog instanceof Dialog) {
Dialog dialog1 = (Dialog) dialog;
if (dialog1.isShowing()) {
dialog1.dismiss();
}
} else if (dialog instanceof AppCompatDialog) {
AppCompatDialog dialog2 = (AppCompatDialog) dialog;
if (dialog2.isShowing()) {
dialog2.dismiss();
}
}
}
}
}
/**
* 关闭弹出框
*/
public static void dismiss(BuildBean buildBean) {
if (buildBean != null) {
if (buildBean.dialog != null && buildBean.dialog.isShowing()) {
buildBean.dialog.dismiss();
}
if (buildBean.alertDialog != null && buildBean.alertDialog.isShowing()) {
buildBean.alertDialog.dismiss();
}
}
}
/**
* 关闭弹出框
*/
public static void dismiss(Dialog dialog) {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
/***
* 弹出日期选择器
*
* @param context 上下文
* @param gravity 显示位置
* @param dateTitle 显示标题
* @param date 当前选择日志
* @param dateType 显示日期样式DateSelectorWheelView.TYPE_YYYYMMDD TYPE_YYYYMMDDHHMM TYPE_YYYYMMDDHHMMSS
* @param tag view标记tag 一个页面多个日期选择器是可以加标记区分
* @param listener
* @return
*/
public static BuildBean showDatePick(Context context, int gravity, String dateTitle, long date, int dateType, int tag, DialogUIDateTimeSaveListener listener) {
return DialogAssigner.getInstance().assignDatePick(context, gravity, dateTitle, date, dateType, tag, listener);
}
/**
* 弹出toast 默认可取消可点击
*
* @param context 上下文
* @param msg 提示文本
*/
public static BuildBean showDialogTie(Context context, CharSequence msg) {
return showDialogTie(context, msg, true, true);
}
/**
* 弹出toast
*
* @param context 上下文
* @param msg 提示文本
* @param cancleable true为可以取消false为不可取消
* @param outsideTouchable true为可以点击空白区域false为不可点击
*/
public static BuildBean showDialogTie(Context context, CharSequence msg, boolean cancleable, boolean outsideTouchable) {
return DialogAssigner.getInstance().assignAlert(context, "", msg, "", "", "", "", true, cancleable, outsideTouchable, null);
}
/**
* 横向加载框 默认白色背景可取消可点击
*
* @param context 上下文
* @param msg 提示文本
*/
public static BuildBean showLoadingHorizontal(Context context, CharSequence msg) {
return showLoadingHorizontal(context, msg, true, true, true);
}
/**
* 横向加载框 默认可取消可点击
*
* @param context 上下文
* @param msg 提示文本
* @param isWhiteBg true为白色背景false为灰色背景
*/
public static BuildBean showLoadingHorizontal(Context context, CharSequence msg, boolean isWhiteBg) {
return showLoadingHorizontal(context, msg, true, true, isWhiteBg);
}
/**
* 横向加载框
*
* @param context 上下文
* @param msg 提示文本
* @param cancleable true为可以取消false为不可取消
* @param outsideTouchable true为可以点击空白区域false为不可点击
* @param isWhiteBg true为白色背景false为灰色背景
*/
public static BuildBean showLoadingHorizontal(Context context, CharSequence msg, boolean cancleable, boolean outsideTouchable, boolean isWhiteBg) {
return DialogAssigner.getInstance().assignLoadingHorizontal(context, msg, cancleable, outsideTouchable, isWhiteBg);
}
/**
* md风格横向加载框 默认白色背景可取消可点击
*
* @param context 上下文
* @param msg 提示文本
*/
public static BuildBean showMdLoadingHorizontal(Context context, CharSequence msg) {
return showMdLoadingHorizontal(context, msg, true, true, true);
}
/**
* md风格横向加载框 默认可取消可点击
*
* @param context 上下文
* @param msg 提示文本
* @param isWhiteBg true为白色背景false为灰色背景
*/
public static BuildBean showMdLoadingHorizontal(Context context, CharSequence msg, boolean isWhiteBg) {
return showMdLoadingHorizontal(context, msg, true, true, isWhiteBg);
}
/**
* md风格横向加载框
*
* @param context 上下文
* @param msg 提示文本
* @param cancleable true为可以取消false为不可取消
* @param outsideTouchable true为可以点击空白区域false为不可点击
* @param isWhiteBg true为白色背景false为灰色背景
*/
public static BuildBean showMdLoadingHorizontal(Context context, CharSequence msg, boolean cancleable, boolean outsideTouchable, boolean isWhiteBg) {
return DialogAssigner.getInstance().assignMdLoadingHorizontal(context, msg, cancleable, outsideTouchable, isWhiteBg);
}
/**
* 竖向加载框 默认白色背景可取消可点击
*
* @param context 上下文
* @param msg 提示文本
*/
public static BuildBean showLoadingVertical(Context context, CharSequence msg) {
return showLoadingVertical(context, msg, true, true, true);
}
/**
* 竖向加载框 默认可取消可点击
*
* @param context 上下文
* @param msg 提示文本
* @param isWhiteBg true为白色背景false为灰色背景
*/
public static BuildBean showLoadingVertical(Context context, CharSequence msg, boolean isWhiteBg) {
return showLoadingVertical(context, msg, true, true, isWhiteBg);
}
/**
* 竖向加载框
*
* @param context 上下文
* @param msg 提示文本
* @param cancleable true为可以取消false为不可取消
* @param outsideTouchable true为可以点击空白区域false为不可点击
* @param isWhiteBg true为白色背景false为灰色背景
*/
public static BuildBean showLoadingVertical(Context context, CharSequence msg, boolean cancleable, boolean outsideTouchable, boolean isWhiteBg) {
return DialogAssigner.getInstance().assignLoadingVertical(context, msg, cancleable, outsideTouchable, isWhiteBg);
}
/**
* md风格竖向加载框 默认白色背景可取消可点击
*
* @param context 上下文
* @param msg 提示文本
*/
public static BuildBean showMdLoadingVertical(Context context, CharSequence msg) {
return showMdLoadingVertical(context, msg, true, true, true);
}
/**
* md风格竖向加载框 默认可取消可点击
*
* @param context 上下文
* @param msg 提示文本
* @param isWhiteBg true为白色背景false为灰色背景
*/
public static BuildBean showMdLoadingVertical(Context context, CharSequence msg, boolean isWhiteBg) {
return showMdLoadingVertical(context, msg, true, true, isWhiteBg);
}
/**
* md风格竖向加载框
*
* @param context 上下文
* @param msg 提示文本
* @param cancleable true为可以取消false为不可取消
* @param outsideTouchable true为可以点击空白区域false为不可点击
* @param isWhiteBg true为白色背景false为灰色背景
*/
public static BuildBean showMdLoadingVertical(Context context, CharSequence msg, boolean cancleable, boolean outsideTouchable, boolean isWhiteBg) {
return DialogAssigner.getInstance().assignMdLoadingVertical(context, msg, cancleable, outsideTouchable, isWhiteBg);
}
/***
* md风格弹出框 默认可取消可点击
*
* @param activity 所在activity
* @param title 标题 不传则无标题
* @param msg 消息
* @param listener 事件监听
* @return
*/
public static BuildBean showMdAlert(Activity activity, CharSequence title, CharSequence msg, DialogUIListener listener) {
return showMdAlert(activity, title, msg, true, true, listener);
}
/***
* md风格弹出框
*
* @param activity 所在activity
* @param title 标题 不传则无标题
* @param msg 消息
* @param cancleable true为可以取消false为不可取消
* @param outsideTouchable true为可以点击空白区域false为不可点击
* @param listener 事件监听
* @return
*/
public static BuildBean showMdAlert(Activity activity, CharSequence title, CharSequence msg, boolean cancleable, boolean outsideTouchable, DialogUIListener listener) {
return DialogAssigner.getInstance().assignMdAlert(activity, title, msg, cancleable, outsideTouchable, listener);
}
/**
* md风格多选框 默认可取消可点击
*
* @param activity 所在activity
* @param title 标题 不传则无标题
* @param words 消息数组
* @param checkedItems 默认选中项
* @param listener 事件监听
*/
public static BuildBean showMdMultiChoose(Activity activity, CharSequence title, CharSequence[] words, boolean[] checkedItems, DialogUIListener listener) {
return showMdMultiChoose(activity, title, words, checkedItems, true, true, listener);
}
/***
* md风格多选框
*
* @param activity 所在activity
* @param title 标题 不传则无标题
* @param words 消息数组
* @param checkedItems 默认选中项
* @param cancleable true为可以取消false为不可取消
* @param outsideTouchable true为可以点击空白区域false为不可点击
* @param listener 事件监听
* @return
*/
public static BuildBean showMdMultiChoose(Activity activity, CharSequence title, CharSequence[] words, boolean[] checkedItems, boolean cancleable, boolean outsideTouchable, DialogUIListener listener) {
return DialogAssigner.getInstance().assignMdMultiChoose(activity, title, words, checkedItems, cancleable, outsideTouchable, listener);
}
/**
* 单选框 默认可取消可点击
*
* @param activity 所在activity
* @param title 标题 不传则无标题
* @param defaultChosen 默认选中项
* @param words 消息数组
* @param listener 事件监听
*/
public static BuildBean showSingleChoose(Activity activity, CharSequence title, int defaultChosen, CharSequence[] words, DialogUIItemListener listener) {
return showSingleChoose(activity, title, defaultChosen, words, true, true, listener);
}
/**
* 单选框
*
* @param activity 所在activity
* @param title 标题 不传则无标题
* @param defaultChosen 默认选中项
* @param words 消息数组
* @param cancleable true为可以取消false为不可取消
* @param outsideTouchable true为可以点击空白区域false为不可点击
* @param listener 事件监听
*/
public static BuildBean showSingleChoose(Activity activity, CharSequence title, int defaultChosen, CharSequence[] words, boolean cancleable, boolean outsideTouchable, DialogUIItemListener listener) {
return DialogAssigner.getInstance().assignSingleChoose(activity, title, defaultChosen, words, cancleable, outsideTouchable, listener);
}
/**
* 提示弹出框 默认可取消可点击
*
* @param activity 所在activity
* @param title 标题 不传则无标题
* @param listener 事件监听
*/
public static BuildBean showAlert(Activity activity, CharSequence title, CharSequence msg, CharSequence hint1, CharSequence hint2,
CharSequence firstTxt, CharSequence secondTxt, boolean isVertical, DialogUIListener listener) {
return showAlert(activity, title, msg, hint1, hint2, firstTxt, secondTxt, isVertical, true, true, listener);
}
/**
* 提示弹出框
*
* @param activity 所在activity
* @param title 标题 不传则无标题
* @param cancleable true为可以取消false为不可取消
* @param outsideTouchable true为可以点击空白区域false为不可点击
* @param listener 事件监听
*/
public static BuildBean showAlert(Activity activity, CharSequence title, CharSequence msg, CharSequence hint1, CharSequence hint2,
CharSequence firstTxt, CharSequence secondTxt, boolean isVertical, boolean cancleable, boolean outsideTouchable, DialogUIListener listener) {
return DialogAssigner.getInstance().assignAlert(activity, title, msg, hint1, hint2, firstTxt, secondTxt, isVertical, cancleable, outsideTouchable, listener);
}
/**
* 中间弹出列表 默认可取消可点击
*
* @param context 上下文
* @param datas 素组集合
* @param listener 事件监听
* @return
*/
public static BuildBean showCenterSheet(Context context, List<TieBean> datas, DialogUIItemListener listener) {
return showCenterSheet(context, datas, true, true, listener);
}
/***
* 中间弹出列表
*
* @param context 上下文
* @param datas 素组集合
* @param cancleable true为可以取消false为不可取消
* @param outsideTouchable true为可以点击空白区域false为不可点击
* @param listener 事件监听
* @return
*/
public static BuildBean showCenterSheet(Context context, List<TieBean> datas, boolean cancleable, boolean outsideTouchable, DialogUIItemListener listener) {
return DialogAssigner.getInstance().assignCenterSheet(context, datas, cancleable, outsideTouchable, listener);
}
/**
* md风格竖向底部弹出列表 默认可取消可点击
*
* @param context 上下文
* @param title 标题
* @param datas 集合需要BottomSheetBean对象
* @param bottomTxt 底部item文本
* @param listener 事件监听
* @return
*/
public static BuildBean showMdBottomSheet(Context context, boolean isVertical, CharSequence title, List<TieBean> datas, CharSequence bottomTxt, int columnsNum, DialogUIItemListener listener) {
return showMdBottomSheet(context, isVertical, title, datas, bottomTxt, columnsNum, true, true, listener);
}
/***
* md风格弹出列表
*
* @param context 上下文
* @param title 标题
* @param datas 集合需要BottomSheetBean对象
* @param bottomTxt 底部item文本
* @param cancleable true为可以取消false为不可取消
* @param outsideTouchable true为可以点击空白区域false为不可点击
* @param listener 事件监听
* @return
*/
public static BuildBean showMdBottomSheet(Context context, boolean isVertical, CharSequence title, List<TieBean> datas, CharSequence bottomTxt, int columnsNum, boolean cancleable, boolean outsideTouchable, DialogUIItemListener listener) {
return DialogAssigner.getInstance().assignMdBottomSheet(context, isVertical, title, datas, bottomTxt, columnsNum, cancleable, outsideTouchable, listener);
}
/**
* 自定义弹出框 默认居中可取消可点击
*
* @param context 上下问
* @param contentView 自定义view
* @return
*/
public static BuildBean showCustomAlert(Context context, View contentView) {
return showCustomAlert(context, contentView, Gravity.CENTER, true, true);
}
/**
* 自定义弹出框 默认可取消可点击
*
* @param context 上下文
* @param contentView 自定义view
* @param gravity 显示window的位置例如Gravity.center
* @return
*/
public static BuildBean showCustomAlert(Context context, View contentView, int gravity) {
return showCustomAlert(context, contentView, gravity, true, true);
}
/***
* 自定义弹出框
*
* @param context 上下文
* @param contentView 自定义view
* @param gravity 显示window的位置例如Gravity.center
* @param cancleable true为可以取消false为不可取消
* @param outsideTouchable true为可以点击空白区域false为不可点击
* @return
*/
public static BuildBean showCustomAlert(Context context, View contentView, int gravity, boolean cancleable, boolean outsideTouchable) {
return DialogAssigner.getInstance().assignCustomAlert(context, contentView, gravity, cancleable, outsideTouchable);
}
/**
* 自定义底部弹出框 默认居中可取消可点击
*
* @param context 上下问
* @param contentView 自定义view
* @return
*/
public static BuildBean showCustomBottomAlert(Context context, View contentView) {
return showCustomBottomAlert(context, contentView, true, true);
}
/***
* 自定义底部弹出框
*
* @param context 上下文
* @param contentView 自定义view
* @param cancleable true为可以取消false为不可取消
* @param outsideTouchable true为可以点击空白区域false为不可点击
* @return
*/
public static BuildBean showCustomBottomAlert(Context context, View contentView, boolean cancleable, boolean outsideTouchable) {
return DialogAssigner.getInstance().assignCustomBottomAlert(context, contentView, cancleable, outsideTouchable);
}
/**
* 短时间中下位置显示。线程安全,可以在非UI线程调用。
*/
public static void showToast(final int resId) {
showToast(ToolUtils.getString(appContext, resId));
}
/**
* 短时间中下位置显示。
*/
public static void showToast(final String str) {
showToast(str, Toast.LENGTH_SHORT, Gravity.BOTTOM);
}
/**
* 长时间中下位置显示。
*/
public static void showToastLong(final int resId) {
showToastLong(ToolUtils.getString(appContext, resId));
}
/**
* 长时间中下位置显示。
*/
public static void showToastLong(final String str) {
showToast(str, Toast.LENGTH_LONG, Gravity.BOTTOM);
}
/**
* 短时间居中位置显示。
*/
public static void showToastCenter(final int resId) {
showToastCenter(ToolUtils.getString(appContext, resId));
}
/**
* 短时间居中位置显示。
*/
public static void showToastCenter(final String str) {
showToast(str, Toast.LENGTH_SHORT, Gravity.CENTER);
}
/**
* 长时间居中位置显示。
*/
public static void showToastCenterLong(final int resId) {
showToastCenterLong(ToolUtils.getString(appContext, resId));
}
/**
* 长时间居中位置显示。
*/
public static void showToastCenterLong(final String str) {
showToast(str, Toast.LENGTH_LONG, Gravity.CENTER);
}
/**
* 短时间居中位置显示。
*/
public static void showToastTop(final int resId) {
showToastTop(ToolUtils.getString(appContext, resId));
}
/**
* 短时间居中位置显示。
*/
public static void showToastTop(final String str) {
showToast(str, Toast.LENGTH_SHORT, Gravity.TOP);
}
/**
* 长时间居中位置显示。
*/
public static void showToastTopLong(final int resId) {
showToastTopLong(ToolUtils.getString(appContext, resId));
}
/**
* 长时间居中位置显示。
*/
public static void showToastTopLong(final String str) {
showToast(str, Toast.LENGTH_LONG, Gravity.TOP);
}
/**
* 只定义一个Toast
*/
private static Toast mToast;
private static Toast mToastTop;
private static Toast mToastCenter;
private static Toast mToastBottom;
/**
* 对toast的简易封装。线程不安全,不可以在非UI线程调用。
*/
private static void showToast(String str, int showTime, int gravity) {
if (appContext == null) {
throw new RuntimeException("DialogUIUtils not initialized!");
}
if (gravity == Gravity.TOP) {
if (mToastTop == null) {
mToastTop = Toast.makeText(appContext, str, showTime);
LayoutInflater inflate = (LayoutInflater)
appContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflate.inflate(R.layout.dialogui_toast, null);
mToastTop.setView(view);
mToastTop.setGravity(gravity, 0, appContext.getResources().getDimensionPixelSize(R.dimen.dialogui_toast_margin));
}
mToast = mToastTop;
mToast.setText(str);
mToast.show();
} else if (gravity == Gravity.CENTER) {
if (mToastCenter == null) {
mToastCenter = Toast.makeText(appContext, str, showTime);
LayoutInflater inflate = (LayoutInflater)
appContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflate.inflate(R.layout.dialogui_toast, null);
mToastCenter.setView(view);
mToastCenter.setGravity(gravity, 0, 0);
}
mToast = mToastCenter;
mToast.setText(str);
mToast.show();
} else if (gravity == Gravity.BOTTOM) {
if (mToastBottom == null) {
mToastBottom = Toast.makeText(appContext, str, showTime);
LayoutInflater inflate = (LayoutInflater)
appContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflate.inflate(R.layout.dialogui_toast, null);
mToastBottom.setView(view);
mToastBottom.setGravity(gravity, 0, appContext.getResources().getDimensionPixelSize(R.dimen.dialogui_toast_margin));
}
mToast = mToastBottom;
mToast.setText(str);
mToast.show();
}
}
/**
* 展示一个从下方弹出图库选择提示框
*
* @param activity
* @param onImagesListListenr 图库按钮监听
*/
public static void showBottomSheetDialog_SeletorImages(Activity activity,
ActionSheetDialog.OnSheetItemClickListener onImagesListListenr) {
new ActionSheetDialog(activity)
.builder()
.setCancelable(true)
.setCanceledOnTouchOutside(true)
.setTitle("请选择图片来源")
.addSheetItem("图库", ActionSheetDialog.SheetItemColor.Blue, onImagesListListenr)
// .addSheetItem("相机", ActionSheetDialog.SheetItemColor.Blue, onCameraListener)
.show();
}
/**
* 展示一个从下方弹出的带红色删除item和取消按钮的sheet对话框.仿iOS
*
* @param activity 必须为activity
* @param title 标题
* @param onDeleteButtonTouchListener 删除按钮监听器
* @return
*/
public static void showIsDeleteSheetDialog(Activity activity, String title, ActionSheetDialog.OnSheetItemClickListener onDeleteButtonTouchListener) {
new ActionSheetDialog(activity)
.builder()
.setCancelable(false)
.setCanceledOnTouchOutside(false)
.setTitle(title)
.addSheetItem("删除", ActionSheetDialog.SheetItemColor.Red, onDeleteButtonTouchListener).show();
}
/**
* 展示一个仅有一个按钮的对话框 仿iOS中间弹出
*
* @param activity 必须为activity
* @param msg 提示的内容
* @param bt_msg 按钮的文字
* @param onClickListener 点击事件监听
*/
public static void showOnlyOneButtonAlertDialog(Activity activity, String msg, String bt_msg, View.OnClickListener onClickListener) {
new AlertDialog(activity).builder().setMsg(msg)
.setNegativeButton(bt_msg, onClickListener).show();
}
/**
* 展示一个有两个按钮的对话框 仿iOS中间弹出
*
* @param activity 必须为activity
* @param title 标题
* @param msg 提示语
* @param bt_msg_left 左边按钮的文字
* @param listener_left 左边按钮点击事件
* @param bt_msg_right 右边按钮文字
* @param listener_right 右边按钮点击事件
* @param cancelable 点击空白处取消?
*/
public static void showTwoButtonAlertDialog(Activity activity, String title, String msg, String bt_msg_left, View.OnClickListener listener_left, String bt_msg_right, View.OnClickListener listener_right, boolean cancelable) {
new AlertDialog(activity).builder().setTitle(title)
.setMsg(msg)
.setPositiveButton(bt_msg_right, listener_right).setNegativeButton(bt_msg_left, listener_left).setCancelable(cancelable).show();
}
}
|
apache-2.0
|
stikbomb/amolodid
|
professions/src/main/java/ru/job4j/professions/Paper.java
|
1921
|
package ru.job4j.professions;
/**
* Класс Бамага, родительский класс для всех "бумажных" классов в этом приммере.
*/
public class Paper {
/**
* Имя.
*/
private String name;
/**
* Сеттер.
* @param name - имя.
*/
public void setName(String name) {
this.name = name;
}
/**
* Геттер.
* @return - возвращает имя.
*/
public String getName() {
return this.name;
}
}
/**
* Класс Мануал (Руководство), дочерний к классу Бумага.
*/
class Manual extends Paper {
/**
* Конструктор.
* @param name - имя.
*/
Manual(String name) {
this.setName(name);
}
}
/**
* Класс Заметка, дочерний к классу Бумага.
*/
class Outline extends Paper {
}
/**
* Класс Рецепт, дочерний к класса Бумага.
*/
class Recipe extends Paper {
/**
* Номер рецепта.
*/
private int number;
/**
* Сеттер.
* @param number - имя.
*/
public void setNumber(int number) {
this.number = number;
}
/**
* Геттер.
* @return - возвращает имя.
*/
public int getNumber() {
return this.number;
}
}
/**
* Класс Чертёж, дочерний к классу Бумага.
*/
class Blueprint extends Paper {
}
/**
* Класс Проект, дочерний к классу Бумага.
*/
class Project extends Paper {
}
/**
* Класс Конспект, дочерний к классу Бумага.
*/
class Conspect extends Paper {
/**
* Конструктор.
* @param name - имя.
*/
Conspect(String name) {
this.setName(name);
}
}
|
apache-2.0
|
aws/aws-sdk-java
|
aws-java-sdk-resiliencehub/src/main/java/com/amazonaws/services/resiliencehub/model/transform/DescribeAppVersionResourcesResolutionStatusResultJsonUnmarshaller.java
|
4309
|
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.resiliencehub.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.resiliencehub.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* DescribeAppVersionResourcesResolutionStatusResult JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeAppVersionResourcesResolutionStatusResultJsonUnmarshaller implements
Unmarshaller<DescribeAppVersionResourcesResolutionStatusResult, JsonUnmarshallerContext> {
public DescribeAppVersionResourcesResolutionStatusResult unmarshall(JsonUnmarshallerContext context) throws Exception {
DescribeAppVersionResourcesResolutionStatusResult describeAppVersionResourcesResolutionStatusResult = new DescribeAppVersionResourcesResolutionStatusResult();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return describeAppVersionResourcesResolutionStatusResult;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("appArn", targetDepth)) {
context.nextToken();
describeAppVersionResourcesResolutionStatusResult.setAppArn(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("appVersion", targetDepth)) {
context.nextToken();
describeAppVersionResourcesResolutionStatusResult.setAppVersion(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("errorMessage", targetDepth)) {
context.nextToken();
describeAppVersionResourcesResolutionStatusResult.setErrorMessage(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("resolutionId", targetDepth)) {
context.nextToken();
describeAppVersionResourcesResolutionStatusResult.setResolutionId(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("status", targetDepth)) {
context.nextToken();
describeAppVersionResourcesResolutionStatusResult.setStatus(context.getUnmarshaller(String.class).unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return describeAppVersionResourcesResolutionStatusResult;
}
private static DescribeAppVersionResourcesResolutionStatusResultJsonUnmarshaller instance;
public static DescribeAppVersionResourcesResolutionStatusResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new DescribeAppVersionResourcesResolutionStatusResultJsonUnmarshaller();
return instance;
}
}
|
apache-2.0
|
TommyPersson/scala-mvvm-example
|
src/main/scala/com/tpersson/client/common/services/navigation/NavigationService.scala
|
274
|
package com.tpersson.client.common.services.navigation
import javafx.beans.property.ReadOnlyObjectProperty
trait NavigationService {
val currentPageType: ReadOnlyObjectProperty[PageViewType]
def navigateTo(viewType: PageViewType): Unit
def navigateBack(): Unit
}
|
apache-2.0
|
googleapis/java-notebooks
|
proto-google-cloud-notebooks-v1/src/main/java/com/google/cloud/notebooks/v1/RuntimeName.java
|
6138
|
/*
* Copyright 2021 Google LLC
*
* 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
*
* https://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.cloud.notebooks.v1;
import com.google.api.pathtemplate.PathTemplate;
import com.google.api.resourcenames.ResourceName;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import javax.annotation.Generated;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
@Generated("by gapic-generator-java")
public class RuntimeName implements ResourceName {
private static final PathTemplate PROJECT_LOCATION_RUNTIME =
PathTemplate.createWithoutUrlEncoding(
"projects/{project}/locations/{location}/runtimes/{runtime}");
private volatile Map<String, String> fieldValuesMap;
private final String project;
private final String location;
private final String runtime;
@Deprecated
protected RuntimeName() {
project = null;
location = null;
runtime = null;
}
private RuntimeName(Builder builder) {
project = Preconditions.checkNotNull(builder.getProject());
location = Preconditions.checkNotNull(builder.getLocation());
runtime = Preconditions.checkNotNull(builder.getRuntime());
}
public String getProject() {
return project;
}
public String getLocation() {
return location;
}
public String getRuntime() {
return runtime;
}
public static Builder newBuilder() {
return new Builder();
}
public Builder toBuilder() {
return new Builder(this);
}
public static RuntimeName of(String project, String location, String runtime) {
return newBuilder().setProject(project).setLocation(location).setRuntime(runtime).build();
}
public static String format(String project, String location, String runtime) {
return newBuilder()
.setProject(project)
.setLocation(location)
.setRuntime(runtime)
.build()
.toString();
}
public static RuntimeName parse(String formattedString) {
if (formattedString.isEmpty()) {
return null;
}
Map<String, String> matchMap =
PROJECT_LOCATION_RUNTIME.validatedMatch(
formattedString, "RuntimeName.parse: formattedString not in valid format");
return of(matchMap.get("project"), matchMap.get("location"), matchMap.get("runtime"));
}
public static List<RuntimeName> parseList(List<String> formattedStrings) {
List<RuntimeName> list = new ArrayList<>(formattedStrings.size());
for (String formattedString : formattedStrings) {
list.add(parse(formattedString));
}
return list;
}
public static List<String> toStringList(List<RuntimeName> values) {
List<String> list = new ArrayList<>(values.size());
for (RuntimeName value : values) {
if (value == null) {
list.add("");
} else {
list.add(value.toString());
}
}
return list;
}
public static boolean isParsableFrom(String formattedString) {
return PROJECT_LOCATION_RUNTIME.matches(formattedString);
}
@Override
public Map<String, String> getFieldValuesMap() {
if (fieldValuesMap == null) {
synchronized (this) {
if (fieldValuesMap == null) {
ImmutableMap.Builder<String, String> fieldMapBuilder = ImmutableMap.builder();
if (project != null) {
fieldMapBuilder.put("project", project);
}
if (location != null) {
fieldMapBuilder.put("location", location);
}
if (runtime != null) {
fieldMapBuilder.put("runtime", runtime);
}
fieldValuesMap = fieldMapBuilder.build();
}
}
}
return fieldValuesMap;
}
public String getFieldValue(String fieldName) {
return getFieldValuesMap().get(fieldName);
}
@Override
public String toString() {
return PROJECT_LOCATION_RUNTIME.instantiate(
"project", project, "location", location, "runtime", runtime);
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (o != null || getClass() == o.getClass()) {
RuntimeName that = ((RuntimeName) o);
return Objects.equals(this.project, that.project)
&& Objects.equals(this.location, that.location)
&& Objects.equals(this.runtime, that.runtime);
}
return false;
}
@Override
public int hashCode() {
int h = 1;
h *= 1000003;
h ^= Objects.hashCode(project);
h *= 1000003;
h ^= Objects.hashCode(location);
h *= 1000003;
h ^= Objects.hashCode(runtime);
return h;
}
/** Builder for projects/{project}/locations/{location}/runtimes/{runtime}. */
public static class Builder {
private String project;
private String location;
private String runtime;
protected Builder() {}
public String getProject() {
return project;
}
public String getLocation() {
return location;
}
public String getRuntime() {
return runtime;
}
public Builder setProject(String project) {
this.project = project;
return this;
}
public Builder setLocation(String location) {
this.location = location;
return this;
}
public Builder setRuntime(String runtime) {
this.runtime = runtime;
return this;
}
private Builder(RuntimeName runtimeName) {
this.project = runtimeName.project;
this.location = runtimeName.location;
this.runtime = runtimeName.runtime;
}
public RuntimeName build() {
return new RuntimeName(this);
}
}
}
|
apache-2.0
|
Gadreel/dcraft
|
dcraft.core/src/main/java/dcraft/db/proc/InitiateRecovery.java
|
1912
|
package dcraft.db.proc;
import org.joda.time.DateTime;
import dcraft.db.DatabaseInterface;
import dcraft.db.DatabaseTask;
import dcraft.db.IStoredProc;
import dcraft.db.TablesAdapter;
import dcraft.lang.BigDateTime;
import dcraft.lang.op.OperationResult;
import dcraft.struct.RecordStruct;
import dcraft.struct.builder.ICompositeBuilder;
import dcraft.util.StringUtil;
public class InitiateRecovery implements IStoredProc {
@Override
public void execute(DatabaseInterface conn, DatabaseTask task, OperationResult log) {
TablesAdapter db = new TablesAdapter(conn, task);
BigDateTime when = BigDateTime.nowDateTime();
RecordStruct params = task.getParamsAsRecord();
String user = params.getFieldAsString("User");
try {
if (task.isReplicating()) {
// TODO
}
else {
boolean uisemail = false;
Object userid = db.firstInIndex("dcUser", "dcUsername", user, when, false);
if (userid == null) {
userid = db.firstInIndex("dcUser", "dcEmail", user, when, false);
uisemail = true; // true for email or backup email
}
if (userid == null)
userid = db.firstInIndex("dcUser", "dcBackupEmail", user, when, false);
if (userid == null) {
log.error("Unable to complete recovery");
task.complete();
return;
}
String uid = userid.toString();
String code = StringUtil.buildSecurityCode();
db.setStaticScalar("dcUser", uid, "dcConfirmCode", code);
db.setStaticScalar("dcUser", uid, "dcRecoverAt", new DateTime());
String email = uisemail ? uid : (String) db.getDynamicScalar("dcUser", uid, "dcEmail", when);
ICompositeBuilder out = task.getBuilder();
out.startRecord();
out.field("Code", code);
out.field("Email", email);
out.endRecord();
}
}
catch (Exception x) {
log.error("Account Recovery: Unable to create resp: " + x);
}
task.complete();
}
}
|
apache-2.0
|
taegeonum/incubator-reef
|
lang/java/reef-wake/wake/src/main/java/org/apache/reef/wake/impl/PubSubEventHandler.java
|
3506
|
/*
* 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.reef.wake.impl;
import org.apache.reef.wake.EventHandler;
import org.apache.reef.wake.exception.WakeRuntimeException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Event handler that provides publish/subscribe interfaces.
*
* @param <T> type
*/
public class PubSubEventHandler<T> implements EventHandler<T> {
private static final Logger LOG = Logger.getLogger(PubSubEventHandler.class.getCanonicalName());
private final Map<Class<? extends T>, List<EventHandler<? extends T>>> clazzToListOfHandlersMap;
private final ReadWriteLock lock = new ReentrantReadWriteLock();
/**
* Constructs a pub-sub event handler.
*/
public PubSubEventHandler() {
this.clazzToListOfHandlersMap = new HashMap<Class<? extends T>, List<EventHandler<? extends T>>>();
}
/**
* Constructs a pub-sub event handler with initial subscribed event handlers.
*
* @param map a map of event class types to lists of event handlers
*/
public PubSubEventHandler(Map<Class<? extends T>, List<EventHandler<? extends T>>> clazzToListOfHandlersMap) {
this.clazzToListOfHandlersMap = clazzToListOfHandlersMap;
}
/**
* Subscribes an event handler for an event class type.
*
* @param clazz an event class
* @param handler an event handler
*/
public void subscribe(Class<? extends T> clazz, EventHandler<? extends T> handler) {
lock.writeLock().lock();
try {
List<EventHandler<? extends T>> list = clazzToListOfHandlersMap.get(clazz);
if (list == null) {
list = new LinkedList<EventHandler<? extends T>>();
clazzToListOfHandlersMap.put(clazz, list);
}
list.add(handler);
} finally {
lock.writeLock().unlock();
}
}
/**
* Invokes subscribed handlers for the event class type.
*
* @param event an event
* @throws WakeRuntimeException
*/
@Override
public void onNext(T event) {
LOG.log(Level.FINEST, "Invoked for event: {0}", event);
lock.readLock().lock();
List<EventHandler<? extends T>> list;
try {
list = clazzToListOfHandlersMap.get(event.getClass());
if (list == null) {
throw new WakeRuntimeException("No event " + event.getClass() + " handler");
}
for (final EventHandler<? extends T> handler : list) {
LOG.log(Level.FINEST, "Invoking {0}", handler);
((EventHandler<T>) handler).onNext(event);
}
} finally {
lock.readLock().unlock();
}
}
}
|
apache-2.0
|
KRMAssociatesInc/eHMP
|
ehmp/product/production/osync/utils/jds-utils.js
|
1702
|
'use strict';
var _ = require('lodash');
var url = require('url');
var request = require('request');
function saveToJDS(log, config, key, value, cb) {
var postdata = _.merge({}, { "_id": key}, value);
var endpoint = url.format({
protocol: config.jds.protocol,
host: config.jds.host + ":" + config.jds.port,
pathname: config.jds.jdsSaveURI
});
var options = {
url: endpoint,
body: postdata,
method: 'POST',
json: true
};
request(options, function (error, response) {
//log.debug("saveToJDS: response: %s", response);
if ((_.isNull(error) || _.isUndefined(error)) && response.statusCode == 200) {
// log.debug('saveToJDS: saved: %s ', postdata);
cb(null, response);
}
else {
//log.error('saveToJDS: failed to save to JDS: %s ', postdata);
cb(error, null);
}
});
}
function getFromJDS(log, config, key, cb) {
var endpoint = url.format({
protocol: config.jds.protocol,
host: config.jds.host + ":" + config.jds.port,
pathname: config.jds.jdsGetURI + "/" + key
});
var options = {
url: endpoint,
method: 'GET'
};
request(options, function (error, response) {
//log.debug("getFromJDS: response: %s", response);
if ((_.isNull(error) || _.isUndefined(error)) && response.statusCode == 200) {
// log.debug('getFromJDS: Success');
}
else {
// log.error('getFromJDS: failed to GET from JDS');
}
cb(error, response);
});
}
module.exports.saveToJDS = saveToJDS;
module.exports.getFromJDS = getFromJDS;
|
apache-2.0
|
be-hase/honoumi
|
src/test/java/com/be_hase/honoumi/netty/server/ServerTest.java
|
2010
|
package com.be_hase.honoumi.netty.server;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import com.be_hase.honoumi.HttpUtilForTest;
import com.be_hase.honoumi.controller.TestController;
import com.be_hase.honoumi.guice.TestModule;
import com.be_hase.honoumi.routing.Router;
import com.google.common.collect.Lists;
import com.google.inject.AbstractModule;
import junit.framework.TestCase;
public class ServerTest extends TestCase {
@Before
public void setUp() {
System.setProperty("application.environment", "local");
System.setProperty("application.properties", "test1.properties,test2.properties,server.properties");
}
@Test
public void test_create() {
Router router = new Router();
router.GET().route("/hoge").with(TestController.class, "hoge");
router.GET().route("/bar/{path1}/{path2}").with(TestController.class, "bar");
router.GET().route("/fuga/{path1}/{path2}").with(TestController.class, "fuga");
List<AbstractModule> modules = Lists.newArrayList();
modules.add(new TestModule());
Server testServer = Server.create("testServer", router, modules);
testServer.start();
MonitoringServer monitoringServer = MonitoringServer.create(testServer);
monitoringServer.start();
assertEquals("testServer", testServer.getServerName());
assertEquals(22222, testServer.getPort());
assertEquals("UTF-8", testServer.getCharsetStr());
assertEquals("true", testServer.getServerBootstrap().getOption("reuseAddress").toString());
assertEquals("true", testServer.getServerBootstrap().getOption("child.keepAlive").toString());
assertEquals("true", testServer.getServerBootstrap().getOption("child.tcpNoDelay").toString());
assertEquals("hoge", HttpUtilForTest.get("http://localhost:22222/hoge", null).getResponse());
assertEquals("12", HttpUtilForTest.get("http://localhost:22222/bar/1/2", null).getResponse());
assertEquals("{\"path1\":\"1\",\"path2\":\"2\"}", HttpUtilForTest.get("http://localhost:22222/fuga/1/2", null).getResponse());
}
}
|
apache-2.0
|
lsmaira/gradle
|
subprojects/core/src/main/java/org/gradle/api/internal/changedetection/rules/ChangeDetectorVisitor.java
|
1088
|
/*
* Copyright 2018 the original author or 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 org.gradle.api.internal.changedetection.rules;
import org.gradle.internal.changes.TaskStateChange;
import org.gradle.internal.changes.TaskStateChangeVisitor;
public class ChangeDetectorVisitor implements TaskStateChangeVisitor {
private boolean anyChanges;
@Override
public boolean visitChange(TaskStateChange change) {
anyChanges = true;
return false;
}
public boolean hasAnyChanges() {
return anyChanges;
}
}
|
apache-2.0
|
royyau41/presentation
|
Resources/iphone/alloy/controllers/viewFile/viewFile.js
|
3549
|
function __processArg(obj, key) {
var arg = null;
if (obj) {
arg = obj[key] || null;
delete obj[key];
}
return arg;
}
function Controller() {
require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
this.__controllerPath = "viewFile/viewFile";
if (arguments[0]) {
{
__processArg(arguments[0], "__parentSymbol");
}
{
__processArg(arguments[0], "$model");
}
{
__processArg(arguments[0], "__itemTemplate");
}
}
var $ = this;
var exports = {};
$.__views.viewFileWin = Ti.UI.createWindow({
navBarHidden: true,
fullscreen: true,
orientationModes: [ 3, 4 ],
theme: "Theme.noActionBar",
width: "100%",
height: "100%",
backgroundColor: "black",
opacity: 1,
id: "viewFileWin"
});
$.__views.viewFileWin && $.addTopLevelView($.__views.viewFileWin);
$.__views.topView = Ti.UI.createView({
width: Ti.UI.Fill,
height: Ti.UI.SIZE,
top: 0,
left: 0,
backgroundColor: "grey",
zIndex: 100,
id: "topView"
});
$.__views.viewFileWin.add($.__views.topView);
$.__views.backBtn = Ti.UI.createButton({
left: 5,
top: 5,
width: 80,
height: 43,
id: "backBtn"
});
$.__views.topView.add($.__views.backBtn);
$.__views.contentView = Ti.UI.createView({
contentWidth: "auto",
contentHeight: "auto",
showVerticalScrollIndicator: true,
showHorizontalScrollIndicator: true,
maxZoomScale: 10,
minZoomScale: .1,
width: Ti.UI.FILL,
height: Ti.UI.FILL,
id: "contentView"
});
$.__views.viewFileWin.add($.__views.contentView);
$.__views.bottomView = Ti.UI.createView({
width: "100%",
bottom: 0,
height: "40dp",
backgroundColor: "grey",
id: "bottomView"
});
$.__views.viewFileWin.add($.__views.bottomView);
exports.destroy = function() {};
_.extend($, $.__views);
var args = arguments[0] || {};
$.backBtn.backgroundImage = "/temp/" + Alloy.Globals.langIso + "/imgback.png";
$.backBtn.addEventListener("click", function() {
$.viewFileWin.close({
transition: Titanium.UI.iPhone.AnimationStyle.CURL_DOWN
});
});
var topViewShow = Ti.UI.createAnimation({
top: 0,
duration: 500
});
var topViewHide = Ti.UI.createAnimation({
top: "-" + $.topView.toImage().height,
duration: 500
});
var bottomViewShow = Ti.UI.createAnimation({
bottom: 0,
duration: 500
});
var bottomViewHide = Ti.UI.createAnimation({
bottom: "-" + $.bottomView.toImage().height,
duration: 500
});
var showView = false;
"pdf" != args["type"] && setTimeout(function() {
$.topView.animate(topViewHide);
$.bottomView.animate(bottomViewHide);
}, 2e3);
$.contentView.addEventListener("click", function() {
if (showView) {
$.topView.animate(topViewHide);
$.bottomView.animate(bottomViewHide);
showView = false;
} else {
$.topView.animate(topViewShow);
$.bottomView.animate(bottomViewShow);
showView = true;
}
});
_.extend($, exports);
}
var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;
module.exports = Controller;
|
apache-2.0
|
rdhyee/osf.io
|
website/institutions/model.py
|
7040
|
from django.core.urlresolvers import reverse
from modularodm import Q
from modularodm.exceptions import NoResultsFound
from modularodm.query.query import RawQuery
from modularodm.storage.mongostorage import MongoQuerySet
class AffiliatedInstitutionsList(list):
'''
A list to implement append and remove methods to a private node list through a
public Institution-returning property. Initialization should occur with the instance of the public list,
the object the list belongs to, and the private attribute ( a list) the public property
is attached to, and as the return value of the property.
Ex:
class Node():
_affiliated_institutions = []
@property
affiliated_institutions(self):
return AffiliatedInstitutionsList(
[Institution(node) for node in self._affiliated_institutions],
obj=self, private_target='_affiliated_institutions')
)
'''
def __init__(self, init, obj, private_target):
super(AffiliatedInstitutionsList, self).__init__(init or [])
self.obj = obj
self.target = private_target
def append(self, to_append):
temp_list = getattr(self.obj, self.target)
temp_list.append(to_append.node)
setattr(self.obj, self.target, temp_list)
def remove(self, to_remove):
temp_list = getattr(self.obj, self.target)
temp_list.remove(to_remove.node)
setattr(self.obj, self.target, temp_list)
class InstitutionQuerySet(MongoQuerySet):
def __init__(self, queryset):
super(InstitutionQuerySet, self).__init__(queryset.schema, queryset.data)
def __iter__(self):
for each in super(InstitutionQuerySet, self).__iter__():
yield Institution(each)
def _do_getitem(self, index):
item = super(InstitutionQuerySet, self)._do_getitem(index)
if isinstance(item, MongoQuerySet):
return self.__class__(item)
return Institution(item)
class Institution(object):
'''
"wrapper" class for Node. Together with the find and institution attributes & methods in Node,
this is to be used to allow interaction with Institutions, which are Nodes (with ' institution_id ' != None),
as if they were a wholly separate collection. To find an institution, use the find methods here,
and to use a Node as Institution, instantiate an Institution with ' Institution(node) '
'''
attribute_map = {
'_id': 'institution_id',
'auth_url': 'institution_auth_url',
'logout_url': 'institution_logout_url',
'domains': 'institution_domains',
'name': 'title',
'logo_name': 'institution_logo_name',
'description': 'description',
'email_domains': 'institution_email_domains',
'banner_name': 'institution_banner_name',
'is_deleted': 'is_deleted',
}
def __init__(self, node=None):
self.node = node
if node is None:
return
for key, value in self.attribute_map.iteritems():
setattr(self, key, getattr(node, value))
def __getattr__(self, item):
return getattr(self.node, item)
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self._id == other._id
def save(self):
from website.search.search import update_institution
update_institution(self)
for key, value in self.attribute_map.iteritems():
if getattr(self, key) != getattr(self.node, value):
setattr(self.node, value, getattr(self, key))
self.node.save()
@classmethod
def find(cls, query=None, deleted=False, **kwargs):
from website.models import Node # done to prevent import error
if query and getattr(query, 'nodes', False):
for node in query.nodes:
replacement_attr = cls.attribute_map.get(node.attribute, False)
node.attribute = replacement_attr or node.attribute
elif isinstance(query, RawQuery):
replacement_attr = cls.attribute_map.get(query.attribute, False)
query.attribute = replacement_attr or query.attribute
query = query & Q('institution_id', 'ne', None) if query else Q('institution_id', 'ne', None)
query = query & Q('is_deleted', 'ne', True) if not deleted else query
nodes = Node.find(query, allow_institution=True, **kwargs)
return InstitutionQuerySet(nodes)
@classmethod
def find_one(cls, query=None, deleted=False, **kwargs):
from website.models import Node
if query and getattr(query, 'nodes', False):
for node in query.nodes:
replacement_attr = cls.attribute_map.get(node.attribute, False)
node.attribute = replacement_attr if replacement_attr else node.attribute
elif isinstance(query, RawQuery):
replacement_attr = cls.attribute_map.get(query.attribute, False)
query.attribute = replacement_attr if replacement_attr else query.attribute
query = query & Q('institution_id', 'ne', None) if query else Q('institution_id', 'ne', None)
query = query & Q('is_deleted', 'ne', True) if not deleted else query
node = Node.find_one(query, allow_institution=True, **kwargs)
return cls(node)
@classmethod
def load(cls, key):
from website.models import Node
try:
node = Node.find_one(Q('institution_id', 'eq', key), allow_institution=True)
return cls(node)
except NoResultsFound:
return None
def __repr__(self):
return '<Institution ({}) with id \'{}\'>'.format(self.name, self._id)
@property
def pk(self):
return self._id
@property
def api_v2_url(self):
return reverse('institutions:institution-detail', kwargs={'institution_id': self._id, 'version': 'v2'})
@property
def absolute_api_v2_url(self):
from api.base.utils import absolute_reverse
return absolute_reverse('institutions:institution-detail', kwargs={'institution_id': self._id, 'version': 'v2'})
@property
def nodes_url(self):
return self.absolute_api_v2_url + 'nodes/'
@property
def nodes_relationship_url(self):
return self.absolute_api_v2_url + 'relationships/nodes/'
@property
def logo_path(self):
if self.logo_name:
return '/static/img/institutions/shields/{}'.format(self.logo_name)
else:
return None
@property
def logo_path_rounded_corners(self):
logo_base = '/static/img/institutions/shields-rounded-corners/{}-rounded-corners.png'
if self.logo_name:
return logo_base.format(self.logo_name.replace('.png', ''))
else:
return None
@property
def banner_path(self):
if self.banner_name:
return '/static/img/institutions/banners/{}'.format(self.banner_name)
else:
return None
|
apache-2.0
|
dufangyu1990/NewGpsTest
|
app/src/main/java/com/example/listener/FenceListenerManager.java
|
406
|
package com.example.listener;
public class FenceListenerManager {
private FenceListener mListener;
public void setFenceListener(FenceListener listener){
mListener = listener;
}
public void sendNotifyMessage(String param1,String param2,String param3,String param4,String param5){
mListener.showFence(param1,param2,param3,param4,param5);
}
public void locateCarPos()
{
mListener.showCarLoc();
}
}
|
apache-2.0
|
mjanicek/rembulan
|
rembulan-compiler/src/main/java/net/sandius/rembulan/compiler/analysis/LivenessInfo.java
|
2723
|
/*
* Copyright 2016 Miroslav Janíček
*
* 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 net.sandius.rembulan.compiler.analysis;
import net.sandius.rembulan.compiler.ir.AbstractVal;
import net.sandius.rembulan.compiler.ir.IRNode;
import net.sandius.rembulan.compiler.ir.Var;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Set;
public class LivenessInfo {
private final Map<IRNode, Entry> entries;
public LivenessInfo(Map<IRNode, Entry> entries) {
this.entries = Objects.requireNonNull(entries);
}
public static class Entry {
private final Set<Var> var_in;
private final Set<Var> var_out;
private final Set<AbstractVal> val_in;
private final Set<AbstractVal> val_out;
Entry(Set<Var> var_in, Set<Var> var_out, Set<AbstractVal> val_in, Set<AbstractVal> val_out) {
this.var_in = Objects.requireNonNull(var_in);
this.var_out = Objects.requireNonNull(var_out);
this.val_in = Objects.requireNonNull(val_in);
this.val_out = Objects.requireNonNull(val_out);
}
public Entry immutableCopy() {
return new Entry(
Collections.unmodifiableSet(new HashSet<>(var_in)),
Collections.unmodifiableSet(new HashSet<>(var_out)),
Collections.unmodifiableSet(new HashSet<>(val_in)),
Collections.unmodifiableSet(new HashSet<>(val_out)));
}
public Set<Var> inVar() {
return var_in;
}
public Set<Var> outVar() {
return var_out;
}
public Set<AbstractVal> inVal() {
return val_in;
}
public Set<AbstractVal> outVal() {
return val_out;
}
}
public Entry entry(IRNode node) {
Objects.requireNonNull(node);
Entry e = entries.get(node);
if (e == null) {
throw new NoSuchElementException("No liveness information for " + node);
}
else {
return e;
}
}
public Iterable<Var> liveInVars(IRNode node) {
return entry(node).inVar();
}
public Iterable<Var> liveOutVars(IRNode node) {
return entry(node).outVar();
}
public Iterable<AbstractVal> liveInVals(IRNode node) {
return entry(node).inVal();
}
public Iterable<AbstractVal> liveOutVals(IRNode node) {
return entry(node).outVal();
}
}
|
apache-2.0
|
oppodeldoc/rexray
|
libstorage/drivers/storage/ebs/utils/utils_test.go
|
523
|
package utils
import (
"os"
"strconv"
"testing"
"github.com/stretchr/testify/assert"
"github.com/codedellemc/rexray/libstorage/api/context"
"github.com/codedellemc/rexray/libstorage/drivers/storage/ebs"
)
func skipTest(t *testing.T) {
if ok, _ := strconv.ParseBool(os.Getenv("EBS_UTILS_TEST")); !ok {
t.Skip()
}
}
func TestInstanceID(t *testing.T) {
skipTest(t)
iid, err := InstanceID(context.Background(), ebs.Name)
if !assert.NoError(t, err) {
t.FailNow()
}
t.Logf("instanceID=%s", iid.String())
}
|
apache-2.0
|
trialmanager/voxce
|
WebContent/JQuery/jquery-1.7.1.js
|
248240
|
/*!
* jQuery JavaScript Library v1.7.1
* http://jquery.com/
*
* Copyright 2011, John Resig
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* Includes Sizzle.js
* http://sizzlejs.com/
* Copyright 2011, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
*
* Date: Mon Nov 21 21:11:03 2011 -0500
*/
(function( window, undefined ) {
// Use the correct document accordingly with window argument (sandbox)
var document = window.document,
navigator = window.navigator,
location = window.location;
var jQuery = (function() {
// Define a local copy of jQuery
var jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// A central reference to the root jQuery(document)
rootjQuery,
// A simple way to check for HTML strings or ID strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,
// Check if a string has a non-whitespace character in it
rnotwhite = /\S/,
// Used for trimming whitespace
trimLeft = /^\s+/,
trimRight = /\s+$/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/,
// JSON RegExp
rvalidchars = /^[\],:{}\s]*$/,
rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
// Useragent RegExp
rwebkit = /(webkit)[ \/]([\w.]+)/,
ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/,
rmsie = /(msie) ([\w.]+)/,
rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/,
// Matches dashed string for camelizing
rdashAlpha = /-([a-z]|[0-9])/ig,
rmsPrefix = /^-ms-/,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return ( letter + "" ).toUpperCase();
},
// Keep a UserAgent string for use with jQuery.browser
userAgent = navigator.userAgent,
// For matching the engine and version of the browser
browserMatch,
// The deferred used on DOM ready
readyList,
// The ready event handler
DOMContentLoaded,
// Save a reference to some core methods
toString = Object.prototype.toString,
hasOwn = Object.prototype.hasOwnProperty,
push = Array.prototype.push,
slice = Array.prototype.slice,
trim = String.prototype.trim,
indexOf = Array.prototype.indexOf,
// [[Class]] -> type pairs
class2type = {};
jQuery.fn = jQuery.prototype = {
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem, ret, doc;
// Handle $(""), $(null), or $(undefined)
if ( !selector ) {
return this;
}
// Handle $(DOMElement)
if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
}
// The body element only exists once, optimize finding it
if ( selector === "body" && !context && document.body ) {
this.context = document;
this[0] = document.body;
this.selector = selector;
this.length = 1;
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
// Are we dealing with HTML string or an ID?
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = quickExpr.exec( selector );
}
// Verify a match, and that no context was specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
doc = ( context ? context.ownerDocument || context : document );
// If a single string is passed in and it's a single tag
// just do a createElement and skip the rest
ret = rsingleTag.exec( selector );
if ( ret ) {
if ( jQuery.isPlainObject( context ) ) {
selector = [ document.createElement( ret[1] ) ];
jQuery.fn.attr.call( selector, context, true );
} else {
selector = [ doc.createElement( ret[1] ) ];
}
} else {
ret = jQuery.buildFragment( [ match[1] ], [ doc ] );
selector = ( ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment ).childNodes;
}
return jQuery.merge( this, selector );
// HANDLE: $("#id")
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The current version of jQuery being used
jquery: "1.7.1",
// The default length of a jQuery object is 0
length: 0,
// The number of elements contained in the matched element set
size: function() {
return this.length;
},
toArray: function() {
return slice.call( this, 0 );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems, name, selector ) {
// Build a new jQuery matched element set
var ret = this.constructor();
if ( jQuery.isArray( elems ) ) {
push.apply( ret, elems );
} else {
jQuery.merge( ret, elems );
}
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
if ( name === "find" ) {
ret.selector = this.selector + ( this.selector ? " " : "" ) + selector;
} else if ( name ) {
ret.selector = this.selector + "." + name + "(" + selector + ")";
}
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Attach the listeners
jQuery.bindReady();
// Add the callback
readyList.add( fn );
return this;
},
eq: function( i ) {
i = +i;
return i === -1 ?
this.slice( i ) :
this.slice( i, i + 1 );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
slice: function() {
return this.pushStack( slice.apply( this, arguments ),
"slice", slice.call(arguments).join(",") );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Either a released hold or an DOMready/load event and not yet ready
if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) {
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready, 1 );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.fireWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger( "ready" ).off( "ready" );
}
}
},
bindReady: function() {
if ( readyList ) {
return;
}
readyList = jQuery.Callbacks( "once memory" );
// Catch cases where $(document).ready() is called after the
// browser event has already occurred.
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
return setTimeout( jQuery.ready, 1 );
}
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", jQuery.ready, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload,
// maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", DOMContentLoaded );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", jQuery.ready );
// If IE and not a frame
// continually check to see if the document is ready
var toplevel = false;
try {
toplevel = window.frameElement == null;
} catch(e) {}
if ( document.documentElement.doScroll && toplevel ) {
doScrollCheck();
}
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
// A crude way of determining if an object is a window
isWindow: function( obj ) {
return obj && typeof obj === "object" && "setInterval" in obj;
},
isNumeric: function( obj ) {
return !isNaN( parseFloat(obj) ) && isFinite( obj );
},
type: function( obj ) {
return obj == null ?
String( obj ) :
class2type[ toString.call(obj) ] || "object";
},
isPlainObject: function( obj ) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!hasOwn.call(obj, "constructor") &&
!hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || hasOwn.call( obj, key );
},
isEmptyObject: function( obj ) {
for ( var name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw new Error( msg );
},
parseJSON: function( data ) {
if ( typeof data !== "string" || !data ) {
return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return ( new Function( "return " + data ) )();
}
jQuery.error( "Invalid JSON: " + data );
},
// Cross-browser xml parsing
parseXML: function( data ) {
var xml, tmp;
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && rnotwhite.test( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();
},
// args is for internal usage only
each: function( object, callback, args ) {
var name, i = 0,
length = object.length,
isObj = length === undefined || jQuery.isFunction( object );
if ( args ) {
if ( isObj ) {
for ( name in object ) {
if ( callback.apply( object[ name ], args ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.apply( object[ i++ ], args ) === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isObj ) {
for ( name in object ) {
if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) {
break;
}
}
}
}
return object;
},
// Use native String.trim function wherever possible
trim: trim ?
function( text ) {
return text == null ?
"" :
trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
text.toString().replace( trimLeft, "" ).replace( trimRight, "" );
},
// results is for internal usage only
makeArray: function( array, results ) {
var ret = results || [];
if ( array != null ) {
// The window, strings (and functions) also have 'length'
// Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
var type = jQuery.type( array );
if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) {
push.call( ret, array );
} else {
jQuery.merge( ret, array );
}
}
return ret;
},
inArray: function( elem, array, i ) {
var len;
if ( array ) {
if ( indexOf ) {
return indexOf.call( array, elem, i );
}
len = array.length;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
for ( ; i < len; i++ ) {
// Skip accessing in sparse arrays
if ( i in array && array[ i ] === elem ) {
return i;
}
}
}
return -1;
},
merge: function( first, second ) {
var i = first.length,
j = 0;
if ( typeof second.length === "number" ) {
for ( var l = second.length; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var ret = [], retVal;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( var i = 0, length = elems.length; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value, key, ret = [],
i = 0,
length = elems.length,
// jquery objects are treated as arrays
isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ;
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( key in elems ) {
value = callback( elems[ key ], key, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return ret.concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
if ( typeof context === "string" ) {
var tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
var args = slice.call( arguments, 2 ),
proxy = function() {
return fn.apply( context, args.concat( slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;
return proxy;
},
// Mutifunctional method to get and set values to a collection
// The value/s can optionally be executed if it's a function
access: function( elems, key, value, exec, fn, pass ) {
var length = elems.length;
// Setting many attributes
if ( typeof key === "object" ) {
for ( var k in key ) {
jQuery.access( elems, k, key[k], exec, fn, value );
}
return elems;
}
// Setting one attribute
if ( value !== undefined ) {
// Optionally, function values get executed if exec is true
exec = !pass && exec && jQuery.isFunction(value);
for ( var i = 0; i < length; i++ ) {
fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
}
return elems;
}
// Getting an attribute
return length ? fn( elems[0], key ) : undefined;
},
now: function() {
return ( new Date() ).getTime();
},
// Use of jQuery.browser is frowned upon.
// More details: http://docs.jquery.com/Utilities/jQuery.browser
uaMatch: function( ua ) {
ua = ua.toLowerCase();
var match = rwebkit.exec( ua ) ||
ropera.exec( ua ) ||
rmsie.exec( ua ) ||
ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) ||
[];
return { browser: match[1] || "", version: match[2] || "0" };
},
sub: function() {
function jQuerySub( selector, context ) {
return new jQuerySub.fn.init( selector, context );
}
jQuery.extend( true, jQuerySub, this );
jQuerySub.superclass = this;
jQuerySub.fn = jQuerySub.prototype = this();
jQuerySub.fn.constructor = jQuerySub;
jQuerySub.sub = this.sub;
jQuerySub.fn.init = function init( selector, context ) {
if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
context = jQuerySub( context );
}
return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
};
jQuerySub.fn.init.prototype = jQuerySub.fn;
var rootjQuerySub = jQuerySub(document);
return jQuerySub;
},
browser: {}
});
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
browserMatch = jQuery.uaMatch( userAgent );
if ( browserMatch.browser ) {
jQuery.browser[ browserMatch.browser ] = true;
jQuery.browser.version = browserMatch.version;
}
// Deprecated, use jQuery.browser.webkit instead
if ( jQuery.browser.webkit ) {
jQuery.browser.safari = true;
}
// IE doesn't match non-breaking spaces with \s
if ( rnotwhite.test( "\xA0" ) ) {
trimLeft = /^[\s\xA0]+/;
trimRight = /[\s\xA0]+$/;
}
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
// Cleanup functions for the document ready method
if ( document.addEventListener ) {
DOMContentLoaded = function() {
document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
jQuery.ready();
};
} else if ( document.attachEvent ) {
DOMContentLoaded = function() {
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( document.readyState === "complete" ) {
document.detachEvent( "onreadystatechange", DOMContentLoaded );
jQuery.ready();
}
};
}
// The DOM ready check for Internet Explorer
function doScrollCheck() {
if ( jQuery.isReady ) {
return;
}
try {
// If IE is used, use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
document.documentElement.doScroll("left");
} catch(e) {
setTimeout( doScrollCheck, 1 );
return;
}
// and execute any waiting functions
jQuery.ready();
}
return jQuery;
})();
// String to Object flags format cache
var flagsCache = {};
// Convert String-formatted flags into Object-formatted ones and store in cache
function createFlags( flags ) {
var object = flagsCache[ flags ] = {},
i, length;
flags = flags.split( /\s+/ );
for ( i = 0, length = flags.length; i < length; i++ ) {
object[ flags[i] ] = true;
}
return object;
}
/*
* Create a callback list using the following parameters:
*
* flags: an optional list of space-separated flags that will change how
* the callback list behaves
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible flags:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( flags ) {
// Convert flags from String-formatted to Object-formatted
// (we check in cache first)
flags = flags ? ( flagsCache[ flags ] || createFlags( flags ) ) : {};
var // Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = [],
// Last fire value (for non-forgettable lists)
memory,
// Flag to know if list is currently firing
firing,
// First callback to fire (used internally by add and fireWith)
firingStart,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// Add one or several callbacks to the list
add = function( args ) {
var i,
length,
elem,
type,
actual;
for ( i = 0, length = args.length; i < length; i++ ) {
elem = args[ i ];
type = jQuery.type( elem );
if ( type === "array" ) {
// Inspect recursively
add( elem );
} else if ( type === "function" ) {
// Add if not in unique mode and callback is not in
if ( !flags.unique || !self.has( elem ) ) {
list.push( elem );
}
}
}
},
// Fire callbacks
fire = function( context, args ) {
args = args || [];
memory = !flags.memory || [ context, args ];
firing = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( context, args ) === false && flags.stopOnFalse ) {
memory = true; // Mark as halted
break;
}
}
firing = false;
if ( list ) {
if ( !flags.once ) {
if ( stack && stack.length ) {
memory = stack.shift();
self.fireWith( memory[ 0 ], memory[ 1 ] );
}
} else if ( memory === true ) {
self.disable();
} else {
list = [];
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
var length = list.length;
add( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away, unless previous
// firing was halted (stopOnFalse)
} else if ( memory && memory !== true ) {
firingStart = length;
fire( memory[ 0 ], memory[ 1 ] );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
var args = arguments,
argIndex = 0,
argLength = args.length;
for ( ; argIndex < argLength ; argIndex++ ) {
for ( var i = 0; i < list.length; i++ ) {
if ( args[ argIndex ] === list[ i ] ) {
// Handle firingIndex and firingLength
if ( firing ) {
if ( i <= firingLength ) {
firingLength--;
if ( i <= firingIndex ) {
firingIndex--;
}
}
}
// Remove the element
list.splice( i--, 1 );
// If we have some unicity property then
// we only need to do this once
if ( flags.unique ) {
break;
}
}
}
}
}
return this;
},
// Control if a given callback is in the list
has: function( fn ) {
if ( list ) {
var i = 0,
length = list.length;
for ( ; i < length; i++ ) {
if ( fn === list[ i ] ) {
return true;
}
}
}
return false;
},
// Remove all callbacks from the list
empty: function() {
list = [];
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory || memory === true ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
if ( stack ) {
if ( firing ) {
if ( !flags.once ) {
stack.push( [ context, args ] );
}
} else if ( !( flags.once && memory ) ) {
fire( context, args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!memory;
}
};
return self;
};
var // Static reference to slice
sliceDeferred = [].slice;
jQuery.extend({
Deferred: function( func ) {
var doneList = jQuery.Callbacks( "once memory" ),
failList = jQuery.Callbacks( "once memory" ),
progressList = jQuery.Callbacks( "memory" ),
state = "pending",
lists = {
resolve: doneList,
reject: failList,
notify: progressList
},
promise = {
done: doneList.add,
fail: failList.add,
progress: progressList.add,
state: function() {
return state;
},
// Deprecated
isResolved: doneList.fired,
isRejected: failList.fired,
then: function( doneCallbacks, failCallbacks, progressCallbacks ) {
deferred.done( doneCallbacks ).fail( failCallbacks ).progress( progressCallbacks );
return this;
},
always: function() {
deferred.done.apply( deferred, arguments ).fail.apply( deferred, arguments );
return this;
},
pipe: function( fnDone, fnFail, fnProgress ) {
return jQuery.Deferred(function( newDefer ) {
jQuery.each( {
done: [ fnDone, "resolve" ],
fail: [ fnFail, "reject" ],
progress: [ fnProgress, "notify" ]
}, function( handler, data ) {
var fn = data[ 0 ],
action = data[ 1 ],
returned;
if ( jQuery.isFunction( fn ) ) {
deferred[ handler ](function() {
returned = fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise().then( newDefer.resolve, newDefer.reject, newDefer.notify );
} else {
newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] );
}
});
} else {
deferred[ handler ]( newDefer[ action ] );
}
});
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
if ( obj == null ) {
obj = promise;
} else {
for ( var key in promise ) {
obj[ key ] = promise[ key ];
}
}
return obj;
}
},
deferred = promise.promise({}),
key;
for ( key in lists ) {
deferred[ key ] = lists[ key ].fire;
deferred[ key + "With" ] = lists[ key ].fireWith;
}
// Handle state
deferred.done( function() {
state = "resolved";
}, failList.disable, progressList.lock ).fail( function() {
state = "rejected";
}, doneList.disable, progressList.lock );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( firstParam ) {
var args = sliceDeferred.call( arguments, 0 ),
i = 0,
length = args.length,
pValues = new Array( length ),
count = length,
pCount = length,
deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ?
firstParam :
jQuery.Deferred(),
promise = deferred.promise();
function resolveFunc( i ) {
return function( value ) {
args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value;
if ( !( --count ) ) {
deferred.resolveWith( deferred, args );
}
};
}
function progressFunc( i ) {
return function( value ) {
pValues[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value;
deferred.notifyWith( promise, pValues );
};
}
if ( length > 1 ) {
for ( ; i < length; i++ ) {
if ( args[ i ] && args[ i ].promise && jQuery.isFunction( args[ i ].promise ) ) {
args[ i ].promise().then( resolveFunc(i), deferred.reject, progressFunc(i) );
} else {
--count;
}
}
if ( !count ) {
deferred.resolveWith( deferred, args );
}
} else if ( deferred !== firstParam ) {
deferred.resolveWith( deferred, length ? [ firstParam ] : [] );
}
return promise;
}
});
jQuery.support = (function() {
var support,
all,
a,
select,
opt,
input,
marginDiv,
fragment,
tds,
events,
eventName,
i,
isSupported,
div = document.createElement( "div" ),
documentElement = document.documentElement;
// Preliminary tests
div.setAttribute("className", "t");
div.innerHTML = " <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>";
all = div.getElementsByTagName( "*" );
a = div.getElementsByTagName( "a" )[ 0 ];
// Can't get basic test support
if ( !all || !all.length || !a ) {
return {};
}
// First batch of supports tests
select = document.createElement( "select" );
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName( "input" )[ 0 ];
support = {
// IE strips leading whitespace when .innerHTML is used
leadingWhitespace: ( div.firstChild.nodeType === 3 ),
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
tbody: !div.getElementsByTagName("tbody").length,
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
htmlSerialize: !!div.getElementsByTagName("link").length,
// Get the style information from getAttribute
// (IE uses .cssText instead)
style: /top/.test( a.getAttribute("style") ),
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
hrefNormalized: ( a.getAttribute("href") === "/a" ),
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
opacity: /^0.55/.test( a.style.opacity ),
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
cssFloat: !!a.style.cssFloat,
// Make sure that if no value is specified for a checkbox
// that it defaults to "on".
// (WebKit defaults to "" instead)
checkOn: ( input.value === "on" ),
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
optSelected: opt.selected,
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
getSetAttribute: div.className !== "t",
// Tests for enctype support on a form(#6743)
enctype: !!document.createElement("form").enctype,
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>",
// Will be defined later
submitBubbles: true,
changeBubbles: true,
focusinBubbles: false,
deleteExpando: true,
noCloneEvent: true,
inlineBlockNeedsLayout: false,
shrinkWrapBlocks: false,
reliableMarginRight: true
};
// Make sure checked status is properly cloned
input.checked = true;
support.noCloneChecked = input.cloneNode( true ).checked;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Test to see if it's possible to delete an expando from an element
// Fails in Internet Explorer
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
if ( !div.addEventListener && div.attachEvent && div.fireEvent ) {
div.attachEvent( "onclick", function() {
// Cloning a node shouldn't copy over any
// bound event handlers (IE does this)
support.noCloneEvent = false;
});
div.cloneNode( true ).fireEvent( "onclick" );
}
// Check if a radio maintains its value
// after being appended to the DOM
input = document.createElement("input");
input.value = "t";
input.setAttribute("type", "radio");
support.radioValue = input.value === "t";
input.setAttribute("checked", "checked");
div.appendChild( input );
fragment = document.createDocumentFragment();
fragment.appendChild( div.lastChild );
// WebKit doesn't clone checked state correctly in fragments
support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
support.appendChecked = input.checked;
fragment.removeChild( input );
fragment.appendChild( div );
div.innerHTML = "";
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. For more
// info see bug #3333
// Fails in WebKit before Feb 2011 nightlies
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
if ( window.getComputedStyle ) {
marginDiv = document.createElement( "div" );
marginDiv.style.width = "0";
marginDiv.style.marginRight = "0";
div.style.width = "2px";
div.appendChild( marginDiv );
support.reliableMarginRight =
( parseInt( ( window.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0;
}
// Technique from Juriy Zaytsev
// http://perfectionkills.com/detecting-event-support-without-browser-sniffing/
// We only care about the case where non-standard event systems
// are used, namely in IE. Short-circuiting here helps us to
// avoid an eval call (in setAttribute) which can cause CSP
// to go haywire. See: https://developer.mozilla.org/en/Security/CSP
if ( div.attachEvent ) {
for( i in {
submit: 1,
change: 1,
focusin: 1
}) {
eventName = "on" + i;
isSupported = ( eventName in div );
if ( !isSupported ) {
div.setAttribute( eventName, "return;" );
isSupported = ( typeof div[ eventName ] === "function" );
}
support[ i + "Bubbles" ] = isSupported;
}
}
fragment.removeChild( div );
// Null elements to avoid leaks in IE
fragment = select = opt = marginDiv = div = input = null;
// Run tests that need a body at doc ready
jQuery(function() {
var container, outer, inner, table, td, offsetSupport,
conMarginTop, ptlm, vb, style, html,
body = document.getElementsByTagName("body")[0];
if ( !body ) {
// Return for frameset docs that don't have a body
return;
}
conMarginTop = 1;
ptlm = "position:absolute;top:0;left:0;width:1px;height:1px;margin:0;";
vb = "visibility:hidden;border:0;";
style = "style='" + ptlm + "border:5px solid #000;padding:0;'";
html = "<div " + style + "><div></div></div>" +
"<table " + style + " cellpadding='0' cellspacing='0'>" +
"<tr><td></td></tr></table>";
container = document.createElement("div");
container.style.cssText = vb + "width:0;height:0;position:static;top:0;margin-top:" + conMarginTop + "px";
body.insertBefore( container, body.firstChild );
// Construct the test element
div = document.createElement("div");
container.appendChild( div );
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
// (only IE 8 fails this test)
div.innerHTML = "<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>";
tds = div.getElementsByTagName( "td" );
isSupported = ( tds[ 0 ].offsetHeight === 0 );
tds[ 0 ].style.display = "";
tds[ 1 ].style.display = "none";
// Check if empty table cells still have offsetWidth/Height
// (IE <= 8 fail this test)
support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
// Figure out if the W3C box model works as expected
div.innerHTML = "";
div.style.width = div.style.paddingLeft = "1px";
jQuery.boxModel = support.boxModel = div.offsetWidth === 2;
if ( typeof div.style.zoom !== "undefined" ) {
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
// (IE < 8 does this)
div.style.display = "inline";
div.style.zoom = 1;
support.inlineBlockNeedsLayout = ( div.offsetWidth === 2 );
// Check if elements with layout shrink-wrap their children
// (IE 6 does this)
div.style.display = "";
div.innerHTML = "<div style='width:4px;'></div>";
support.shrinkWrapBlocks = ( div.offsetWidth !== 2 );
}
div.style.cssText = ptlm + vb;
div.innerHTML = html;
outer = div.firstChild;
inner = outer.firstChild;
td = outer.nextSibling.firstChild.firstChild;
offsetSupport = {
doesNotAddBorder: ( inner.offsetTop !== 5 ),
doesAddBorderForTableAndCells: ( td.offsetTop === 5 )
};
inner.style.position = "fixed";
inner.style.top = "20px";
// safari subtracts parent border width here which is 5px
offsetSupport.fixedPosition = ( inner.offsetTop === 20 || inner.offsetTop === 15 );
inner.style.position = inner.style.top = "";
outer.style.overflow = "hidden";
outer.style.position = "relative";
offsetSupport.subtractsBorderForOverflowNotVisible = ( inner.offsetTop === -5 );
offsetSupport.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== conMarginTop );
body.removeChild( container );
div = container = null;
jQuery.extend( support, offsetSupport );
});
return support;
})();
var rbrace = /^(?:\{.*\}|\[.*\])$/,
rmultiDash = /([A-Z])/g;
jQuery.extend({
cache: {},
// Please use with caution
uuid: 0,
// Unique for each copy of jQuery on the page
// Non-digits removed to match rinlinejQuery
expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ),
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
noData: {
"embed": true,
// Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
"applet": true
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var privateCache, thisCache, ret,
internalKey = jQuery.expando,
getByName = typeof name === "string",
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey,
isEvents = name === "events";
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( (!id || !cache[id] || (!isEvents && !pvt && !cache[id].data)) && getByName && data === undefined ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
elem[ internalKey ] = id = ++jQuery.uuid;
} else {
id = internalKey;
}
}
if ( !cache[ id ] ) {
cache[ id ] = {};
// Avoids exposing jQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
if ( !isNode ) {
cache[ id ].toJSON = jQuery.noop;
}
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ] = jQuery.extend( cache[ id ], name );
} else {
cache[ id ].data = jQuery.extend( cache[ id ].data, name );
}
}
privateCache = thisCache = cache[ id ];
// jQuery data() is stored in a separate object inside the object's internal data
// cache in order to avoid key collisions between internal data and user-defined
// data.
if ( !pvt ) {
if ( !thisCache.data ) {
thisCache.data = {};
}
thisCache = thisCache.data;
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// Users should not attempt to inspect the internal events object using jQuery.data,
// it is undocumented and subject to change. But does anyone listen? No.
if ( isEvents && !thisCache[ name ] ) {
return privateCache.events;
}
// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if ( getByName ) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if ( ret == null ) {
// Try to find the camelCased property
ret = thisCache[ jQuery.camelCase( name ) ];
}
} else {
ret = thisCache;
}
return ret;
},
removeData: function( elem, name, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, i, l,
// Reference to internal data cache key
internalKey = jQuery.expando,
isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
// See jQuery.data for more information
id = isNode ? elem[ internalKey ] : internalKey;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
thisCache = pvt ? cache[ id ] : cache[ id ].data;
if ( thisCache ) {
// Support array or space separated string names for data keys
if ( !jQuery.isArray( name ) ) {
// try the string as a key before any manipulation
if ( name in thisCache ) {
name = [ name ];
} else {
// split the camel cased version by spaces unless a key with the spaces exists
name = jQuery.camelCase( name );
if ( name in thisCache ) {
name = [ name ];
} else {
name = name.split( " " );
}
}
}
for ( i = 0, l = name.length; i < l; i++ ) {
delete thisCache[ name[i] ];
}
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) {
return;
}
}
}
// See jQuery.data for more information
if ( !pvt ) {
delete cache[ id ].data;
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject(cache[ id ]) ) {
return;
}
}
// Browsers that fail expando deletion also refuse to delete expandos on
// the window, but it will allow it on all other JS objects; other browsers
// don't care
// Ensure that `cache` is not a window object #10080
if ( jQuery.support.deleteExpando || !cache.setInterval ) {
delete cache[ id ];
} else {
cache[ id ] = null;
}
// We destroyed the cache and need to eliminate the expando on the node to avoid
// false lookups in the cache for entries that no longer exist
if ( isNode ) {
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( jQuery.support.deleteExpando ) {
delete elem[ internalKey ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = null;
}
}
},
// For internal use only.
_data: function( elem, name, data ) {
return jQuery.data( elem, name, data, true );
},
// A method for determining if a DOM node can handle the data expando
acceptData: function( elem ) {
if ( elem.nodeName ) {
var match = jQuery.noData[ elem.nodeName.toLowerCase() ];
if ( match ) {
return !(match === true || elem.getAttribute("classid") !== match);
}
}
return true;
}
});
jQuery.fn.extend({
data: function( key, value ) {
var parts, attr, name,
data = null;
if ( typeof key === "undefined" ) {
if ( this.length ) {
data = jQuery.data( this[0] );
if ( this[0].nodeType === 1 && !jQuery._data( this[0], "parsedAttrs" ) ) {
attr = this[0].attributes;
for ( var i = 0, l = attr.length; i < l; i++ ) {
name = attr[i].name;
if ( name.indexOf( "data-" ) === 0 ) {
name = jQuery.camelCase( name.substring(5) );
dataAttr( this[0], name, data[ name ] );
}
}
jQuery._data( this[0], "parsedAttrs", true );
}
}
return data;
} else if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
parts = key.split(".");
parts[1] = parts[1] ? "." + parts[1] : "";
if ( value === undefined ) {
data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);
// Try to fetch any internally stored data first
if ( data === undefined && this.length ) {
data = jQuery.data( this[0], key );
data = dataAttr( this[0], key, data );
}
return data === undefined && parts[1] ?
this.data( parts[0] ) :
data;
} else {
return this.each(function() {
var self = jQuery( this ),
args = [ parts[0], value ];
self.triggerHandler( "setData" + parts[1] + "!", args );
jQuery.data( this, key, value );
self.triggerHandler( "changeData" + parts[1] + "!", args );
});
}
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
jQuery.isNumeric( data ) ? parseFloat( data ) :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
for ( var name in obj ) {
// if the public data object is empty, the private is still empty
if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
continue;
}
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
function handleQueueMarkDefer( elem, type, src ) {
var deferDataKey = type + "defer",
queueDataKey = type + "queue",
markDataKey = type + "mark",
defer = jQuery._data( elem, deferDataKey );
if ( defer &&
( src === "queue" || !jQuery._data(elem, queueDataKey) ) &&
( src === "mark" || !jQuery._data(elem, markDataKey) ) ) {
// Give room for hard-coded callbacks to fire first
// and eventually mark/queue something else on the element
setTimeout( function() {
if ( !jQuery._data( elem, queueDataKey ) &&
!jQuery._data( elem, markDataKey ) ) {
jQuery.removeData( elem, deferDataKey, true );
defer.fire();
}
}, 0 );
}
}
jQuery.extend({
_mark: function( elem, type ) {
if ( elem ) {
type = ( type || "fx" ) + "mark";
jQuery._data( elem, type, (jQuery._data( elem, type ) || 0) + 1 );
}
},
_unmark: function( force, elem, type ) {
if ( force !== true ) {
type = elem;
elem = force;
force = false;
}
if ( elem ) {
type = type || "fx";
var key = type + "mark",
count = force ? 0 : ( (jQuery._data( elem, key ) || 1) - 1 );
if ( count ) {
jQuery._data( elem, key, count );
} else {
jQuery.removeData( elem, key, true );
handleQueueMarkDefer( elem, type, "mark" );
}
}
},
queue: function( elem, type, data ) {
var q;
if ( elem ) {
type = ( type || "fx" ) + "queue";
q = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !q || jQuery.isArray(data) ) {
q = jQuery._data( elem, type, jQuery.makeArray(data) );
} else {
q.push( data );
}
}
return q || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
fn = queue.shift(),
hooks = {};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
jQuery._data( elem, type + ".run", hooks );
fn.call( elem, function() {
jQuery.dequeue( elem, type );
}, hooks );
}
if ( !queue.length ) {
jQuery.removeData( elem, type + "queue " + type + ".run", true );
handleQueueMarkDefer( elem, type, "queue" );
}
}
});
jQuery.fn.extend({
queue: function( type, data ) {
if ( typeof type !== "string" ) {
data = type;
type = "fx";
}
if ( data === undefined ) {
return jQuery.queue( this[0], type );
}
return this.each(function() {
var queue = jQuery.queue( this, type, data );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
delay: function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, object ) {
if ( typeof type !== "string" ) {
object = type;
type = undefined;
}
type = type || "fx";
var defer = jQuery.Deferred(),
elements = this,
i = elements.length,
count = 1,
deferDataKey = type + "defer",
queueDataKey = type + "queue",
markDataKey = type + "mark",
tmp;
function resolve() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
}
while( i-- ) {
if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) ||
( jQuery.data( elements[ i ], queueDataKey, undefined, true ) ||
jQuery.data( elements[ i ], markDataKey, undefined, true ) ) &&
jQuery.data( elements[ i ], deferDataKey, jQuery.Callbacks( "once memory" ), true ) )) {
count++;
tmp.add( resolve );
}
}
resolve();
return defer.promise();
}
});
var rclass = /[\n\t\r]/g,
rspace = /\s+/,
rreturn = /\r/g,
rtype = /^(?:button|input)$/i,
rfocusable = /^(?:button|input|object|select|textarea)$/i,
rclickable = /^a(?:rea)?$/i,
rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,
getSetAttribute = jQuery.support.getSetAttribute,
nodeHook, boolHook, fixSpecified;
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, name, value, true, jQuery.attr );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
},
prop: function( name, value ) {
return jQuery.access( this, name, value, true, jQuery.prop );
},
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each(function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch( e ) {}
});
},
addClass: function( value ) {
var classNames, i, l, elem,
setClass, c, cl;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call(this, j, this.className) );
});
}
if ( value && typeof value === "string" ) {
classNames = value.split( rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 ) {
if ( !elem.className && classNames.length === 1 ) {
elem.className = value;
} else {
setClass = " " + elem.className + " ";
for ( c = 0, cl = classNames.length; c < cl; c++ ) {
if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) {
setClass += classNames[ c ] + " ";
}
}
elem.className = jQuery.trim( setClass );
}
}
}
}
return this;
},
removeClass: function( value ) {
var classNames, i, l, elem, className, c, cl;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call(this, j, this.className) );
});
}
if ( (value && typeof value === "string") || value === undefined ) {
classNames = ( value || "" ).split( rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 && elem.className ) {
if ( value ) {
className = (" " + elem.className + " ").replace( rclass, " " );
for ( c = 0, cl = classNames.length; c < cl; c++ ) {
className = className.replace(" " + classNames[ c ] + " ", " ");
}
elem.className = jQuery.trim( className );
} else {
elem.className = "";
}
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value,
isBool = typeof stateVal === "boolean";
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
state = stateVal,
classNames = value.split( rspace );
while ( (className = classNames[ i++ ]) ) {
// check each className given, space seperated list
state = isBool ? state : !self.hasClass( className );
self[ state ? "addClass" : "removeClass" ]( className );
}
} else if ( type === "undefined" || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery._data( this, "__className__", this.className );
}
// toggle whole className
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) {
return true;
}
}
return false;
},
val: function( value ) {
var hooks, ret, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.nodeName.toLowerCase() ] || jQuery.valHooks[ elem.type ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var self = jQuery(this), val;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, self.val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map(val, function ( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.nodeName.toLowerCase() ] || jQuery.valHooks[ this.type ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
// attributes.value is undefined in Blackberry 4.7 but
// uses .value. See #6932
var val = elem.attributes.value;
return !val || val.specified ? elem.value : elem.text;
}
},
select: {
get: function( elem ) {
var value, i, max, option,
index = elem.selectedIndex,
values = [],
options = elem.options,
one = elem.type === "select-one";
// Nothing was selected
if ( index < 0 ) {
return null;
}
// Loop through all the selected options
i = one ? index : 0;
max = one ? index + 1 : options.length;
for ( ; i < max; i++ ) {
option = options[ i ];
// Don't return options that are disabled or in a disabled optgroup
if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) &&
(!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
// Fixes Bug #2551 -- select.val() broken in IE after form.reset()
if ( one && !values.length && options.length ) {
return jQuery( options[ index ] ).val();
}
return values;
},
set: function( elem, value ) {
var values = jQuery.makeArray( value );
jQuery(elem).find("option").each(function() {
this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
});
if ( !values.length ) {
elem.selectedIndex = -1;
}
return values;
}
}
},
attrFn: {
val: true,
css: true,
html: true,
text: true,
data: true,
width: true,
height: true,
offset: true
},
attr: function( elem, name, value, pass ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
if ( pass && name in jQuery.attrFn ) {
return jQuery( elem )[ name ]( value );
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === "undefined" ) {
return jQuery.prop( elem, name, value );
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( notxml ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
return;
} else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, "" + value );
return value;
}
} else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = elem.getAttribute( name );
// Non-existent attributes return null, we normalize to undefined
return ret === null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var propName, attrNames, name, l,
i = 0;
if ( value && elem.nodeType === 1 ) {
attrNames = value.toLowerCase().split( rspace );
l = attrNames.length;
for ( ; i < l; i++ ) {
name = attrNames[ i ];
if ( name ) {
propName = jQuery.propFix[ name ] || name;
// See #9699 for explanation of this approach (setting first, then removal)
jQuery.attr( elem, name, "" );
elem.removeAttribute( getSetAttribute ? name : propName );
// Set corresponding property to false for boolean attributes
if ( rboolean.test( name ) && propName in elem ) {
elem[ propName ] = false;
}
}
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
// We can't allow the type property to be changed (since it causes problems in IE)
if ( rtype.test( elem.nodeName ) && elem.parentNode ) {
jQuery.error( "type property can't be changed" );
} else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to it's default in case type is set after value
// This is for element creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
},
// Use the value property for back compat
// Use the nodeHook for button elements in IE6/7 (#1954)
value: {
get: function( elem, name ) {
if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
return nodeHook.get( elem, name );
}
return name in elem ?
elem.value :
null;
},
set: function( elem, value, name ) {
if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
return nodeHook.set( elem, value, name );
}
// Does not return so that setAttribute is also used
elem.value = value;
}
}
},
propFix: {
tabindex: "tabIndex",
readonly: "readOnly",
"for": "htmlFor",
"class": "className",
maxlength: "maxLength",
cellspacing: "cellSpacing",
cellpadding: "cellPadding",
rowspan: "rowSpan",
colspan: "colSpan",
usemap: "useMap",
frameborder: "frameBorder",
contenteditable: "contentEditable"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
return ( elem[ name ] = value );
}
} else {
if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
return elem[ name ];
}
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
var attributeNode = elem.getAttributeNode("tabindex");
return attributeNode && attributeNode.specified ?
parseInt( attributeNode.value, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
undefined;
}
}
}
});
// Add the tabIndex propHook to attrHooks for back-compat (different case is intentional)
jQuery.attrHooks.tabindex = jQuery.propHooks.tabIndex;
// Hook for boolean attributes
boolHook = {
get: function( elem, name ) {
// Align boolean attributes with corresponding properties
// Fall back to attribute presence where some booleans are not supported
var attrNode,
property = jQuery.prop( elem, name );
return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ?
name.toLowerCase() :
undefined;
},
set: function( elem, value, name ) {
var propName;
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else {
// value is true since we know at this point it's type boolean and not false
// Set boolean attributes to the same name and set the DOM property
propName = jQuery.propFix[ name ] || name;
if ( propName in elem ) {
// Only set the IDL specifically if it already exists on the element
elem[ propName ] = true;
}
elem.setAttribute( name, name.toLowerCase() );
}
return name;
}
};
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {
fixSpecified = {
name: true,
id: true
};
// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = jQuery.valHooks.button = {
get: function( elem, name ) {
var ret;
ret = elem.getAttributeNode( name );
return ret && ( fixSpecified[ name ] ? ret.nodeValue !== "" : ret.specified ) ?
ret.nodeValue :
undefined;
},
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
ret = document.createAttribute( name );
elem.setAttributeNode( ret );
}
return ( ret.nodeValue = value + "" );
}
};
// Apply the nodeHook to tabindex
jQuery.attrHooks.tabindex.set = nodeHook.set;
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
});
});
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable = {
get: nodeHook.get,
set: function( elem, value, name ) {
if ( value === "" ) {
value = "false";
}
nodeHook.set( elem, value, name );
}
};
}
// Some attributes require a special call on IE
if ( !jQuery.support.hrefNormalized ) {
jQuery.each([ "href", "src", "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
get: function( elem ) {
var ret = elem.getAttribute( name, 2 );
return ret === null ? undefined : ret;
}
});
});
}
if ( !jQuery.support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Normalize to lowercase since IE uppercases css property names
return elem.style.cssText.toLowerCase() || undefined;
},
set: function( elem, value ) {
return ( elem.style.cssText = "" + value );
}
};
}
// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !jQuery.support.optSelected ) {
jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
return null;
}
});
}
// IE6/7 call enctype encoding
if ( !jQuery.support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
// Radios and checkboxes getter/setter
if ( !jQuery.support.checkOn ) {
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
get: function( elem ) {
// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
}
};
});
}
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
});
});
var rformElems = /^(?:textarea|input|select)$/i,
rtypenamespace = /^([^\.]*)?(?:\.(.+))?$/,
rhoverHack = /\bhover(\.\S+)?\b/,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rquickIs = /^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,
quickParse = function( selector ) {
var quick = rquickIs.exec( selector );
if ( quick ) {
// 0 1 2 3
// [ _, tag, id, class ]
quick[1] = ( quick[1] || "" ).toLowerCase();
quick[3] = quick[3] && new RegExp( "(?:^|\\s)" + quick[3] + "(?:\\s|$)" );
}
return quick;
},
quickIs = function( elem, m ) {
var attrs = elem.attributes || {};
return (
(!m[1] || elem.nodeName.toLowerCase() === m[1]) &&
(!m[2] || (attrs.id || {}).value === m[2]) &&
(!m[3] || m[3].test( (attrs[ "class" ] || {}).value ))
);
},
hoverHack = function( events ) {
return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" );
};
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
add: function( elem, types, handler, data, selector ) {
var elemData, eventHandle, events,
t, tns, type, namespaces, handleObj,
handleObjIn, quick, handlers, special;
// Don't attach events to noData or text/comment nodes (allow plain objects tho)
if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
events = elemData.events;
if ( !events ) {
elemData.events = events = {};
}
eventHandle = elemData.handle;
if ( !eventHandle ) {
elemData.handle = eventHandle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
// jQuery(...).bind("mouseover mouseout", fn);
types = jQuery.trim( hoverHack(types) ).split( " " );
for ( t = 0; t < types.length; t++ ) {
tns = rtypenamespace.exec( types[t] ) || [];
type = tns[1];
namespaces = ( tns[2] || "" ).split( "." ).sort();
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: tns[1],
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
quick: quickParse( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
handlers = events[ type ];
if ( !handlers ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener/attachEvent if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
global: {},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var elemData = jQuery.hasData( elem ) && jQuery._data( elem ),
t, tns, type, origType, namespaces, origCount,
j, events, special, handle, eventType, handleObj;
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = jQuery.trim( hoverHack( types || "" ) ).split(" ");
for ( t = 0; t < types.length; t++ ) {
tns = rtypenamespace.exec( types[t] ) || [];
type = origType = tns[1];
namespaces = tns[2];
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector? special.delegateType : special.bindType ) || type;
eventType = events[ type ] || [];
origCount = eventType.length;
namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.)?") + "(\\.|$)") : null;
// Remove matching events
for ( j = 0; j < eventType.length; j++ ) {
handleObj = eventType[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !namespaces || namespaces.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
eventType.splice( j--, 1 );
if ( handleObj.selector ) {
eventType.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( eventType.length === 0 && origCount !== eventType.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
handle = elemData.handle;
if ( handle ) {
handle.elem = null;
}
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery.removeData( elem, [ "events", "handle" ], true );
}
},
// Events that are safe to short-circuit if no handlers are attached.
// Native DOM events should not be added, they may have inline handlers.
customEvent: {
"getData": true,
"setData": true,
"changeData": true
},
trigger: function( event, data, elem, onlyHandlers ) {
// Don't do events on text and comment nodes
if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) {
return;
}
// Event object or event type
var type = event.type || event,
namespaces = [],
cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType;
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf( "!" ) >= 0 ) {
// Exclusive events trigger only for the exact event (no namespaces)
type = type.slice(0, -1);
exclusive = true;
}
if ( type.indexOf( "." ) >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) {
// No jQuery handlers for this event type, and it can't have inline handlers
return;
}
// Caller can pass in an Event, Object, or just an event type string
event = typeof event === "object" ?
// jQuery.Event object
event[ jQuery.expando ] ? event :
// Object literal
new jQuery.Event( type, event ) :
// Just the event type (string)
new jQuery.Event( type );
event.type = type;
event.isTrigger = true;
event.exclusive = exclusive;
event.namespace = namespaces.join( "." );
event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)") : null;
ontype = type.indexOf( ":" ) < 0 ? "on" + type : "";
// Handle a global trigger
if ( !elem ) {
// TODO: Stop taunting the data cache; remove global events and always attach to document
cache = jQuery.cache;
for ( i in cache ) {
if ( cache[ i ].events && cache[ i ].events[ type ] ) {
jQuery.event.trigger( event, data, cache[ i ].handle.elem, true );
}
}
return;
}
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data != null ? jQuery.makeArray( data ) : [];
data.unshift( event );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
eventPath = [[ elem, special.bindType || type ]];
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode;
old = null;
for ( ; cur; cur = cur.parentNode ) {
eventPath.push([ cur, bubbleType ]);
old = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( old && old === elem.ownerDocument ) {
eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]);
}
}
// Fire handlers on the event path
for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) {
cur = eventPath[i][0];
event.type = eventPath[i][1];
handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Note that this is a bare JS function and not a jQuery handler
handle = ontype && cur[ ontype ];
if ( handle && jQuery.acceptData( cur ) && handle.apply( cur, data ) === false ) {
event.preventDefault();
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) &&
!(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction() check here because IE6/7 fails that test.
// Don't do default actions on window, that's where global variables be (#6170)
// IE<9 dies on focus/blur to hidden element (#1486)
if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
old = elem[ ontype ];
if ( old ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
elem[ type ]();
jQuery.event.triggered = undefined;
if ( old ) {
elem[ ontype ] = old;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event || window.event );
var handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []),
delegateCount = handlers.delegateCount,
args = [].slice.call( arguments, 0 ),
run_all = !event.exclusive && !event.namespace,
handlerQueue = [],
i, j, cur, jqcur, ret, selMatch, matched, matches, handleObj, sel, related;
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Determine handlers that should run if there are delegated events
// Avoid disabled elements in IE (#6911) and non-left-click bubbling in Firefox (#3861)
if ( delegateCount && !event.target.disabled && !(event.button && event.type === "click") ) {
// Pregenerate a single jQuery object for reuse with .is()
jqcur = jQuery(this);
jqcur.context = this.ownerDocument || this;
for ( cur = event.target; cur != this; cur = cur.parentNode || this ) {
selMatch = {};
matches = [];
jqcur[0] = cur;
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
sel = handleObj.selector;
if ( selMatch[ sel ] === undefined ) {
selMatch[ sel ] = (
handleObj.quick ? quickIs( cur, handleObj.quick ) : jqcur.is( sel )
);
}
if ( selMatch[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, matches: matches });
}
}
}
// Add the remaining (directly-bound) handlers
if ( handlers.length > delegateCount ) {
handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) });
}
// Run delegates first; they may want to stop propagation beneath us
for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) {
matched = handlerQueue[ i ];
event.currentTarget = matched.elem;
for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) {
handleObj = matched.matches[ j ];
// Triggered event must either 1) be non-exclusive and have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) {
event.data = handleObj.data;
event.handleObj = handleObj;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
event.result = ret;
if ( ret === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
return event.result;
},
// Includes some event props shared by KeyEvent and MouseEvent
// *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 ***
props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var eventDoc, doc, body,
button = original.button,
fromElement = original.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && fromElement ) {
event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop,
originalEvent = event,
fixHook = jQuery.event.fixHooks[ event.type ] || {},
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = jQuery.Event( originalEvent );
for ( i = copy.length; i; ) {
prop = copy[ --i ];
event[ prop ] = originalEvent[ prop ];
}
// Fix target property, if necessary (#1925, IE 6/7/8 & Safari2)
if ( !event.target ) {
event.target = originalEvent.srcElement || document;
}
// Target should not be a text node (#504, Safari)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// For mouse/key events; add metaKey if it's not there (#3368, IE6/7/8)
if ( event.metaKey === undefined ) {
event.metaKey = event.ctrlKey;
}
return fixHook.filter? fixHook.filter( event, originalEvent ) : event;
},
special: {
ready: {
// Make sure the ready event is setup
setup: jQuery.bindReady
},
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
delegateType: "focusin"
},
blur: {
delegateType: "focusout"
},
beforeunload: {
setup: function( data, namespaces, eventHandle ) {
// We only want to do this special case on windows
if ( jQuery.isWindow( this ) ) {
this.onbeforeunload = eventHandle;
}
},
teardown: function( namespaces, eventHandle ) {
if ( this.onbeforeunload === eventHandle ) {
this.onbeforeunload = null;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{ type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
// Some plugins are using, but it's undocumented/deprecated and will be removed.
// The 1.7 special event interface should provide all the hooks needed now.
jQuery.event.handle = jQuery.event.dispatch;
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
if ( elem.detachEvent ) {
elem.detachEvent( "on" + type, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false ||
src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
function returnFalse() {
return false;
}
function returnTrue() {
return true;
}
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
preventDefault: function() {
this.isDefaultPrevented = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if preventDefault exists run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// otherwise set the returnValue property of the original event to false (IE)
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
this.isPropagationStopped = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if stopPropagation exists run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// otherwise set the cancelBubble property of the original event to true (IE)
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
},
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse
};
// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var target = this,
related = event.relatedTarget,
handleObj = event.handleObj,
selector = handleObj.selector,
ret;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// IE submit delegation
if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
// Node name check avoids a VML-related crash in IE (#9807)
var elem = e.target,
form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
if ( form && !form._submit_attached ) {
jQuery.event.add( form, "submit._submit", function( event ) {
// If form was submitted by the user, bubble the event up the tree
if ( this.parentNode && !event.isTrigger ) {
jQuery.event.simulate( "submit", this.parentNode, event, true );
}
});
form._submit_attached = true;
}
});
// return undefined since we don't need an event listener
},
teardown: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
jQuery.event.remove( this, "._submit" );
}
};
}
// IE change delegation and checkbox/radio fix
if ( !jQuery.support.changeBubbles ) {
jQuery.event.special.change = {
setup: function() {
if ( rformElems.test( this.nodeName ) ) {
// IE doesn't fire change on a check/radio until blur; trigger it on click
// after a propertychange. Eat the blur-change in special.change.handle.
// This still fires onchange a second time for check/radio after blur.
if ( this.type === "checkbox" || this.type === "radio" ) {
jQuery.event.add( this, "propertychange._change", function( event ) {
if ( event.originalEvent.propertyName === "checked" ) {
this._just_changed = true;
}
});
jQuery.event.add( this, "click._change", function( event ) {
if ( this._just_changed && !event.isTrigger ) {
this._just_changed = false;
jQuery.event.simulate( "change", this, event, true );
}
});
}
return false;
}
// Delegated event; lazy-add a change handler on descendant inputs
jQuery.event.add( this, "beforeactivate._change", function( e ) {
var elem = e.target;
if ( rformElems.test( elem.nodeName ) && !elem._change_attached ) {
jQuery.event.add( elem, "change._change", function( event ) {
if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
jQuery.event.simulate( "change", this.parentNode, event, true );
}
});
elem._change_attached = true;
}
});
},
handle: function( event ) {
var elem = event.target;
// Swallow native change events from checkbox/radio, we already triggered them above
if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
return event.handleObj.handler.apply( this, arguments );
}
},
teardown: function() {
jQuery.event.remove( this, "._change" );
return rformElems.test( this.nodeName );
}
};
}
// Create "bubbling" focus and blur events
if ( !jQuery.support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler while someone wants focusin/focusout
var attaches = 0,
handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
if ( attaches++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --attaches === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var origFn, type;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on.call( this, types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
var handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace? handleObj.type + "." + handleObj.namespace : handleObj.type,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( var type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
live: function( types, data, fn ) {
jQuery( this.context ).on( types, this.selector, data, fn );
return this;
},
die: function( types, fn ) {
jQuery( this.context ).off( types, this.selector || "**", fn );
return this;
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length == 1? this.off( selector, "**" ) : this.off( types, selector, fn );
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
if ( this[0] ) {
return jQuery.event.trigger( type, data, this[0], true );
}
},
toggle: function( fn ) {
// Save reference to arguments for access in closure
var args = arguments,
guid = fn.guid || jQuery.guid++,
i = 0,
toggler = function( event ) {
// Figure out which function to execute
var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i;
jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 );
// Make sure that clicks stop
event.preventDefault();
// and execute the function
return args[ lastToggle ].apply( this, arguments ) || false;
};
// link all the functions, so any of them can unbind this click handler
toggler.guid = guid;
while ( i < args.length ) {
args[ i++ ].guid = guid;
}
return this.click( toggler );
},
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
}
});
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
if ( jQuery.attrFn ) {
jQuery.attrFn[ name ] = true;
}
if ( rkeyEvent.test( name ) ) {
jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks;
}
if ( rmouseEvent.test( name ) ) {
jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks;
}
});
/*!
* Sizzle CSS Selector Engine
* Copyright 2011, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
* More information: http://sizzlejs.com/
*/
(function(){
var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
expando = "sizcache" + (Math.random() + '').replace('.', ''),
done = 0,
toString = Object.prototype.toString,
hasDuplicate = false,
baseHasDuplicate = true,
rBackslash = /\\/g,
rReturn = /\r\n/g,
rNonWord = /\W/;
// Here we check if the JavaScript engine is using some sort of
// optimization where it does not always call our comparision
// function. If that is the case, discard the hasDuplicate value.
// Thus far that includes Google Chrome.
[0, 0].sort(function() {
baseHasDuplicate = false;
return 0;
});
var Sizzle = function( selector, context, results, seed ) {
results = results || [];
context = context || document;
var origContext = context;
if ( context.nodeType !== 1 && context.nodeType !== 9 ) {
return [];
}
if ( !selector || typeof selector !== "string" ) {
return results;
}
var m, set, checkSet, extra, ret, cur, pop, i,
prune = true,
contextXML = Sizzle.isXML( context ),
parts = [],
soFar = selector;
// Reset the position of the chunker regexp (start from head)
do {
chunker.exec( "" );
m = chunker.exec( soFar );
if ( m ) {
soFar = m[3];
parts.push( m[1] );
if ( m[2] ) {
extra = m[3];
break;
}
}
} while ( m );
if ( parts.length > 1 && origPOS.exec( selector ) ) {
if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
set = posProcess( parts[0] + parts[1], context, seed );
} else {
set = Expr.relative[ parts[0] ] ?
[ context ] :
Sizzle( parts.shift(), context );
while ( parts.length ) {
selector = parts.shift();
if ( Expr.relative[ selector ] ) {
selector += parts.shift();
}
set = posProcess( selector, set, seed );
}
}
} else {
// Take a shortcut and set the context if the root selector is an ID
// (but not if it'll be faster if the inner selector is an ID)
if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML &&
Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) {
ret = Sizzle.find( parts.shift(), context, contextXML );
context = ret.expr ?
Sizzle.filter( ret.expr, ret.set )[0] :
ret.set[0];
}
if ( context ) {
ret = seed ?
{ expr: parts.pop(), set: makeArray(seed) } :
Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML );
set = ret.expr ?
Sizzle.filter( ret.expr, ret.set ) :
ret.set;
if ( parts.length > 0 ) {
checkSet = makeArray( set );
} else {
prune = false;
}
while ( parts.length ) {
cur = parts.pop();
pop = cur;
if ( !Expr.relative[ cur ] ) {
cur = "";
} else {
pop = parts.pop();
}
if ( pop == null ) {
pop = context;
}
Expr.relative[ cur ]( checkSet, pop, contextXML );
}
} else {
checkSet = parts = [];
}
}
if ( !checkSet ) {
checkSet = set;
}
if ( !checkSet ) {
Sizzle.error( cur || selector );
}
if ( toString.call(checkSet) === "[object Array]" ) {
if ( !prune ) {
results.push.apply( results, checkSet );
} else if ( context && context.nodeType === 1 ) {
for ( i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) {
results.push( set[i] );
}
}
} else {
for ( i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
results.push( set[i] );
}
}
}
} else {
makeArray( checkSet, results );
}
if ( extra ) {
Sizzle( extra, origContext, results, seed );
Sizzle.uniqueSort( results );
}
return results;
};
Sizzle.uniqueSort = function( results ) {
if ( sortOrder ) {
hasDuplicate = baseHasDuplicate;
results.sort( sortOrder );
if ( hasDuplicate ) {
for ( var i = 1; i < results.length; i++ ) {
if ( results[i] === results[ i - 1 ] ) {
results.splice( i--, 1 );
}
}
}
}
return results;
};
Sizzle.matches = function( expr, set ) {
return Sizzle( expr, null, null, set );
};
Sizzle.matchesSelector = function( node, expr ) {
return Sizzle( expr, null, null, [node] ).length > 0;
};
Sizzle.find = function( expr, context, isXML ) {
var set, i, len, match, type, left;
if ( !expr ) {
return [];
}
for ( i = 0, len = Expr.order.length; i < len; i++ ) {
type = Expr.order[i];
if ( (match = Expr.leftMatch[ type ].exec( expr )) ) {
left = match[1];
match.splice( 1, 1 );
if ( left.substr( left.length - 1 ) !== "\\" ) {
match[1] = (match[1] || "").replace( rBackslash, "" );
set = Expr.find[ type ]( match, context, isXML );
if ( set != null ) {
expr = expr.replace( Expr.match[ type ], "" );
break;
}
}
}
}
if ( !set ) {
set = typeof context.getElementsByTagName !== "undefined" ?
context.getElementsByTagName( "*" ) :
[];
}
return { set: set, expr: expr };
};
Sizzle.filter = function( expr, set, inplace, not ) {
var match, anyFound,
type, found, item, filter, left,
i, pass,
old = expr,
result = [],
curLoop = set,
isXMLFilter = set && set[0] && Sizzle.isXML( set[0] );
while ( expr && set.length ) {
for ( type in Expr.filter ) {
if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) {
filter = Expr.filter[ type ];
left = match[1];
anyFound = false;
match.splice(1,1);
if ( left.substr( left.length - 1 ) === "\\" ) {
continue;
}
if ( curLoop === result ) {
result = [];
}
if ( Expr.preFilter[ type ] ) {
match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );
if ( !match ) {
anyFound = found = true;
} else if ( match === true ) {
continue;
}
}
if ( match ) {
for ( i = 0; (item = curLoop[i]) != null; i++ ) {
if ( item ) {
found = filter( item, match, i, curLoop );
pass = not ^ found;
if ( inplace && found != null ) {
if ( pass ) {
anyFound = true;
} else {
curLoop[i] = false;
}
} else if ( pass ) {
result.push( item );
anyFound = true;
}
}
}
}
if ( found !== undefined ) {
if ( !inplace ) {
curLoop = result;
}
expr = expr.replace( Expr.match[ type ], "" );
if ( !anyFound ) {
return [];
}
break;
}
}
}
// Improper expression
if ( expr === old ) {
if ( anyFound == null ) {
Sizzle.error( expr );
} else {
break;
}
}
old = expr;
}
return curLoop;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
/**
* Utility function for retreiving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
var getText = Sizzle.getText = function( elem ) {
var i, node,
nodeType = elem.nodeType,
ret = "";
if ( nodeType ) {
if ( nodeType === 1 || nodeType === 9 ) {
// Use textContent || innerText for elements
if ( typeof elem.textContent === 'string' ) {
return elem.textContent;
} else if ( typeof elem.innerText === 'string' ) {
// Replace IE's carriage returns
return elem.innerText.replace( rReturn, '' );
} else {
// Traverse it's children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
} else {
// If no nodeType, this is expected to be an array
for ( i = 0; (node = elem[i]); i++ ) {
// Do not traverse comment nodes
if ( node.nodeType !== 8 ) {
ret += getText( node );
}
}
}
return ret;
};
var Expr = Sizzle.selectors = {
order: [ "ID", "NAME", "TAG" ],
match: {
ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,
ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,
TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,
CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,
POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,
PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/
},
leftMatch: {},
attrMap: {
"class": "className",
"for": "htmlFor"
},
attrHandle: {
href: function( elem ) {
return elem.getAttribute( "href" );
},
type: function( elem ) {
return elem.getAttribute( "type" );
}
},
relative: {
"+": function(checkSet, part){
var isPartStr = typeof part === "string",
isTag = isPartStr && !rNonWord.test( part ),
isPartStrNotTag = isPartStr && !isTag;
if ( isTag ) {
part = part.toLowerCase();
}
for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
if ( (elem = checkSet[i]) ) {
while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}
checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ?
elem || false :
elem === part;
}
}
if ( isPartStrNotTag ) {
Sizzle.filter( part, checkSet, true );
}
},
">": function( checkSet, part ) {
var elem,
isPartStr = typeof part === "string",
i = 0,
l = checkSet.length;
if ( isPartStr && !rNonWord.test( part ) ) {
part = part.toLowerCase();
for ( ; i < l; i++ ) {
elem = checkSet[i];
if ( elem ) {
var parent = elem.parentNode;
checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false;
}
}
} else {
for ( ; i < l; i++ ) {
elem = checkSet[i];
if ( elem ) {
checkSet[i] = isPartStr ?
elem.parentNode :
elem.parentNode === part;
}
}
if ( isPartStr ) {
Sizzle.filter( part, checkSet, true );
}
}
},
"": function(checkSet, part, isXML){
var nodeCheck,
doneName = done++,
checkFn = dirCheck;
if ( typeof part === "string" && !rNonWord.test( part ) ) {
part = part.toLowerCase();
nodeCheck = part;
checkFn = dirNodeCheck;
}
checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML );
},
"~": function( checkSet, part, isXML ) {
var nodeCheck,
doneName = done++,
checkFn = dirCheck;
if ( typeof part === "string" && !rNonWord.test( part ) ) {
part = part.toLowerCase();
nodeCheck = part;
checkFn = dirNodeCheck;
}
checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML );
}
},
find: {
ID: function( match, context, isXML ) {
if ( typeof context.getElementById !== "undefined" && !isXML ) {
var m = context.getElementById(match[1]);
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
},
NAME: function( match, context ) {
if ( typeof context.getElementsByName !== "undefined" ) {
var ret = [],
results = context.getElementsByName( match[1] );
for ( var i = 0, l = results.length; i < l; i++ ) {
if ( results[i].getAttribute("name") === match[1] ) {
ret.push( results[i] );
}
}
return ret.length === 0 ? null : ret;
}
},
TAG: function( match, context ) {
if ( typeof context.getElementsByTagName !== "undefined" ) {
return context.getElementsByTagName( match[1] );
}
}
},
preFilter: {
CLASS: function( match, curLoop, inplace, result, not, isXML ) {
match = " " + match[1].replace( rBackslash, "" ) + " ";
if ( isXML ) {
return match;
}
for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
if ( elem ) {
if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) {
if ( !inplace ) {
result.push( elem );
}
} else if ( inplace ) {
curLoop[i] = false;
}
}
}
return false;
},
ID: function( match ) {
return match[1].replace( rBackslash, "" );
},
TAG: function( match, curLoop ) {
return match[1].replace( rBackslash, "" ).toLowerCase();
},
CHILD: function( match ) {
if ( match[1] === "nth" ) {
if ( !match[2] ) {
Sizzle.error( match[0] );
}
match[2] = match[2].replace(/^\+|\s*/g, '');
// parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec(
match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" ||
!/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);
// calculate the numbers (first)n+(last) including if they are negative
match[2] = (test[1] + (test[2] || 1)) - 0;
match[3] = test[3] - 0;
}
else if ( match[2] ) {
Sizzle.error( match[0] );
}
// TODO: Move to normal caching system
match[0] = done++;
return match;
},
ATTR: function( match, curLoop, inplace, result, not, isXML ) {
var name = match[1] = match[1].replace( rBackslash, "" );
if ( !isXML && Expr.attrMap[name] ) {
match[1] = Expr.attrMap[name];
}
// Handle if an un-quoted value was used
match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" );
if ( match[2] === "~=" ) {
match[4] = " " + match[4] + " ";
}
return match;
},
PSEUDO: function( match, curLoop, inplace, result, not ) {
if ( match[1] === "not" ) {
// If we're dealing with a complex expression, or a simple one
if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) {
match[3] = Sizzle(match[3], null, null, curLoop);
} else {
var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
if ( !inplace ) {
result.push.apply( result, ret );
}
return false;
}
} else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
return true;
}
return match;
},
POS: function( match ) {
match.unshift( true );
return match;
}
},
filters: {
enabled: function( elem ) {
return elem.disabled === false && elem.type !== "hidden";
},
disabled: function( elem ) {
return elem.disabled === true;
},
checked: function( elem ) {
return elem.checked === true;
},
selected: function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
parent: function( elem ) {
return !!elem.firstChild;
},
empty: function( elem ) {
return !elem.firstChild;
},
has: function( elem, i, match ) {
return !!Sizzle( match[3], elem ).length;
},
header: function( elem ) {
return (/h\d/i).test( elem.nodeName );
},
text: function( elem ) {
var attr = elem.getAttribute( "type" ), type = elem.type;
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null );
},
radio: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type;
},
checkbox: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type;
},
file: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "file" === elem.type;
},
password: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "password" === elem.type;
},
submit: function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && "submit" === elem.type;
},
image: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "image" === elem.type;
},
reset: function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && "reset" === elem.type;
},
button: function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && "button" === elem.type || name === "button";
},
input: function( elem ) {
return (/input|select|textarea|button/i).test( elem.nodeName );
},
focus: function( elem ) {
return elem === elem.ownerDocument.activeElement;
}
},
setFilters: {
first: function( elem, i ) {
return i === 0;
},
last: function( elem, i, match, array ) {
return i === array.length - 1;
},
even: function( elem, i ) {
return i % 2 === 0;
},
odd: function( elem, i ) {
return i % 2 === 1;
},
lt: function( elem, i, match ) {
return i < match[3] - 0;
},
gt: function( elem, i, match ) {
return i > match[3] - 0;
},
nth: function( elem, i, match ) {
return match[3] - 0 === i;
},
eq: function( elem, i, match ) {
return match[3] - 0 === i;
}
},
filter: {
PSEUDO: function( elem, match, i, array ) {
var name = match[1],
filter = Expr.filters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
} else if ( name === "contains" ) {
return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0;
} else if ( name === "not" ) {
var not = match[3];
for ( var j = 0, l = not.length; j < l; j++ ) {
if ( not[j] === elem ) {
return false;
}
}
return true;
} else {
Sizzle.error( name );
}
},
CHILD: function( elem, match ) {
var first, last,
doneName, parent, cache,
count, diff,
type = match[1],
node = elem;
switch ( type ) {
case "only":
case "first":
while ( (node = node.previousSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
if ( type === "first" ) {
return true;
}
node = elem;
case "last":
while ( (node = node.nextSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
return true;
case "nth":
first = match[2];
last = match[3];
if ( first === 1 && last === 0 ) {
return true;
}
doneName = match[0];
parent = elem.parentNode;
if ( parent && (parent[ expando ] !== doneName || !elem.nodeIndex) ) {
count = 0;
for ( node = parent.firstChild; node; node = node.nextSibling ) {
if ( node.nodeType === 1 ) {
node.nodeIndex = ++count;
}
}
parent[ expando ] = doneName;
}
diff = elem.nodeIndex - last;
if ( first === 0 ) {
return diff === 0;
} else {
return ( diff % first === 0 && diff / first >= 0 );
}
}
},
ID: function( elem, match ) {
return elem.nodeType === 1 && elem.getAttribute("id") === match;
},
TAG: function( elem, match ) {
return (match === "*" && elem.nodeType === 1) || !!elem.nodeName && elem.nodeName.toLowerCase() === match;
},
CLASS: function( elem, match ) {
return (" " + (elem.className || elem.getAttribute("class")) + " ")
.indexOf( match ) > -1;
},
ATTR: function( elem, match ) {
var name = match[1],
result = Sizzle.attr ?
Sizzle.attr( elem, name ) :
Expr.attrHandle[ name ] ?
Expr.attrHandle[ name ]( elem ) :
elem[ name ] != null ?
elem[ name ] :
elem.getAttribute( name ),
value = result + "",
type = match[2],
check = match[4];
return result == null ?
type === "!=" :
!type && Sizzle.attr ?
result != null :
type === "=" ?
value === check :
type === "*=" ?
value.indexOf(check) >= 0 :
type === "~=" ?
(" " + value + " ").indexOf(check) >= 0 :
!check ?
value && result !== false :
type === "!=" ?
value !== check :
type === "^=" ?
value.indexOf(check) === 0 :
type === "$=" ?
value.substr(value.length - check.length) === check :
type === "|=" ?
value === check || value.substr(0, check.length + 1) === check + "-" :
false;
},
POS: function( elem, match, i, array ) {
var name = match[2],
filter = Expr.setFilters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
}
}
}
};
var origPOS = Expr.match.POS,
fescape = function(all, num){
return "\\" + (num - 0 + 1);
};
for ( var type in Expr.match ) {
Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) );
Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) );
}
var makeArray = function( array, results ) {
array = Array.prototype.slice.call( array, 0 );
if ( results ) {
results.push.apply( results, array );
return results;
}
return array;
};
// Perform a simple check to determine if the browser is capable of
// converting a NodeList to an array using builtin methods.
// Also verifies that the returned array holds DOM nodes
// (which is not the case in the Blackberry browser)
try {
Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType;
// Provide a fallback method if it does not work
} catch( e ) {
makeArray = function( array, results ) {
var i = 0,
ret = results || [];
if ( toString.call(array) === "[object Array]" ) {
Array.prototype.push.apply( ret, array );
} else {
if ( typeof array.length === "number" ) {
for ( var l = array.length; i < l; i++ ) {
ret.push( array[i] );
}
} else {
for ( ; array[i]; i++ ) {
ret.push( array[i] );
}
}
}
return ret;
};
}
var sortOrder, siblingCheck;
if ( document.documentElement.compareDocumentPosition ) {
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
return 0;
}
if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) {
return a.compareDocumentPosition ? -1 : 1;
}
return a.compareDocumentPosition(b) & 4 ? -1 : 1;
};
} else {
sortOrder = function( a, b ) {
// The nodes are identical, we can exit early
if ( a === b ) {
hasDuplicate = true;
return 0;
// Fallback to using sourceIndex (in IE) if it's available on both nodes
} else if ( a.sourceIndex && b.sourceIndex ) {
return a.sourceIndex - b.sourceIndex;
}
var al, bl,
ap = [],
bp = [],
aup = a.parentNode,
bup = b.parentNode,
cur = aup;
// If the nodes are siblings (or identical) we can do a quick check
if ( aup === bup ) {
return siblingCheck( a, b );
// If no parents were found then the nodes are disconnected
} else if ( !aup ) {
return -1;
} else if ( !bup ) {
return 1;
}
// Otherwise they're somewhere else in the tree so we need
// to build up a full list of the parentNodes for comparison
while ( cur ) {
ap.unshift( cur );
cur = cur.parentNode;
}
cur = bup;
while ( cur ) {
bp.unshift( cur );
cur = cur.parentNode;
}
al = ap.length;
bl = bp.length;
// Start walking down the tree looking for a discrepancy
for ( var i = 0; i < al && i < bl; i++ ) {
if ( ap[i] !== bp[i] ) {
return siblingCheck( ap[i], bp[i] );
}
}
// We ended someplace up the tree so do a sibling check
return i === al ?
siblingCheck( a, bp[i], -1 ) :
siblingCheck( ap[i], b, 1 );
};
siblingCheck = function( a, b, ret ) {
if ( a === b ) {
return ret;
}
var cur = a.nextSibling;
while ( cur ) {
if ( cur === b ) {
return -1;
}
cur = cur.nextSibling;
}
return 1;
};
}
// Check to see if the browser returns elements by name when
// querying by getElementById (and provide a workaround)
(function(){
// We're going to inject a fake input element with a specified name
var form = document.createElement("div"),
id = "script" + (new Date()).getTime(),
root = document.documentElement;
form.innerHTML = "<a name='" + id + "'/>";
// Inject it into the root element, check its status, and remove it quickly
root.insertBefore( form, root.firstChild );
// The workaround has to do additional checks after a getElementById
// Which slows things down for other browsers (hence the branching)
if ( document.getElementById( id ) ) {
Expr.find.ID = function( match, context, isXML ) {
if ( typeof context.getElementById !== "undefined" && !isXML ) {
var m = context.getElementById(match[1]);
return m ?
m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ?
[m] :
undefined :
[];
}
};
Expr.filter.ID = function( elem, match ) {
var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
return elem.nodeType === 1 && node && node.nodeValue === match;
};
}
root.removeChild( form );
// release memory in IE
root = form = null;
})();
(function(){
// Check to see if the browser returns only elements
// when doing getElementsByTagName("*")
// Create a fake element
var div = document.createElement("div");
div.appendChild( document.createComment("") );
// Make sure no comments are found
if ( div.getElementsByTagName("*").length > 0 ) {
Expr.find.TAG = function( match, context ) {
var results = context.getElementsByTagName( match[1] );
// Filter out possible comments
if ( match[1] === "*" ) {
var tmp = [];
for ( var i = 0; results[i]; i++ ) {
if ( results[i].nodeType === 1 ) {
tmp.push( results[i] );
}
}
results = tmp;
}
return results;
};
}
// Check to see if an attribute returns normalized href attributes
div.innerHTML = "<a href='#'></a>";
if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
div.firstChild.getAttribute("href") !== "#" ) {
Expr.attrHandle.href = function( elem ) {
return elem.getAttribute( "href", 2 );
};
}
// release memory in IE
div = null;
})();
if ( document.querySelectorAll ) {
(function(){
var oldSizzle = Sizzle,
div = document.createElement("div"),
id = "__sizzle__";
div.innerHTML = "<p class='TEST'></p>";
// Safari can't handle uppercase or unicode characters when
// in quirks mode.
if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
return;
}
Sizzle = function( query, context, extra, seed ) {
context = context || document;
// Only use querySelectorAll on non-XML documents
// (ID selectors don't work in non-HTML documents)
if ( !seed && !Sizzle.isXML(context) ) {
// See if we find a selector to speed up
var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query );
if ( match && (context.nodeType === 1 || context.nodeType === 9) ) {
// Speed-up: Sizzle("TAG")
if ( match[1] ) {
return makeArray( context.getElementsByTagName( query ), extra );
// Speed-up: Sizzle(".CLASS")
} else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) {
return makeArray( context.getElementsByClassName( match[2] ), extra );
}
}
if ( context.nodeType === 9 ) {
// Speed-up: Sizzle("body")
// The body element only exists once, optimize finding it
if ( query === "body" && context.body ) {
return makeArray( [ context.body ], extra );
// Speed-up: Sizzle("#ID")
} else if ( match && match[3] ) {
var elem = context.getElementById( match[3] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id === match[3] ) {
return makeArray( [ elem ], extra );
}
} else {
return makeArray( [], extra );
}
}
try {
return makeArray( context.querySelectorAll(query), extra );
} catch(qsaError) {}
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
} else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
var oldContext = context,
old = context.getAttribute( "id" ),
nid = old || id,
hasParent = context.parentNode,
relativeHierarchySelector = /^\s*[+~]/.test( query );
if ( !old ) {
context.setAttribute( "id", nid );
} else {
nid = nid.replace( /'/g, "\\$&" );
}
if ( relativeHierarchySelector && hasParent ) {
context = context.parentNode;
}
try {
if ( !relativeHierarchySelector || hasParent ) {
return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra );
}
} catch(pseudoError) {
} finally {
if ( !old ) {
oldContext.removeAttribute( "id" );
}
}
}
}
return oldSizzle(query, context, extra, seed);
};
for ( var prop in oldSizzle ) {
Sizzle[ prop ] = oldSizzle[ prop ];
}
// release memory in IE
div = null;
})();
}
(function(){
var html = document.documentElement,
matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector;
if ( matches ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9 fails this)
var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ),
pseudoWorks = false;
try {
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( document.documentElement, "[test!='']:sizzle" );
} catch( pseudoError ) {
pseudoWorks = true;
}
Sizzle.matchesSelector = function( node, expr ) {
// Make sure that attribute selectors are quoted
expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']");
if ( !Sizzle.isXML( node ) ) {
try {
if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) {
var ret = matches.call( node, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || !disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9, so check for that
node.document && node.document.nodeType !== 11 ) {
return ret;
}
}
} catch(e) {}
}
return Sizzle(expr, null, null, [node]).length > 0;
};
}
})();
(function(){
var div = document.createElement("div");
div.innerHTML = "<div class='test e'></div><div class='test'></div>";
// Opera can't find a second classname (in 9.6)
// Also, make sure that getElementsByClassName actually exists
if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) {
return;
}
// Safari caches class attributes, doesn't catch changes (in 3.2)
div.lastChild.className = "e";
if ( div.getElementsByClassName("e").length === 1 ) {
return;
}
Expr.order.splice(1, 0, "CLASS");
Expr.find.CLASS = function( match, context, isXML ) {
if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {
return context.getElementsByClassName(match[1]);
}
};
// release memory in IE
div = null;
})();
function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
var match = false;
elem = elem[dir];
while ( elem ) {
if ( elem[ expando ] === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 && !isXML ){
elem[ expando ] = doneName;
elem.sizset = i;
}
if ( elem.nodeName.toLowerCase() === cur ) {
match = elem;
break;
}
elem = elem[dir];
}
checkSet[i] = match;
}
}
}
function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
var match = false;
elem = elem[dir];
while ( elem ) {
if ( elem[ expando ] === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 ) {
if ( !isXML ) {
elem[ expando ] = doneName;
elem.sizset = i;
}
if ( typeof cur !== "string" ) {
if ( elem === cur ) {
match = true;
break;
}
} else if ( Sizzle.filter( cur, [elem] ).length > 0 ) {
match = elem;
break;
}
}
elem = elem[dir];
}
checkSet[i] = match;
}
}
}
if ( document.documentElement.contains ) {
Sizzle.contains = function( a, b ) {
return a !== b && (a.contains ? a.contains(b) : true);
};
} else if ( document.documentElement.compareDocumentPosition ) {
Sizzle.contains = function( a, b ) {
return !!(a.compareDocumentPosition(b) & 16);
};
} else {
Sizzle.contains = function() {
return false;
};
}
Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
var posProcess = function( selector, context, seed ) {
var match,
tmpSet = [],
later = "",
root = context.nodeType ? [context] : context;
// Position selectors must be done after the filter
// And so must :not(positional) so we move all PSEUDOs to the end
while ( (match = Expr.match.PSEUDO.exec( selector )) ) {
later += match[0];
selector = selector.replace( Expr.match.PSEUDO, "" );
}
selector = Expr.relative[selector] ? selector + "*" : selector;
for ( var i = 0, l = root.length; i < l; i++ ) {
Sizzle( selector, root[i], tmpSet, seed );
}
return Sizzle.filter( later, tmpSet );
};
// EXPOSE
// Override sizzle attribute retrieval
Sizzle.attr = jQuery.attr;
Sizzle.selectors.attrMap = {};
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.filters;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
})();
var runtil = /Until$/,
rparentsprev = /^(?:parents|prevUntil|prevAll)/,
// Note: This RegExp should be improved, or likely pulled from Sizzle
rmultiselector = /,/,
isSimple = /^.[^:#\[\.,]*$/,
slice = Array.prototype.slice,
POS = jQuery.expr.match.POS,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend({
find: function( selector ) {
var self = this,
i, l;
if ( typeof selector !== "string" ) {
return jQuery( selector ).filter(function() {
for ( i = 0, l = self.length; i < l; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
});
}
var ret = this.pushStack( "", "find", selector ),
length, n, r;
for ( i = 0, l = this.length; i < l; i++ ) {
length = ret.length;
jQuery.find( selector, this[i], ret );
if ( i > 0 ) {
// Make sure that the results are unique
for ( n = length; n < ret.length; n++ ) {
for ( r = 0; r < length; r++ ) {
if ( ret[r] === ret[n] ) {
ret.splice(n--, 1);
break;
}
}
}
}
}
return ret;
},
has: function( target ) {
var targets = jQuery( target );
return this.filter(function() {
for ( var i = 0, l = targets.length; i < l; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
not: function( selector ) {
return this.pushStack( winnow(this, selector, false), "not", selector);
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector, true), "filter", selector );
},
is: function( selector ) {
return !!selector && (
typeof selector === "string" ?
// If this is a positional selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
POS.test( selector ) ?
jQuery( selector, this.context ).index( this[0] ) >= 0 :
jQuery.filter( selector, this ).length > 0 :
this.filter( selector ).length > 0 );
},
closest: function( selectors, context ) {
var ret = [], i, l, cur = this[0];
// Array (deprecated as of jQuery 1.7)
if ( jQuery.isArray( selectors ) ) {
var level = 1;
while ( cur && cur.ownerDocument && cur !== context ) {
for ( i = 0; i < selectors.length; i++ ) {
if ( jQuery( cur ).is( selectors[ i ] ) ) {
ret.push({ selector: selectors[ i ], elem: cur, level: level });
}
}
cur = cur.parentNode;
level++;
}
return ret;
}
// String
var pos = POS.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( i = 0, l = this.length; i < l; i++ ) {
cur = this[i];
while ( cur ) {
if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
ret.push( cur );
break;
} else {
cur = cur.parentNode;
if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) {
break;
}
}
}
}
ret = ret.length > 1 ? jQuery.unique( ret ) : ret;
return this.pushStack( ret, "closest", selectors );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return jQuery.inArray( this[0], jQuery( elem ) );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem, this );
},
add: function( selector, context ) {
var set = typeof selector === "string" ?
jQuery( selector, context ) :
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ?
all :
jQuery.unique( all ) );
},
andSelf: function() {
return this.add( this.prevObject );
}
});
// A painfully simple check to see if an element is disconnected
// from a document (should be improved, where feasible).
function isDisconnected( node ) {
return !node || !node.parentNode || node.parentNode.nodeType === 11;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return jQuery.nth( elem, 2, "nextSibling" );
},
prev: function( elem ) {
return jQuery.nth( elem, 2, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( elem.parentNode.firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.makeArray( elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until );
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret, name, slice.call( arguments ).join(",") );
};
});
jQuery.extend({
filter: function( expr, elems, not ) {
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 ?
jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
jQuery.find.matches(expr, elems);
},
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
matched.push( cur );
}
cur = cur[dir];
}
return matched;
},
nth: function( cur, result, dir, elem ) {
result = result || 1;
var num = 0;
for ( ; cur; cur = cur[dir] ) {
if ( cur.nodeType === 1 && ++num === result ) {
break;
}
}
return cur;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, keep ) {
// Can't pass null or undefined to indexOf in Firefox 4
// Set to 0 to skip string check
qualifier = qualifier || 0;
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep(elements, function( elem, i ) {
var retVal = !!qualifier.call( elem, i, elem );
return retVal === keep;
});
} else if ( qualifier.nodeType ) {
return jQuery.grep(elements, function( elem, i ) {
return ( elem === qualifier ) === keep;
});
} else if ( typeof qualifier === "string" ) {
var filtered = jQuery.grep(elements, function( elem ) {
return elem.nodeType === 1;
});
if ( isSimple.test( qualifier ) ) {
return jQuery.filter(qualifier, filtered, !keep);
} else {
qualifier = jQuery.filter( qualifier, filtered );
}
}
return jQuery.grep(elements, function( elem, i ) {
return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep;
});
}
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
var nodeNames = "abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|" +
"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g,
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style)/i,
rnocache = /<(?:script|object|embed|option|style)/i,
rnoshimcache = new RegExp("<(?:" + nodeNames + ")", "i"),
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /\/(java|ecma)script/i,
rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)/,
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
area: [ 1, "<map>", "</map>" ],
_default: [ 0, "", "" ]
},
safeFragment = createSafeFragment( document );
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
// IE can't serialize <link> and <script> tags normally
if ( !jQuery.support.htmlSerialize ) {
wrapMap._default = [ 1, "div<div>", "</div>" ];
}
jQuery.fn.extend({
text: function( text ) {
if ( jQuery.isFunction(text) ) {
return this.each(function(i) {
var self = jQuery( this );
self.text( text.call(this, i, self.text()) );
});
}
if ( typeof text !== "object" && text !== undefined ) {
return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
}
return jQuery.text( this );
},
wrapAll: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapAll( html.call(this, i) );
});
}
if ( this[0] ) {
// The elements to wrap the target around
var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
if ( this[0].parentNode ) {
wrap.insertBefore( this[0] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
elem = elem.firstChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each(function(i) {
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
},
append: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 ) {
this.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 ) {
this.insertBefore( elem, this.firstChild );
}
});
},
before: function() {
if ( this[0] && this[0].parentNode ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this );
});
} else if ( arguments.length ) {
var set = jQuery.clean( arguments );
set.push.apply( set, this.toArray() );
return this.pushStack( set, "before", arguments );
}
},
after: function() {
if ( this[0] && this[0].parentNode ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this.nextSibling );
});
} else if ( arguments.length ) {
var set = this.pushStack( this, "after", arguments );
set.push.apply( set, jQuery.clean(arguments) );
return set;
}
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
jQuery.cleanData( [ elem ] );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
}
}
return this;
},
empty: function() {
for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function () {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
if ( value === undefined ) {
return this[0] && this[0].nodeType === 1 ?
this[0].innerHTML.replace(rinlinejQuery, "") :
null;
// See if we can take a shortcut and just use innerHTML
} else if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
(jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) &&
!wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) {
value = value.replace(rxhtmlTag, "<$1></$2>");
try {
for ( var i = 0, l = this.length; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
if ( this[i].nodeType === 1 ) {
jQuery.cleanData( this[i].getElementsByTagName("*") );
this[i].innerHTML = value;
}
}
// If using innerHTML throws an exception, use the fallback method
} catch(e) {
this.empty().append( value );
}
} else if ( jQuery.isFunction( value ) ) {
this.each(function(i){
var self = jQuery( this );
self.html( value.call(this, i, self.html()) );
});
} else {
this.empty().append( value );
}
return this;
},
replaceWith: function( value ) {
if ( this[0] && this[0].parentNode ) {
// Make sure that the elements are removed from the DOM before they are inserted
// this can help fix replacing a parent with child elements
if ( jQuery.isFunction( value ) ) {
return this.each(function(i) {
var self = jQuery(this), old = self.html();
self.replaceWith( value.call( this, i, old ) );
});
}
if ( typeof value !== "string" ) {
value = jQuery( value ).detach();
}
return this.each(function() {
var next = this.nextSibling,
parent = this.parentNode;
jQuery( this ).remove();
if ( next ) {
jQuery(next).before( value );
} else {
jQuery(parent).append( value );
}
});
} else {
return this.length ?
this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) :
this;
}
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, table, callback ) {
var results, first, fragment, parent,
value = args[0],
scripts = [];
// We can't cloneNode fragments that contain checked, in WebKit
if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) {
return this.each(function() {
jQuery(this).domManip( args, table, callback, true );
});
}
if ( jQuery.isFunction(value) ) {
return this.each(function(i) {
var self = jQuery(this);
args[0] = value.call(this, i, table ? self.html() : undefined);
self.domManip( args, table, callback );
});
}
if ( this[0] ) {
parent = value && value.parentNode;
// If we're in a fragment, just use that instead of building a new one
if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) {
results = { fragment: parent };
} else {
results = jQuery.buildFragment( args, this, scripts );
}
fragment = results.fragment;
if ( fragment.childNodes.length === 1 ) {
first = fragment = fragment.firstChild;
} else {
first = fragment.firstChild;
}
if ( first ) {
table = table && jQuery.nodeName( first, "tr" );
for ( var i = 0, l = this.length, lastIndex = l - 1; i < l; i++ ) {
callback.call(
table ?
root(this[i], first) :
this[i],
// Make sure that we do not leak memory by inadvertently discarding
// the original fragment (which might have attached data) instead of
// using it; in addition, use the original fragment object for the last
// item instead of first because it can end up being emptied incorrectly
// in certain situations (Bug #8070).
// Fragments from the fragment cache must always be cloned and never used
// in place.
results.cacheable || ( l > 1 && i < lastIndex ) ?
jQuery.clone( fragment, true, true ) :
fragment
);
}
}
if ( scripts.length ) {
jQuery.each( scripts, evalScript );
}
}
return this;
}
});
function root( elem, cur ) {
return jQuery.nodeName(elem, "table") ?
(elem.getElementsByTagName("tbody")[0] ||
elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
elem;
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var type, i, l,
oldData = jQuery._data( src ),
curData = jQuery._data( dest, oldData ),
events = oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type + ( events[ type ][ i ].namespace ? "." : "" ) + events[ type ][ i ].namespace, events[ type ][ i ], events[ type ][ i ].data );
}
}
}
// make the cloned public data object a copy from the original
if ( curData.data ) {
curData.data = jQuery.extend( {}, curData.data );
}
}
function cloneFixAttributes( src, dest ) {
var nodeName;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
// clearAttributes removes the attributes, which we don't want,
// but also removes the attachEvent events, which we *do* want
if ( dest.clearAttributes ) {
dest.clearAttributes();
}
// mergeAttributes, in contrast, only merges back on the
// original attributes, not the events
if ( dest.mergeAttributes ) {
dest.mergeAttributes( src );
}
nodeName = dest.nodeName.toLowerCase();
// IE6-8 fail to clone children inside object elements that use
// the proprietary classid attribute value (rather than the type
// attribute) to identify the type of content to display
if ( nodeName === "object" ) {
dest.outerHTML = src.outerHTML;
} else if ( nodeName === "input" && (src.type === "checkbox" || src.type === "radio") ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
if ( src.checked ) {
dest.defaultChecked = dest.checked = src.checked;
}
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
// Event data gets referenced instead of copied if the expando
// gets copied too
dest.removeAttribute( jQuery.expando );
}
jQuery.buildFragment = function( args, nodes, scripts ) {
var fragment, cacheable, cacheresults, doc,
first = args[ 0 ];
// nodes may contain either an explicit document object,
// a jQuery collection or context object.
// If nodes[0] contains a valid object to assign to doc
if ( nodes && nodes[0] ) {
doc = nodes[0].ownerDocument || nodes[0];
}
// Ensure that an attr object doesn't incorrectly stand in as a document object
// Chrome and Firefox seem to allow this to occur and will throw exception
// Fixes #8950
if ( !doc.createDocumentFragment ) {
doc = document;
}
// Only cache "small" (1/2 KB) HTML strings that are associated with the main document
// Cloning options loses the selected state, so don't cache them
// IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
// Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
// Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501
if ( args.length === 1 && typeof first === "string" && first.length < 512 && doc === document &&
first.charAt(0) === "<" && !rnocache.test( first ) &&
(jQuery.support.checkClone || !rchecked.test( first )) &&
(jQuery.support.html5Clone || !rnoshimcache.test( first )) ) {
cacheable = true;
cacheresults = jQuery.fragments[ first ];
if ( cacheresults && cacheresults !== 1 ) {
fragment = cacheresults;
}
}
if ( !fragment ) {
fragment = doc.createDocumentFragment();
jQuery.clean( args, doc, fragment, scripts );
}
if ( cacheable ) {
jQuery.fragments[ first ] = cacheresults ? fragment : 1;
}
return { fragment: fragment, cacheable: cacheable };
};
jQuery.fragments = {};
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var ret = [],
insert = jQuery( selector ),
parent = this.length === 1 && this[0].parentNode;
if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
insert[ original ]( this[0] );
return this;
} else {
for ( var i = 0, l = insert.length; i < l; i++ ) {
var elems = ( i > 0 ? this.clone(true) : this ).get();
jQuery( insert[i] )[ original ]( elems );
ret = ret.concat( elems );
}
return this.pushStack( ret, name, insert.selector );
}
};
});
function getAll( elem ) {
if ( typeof elem.getElementsByTagName !== "undefined" ) {
return elem.getElementsByTagName( "*" );
} else if ( typeof elem.querySelectorAll !== "undefined" ) {
return elem.querySelectorAll( "*" );
} else {
return [];
}
}
// Used in clean, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( elem.type === "checkbox" || elem.type === "radio" ) {
elem.defaultChecked = elem.checked;
}
}
// Finds all inputs and passes them to fixDefaultChecked
function findInputs( elem ) {
var nodeName = ( elem.nodeName || "" ).toLowerCase();
if ( nodeName === "input" ) {
fixDefaultChecked( elem );
// Skip scripts, get other children
} else if ( nodeName !== "script" && typeof elem.getElementsByTagName !== "undefined" ) {
jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked );
}
}
// Derived From: http://www.iecss.com/shimprove/javascript/shimprove.1-0-1.js
function shimCloneNode( elem ) {
var div = document.createElement( "div" );
safeFragment.appendChild( div );
div.innerHTML = elem.outerHTML;
return div.firstChild;
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var srcElements,
destElements,
i,
// IE<=8 does not properly clone detached, unknown element nodes
clone = jQuery.support.html5Clone || !rnoshimcache.test( "<" + elem.nodeName ) ?
elem.cloneNode( true ) :
shimCloneNode( elem );
if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// IE copies events bound via attachEvent when using cloneNode.
// Calling detachEvent on the clone will also remove the events
// from the original. In order to get around this, we use some
// proprietary methods to clear the events. Thanks to MooTools
// guys for this hotness.
cloneFixAttributes( elem, clone );
// Using Sizzle here is crazy slow, so we use getElementsByTagName instead
srcElements = getAll( elem );
destElements = getAll( clone );
// Weird iteration because IE will replace the length property
// with an element if you are cloning the body and one of the
// elements on the page has a name or id of "length"
for ( i = 0; srcElements[i]; ++i ) {
// Ensure that the destination node is not null; Fixes #9587
if ( destElements[i] ) {
cloneFixAttributes( srcElements[i], destElements[i] );
}
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
cloneCopyEvent( elem, clone );
if ( deepDataAndEvents ) {
srcElements = getAll( elem );
destElements = getAll( clone );
for ( i = 0; srcElements[i]; ++i ) {
cloneCopyEvent( srcElements[i], destElements[i] );
}
}
}
srcElements = destElements = null;
// Return the cloned set
return clone;
},
clean: function( elems, context, fragment, scripts ) {
var checkScriptType;
context = context || document;
// !context.createElement fails in IE with an error but returns typeof 'object'
if ( typeof context.createElement === "undefined" ) {
context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
}
var ret = [], j;
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
if ( typeof elem === "number" ) {
elem += "";
}
if ( !elem ) {
continue;
}
// Convert html string into DOM nodes
if ( typeof elem === "string" ) {
if ( !rhtml.test( elem ) ) {
elem = context.createTextNode( elem );
} else {
// Fix "XHTML"-style tags in all browsers
elem = elem.replace(rxhtmlTag, "<$1></$2>");
// Trim whitespace, otherwise indexOf won't work as expected
var tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(),
wrap = wrapMap[ tag ] || wrapMap._default,
depth = wrap[0],
div = context.createElement("div");
// Append wrapper element to unknown element safe doc fragment
if ( context === document ) {
// Use the fragment we've already created for this document
safeFragment.appendChild( div );
} else {
// Use a fragment created with the owner document
createSafeFragment( context ).appendChild( div );
}
// Go to html and back, then peel off extra wrappers
div.innerHTML = wrap[1] + elem + wrap[2];
// Move to the right depth
while ( depth-- ) {
div = div.lastChild;
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !jQuery.support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
var hasBody = rtbody.test(elem),
tbody = tag === "table" && !hasBody ?
div.firstChild && div.firstChild.childNodes :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !hasBody ?
div.childNodes :
[];
for ( j = tbody.length - 1; j >= 0 ; --j ) {
if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
tbody[ j ].parentNode.removeChild( tbody[ j ] );
}
}
}
// IE completely kills leading whitespace when innerHTML is used
if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
}
elem = div.childNodes;
}
}
// Resets defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
var len;
if ( !jQuery.support.appendChecked ) {
if ( elem[0] && typeof (len = elem.length) === "number" ) {
for ( j = 0; j < len; j++ ) {
findInputs( elem[j] );
}
} else {
findInputs( elem );
}
}
if ( elem.nodeType ) {
ret.push( elem );
} else {
ret = jQuery.merge( ret, elem );
}
}
if ( fragment ) {
checkScriptType = function( elem ) {
return !elem.type || rscriptType.test( elem.type );
};
for ( i = 0; ret[i]; i++ ) {
if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );
} else {
if ( ret[i].nodeType === 1 ) {
var jsTags = jQuery.grep( ret[i].getElementsByTagName( "script" ), checkScriptType );
ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) );
}
fragment.appendChild( ret[i] );
}
}
}
return ret;
},
cleanData: function( elems ) {
var data, id,
cache = jQuery.cache,
special = jQuery.event.special,
deleteExpando = jQuery.support.deleteExpando;
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) {
continue;
}
id = elem[ jQuery.expando ];
if ( id ) {
data = cache[ id ];
if ( data && data.events ) {
for ( var type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
// Null the DOM reference to avoid IE6/7/8 leak (#7054)
if ( data.handle ) {
data.handle.elem = null;
}
}
if ( deleteExpando ) {
delete elem[ jQuery.expando ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( jQuery.expando );
}
delete cache[ id ];
}
}
}
});
function evalScript( i, elem ) {
if ( elem.src ) {
jQuery.ajax({
url: elem.src,
async: false,
dataType: "script"
});
} else {
jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "/*$0*/" ) );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
}
var ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity=([^)]*)/,
// fixed for IE9, see #8346
rupper = /([A-Z]|^ms)/g,
rnumpx = /^-?\d+(?:px)?$/i,
rnum = /^-?\d/,
rrelNum = /^([\-+])=([\-+.\de]+)/,
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssWidth = [ "Left", "Right" ],
cssHeight = [ "Top", "Bottom" ],
curCSS,
getComputedStyle,
currentStyle;
jQuery.fn.css = function( name, value ) {
// Setting 'undefined' is a no-op
if ( arguments.length === 2 && value === undefined ) {
return this;
}
return jQuery.access( this, name, value, true, function( elem, name, value ) {
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
});
};
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity", "opacity" );
return ret === "" ? "1" : ret;
} else {
return elem.style.opacity;
}
}
}
},
// Exclude the following css properties to add px
cssNumber: {
"fillOpacity": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, origName = jQuery.camelCase( name ),
style = elem.style, hooks = jQuery.cssHooks[ origName ];
name = jQuery.cssProps[ origName ] || origName;
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( +( ret[1] + 1) * +ret[2] ) + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that NaN and null values aren't set. See: #7116
if ( value == null || type === "number" && isNaN( value ) ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value )) !== undefined ) {
// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
// Fixes bug #5509
try {
style[ name ] = value;
} catch(e) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra ) {
var ret, hooks;
// Make sure that we're working with the right name
name = jQuery.camelCase( name );
hooks = jQuery.cssHooks[ name ];
name = jQuery.cssProps[ name ] || name;
// cssFloat needs a special treatment
if ( name === "cssFloat" ) {
name = "float";
}
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) {
return ret;
// Otherwise, if a way to get the computed value exists, use that
} else if ( curCSS ) {
return curCSS( elem, name );
}
},
// A method for quickly swapping in/out CSS properties to get correct calculations
swap: function( elem, options, callback ) {
var old = {};
// Remember the old values, and insert the new ones
for ( var name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
callback.call( elem );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
}
});
// DEPRECATED, Use jQuery.css() instead
jQuery.curCSS = jQuery.css;
jQuery.each(["height", "width"], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
var val;
if ( computed ) {
if ( elem.offsetWidth !== 0 ) {
return getWH( elem, name, extra );
} else {
jQuery.swap( elem, cssShow, function() {
val = getWH( elem, name, extra );
});
}
return val;
}
},
set: function( elem, value ) {
if ( rnumpx.test( value ) ) {
// ignore negative width and height values #1599
value = parseFloat( value );
if ( value >= 0 ) {
return value + "px";
}
} else {
return value;
}
}
};
});
if ( !jQuery.support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
( parseFloat( RegExp.$1 ) / 100 ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle,
opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
filter = currentStyle && currentStyle.filter || style.filter || "";
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" ) {
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute( "filter" );
// if there there is no filter style applied in a css rule, we are done
if ( currentStyle && !currentStyle.filter ) {
return;
}
}
// otherwise, set new filter values
style.filter = ralpha.test( filter ) ?
filter.replace( ralpha, opacity ) :
filter + " " + opacity;
}
};
}
jQuery(function() {
// This hook cannot be added until DOM ready because the support test
// for it is not run until after DOM ready
if ( !jQuery.support.reliableMarginRight ) {
jQuery.cssHooks.marginRight = {
get: function( elem, computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
var ret;
jQuery.swap( elem, { "display": "inline-block" }, function() {
if ( computed ) {
ret = curCSS( elem, "margin-right", "marginRight" );
} else {
ret = elem.style.marginRight;
}
});
return ret;
}
};
}
});
if ( document.defaultView && document.defaultView.getComputedStyle ) {
getComputedStyle = function( elem, name ) {
var ret, defaultView, computedStyle;
name = name.replace( rupper, "-$1" ).toLowerCase();
if ( (defaultView = elem.ownerDocument.defaultView) &&
(computedStyle = defaultView.getComputedStyle( elem, null )) ) {
ret = computedStyle.getPropertyValue( name );
if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) {
ret = jQuery.style( elem, name );
}
}
return ret;
};
}
if ( document.documentElement.currentStyle ) {
currentStyle = function( elem, name ) {
var left, rsLeft, uncomputed,
ret = elem.currentStyle && elem.currentStyle[ name ],
style = elem.style;
// Avoid setting ret to empty string here
// so we don't default to auto
if ( ret === null && style && (uncomputed = style[ name ]) ) {
ret = uncomputed;
}
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
if ( !rnumpx.test( ret ) && rnum.test( ret ) ) {
// Remember the original values
left = style.left;
rsLeft = elem.runtimeStyle && elem.runtimeStyle.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
elem.runtimeStyle.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : ( ret || 0 );
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
elem.runtimeStyle.left = rsLeft;
}
}
return ret === "" ? "auto" : ret;
};
}
curCSS = getComputedStyle || currentStyle;
function getWH( elem, name, extra ) {
// Start with offset property
var val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
which = name === "width" ? cssWidth : cssHeight,
i = 0,
len = which.length;
if ( val > 0 ) {
if ( extra !== "border" ) {
for ( ; i < len; i++ ) {
if ( !extra ) {
val -= parseFloat( jQuery.css( elem, "padding" + which[ i ] ) ) || 0;
}
if ( extra === "margin" ) {
val += parseFloat( jQuery.css( elem, extra + which[ i ] ) ) || 0;
} else {
val -= parseFloat( jQuery.css( elem, "border" + which[ i ] + "Width" ) ) || 0;
}
}
}
return val + "px";
}
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name, name );
if ( val < 0 || val == null ) {
val = elem.style[ name ] || 0;
}
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
// Add padding, border, margin
if ( extra ) {
for ( ; i < len; i++ ) {
val += parseFloat( jQuery.css( elem, "padding" + which[ i ] ) ) || 0;
if ( extra !== "padding" ) {
val += parseFloat( jQuery.css( elem, "border" + which[ i ] + "Width" ) ) || 0;
}
if ( extra === "margin" ) {
val += parseFloat( jQuery.css( elem, extra + which[ i ] ) ) || 0;
}
}
}
return val + "px";
}
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.hidden = function( elem ) {
var width = elem.offsetWidth,
height = elem.offsetHeight;
return ( width === 0 && height === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
}
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rhash = /#.*$/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rquery = /\?/,
rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
rselectTextarea = /^(?:select|textarea)/i,
rspacesAjax = /\s+/,
rts = /([?&])_=[^&]*/,
rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,
// Keep a copy of the old load method
_load = jQuery.fn.load,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Document location
ajaxLocation,
// Document location segments
ajaxLocParts,
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = ["*/"] + ["*"];
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
if ( jQuery.isFunction( func ) ) {
var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ),
i = 0,
length = dataTypes.length,
dataType,
list,
placeBefore;
// For each dataType in the dataTypeExpression
for ( ; i < length; i++ ) {
dataType = dataTypes[ i ];
// We control if we're asked to add before
// any existing element
placeBefore = /^\+/.test( dataType );
if ( placeBefore ) {
dataType = dataType.substr( 1 ) || "*";
}
list = structure[ dataType ] = structure[ dataType ] || [];
// then we add to the structure accordingly
list[ placeBefore ? "unshift" : "push" ]( func );
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR,
dataType /* internal */, inspected /* internal */ ) {
dataType = dataType || options.dataTypes[ 0 ];
inspected = inspected || {};
inspected[ dataType ] = true;
var list = structure[ dataType ],
i = 0,
length = list ? list.length : 0,
executeOnly = ( structure === prefilters ),
selection;
for ( ; i < length && ( executeOnly || !selection ); i++ ) {
selection = list[ i ]( options, originalOptions, jqXHR );
// If we got redirected to another dataType
// we try there if executing only and not done already
if ( typeof selection === "string" ) {
if ( !executeOnly || inspected[ selection ] ) {
selection = undefined;
} else {
options.dataTypes.unshift( selection );
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, selection, inspected );
}
}
}
// If we're only executing or nothing was selected
// we try the catchall dataType if not done already
if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) {
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, "*", inspected );
}
// unnecessary when only executing (prefilters)
// but it'll be ignored by the caller in that case
return selection;
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var key, deep,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
}
jQuery.fn.extend({
load: function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
// Don't do a request if no elements are being requested
} else if ( !this.length ) {
return this;
}
var off = url.indexOf( " " );
if ( off >= 0 ) {
var selector = url.slice( off, url.length );
url = url.slice( 0, off );
}
// Default to a GET request
var type = "GET";
// If the second parameter was provided
if ( params ) {
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( typeof params === "object" ) {
params = jQuery.param( params, jQuery.ajaxSettings.traditional );
type = "POST";
}
}
var self = this;
// Request the remote document
jQuery.ajax({
url: url,
type: type,
dataType: "html",
data: params,
// Complete callback (responseText is used internally)
complete: function( jqXHR, status, responseText ) {
// Store the response as specified by the jqXHR object
responseText = jqXHR.responseText;
// If successful, inject the HTML into all the matched elements
if ( jqXHR.isResolved() ) {
// #4825: Get the actual response in case
// a dataFilter is present in ajaxSettings
jqXHR.done(function( r ) {
responseText = r;
});
// See if a selector was specified
self.html( selector ?
// Create a dummy div to hold the results
jQuery("<div>")
// inject the contents of the document in, removing the scripts
// to avoid any 'Permission Denied' errors in IE
.append(responseText.replace(rscript, ""))
// Locate the specified elements
.find(selector) :
// If not, just inject the full result
responseText );
}
if ( callback ) {
self.each( callback, [ responseText, status, jqXHR ] );
}
}
});
return this;
},
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function(){
return this.elements ? jQuery.makeArray( this.elements ) : this;
})
.filter(function(){
return this.name && !this.disabled &&
( this.checked || rselectTextarea.test( this.nodeName ) ||
rinput.test( this.type ) );
})
.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val, i ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
// Attach a bunch of functions for handling common AJAX events
jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){
jQuery.fn[ o ] = function( f ){
return this.on( o, f );
};
});
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
type: method,
url: url,
data: data,
success: callback,
dataType: type
});
};
});
jQuery.extend({
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
if ( settings ) {
// Building a settings object
ajaxExtend( target, jQuery.ajaxSettings );
} else {
// Extending ajaxSettings
settings = target;
target = jQuery.ajaxSettings;
}
ajaxExtend( target, settings );
return target;
},
ajaxSettings: {
url: ajaxLocation,
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
type: "GET",
contentType: "application/x-www-form-urlencoded",
processData: true,
async: true,
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
traditional: false,
headers: {},
*/
accepts: {
xml: "application/xml, text/xml",
html: "text/html",
text: "text/plain",
json: "application/json, text/javascript",
"*": allTypes
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText"
},
// List of data converters
// 1) key format is "source_type destination_type" (a single space in-between)
// 2) the catchall symbol "*" can be used for source_type
converters: {
// Convert anything to text
"* text": window.String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
context: true,
url: true
}
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var // Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events
// It's the callbackContext if one was provided in the options
// and if it's a DOM node or a jQuery collection
globalEventContext = callbackContext !== s &&
( callbackContext.nodeType || callbackContext instanceof jQuery ) ?
jQuery( callbackContext ) : jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks( "once memory" ),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// ifModified key
ifModifiedKey,
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// Response headers
responseHeadersString,
responseHeaders,
// transport
transport,
// timeout handle
timeoutTimer,
// Cross-domain detection vars
parts,
// The jqXHR state
state = 0,
// To know if global events are to be dispatched
fireGlobals,
// Loop variable
i,
// Fake xhr
jqXHR = {
readyState: 0,
// Caches the header
setRequestHeader: function( name, value ) {
if ( !state ) {
var lname = name.toLowerCase();
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while( ( match = rheaders.exec( responseHeadersString ) ) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match === undefined ? null : match;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Cancel the request
abort: function( statusText ) {
statusText = statusText || "abort";
if ( transport ) {
transport.abort( statusText );
}
done( 0, statusText );
return this;
}
};
// Callback for when everything is done
// It is defined here because jslint complains if it is declared
// at the end of the function (which would be more logical and readable)
function done( status, nativeStatusText, responses, headers ) {
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
var isSuccess,
success,
error,
statusText = nativeStatusText,
response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined,
lastModified,
etag;
// If successful, handle type chaining
if ( status >= 200 && status < 300 || status === 304 ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) {
jQuery.lastModified[ ifModifiedKey ] = lastModified;
}
if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) {
jQuery.etag[ ifModifiedKey ] = etag;
}
}
// If not modified
if ( status === 304 ) {
statusText = "notmodified";
isSuccess = true;
// If we have data
} else {
try {
success = ajaxConvert( s, response );
statusText = "success";
isSuccess = true;
} catch(e) {
// We have a parsererror
statusText = "parsererror";
error = e;
}
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if ( !statusText || status ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = "" + ( nativeStatusText || statusText );
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger( "ajaxStop" );
}
}
}
// Attach deferreds
deferred.promise( jqXHR );
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
jqXHR.complete = completeDeferred.add;
// Status-dependent callbacks
jqXHR.statusCode = function( map ) {
if ( map ) {
var tmp;
if ( state < 2 ) {
for ( tmp in map ) {
statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
}
} else {
tmp = map[ jqXHR.status ];
jqXHR.then( tmp, tmp );
}
}
return this;
};
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// We also use the url parameter if available
s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax );
// Determine if a cross-domain request is in order
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] != ajaxLocParts[ 1 ] || parts[ 2 ] != ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
);
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefiler, stop there
if ( state === 2 ) {
return false;
}
// We can fire global events as of now if asked to
fireGlobals = s.global;
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger( "ajaxStart" );
}
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Get ifModifiedKey before adding the anti-cache parameter
ifModifiedKey = s.url;
// Add anti-cache in url if needed
if ( s.cache === false ) {
var ts = jQuery.now(),
// try replacing _= if it is there
ret = s.url.replace( rts, "$1_=" + ts );
// if nothing was replaced, add timestamp to the end
s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
ifModifiedKey = ifModifiedKey || s.url;
if ( jQuery.lastModified[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] );
}
if ( jQuery.etag[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] );
}
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
// Abort if not done already
jqXHR.abort();
return false;
}
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout( function(){
jqXHR.abort( "timeout" );
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch (e) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
return jqXHR;
},
// Serialize an array of form elements or a set of
// key/values into a query string
param: function( a, traditional ) {
var s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : value;
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( var prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
}
});
function buildParams( prefix, obj, traditional, add ) {
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// If array item is non-scalar (array or object), encode its
// numeric index to resolve deserialization ambiguity issues.
// Note that rack (as of 1.0.0) can't currently deserialize
// nested arrays properly, and attempting to do so may cause
// a server error. Possible fixes are to modify rack's
// deserialization algorithm or to provide an option or flag
// to force array serialization to be shallow.
buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && obj != null && typeof obj === "object" ) {
// Serialize object item.
for ( var name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
// This is still on the jQuery object... for now
// Want to move this to jQuery.ajax some day
jQuery.extend({
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {}
});
/* Handles responses to an ajax request:
* - sets all responseXXX fields accordingly
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var contents = s.contents,
dataTypes = s.dataTypes,
responseFields = s.responseFields,
ct,
type,
finalDataType,
firstDataType;
// Fill responseXXX fields
for ( type in responseFields ) {
if ( type in responses ) {
jqXHR[ responseFields[type] ] = responses[ type ];
}
}
// Remove auto dataType and get content-type in the process
while( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader( "content-type" );
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
// Chain conversions given the request and the original response
function ajaxConvert( s, response ) {
// Apply the dataFilter if provided
if ( s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
var dataTypes = s.dataTypes,
converters = {},
i,
key,
length = dataTypes.length,
tmp,
// Current and previous dataTypes
current = dataTypes[ 0 ],
prev,
// Conversion expression
conversion,
// Conversion function
conv,
// Conversion functions (transitive conversion)
conv1,
conv2;
// For each dataType in the chain
for ( i = 1; i < length; i++ ) {
// Create converters map
// with lowercased keys
if ( i === 1 ) {
for ( key in s.converters ) {
if ( typeof key === "string" ) {
converters[ key.toLowerCase() ] = s.converters[ key ];
}
}
}
// Get the dataTypes
prev = current;
current = dataTypes[ i ];
// If current is auto dataType, update it to prev
if ( current === "*" ) {
current = prev;
// If no auto and dataTypes are actually different
} else if ( prev !== "*" && prev !== current ) {
// Get the converter
conversion = prev + " " + current;
conv = converters[ conversion ] || converters[ "* " + current ];
// If there is no direct converter, search transitively
if ( !conv ) {
conv2 = undefined;
for ( conv1 in converters ) {
tmp = conv1.split( " " );
if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) {
conv2 = converters[ tmp[1] + " " + current ];
if ( conv2 ) {
conv1 = converters[ conv1 ];
if ( conv1 === true ) {
conv = conv2;
} else if ( conv2 === true ) {
conv = conv1;
}
break;
}
}
}
}
// If we found no converter, dispatch an error
if ( !( conv || conv2 ) ) {
jQuery.error( "No conversion from " + conversion.replace(" "," to ") );
}
// If found converter is not an equivalence
if ( conv !== true ) {
// Convert with 1 or 2 converters accordingly
response = conv ? conv( response ) : conv2( conv1(response) );
}
}
}
return response;
}
var jsc = jQuery.now(),
jsre = /(\=)\?(&|$)|\?\?/i;
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
return jQuery.expando + "_" + ( jsc++ );
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var inspectData = s.contentType === "application/x-www-form-urlencoded" &&
( typeof s.data === "string" );
if ( s.dataTypes[ 0 ] === "jsonp" ||
s.jsonp !== false && ( jsre.test( s.url ) ||
inspectData && jsre.test( s.data ) ) ) {
var responseContainer,
jsonpCallback = s.jsonpCallback =
jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback,
previous = window[ jsonpCallback ],
url = s.url,
data = s.data,
replace = "$1" + jsonpCallback + "$2";
if ( s.jsonp !== false ) {
url = url.replace( jsre, replace );
if ( s.url === url ) {
if ( inspectData ) {
data = data.replace( jsre, replace );
}
if ( s.data === data ) {
// Add callback manually
url += (/\?/.test( url ) ? "&" : "?") + s.jsonp + "=" + jsonpCallback;
}
}
}
s.url = url;
s.data = data;
// Install callback
window[ jsonpCallback ] = function( response ) {
responseContainer = [ response ];
};
// Clean-up function
jqXHR.always(function() {
// Set callback back to previous value
window[ jsonpCallback ] = previous;
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( previous ) ) {
window[ jsonpCallback ]( responseContainer[ 0 ] );
}
});
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( !responseContainer ) {
jQuery.error( jsonpCallback + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Delegate to script
return "script";
}
});
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /javascript|ecmascript/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
s.global = false;
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script,
head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement( "script" );
script.async = "async";
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( head && script.parentNode ) {
head.removeChild( script );
}
// Dereference the script
script = undefined;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709 and #4378).
head.insertBefore( script, head.firstChild );
},
abort: function() {
if ( script ) {
script.onload( 0, 1 );
}
}
};
}
});
var // #5280: Internet Explorer will keep connections alive if we don't abort on unload
xhrOnUnloadAbort = window.ActiveXObject ? function() {
// Abort all pending requests
for ( var key in xhrCallbacks ) {
xhrCallbacks[ key ]( 0, 1 );
}
} : false,
xhrId = 0,
xhrCallbacks;
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch( e ) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject( "Microsoft.XMLHTTP" );
} catch( e ) {}
}
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject ?
/* Microsoft failed to properly
* implement the XMLHttpRequest in IE7 (can't request local files),
* so we use the ActiveXObject when it is available
* Additionally XMLHttpRequest can be disabled in IE7/IE8 so
* we need a fallback.
*/
function() {
return !this.isLocal && createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
// Determine support properties
(function( xhr ) {
jQuery.extend( jQuery.support, {
ajax: !!xhr,
cors: !!xhr && ( "withCredentials" in xhr )
});
})( jQuery.ajaxSettings.xhr() );
// Create transport if the browser can provide an xhr
if ( jQuery.support.ajax ) {
jQuery.ajaxTransport(function( s ) {
// Cross domain only allowed if supported through XMLHttpRequest
if ( !s.crossDomain || jQuery.support.cors ) {
var callback;
return {
send: function( headers, complete ) {
// Get a new xhr
var xhr = s.xhr(),
handle,
i;
// Open the socket
// Passing null username, generates a login popup on Opera (#2865)
if ( s.username ) {
xhr.open( s.type, s.url, s.async, s.username, s.password );
} else {
xhr.open( s.type, s.url, s.async );
}
// Apply custom fields if provided
if ( s.xhrFields ) {
for ( i in s.xhrFields ) {
xhr[ i ] = s.xhrFields[ i ];
}
}
// Override mime type if needed
if ( s.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( s.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !s.crossDomain && !headers["X-Requested-With"] ) {
headers[ "X-Requested-With" ] = "XMLHttpRequest";
}
// Need an extra try/catch for cross domain requests in Firefox 3
try {
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
} catch( _ ) {}
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( s.hasContent && s.data ) || null );
// Listener
callback = function( _, isAbort ) {
var status,
statusText,
responseHeaders,
responses,
xml;
// Firefox throws exceptions when accessing properties
// of an xhr when a network error occured
// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
try {
// Was never called and is aborted or complete
if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Only called once
callback = undefined;
// Do not keep as active anymore
if ( handle ) {
xhr.onreadystatechange = jQuery.noop;
if ( xhrOnUnloadAbort ) {
delete xhrCallbacks[ handle ];
}
}
// If it's an abort
if ( isAbort ) {
// Abort it manually if needed
if ( xhr.readyState !== 4 ) {
xhr.abort();
}
} else {
status = xhr.status;
responseHeaders = xhr.getAllResponseHeaders();
responses = {};
xml = xhr.responseXML;
// Construct response list
if ( xml && xml.documentElement /* #4958 */ ) {
responses.xml = xml;
}
responses.text = xhr.responseText;
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch( e ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && s.isLocal && !s.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
} catch( firefoxAccessException ) {
if ( !isAbort ) {
complete( -1, firefoxAccessException );
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, responseHeaders );
}
};
// if we're in sync mode or it's in cache
// and has been retrieved directly (IE6 & IE7)
// we need to manually fire the callback
if ( !s.async || xhr.readyState === 4 ) {
callback();
} else {
handle = ++xhrId;
if ( xhrOnUnloadAbort ) {
// Create the active xhrs callbacks list if needed
// and attach the unload handler
if ( !xhrCallbacks ) {
xhrCallbacks = {};
jQuery( window ).unload( xhrOnUnloadAbort );
}
// Add to list of active xhrs callbacks
xhrCallbacks[ handle ] = callback;
}
xhr.onreadystatechange = callback;
}
},
abort: function() {
if ( callback ) {
callback(0,1);
}
}
};
}
});
}
var elemdisplay = {},
iframe, iframeDoc,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,
timerId,
fxAttrs = [
// height animations
[ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ],
// width animations
[ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ],
// opacity animations
[ "opacity" ]
],
fxNow;
jQuery.fn.extend({
show: function( speed, easing, callback ) {
var elem, display;
if ( speed || speed === 0 ) {
return this.animate( genFx("show", 3), speed, easing, callback );
} else {
for ( var i = 0, j = this.length; i < j; i++ ) {
elem = this[ i ];
if ( elem.style ) {
display = elem.style.display;
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !jQuery._data(elem, "olddisplay") && display === "none" ) {
display = elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( display === "" && jQuery.css(elem, "display") === "none" ) {
jQuery._data( elem, "olddisplay", defaultDisplay(elem.nodeName) );
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( i = 0; i < j; i++ ) {
elem = this[ i ];
if ( elem.style ) {
display = elem.style.display;
if ( display === "" || display === "none" ) {
elem.style.display = jQuery._data( elem, "olddisplay" ) || "";
}
}
}
return this;
}
},
hide: function( speed, easing, callback ) {
if ( speed || speed === 0 ) {
return this.animate( genFx("hide", 3), speed, easing, callback);
} else {
var elem, display,
i = 0,
j = this.length;
for ( ; i < j; i++ ) {
elem = this[i];
if ( elem.style ) {
display = jQuery.css( elem, "display" );
if ( display !== "none" && !jQuery._data( elem, "olddisplay" ) ) {
jQuery._data( elem, "olddisplay", display );
}
}
}
// Set the display of the elements in a second loop
// to avoid the constant reflow
for ( i = 0; i < j; i++ ) {
if ( this[i].style ) {
this[i].style.display = "none";
}
}
return this;
}
},
// Save the old toggle function
_toggle: jQuery.fn.toggle,
toggle: function( fn, fn2, callback ) {
var bool = typeof fn === "boolean";
if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) {
this._toggle.apply( this, arguments );
} else if ( fn == null || bool ) {
this.each(function() {
var state = bool ? fn : jQuery(this).is(":hidden");
jQuery(this)[ state ? "show" : "hide" ]();
});
} else {
this.animate(genFx("toggle", 3), fn, fn2, callback);
}
return this;
},
fadeTo: function( speed, to, easing, callback ) {
return this.filter(":hidden").css("opacity", 0).show().end()
.animate({opacity: to}, speed, easing, callback);
},
animate: function( prop, speed, easing, callback ) {
var optall = jQuery.speed( speed, easing, callback );
if ( jQuery.isEmptyObject( prop ) ) {
return this.each( optall.complete, [ false ] );
}
// Do not change referenced properties as per-property easing will be lost
prop = jQuery.extend( {}, prop );
function doAnimation() {
// XXX 'this' does not always have a nodeName when running the
// test suite
if ( optall.queue === false ) {
jQuery._mark( this );
}
var opt = jQuery.extend( {}, optall ),
isElement = this.nodeType === 1,
hidden = isElement && jQuery(this).is(":hidden"),
name, val, p, e,
parts, start, end, unit,
method;
// will store per property easing and be used to determine when an animation is complete
opt.animatedProperties = {};
for ( p in prop ) {
// property name normalization
name = jQuery.camelCase( p );
if ( p !== name ) {
prop[ name ] = prop[ p ];
delete prop[ p ];
}
val = prop[ name ];
// easing resolution: per property > opt.specialEasing > opt.easing > 'swing' (default)
if ( jQuery.isArray( val ) ) {
opt.animatedProperties[ name ] = val[ 1 ];
val = prop[ name ] = val[ 0 ];
} else {
opt.animatedProperties[ name ] = opt.specialEasing && opt.specialEasing[ name ] || opt.easing || 'swing';
}
if ( val === "hide" && hidden || val === "show" && !hidden ) {
return opt.complete.call( this );
}
if ( isElement && ( name === "height" || name === "width" ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
if ( jQuery.css( this, "display" ) === "inline" &&
jQuery.css( this, "float" ) === "none" ) {
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( !jQuery.support.inlineBlockNeedsLayout || defaultDisplay( this.nodeName ) === "inline" ) {
this.style.display = "inline-block";
} else {
this.style.zoom = 1;
}
}
}
}
if ( opt.overflow != null ) {
this.style.overflow = "hidden";
}
for ( p in prop ) {
e = new jQuery.fx( this, opt, p );
val = prop[ p ];
if ( rfxtypes.test( val ) ) {
// Tracks whether to show or hide based on private
// data attached to the element
method = jQuery._data( this, "toggle" + p ) || ( val === "toggle" ? hidden ? "show" : "hide" : 0 );
if ( method ) {
jQuery._data( this, "toggle" + p, method === "show" ? "hide" : "show" );
e[ method ]();
} else {
e[ val ]();
}
} else {
parts = rfxnum.exec( val );
start = e.cur();
if ( parts ) {
end = parseFloat( parts[2] );
unit = parts[3] || ( jQuery.cssNumber[ p ] ? "" : "px" );
// We need to compute starting value
if ( unit !== "px" ) {
jQuery.style( this, p, (end || 1) + unit);
start = ( (end || 1) / e.cur() ) * start;
jQuery.style( this, p, start + unit);
}
// If a +=/-= token was provided, we're doing a relative animation
if ( parts[1] ) {
end = ( (parts[ 1 ] === "-=" ? -1 : 1) * end ) + start;
}
e.custom( start, end, unit );
} else {
e.custom( start, val, "" );
}
}
}
// For JS strict compliance
return true;
}
return optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each(function() {
var index,
hadTimers = false,
timers = jQuery.timers,
data = jQuery._data( this );
// clear marker counters if we know they won't be
if ( !gotoEnd ) {
jQuery._unmark( true, this );
}
function stopQueue( elem, data, index ) {
var hooks = data[ index ];
jQuery.removeData( elem, index, true );
hooks.stop( gotoEnd );
}
if ( type == null ) {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && index.indexOf(".run") === index.length - 4 ) {
stopQueue( this, data, index );
}
}
} else if ( data[ index = type + ".run" ] && data[ index ].stop ){
stopQueue( this, data, index );
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
if ( gotoEnd ) {
// force the next step to be the last
timers[ index ]( true );
} else {
timers[ index ].saveState();
}
hadTimers = true;
timers.splice( index, 1 );
}
}
// start the next in the queue if the last step wasn't forced
// timers currently will call their complete callbacks, which will dequeue
// but only if they were gotoEnd
if ( !( gotoEnd && hadTimers ) ) {
jQuery.dequeue( this, type );
}
});
}
});
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout( clearFxNow, 0 );
return ( fxNow = jQuery.now() );
}
function clearFxNow() {
fxNow = undefined;
}
// Generate parameters to create a standard animation
function genFx( type, num ) {
var obj = {};
jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice( 0, num )), function() {
obj[ this ] = type;
});
return obj;
}
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx( "show", 1 ),
slideUp: genFx( "hide", 1 ),
slideToggle: genFx( "toggle", 1 ),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
});
jQuery.extend({
speed: function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
// normalize opt.queue - true/undefined/null -> "fx"
if ( opt.queue == null || opt.queue === true ) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function( noUnmark ) {
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue ) {
jQuery.dequeue( this, opt.queue );
} else if ( noUnmark !== false ) {
jQuery._unmark( this );
}
};
return opt;
},
easing: {
linear: function( p, n, firstNum, diff ) {
return firstNum + diff * p;
},
swing: function( p, n, firstNum, diff ) {
return ( ( -Math.cos( p*Math.PI ) / 2 ) + 0.5 ) * diff + firstNum;
}
},
timers: [],
fx: function( elem, options, prop ) {
this.options = options;
this.elem = elem;
this.prop = prop;
options.orig = options.orig || {};
}
});
jQuery.fx.prototype = {
// Simple function for setting a style value
update: function() {
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
( jQuery.fx.step[ this.prop ] || jQuery.fx.step._default )( this );
},
// Get the current size
cur: function() {
if ( this.elem[ this.prop ] != null && (!this.elem.style || this.elem.style[ this.prop ] == null) ) {
return this.elem[ this.prop ];
}
var parsed,
r = jQuery.css( this.elem, this.prop );
// Empty strings, null, undefined and "auto" are converted to 0,
// complex values such as "rotate(1rad)" are returned as is,
// simple values such as "10px" are parsed to Float.
return isNaN( parsed = parseFloat( r ) ) ? !r || r === "auto" ? 0 : r : parsed;
},
// Start an animation from one number to another
custom: function( from, to, unit ) {
var self = this,
fx = jQuery.fx;
this.startTime = fxNow || createFxNow();
this.end = to;
this.now = this.start = from;
this.pos = this.state = 0;
this.unit = unit || this.unit || ( jQuery.cssNumber[ this.prop ] ? "" : "px" );
function t( gotoEnd ) {
return self.step( gotoEnd );
}
t.queue = this.options.queue;
t.elem = this.elem;
t.saveState = function() {
if ( self.options.hide && jQuery._data( self.elem, "fxshow" + self.prop ) === undefined ) {
jQuery._data( self.elem, "fxshow" + self.prop, self.start );
}
};
if ( t() && jQuery.timers.push(t) && !timerId ) {
timerId = setInterval( fx.tick, fx.interval );
}
},
// Simple 'show' function
show: function() {
var dataShow = jQuery._data( this.elem, "fxshow" + this.prop );
// Remember where we started, so that we can go back to it later
this.options.orig[ this.prop ] = dataShow || jQuery.style( this.elem, this.prop );
this.options.show = true;
// Begin the animation
// Make sure that we start at a small width/height to avoid any flash of content
if ( dataShow !== undefined ) {
// This show is picking up where a previous hide or show left off
this.custom( this.cur(), dataShow );
} else {
this.custom( this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur() );
}
// Start by showing the element
jQuery( this.elem ).show();
},
// Simple 'hide' function
hide: function() {
// Remember where we started, so that we can go back to it later
this.options.orig[ this.prop ] = jQuery._data( this.elem, "fxshow" + this.prop ) || jQuery.style( this.elem, this.prop );
this.options.hide = true;
// Begin the animation
this.custom( this.cur(), 0 );
},
// Each step of an animation
step: function( gotoEnd ) {
var p, n, complete,
t = fxNow || createFxNow(),
done = true,
elem = this.elem,
options = this.options;
if ( gotoEnd || t >= options.duration + this.startTime ) {
this.now = this.end;
this.pos = this.state = 1;
this.update();
options.animatedProperties[ this.prop ] = true;
for ( p in options.animatedProperties ) {
if ( options.animatedProperties[ p ] !== true ) {
done = false;
}
}
if ( done ) {
// Reset the overflow
if ( options.overflow != null && !jQuery.support.shrinkWrapBlocks ) {
jQuery.each( [ "", "X", "Y" ], function( index, value ) {
elem.style[ "overflow" + value ] = options.overflow[ index ];
});
}
// Hide the element if the "hide" operation was done
if ( options.hide ) {
jQuery( elem ).hide();
}
// Reset the properties, if the item has been hidden or shown
if ( options.hide || options.show ) {
for ( p in options.animatedProperties ) {
jQuery.style( elem, p, options.orig[ p ] );
jQuery.removeData( elem, "fxshow" + p, true );
// Toggle data is no longer needed
jQuery.removeData( elem, "toggle" + p, true );
}
}
// Execute the complete function
// in the event that the complete function throws an exception
// we must ensure it won't be called twice. #5684
complete = options.complete;
if ( complete ) {
options.complete = false;
complete.call( elem );
}
}
return false;
} else {
// classical easing cannot be used with an Infinity duration
if ( options.duration == Infinity ) {
this.now = t;
} else {
n = t - this.startTime;
this.state = n / options.duration;
// Perform the easing function, defaults to swing
this.pos = jQuery.easing[ options.animatedProperties[this.prop] ]( this.state, n, 0, 1, options.duration );
this.now = this.start + ( (this.end - this.start) * this.pos );
}
// Perform the next step of the animation
this.update();
}
return true;
}
};
jQuery.extend( jQuery.fx, {
tick: function() {
var timer,
timers = jQuery.timers,
i = 0;
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Checks the timer has not already been removed
if ( !timer() && timers[ i ] === timer ) {
timers.splice( i--, 1 );
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
},
interval: 13,
stop: function() {
clearInterval( timerId );
timerId = null;
},
speeds: {
slow: 600,
fast: 200,
// Default speed
_default: 400
},
step: {
opacity: function( fx ) {
jQuery.style( fx.elem, "opacity", fx.now );
},
_default: function( fx ) {
if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) {
fx.elem.style[ fx.prop ] = fx.now + fx.unit;
} else {
fx.elem[ fx.prop ] = fx.now;
}
}
}
});
// Adds width/height step functions
// Do not set anything below 0
jQuery.each([ "width", "height" ], function( i, prop ) {
jQuery.fx.step[ prop ] = function( fx ) {
jQuery.style( fx.elem, prop, Math.max(0, fx.now) + fx.unit );
};
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
}
// Try to restore the default display value of an element
function defaultDisplay( nodeName ) {
if ( !elemdisplay[ nodeName ] ) {
var body = document.body,
elem = jQuery( "<" + nodeName + ">" ).appendTo( body ),
display = elem.css( "display" );
elem.remove();
// If the simple way fails,
// get element's real default display by attaching it to a temp iframe
if ( display === "none" || display === "" ) {
// No iframe to use yet, so create it
if ( !iframe ) {
iframe = document.createElement( "iframe" );
iframe.frameBorder = iframe.width = iframe.height = 0;
}
body.appendChild( iframe );
// Create a cacheable copy of the iframe document on first call.
// IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML
// document to it; WebKit & Firefox won't allow reusing the iframe document.
if ( !iframeDoc || !iframe.createElement ) {
iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document;
iframeDoc.write( ( document.compatMode === "CSS1Compat" ? "<!doctype html>" : "" ) + "<html><body>" );
iframeDoc.close();
}
elem = iframeDoc.createElement( nodeName );
iframeDoc.body.appendChild( elem );
display = jQuery.css( elem, "display" );
body.removeChild( iframe );
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return elemdisplay[ nodeName ];
}
var rtable = /^t(?:able|d|h)$/i,
rroot = /^(?:body|html)$/i;
if ( "getBoundingClientRect" in document.documentElement ) {
jQuery.fn.offset = function( options ) {
var elem = this[0], box;
if ( options ) {
return this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
if ( !elem || !elem.ownerDocument ) {
return null;
}
if ( elem === elem.ownerDocument.body ) {
return jQuery.offset.bodyOffset( elem );
}
try {
box = elem.getBoundingClientRect();
} catch(e) {}
var doc = elem.ownerDocument,
docElem = doc.documentElement;
// Make sure we're not dealing with a disconnected DOM node
if ( !box || !jQuery.contains( docElem, elem ) ) {
return box ? { top: box.top, left: box.left } : { top: 0, left: 0 };
}
var body = doc.body,
win = getWindow(doc),
clientTop = docElem.clientTop || body.clientTop || 0,
clientLeft = docElem.clientLeft || body.clientLeft || 0,
scrollTop = win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop,
scrollLeft = win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft,
top = box.top + scrollTop - clientTop,
left = box.left + scrollLeft - clientLeft;
return { top: top, left: left };
};
} else {
jQuery.fn.offset = function( options ) {
var elem = this[0];
if ( options ) {
return this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
if ( !elem || !elem.ownerDocument ) {
return null;
}
if ( elem === elem.ownerDocument.body ) {
return jQuery.offset.bodyOffset( elem );
}
var computedStyle,
offsetParent = elem.offsetParent,
prevOffsetParent = elem,
doc = elem.ownerDocument,
docElem = doc.documentElement,
body = doc.body,
defaultView = doc.defaultView,
prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle,
top = elem.offsetTop,
left = elem.offsetLeft;
while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) {
if ( jQuery.support.fixedPosition && prevComputedStyle.position === "fixed" ) {
break;
}
computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle;
top -= elem.scrollTop;
left -= elem.scrollLeft;
if ( elem === offsetParent ) {
top += elem.offsetTop;
left += elem.offsetLeft;
if ( jQuery.support.doesNotAddBorder && !(jQuery.support.doesAddBorderForTableAndCells && rtable.test(elem.nodeName)) ) {
top += parseFloat( computedStyle.borderTopWidth ) || 0;
left += parseFloat( computedStyle.borderLeftWidth ) || 0;
}
prevOffsetParent = offsetParent;
offsetParent = elem.offsetParent;
}
if ( jQuery.support.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) {
top += parseFloat( computedStyle.borderTopWidth ) || 0;
left += parseFloat( computedStyle.borderLeftWidth ) || 0;
}
prevComputedStyle = computedStyle;
}
if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) {
top += body.offsetTop;
left += body.offsetLeft;
}
if ( jQuery.support.fixedPosition && prevComputedStyle.position === "fixed" ) {
top += Math.max( docElem.scrollTop, body.scrollTop );
left += Math.max( docElem.scrollLeft, body.scrollLeft );
}
return { top: top, left: left };
};
}
jQuery.offset = {
bodyOffset: function( body ) {
var top = body.offsetTop,
left = body.offsetLeft;
if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) {
top += parseFloat( jQuery.css(body, "marginTop") ) || 0;
left += parseFloat( jQuery.css(body, "marginLeft") ) || 0;
}
return { top: top, left: left };
},
setOffset: function( elem, options, i ) {
var position = jQuery.css( elem, "position" );
// set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
var curElem = jQuery( elem ),
curOffset = curElem.offset(),
curCSSTop = jQuery.css( elem, "top" ),
curCSSLeft = jQuery.css( elem, "left" ),
calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1,
props = {}, curPosition = {}, curTop, curLeft;
// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
position: function() {
if ( !this[0] ) {
return null;
}
var elem = this[0],
// Get *real* offsetParent
offsetParent = this.offsetParent(),
// Get correct offsets
offset = this.offset(),
parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset();
// Subtract element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0;
offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0;
// Add offsetParent borders
parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0;
parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0;
// Subtract the two offsets
return {
top: offset.top - parentOffset.top,
left: offset.left - parentOffset.left
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || document.body;
while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( ["Left", "Top"], function( i, name ) {
var method = "scroll" + name;
jQuery.fn[ method ] = function( val ) {
var elem, win;
if ( val === undefined ) {
elem = this[ 0 ];
if ( !elem ) {
return null;
}
win = getWindow( elem );
// Return the scroll offset
return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] :
jQuery.support.boxModel && win.document.documentElement[ method ] ||
win.document.body[ method ] :
elem[ method ];
}
// Set the scroll offset
return this.each(function() {
win = getWindow( this );
if ( win ) {
win.scrollTo(
!i ? val : jQuery( win ).scrollLeft(),
i ? val : jQuery( win ).scrollTop()
);
} else {
this[ method ] = val;
}
});
};
});
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
// Create width, height, innerHeight, innerWidth, outerHeight and outerWidth methods
jQuery.each([ "Height", "Width" ], function( i, name ) {
var type = name.toLowerCase();
// innerHeight and innerWidth
jQuery.fn[ "inner" + name ] = function() {
var elem = this[0];
return elem ?
elem.style ?
parseFloat( jQuery.css( elem, type, "padding" ) ) :
this[ type ]() :
null;
};
// outerHeight and outerWidth
jQuery.fn[ "outer" + name ] = function( margin ) {
var elem = this[0];
return elem ?
elem.style ?
parseFloat( jQuery.css( elem, type, margin ? "margin" : "border" ) ) :
this[ type ]() :
null;
};
jQuery.fn[ type ] = function( size ) {
// Get window width or height
var elem = this[0];
if ( !elem ) {
return size == null ? null : this;
}
if ( jQuery.isFunction( size ) ) {
return this.each(function( i ) {
var self = jQuery( this );
self[ type ]( size.call( this, i, self[ type ]() ) );
});
}
if ( jQuery.isWindow( elem ) ) {
// Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
// 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat
var docElemProp = elem.document.documentElement[ "client" + name ],
body = elem.document.body;
return elem.document.compatMode === "CSS1Compat" && docElemProp ||
body && body[ "client" + name ] || docElemProp;
// Get document width or height
} else if ( elem.nodeType === 9 ) {
// Either scroll[Width/Height] or offset[Width/Height], whichever is greater
return Math.max(
elem.documentElement["client" + name],
elem.body["scroll" + name], elem.documentElement["scroll" + name],
elem.body["offset" + name], elem.documentElement["offset" + name]
);
// Get or set width or height on the element
} else if ( size === undefined ) {
var orig = jQuery.css( elem, type ),
ret = parseFloat( orig );
return jQuery.isNumeric( ret ) ? ret : orig;
// Set the width or height on the element (default to pixels if value is unitless)
} else {
return this.css( type, typeof size === "string" ? size : size + "px" );
}
};
});
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
// Expose jQuery as an AMD module, but only for AMD loaders that
// understand the issues with loading multiple versions of jQuery
// in a page that all might call define(). The loader will indicate
// they have special allowances for multiple jQuery versions by
// specifying define.amd.jQuery = true. Register as a named module,
// since jQuery can be concatenated with other files that may use define,
// but not use a proper concatenation script that understands anonymous
// AMD modules. A named AMD is safest and most robust way to register.
// Lowercase jquery is used because AMD module names are derived from
// file names, and jQuery is normally delivered in a lowercase file name.
// Do this after creating the global so that if an AMD module wants to call
// noConflict to hide this version of jQuery, it will work.
if ( typeof define === "function" && define.amd && define.amd.jQuery ) {
define( "jquery", [], function () { return jQuery; } );
}
})( window );
|
apache-2.0
|
jiyeyuran/lib-jitsi-meet
|
modules/proxyconnection/ProxyConnectionPC.js
|
13626
|
import { getLogger } from 'jitsi-meet-logger';
import RTC from '../RTC/RTC';
import RTCEvents from '../../service/RTC/RTCEvents';
import XMPPEvents from '../../service/xmpp/XMPPEvents';
import JingleSessionPC from '../xmpp/JingleSessionPC';
import { DEFAULT_STUN_SERVERS } from '../xmpp/xmpp';
import { ACTIONS } from './constants';
const logger = getLogger(__filename);
/**
* An adapter around {@code JingleSessionPC} so its logic can be re-used without
* an XMPP connection. It is being re-used for consistency with the rest of the
* codebase and to leverage existing peer connection event handling. Also
* this class provides a facade to hide most of the API for
* {@code JingleSessionPC}.
*/
export default class ProxyConnectionPC {
/**
* Initializes a new {@code ProxyConnectionPC} instance.
*
* @param {Object} options - Values to initialize the instance with.
* @param {Object} [options.iceConfig] - The {@code RTCConfiguration} to use
* for the peer connection.
* @param {boolean} [options.isInitiator] - If true, the local client should
* send offers. If false, the local client should send answers. Defaults to
* false.
* @param {Function} options.onRemoteStream - Callback to invoke when a
* remote media stream has been received through the peer connection.
* @param {string} options.peerJid - The jid of the remote client with which
* the peer connection is being establish and which should receive direct
* messages regarding peer connection updates.
* @param {boolean} [options.receiveVideo] - Whether or not the peer
* connection should accept incoming video streams. Defaults to false.
* @param {Function} options.onSendMessage - Callback to invoke when a
* message has to be sent (signaled) out.
*/
constructor(options = {}) {
this._options = {
iceConfig: {},
isInitiator: false,
receiveAudio: false,
receiveVideo: false,
...options
};
/**
* Instances of {@code JitsiTrack} associated with this instance of
* {@code ProxyConnectionPC}.
*
* @type {Array<JitsiTrack>}
*/
this._tracks = [];
/**
* The active instance of {@code JingleSessionPC}.
*
* @type {JingleSessionPC|null}
*/
this._peerConnection = null;
// Bind event handlers so they are only bound once for every instance.
this._onError = this._onError.bind(this);
this._onRemoteStream = this._onRemoteStream.bind(this);
this._onSendMessage = this._onSendMessage.bind(this);
}
/**
* Returns the jid of the remote peer with which this peer connection should
* be established with.
*
* @returns {string}
*/
getPeerJid() {
return this._options.peerJid;
}
/**
* Updates the peer connection based on the passed in jingle.
*
* @param {Object} $jingle - An XML jingle element, wrapped in query,
* describing how the peer connection should be updated.
* @returns {void}
*/
processMessage($jingle) {
switch ($jingle.attr('action')) {
case ACTIONS.ACCEPT:
this._onSessionAccept($jingle);
break;
case ACTIONS.INITIATE:
this._onSessionInitiate($jingle);
break;
case ACTIONS.TERMINATE:
this._onSessionTerminate($jingle);
break;
case ACTIONS.TRANSPORT_INFO:
this._onTransportInfo($jingle);
break;
}
}
/**
* Instantiates a peer connection and starts the offer/answer cycle to
* establish a connection with a remote peer.
*
* @param {Array<JitsiLocalTrack>} localTracks - Initial local tracks to add
* to add to the peer connection.
* @returns {void}
*/
start(localTracks = []) {
if (this._peerConnection) {
return;
}
this._tracks = this._tracks.concat(localTracks);
this._peerConnection = this._createPeerConnection();
this._peerConnection.invite(localTracks);
}
/**
* Begins the process of disconnecting from a remote peer and cleaning up
* the peer connection.
*
* @returns {void}
*/
stop() {
if (this._peerConnection) {
this._peerConnection.terminate();
}
this._onSessionTerminate();
}
/**
* Instantiates a new {@code JingleSessionPC} by stubbing out the various
* dependencies of {@code JingleSessionPC}.
*
* @private
* @returns {JingleSessionPC}
*/
_createPeerConnection() {
/**
* {@code JingleSessionPC} takes in the entire jitsi-meet config.js
* object, which may not be accessible from the caller.
*
* @type {Object}
*/
const configStub = {};
/**
* {@code JingleSessionPC} assumes an XMPP/Strophe connection object is
* passed through, which also has the jingle plugin initialized on it.
* This connection object is used to signal out peer connection updates
* via iqs, and those updates need to be piped back out to the remote
* peer.
*
* @type {Object}
*/
const connectionStub = {
// At the time this is used for Spot and it's okay to say the connection is always connected, because if
// spot has no signalling it will not be in a meeting where this is used.
connected: true,
jingle: {
terminate: () => { /** no-op */ }
},
sendIQ: this._onSendMessage,
// Returns empty function, because it does not add any listeners for real
// eslint-disable-next-line no-empty-function
addEventListener: () => () => { }
};
/**
* {@code JingleSessionPC} can take in a custom ice configuration,
* depending on the peer connection type, peer-to-peer or other.
* However, {@code ProxyConnectionPC} always assume a peer-to-peer
* connection so the ice configuration is hard-coded with defaults.
*
* @type {Object}
*/
const iceConfigStub = {
iceServers: DEFAULT_STUN_SERVERS,
...this._options.iceConfig
};
/**
* {@code JingleSessionPC} expects an instance of
* {@code JitsiConference}, which has an event emitter that is used
* to signal various connection updates that the local client should
* act upon. The conference instance is not a dependency of a proxy
* connection, but the emitted events can be relevant to the proxy
* connection so the event emitter is stubbed.
*
* @param {string} event - The constant for the event type.
* @type {Function}
* @returns {void}
*/
const emitter = event => {
switch (event) {
case XMPPEvents.CONNECTION_ICE_FAILED:
case XMPPEvents.CONNECTION_FAILED:
this._onError(ACTIONS.CONNECTION_ERROR, event);
break;
}
};
/**
* {@link JingleSessionPC} expects an instance of
* {@link ChatRoom} to be passed in. {@link ProxyConnectionPC}
* is instantiated outside of the {@code JitsiConference}, so it must be
* stubbed to prevent errors.
*
* @type {Object}
*/
const roomStub = {
addPresenceListener: () => { /** no-op */ },
connectionTimes: [],
eventEmitter: { emit: emitter },
getMediaPresenceInfo: () => {
// Errors occur if this function does not return an object
return {};
},
removePresenceListener: () => { /** no-op */ }
};
/**
* A {@code JitsiConference} stub passed to the {@link RTC} module.
* @type {Object}
*/
const conferenceStub = {
// FIXME: remove once the temporary code below is gone from
// TraceablePeerConnection.
// TraceablePeerConnection:359
// this.rtc.conference.on(
// TRACK_ADDED,
// maybeSetSenderVideoConstraints);
// this.rtc.conference.on(
// TRACK_MUTE_CHANGED,
// maybeSetSenderVideoConstraints);
// eslint-disable-next-line no-empty-function
on: () => {}
};
/**
* Create an instance of {@code RTC} as it is required for peer
* connection creation by {@code JingleSessionPC}. An existing instance
* of {@code RTC} from elsewhere should not be re-used because it is
* a stateful grouping of utilities.
*/
this._rtc = new RTC(conferenceStub, {});
/**
* Add the remote track listener here as {@code JingleSessionPC} has
* {@code TraceablePeerConnection} which uses {@code RTC}'s event
* emitter.
*/
this._rtc.addListener(
RTCEvents.REMOTE_TRACK_ADDED,
this._onRemoteStream
);
const peerConnection = new JingleSessionPC(
undefined, // sid
undefined, // localJid
this._options.peerJid, // remoteJid
connectionStub, // connection
{
offerToReceiveAudio: this._options.receiveAudio,
offerToReceiveVideo: this._options.receiveVideo
}, // mediaConstraints
iceConfigStub, // iceConfig
true, // isP2P
this._options.isInitiator // isInitiator
);
/**
* An additional initialize call is necessary to properly set instance
* variable for calling.
*/
peerConnection.initialize(roomStub, this._rtc, configStub);
return peerConnection;
}
/**
* Invoked when a connection related issue has been encountered.
*
* @param {string} errorType - The constant indicating the type of the error
* that occured.
* @param {string} details - Optional additional data about the error.
* @private
* @returns {void}
*/
_onError(errorType, details = '') {
this._options.onError(this._options.peerJid, errorType, details);
}
/**
* Callback invoked when the peer connection has received a remote media
* stream.
*
* @param {JitsiRemoteTrack} jitsiRemoteTrack - The remote media stream
* wrapped in {@code JitsiRemoteTrack}.
* @private
* @returns {void}
*/
_onRemoteStream(jitsiRemoteTrack) {
this._tracks.push(jitsiRemoteTrack);
this._options.onRemoteStream(jitsiRemoteTrack);
}
/**
* Callback invoked when {@code JingleSessionPC} needs to signal a message
* out to the remote peer.
*
* @param {XML} iq - The message to signal out.
* @private
* @returns {void}
*/
_onSendMessage(iq) {
this._options.onSendMessage(this._options.peerJid, iq);
}
/**
* Callback invoked in response to an agreement to start a proxy connection.
* The passed in jingle element should contain an SDP answer to a previously
* sent SDP offer.
*
* @param {Object} $jingle - The jingle element wrapped in jQuery.
* @private
* @returns {void}
*/
_onSessionAccept($jingle) {
if (!this._peerConnection) {
logger.error('Received an answer when no peer connection exists.');
return;
}
this._peerConnection.setAnswer($jingle);
}
/**
* Callback invoked in response to a request to start a proxy connection.
* The passed in jingle element should contain an SDP offer.
*
* @param {Object} $jingle - The jingle element wrapped in jQuery.
* @private
* @returns {void}
*/
_onSessionInitiate($jingle) {
if (this._peerConnection) {
logger.error('Received an offer when an offer was already sent.');
return;
}
this._peerConnection = this._createPeerConnection();
this._peerConnection.acceptOffer(
$jingle,
() => { /** no-op */ },
() => this._onError(
this._options.peerJid,
ACTIONS.CONNECTION_ERROR,
'session initiate error'
)
);
}
/**
* Callback invoked in response to a request to disconnect an active proxy
* connection. Cleans up tracks and the peer connection.
*
* @private
* @returns {void}
*/
_onSessionTerminate() {
this._tracks.forEach(track => track.dispose());
this._tracks = [];
if (this._peerConnection) {
this._peerConnection.onTerminated();
}
if (this._rtc) {
this._rtc.removeListener(
RTCEvents.REMOTE_TRACK_ADDED,
this._onRemoteStream
);
this._rtc.destroy();
}
}
/**
* Callback invoked in response to ICE candidates from the remote peer.
* The passed in jingle element should contain an ICE candidate.
*
* @param {Object} $jingle - The jingle element wrapped in jQuery.
* @private
* @returns {void}
*/
_onTransportInfo($jingle) {
this._peerConnection.addIceCandidates($jingle);
}
}
|
apache-2.0
|
DARdk/IBA
|
Sensus.Shared/Model/CustomWebView.cs
|
611
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using Xamarin.Forms;
namespace Sensus.Model
{
public class CustomWebView : WebView
{
public static readonly BindableProperty UriProperty = BindableProperty.Create(propertyName: "Uri",
returnType: typeof(string),
declaringType: typeof(CustomWebView),
defaultValue: default(string));
public string Uri
{
get { return (string)GetValue(UriProperty); }
set { SetValue(UriProperty, value); }
}
}
}
|
apache-2.0
|
vitolibrarius/contenta
|
application/views/upload/ComicVineResults.php
|
5490
|
<?php if (is_array($this->issue) && count($this->issue) > 0): ?>
<?php
$existingGroups = array();
$unknownGroups = array();
$map = array();
foreach ($this->issue as $idx => $item) {
$series_xid = array_valueForKeypath( "volume/id", $item );
$seriesObj = $this->series_model->objectForExternal( $series_xid, \model\network\Endpoint_Type::ComicVine);
if ( $seriesObj instanceof \model\media\SeriesDBO ) {
$map[$series_xid] = $seriesObj;
$existingGroups[$series_xid][] = $item;
}
else {
$unknownGroups[] = $item;
}
}
?>
<?php if ( count($map) > 0 ): ?>
<section>
<h3>Matches with existing series</h3>
<div class="row">
<?php foreach ($map as $series_xid => $seriesObj): ?>
<?php
$searchHits = $existingGroups[$series_xid];
$publisher = $seriesObj->publisher();
?>
<?php foreach ($searchHits as $idx => $item): ?>
<div class="grid_4">
<figure class="card">
<div class="figure_top">
<div class="figure_image">
<?php if ( isset($item['image'], $item['image']['thumb_url'])) : ?>
<img src="<?php echo $item['image']['thumb_url'] ?>" class="thumbnail" />
<?php endif; ?>
<br>
</div>
<div class="figure_details">
<div class="figure_detail_top">
<?php if ( is_null($publisher) == false ) {
echo '<img src="' . Config::Web( "Image", "icon", "publisher", $publisher->id) . '" class="thumbnail" /> ';
echo '<span class="publisher name">' . $publisher->name . '</span>';
} ?>
<h3>
<?php if ( isset($item['site_detail_url'])) : ?>
<a target="comicvine" href="<?php echo $item['site_detail_url']; ?>">
<img class="icon" src="<?php echo Model::Named('Endpoint_Type')->ComicVine()->favicon_url; ?>"
alt="ComicVine">
</a>
<?php endif; ?>
<?php echo (isset($item['volume'], $item['volume']['name']) ? $item['volume']['name'] : ""); ?>
</h3>
<p class="property issue_num"><?php echo $item['issue_number']; ?></p>
<p class="property pub_date"><?php echo (isset($item['cover_date']) ? $item['cover_date'] : ""); ?></p>
</div>
<div class="figure_detail_middle">
<?php
$issue_xid = array_valueForKeypath( "id", $item );
$issue = $seriesObj->publicationForExternal( $issue_xid, \model\network\Endpoint_Type::ComicVine);
if ( $issue instanceof \model\media\PublicationDBO ) {
$mediaList = $issue->media();
if ( is_array($mediaList) && count($mediaList) ) {
echo "<table>";
foreach( $mediaList as $idx => $media ) {
echo "<tr><td>" . $media->mediaType()->code
. "</td><td>" . $media->formattedSize()
. "</td></tr>";
}
echo "</table>";
}
else {
echo "<em>No media for this issue</em>";
}
}
else {
echo "New Issue";
}
?>
</div>
</div>
</div>
<figcaption class="caption">
<h4><?php echo (isset($item['name']) ? $item['name'] : ""); ?></h4>
<div style="min-height: 100px; height: 100px; overflow-y : scroll;"><?php
if ( isset($item['deck']) && strlen($item['deck']) > 0) { echo strip_tags($item['deck']); }
else if (isset($item['description']) ) { echo strip_tags($item['description']); }
?></div>
<a class="button" href="<?php echo Config::Web('/AdminUploadRepair/comicVine_accept/', $this->key, $item['id']); ?>">
Import Match
</a>
</figcaption>
</figure>
</div>
<?php endforeach; ?>
<?php endforeach; ?>
</div>
</section>
<hr>
<?php endif; ?>
<?php if ( count($unknownGroups) > 0 ): ?>
<section>
<h3>Matches for new series (not tracking)</h3>
<div class="row">
<?php foreach ($unknownGroups as $idx => $item): ?>
<div class="grid_4">
<figure class="card">
<div class="figure_top">
<div class="figure_image">
<?php if ( isset($item['image'], $item['image']['thumb_url'])) : ?>
<img src="<?php echo $item['image']['thumb_url'] ?>" class="thumbnail" />
<?php endif; ?>
<br>
</div>
<div class="figure_details">
<div class="figure_detail_top">
<h3>
<?php if ( isset($item['volume'], $item['volume']['site_detail_url'])) : ?>
<a target="comicvine" href="<?php echo $item['volume']['site_detail_url']; ?>">
<img class="icon" src="<?php echo Model::Named('Endpoint_Type')->ComicVine()->favicon_url; ?>"
alt="ComicVine">
</a>
<?php endif; ?>
<?php echo (isset($item['volume'], $item['volume']['name']) ? $item['volume']['name'] : ""); ?>
</h3>
<p class="property issue_num"><?php echo $item['issue_number']; ?></p>
<p class="property pub_date"><?php echo $item['cover_date']; ?></p>
</div>
<div class="figure_detail_middle">
</div>
</div>
</div>
<figcaption class="caption">
<h4><?php echo (isset($item['name']) ? $item['name'] : ""); ?></h4>
<div style="min-height: 100px; height: 100px; overflow-y : scroll;"><?php
if ( isset($item['deck']) && strlen(trim($item['deck'])) > 0) { echo 'deck' .strip_tags($item['deck']); }
else if (isset($item['description']) ) { echo strip_tags($item['description']); }
?></div>
<a class="button" href="<?php echo Config::Web('/AdminUploadRepair/comicVine_accept/', $this->key, $item['id']); ?>">
Import Match
</a>
</figcaption>
</figure>
</div>
<?php endforeach; ?>
</div>
</section>
<?php endif; ?>
<?php else: // has issues ?>
No results found
<?php endif; ?>
|
apache-2.0
|
d0k1/jmeter
|
test/src/org/apache/jmeter/samplers/TestSampleResult.java
|
13305
|
/*
* 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.jmeter.samplers;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.StringWriter;
import org.apache.jmeter.junit.JMeterTestCase;
import org.apache.jmeter.util.Calculator;
import org.apache.log.LogTarget;
import org.apache.log.format.Formatter;
import org.apache.log.format.RawFormatter;
import org.apache.log.output.io.WriterTarget;
import org.junit.Test;
// TODO need more tests - particularly for the new functions
public class TestSampleResult {
@Test
public void testElapsedTrue() throws Exception {
SampleResult res = new SampleResult(true);
// Check sample increments OK
res.sampleStart();
Thread.sleep(110); // Needs to be greater than the minimum to allow for boundary errors
res.sampleEnd();
long time = res.getTime();
if(time < 100){
fail("Sample time should be >=100, actual "+time);
}
}
@Test
public void testElapsedFalse() throws Exception {
SampleResult res = new SampleResult(false);
// Check sample increments OK
res.sampleStart();
Thread.sleep(110); // Needs to be greater than the minimum to allow for boundary errors
res.sampleEnd();
long time = res.getTime();
if(time < 100){
fail("Sample time should be >=100, actual "+time);
}
}
@Test
public void testPauseFalse() throws Exception {
SampleResult res = new SampleResult(false);
// Check sample increments OK
res.sampleStart();
Thread.sleep(100);
res.samplePause();
Thread.sleep(200);
// Re-increment
res.sampleResume();
Thread.sleep(100);
res.sampleEnd();
long sampleTime = res.getTime();
if ((sampleTime < 180) || (sampleTime > 290)) {
fail("Accumulated time (" + sampleTime + ") was not between 180 and 290 ms");
}
}
@Test
public void testPauseTrue() throws Exception {
SampleResult res = new SampleResult(true);
// Check sample increments OK
res.sampleStart();
Thread.sleep(100);
res.samplePause();
Thread.sleep(200);
// Re-increment
res.sampleResume();
Thread.sleep(100);
res.sampleEnd();
long sampleTime = res.getTime();
if ((sampleTime < 180) || (sampleTime > 290)) {
fail("Accumulated time (" + sampleTime + ") was not between 180 and 290 ms");
}
}
private static final Formatter fmt = new RawFormatter();
private StringWriter wr = null;
private void divertLog() {// N.B. This needs to divert the log for SampleResult
wr = new StringWriter(1000);
LogTarget[] lt = { new WriterTarget(wr, fmt) };
SampleResult.log.setLogTargets(lt);
}
@Test
public void testPause2True() throws Exception {
divertLog();
SampleResult res = new SampleResult(true);
res.sampleStart();
res.samplePause();
assertEquals(0, wr.toString().length());
res.samplePause();
assertFalse(wr.toString().length() == 0);
}
@Test
public void testPause2False() throws Exception {
divertLog();
SampleResult res = new SampleResult(false);
res.sampleStart();
res.samplePause();
assertEquals(0, wr.toString().length());
res.samplePause();
assertFalse(wr.toString().length() == 0);
}
@Test
public void testByteCount() throws Exception {
SampleResult res = new SampleResult();
res.sampleStart();
res.setBytes(100);
res.setSampleLabel("sample of size 100 bytes");
res.sampleEnd();
assertEquals(100, res.getBytes());
assertEquals("sample of size 100 bytes", res.getSampleLabel());
}
@Test
public void testSubResultsTrue() throws Exception {
testSubResults(true, 0);
}
@Test
public void testSubResultsTrueThread() throws Exception {
testSubResults(true, 500L, 0);
}
@Test
public void testSubResultsFalse() throws Exception {
testSubResults(false, 0);
}
@Test
public void testSubResultsFalseThread() throws Exception {
testSubResults(false, 500L, 0);
}
@Test
public void testSubResultsTruePause() throws Exception {
testSubResults(true, 100);
}
@Test
public void testSubResultsTruePauseThread() throws Exception {
testSubResults(true, 500L, 100);
}
@Test
public void testSubResultsFalsePause() throws Exception {
testSubResults(false, 100);
}
@Test
public void testSubResultsFalsePauseThread() throws Exception {
testSubResults(false, 500L, 100);
}
// temp test case for exploring settings
public void xtestUntilFail() throws Exception {
while(true) {
testSubResultsTruePause();
testSubResultsFalsePause();
}
}
private void testSubResults(boolean nanoTime, long pause) throws Exception {
testSubResults(nanoTime, 0L, pause); // Don't use nanoThread
}
private void testSubResults(boolean nanoTime, long nanoThreadSleep, long pause) throws Exception {
// This test tries to emulate a http sample, with two
// subsamples, representing images that are downloaded for the
// page representing the first sample.
// Sample that will get two sub results, simulates a web page load
SampleResult parent = new SampleResult(nanoTime, nanoThreadSleep);
JMeterTestCase.assertPrimitiveEquals(nanoTime, parent.useNanoTime);
assertEquals(nanoThreadSleep, parent.nanoThreadSleep);
long beginTest = parent.currentTimeInMillis();
parent.sampleStart();
Thread.sleep(100);
parent.setBytes(300);
parent.setSampleLabel("Parent Sample");
parent.setSuccessful(true);
parent.sampleEnd();
long parentElapsed = parent.getTime();
// Sample with no sub results, simulates an image download
SampleResult child1 = new SampleResult(nanoTime);
child1.sampleStart();
Thread.sleep(100);
child1.setBytes(100);
child1.setSampleLabel("Child1 Sample");
child1.setSuccessful(true);
child1.sampleEnd();
long child1Elapsed = child1.getTime();
assertTrue(child1.isSuccessful());
assertEquals(100, child1.getBytes());
assertEquals("Child1 Sample", child1.getSampleLabel());
assertEquals(1, child1.getSampleCount());
assertEquals(0, child1.getSubResults().length);
long actualPause = 0;
if (pause > 0) {
long t1 = parent.currentTimeInMillis();
Thread.sleep(pause);
actualPause = parent.currentTimeInMillis() - t1;
}
// Sample with no sub results, simulates an image download
SampleResult child2 = new SampleResult(nanoTime);
child2.sampleStart();
Thread.sleep(100);
child2.setBytes(200);
child2.setSampleLabel("Child2 Sample");
child2.setSuccessful(true);
child2.sampleEnd();
long child2Elapsed = child2.getTime();
assertTrue(child2.isSuccessful());
assertEquals(200, child2.getBytes());
assertEquals("Child2 Sample", child2.getSampleLabel());
assertEquals(1, child2.getSampleCount());
assertEquals(0, child2.getSubResults().length);
// Now add the subsamples to the sample
parent.addSubResult(child1);
parent.addSubResult(child2);
assertTrue(parent.isSuccessful());
assertEquals(600, parent.getBytes());
assertEquals("Parent Sample", parent.getSampleLabel());
assertEquals(1, parent.getSampleCount());
assertEquals(2, parent.getSubResults().length);
long parentElapsedTotal = parent.getTime();
long overallTime = parent.currentTimeInMillis() - beginTest;
long sumSamplesTimes = parentElapsed + child1Elapsed + actualPause + child2Elapsed;
/*
* Parent elapsed total should be no smaller than the sum of the individual samples.
* It may be greater by the timer granularity.
*/
long diff = parentElapsedTotal - sumSamplesTimes;
long maxDiff = nanoTime ? 2 : 16; // TimeMillis has granularity of 10-20
if (diff < 0 || diff > maxDiff) {
fail("ParentElapsed: " + parentElapsedTotal + " - " + " sum(samples): " + sumSamplesTimes
+ " = " + diff + " not in [0," + maxDiff + "]; nanotime=" + nanoTime);
}
/**
* The overall time to run the test must be no less than,
* and may be greater (but not much greater) than the parent elapsed time
*/
diff = overallTime - parentElapsedTotal;
if (diff < 0 || diff > maxDiff) {
fail("TestElapsed: " + overallTime + " - " + " ParentElapsed: " + parentElapsedTotal
+ " = " + diff + " not in [0," + maxDiff + "]; nanotime="+nanoTime);
}
// Check that calculator gets the correct statistics from the sample
Calculator calculator = new Calculator();
calculator.addSample(parent);
assertEquals(600, calculator.getTotalBytes());
assertEquals(1, calculator.getCount());
assertEquals(1d / (parentElapsedTotal / 1000d), calculator.getRate(),0.0001d); // Allow for some margin of error
// Check that the throughput uses the time elapsed for the sub results
assertFalse(1d / (parentElapsed / 1000d) <= calculator.getRate());
}
// TODO some more invalid sequence tests needed
@Test
public void testEncodingAndType() throws Exception {
// check default
SampleResult res = new SampleResult();
assertEquals(SampleResult.DEFAULT_ENCODING,res.getDataEncodingWithDefault());
assertEquals("DataType should be blank","",res.getDataType());
assertNull(res.getDataEncodingNoDefault());
// check null changes nothing
res.setEncodingAndType(null);
assertEquals(SampleResult.DEFAULT_ENCODING,res.getDataEncodingWithDefault());
assertEquals("DataType should be blank","",res.getDataType());
assertNull(res.getDataEncodingNoDefault());
// check no charset
res.setEncodingAndType("text/html");
assertEquals(SampleResult.DEFAULT_ENCODING,res.getDataEncodingWithDefault());
assertEquals("text",res.getDataType());
assertNull(res.getDataEncodingNoDefault());
// Check unquoted charset
res.setEncodingAndType("text/html; charset=aBcd");
assertEquals("aBcd",res.getDataEncodingWithDefault());
assertEquals("aBcd",res.getDataEncodingNoDefault());
assertEquals("text",res.getDataType());
// Check quoted charset
res.setEncodingAndType("text/html; charset=\"aBCd\"");
assertEquals("aBCd",res.getDataEncodingWithDefault());
assertEquals("aBCd",res.getDataEncodingNoDefault());
assertEquals("text",res.getDataType());
}
}
|
apache-2.0
|
mkauf/AutobahnTestSuite
|
autobahntestsuite/setup.py
|
4326
|
###############################################################################
##
## Copyright (C) 2011-2014 Tavendo GmbH
##
## Licensed under the Apache License, Version 2.0 (the "License");
## you may not use this file except in compliance with the License.
## You may obtain a copy of the License at
##
## http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.
##
###############################################################################
from setuptools import setup, find_packages
LONGSDESC = """
Twisted-based WebSocket/WAMP protocol implementation test suite.
Autobahn|Testsuite provides a fully automated test suite to verify client and
server implementations of the WebSocket protocol.
The test suite will check an implementation by doing basic WebSocket
conversations, extensive protocol compliance verification and
performance and limits testing.
Contains over 500 test cases covering
* Framing
* Pings/Pongs
* Reserved Bits
* Opcodes
* Fragmentation
* UTF-8 Handling
* Limits/Performance
* Closing Handshake
* Opening Handshake (under development)
* WebSocket compression (permessage-deflate extension)
Besides the automated test suite, wstest also includes a number
of other handy developer tools:
* WebSocket echo server and client
* WebSocket broadcast server (and client driver)
* Testee modes to test Autobahn itself against the test suite
* wsperf controller and master (see http://www.zaphoyd.com/wsperf)
* WAMP server and client, for developing WAMP implementations
More information:
* http://autobahn.ws/testsuite
* https://github.com/crossbario/autobahn-testsuite
* http://tools.ietf.org/html/rfc6455
* http://wamp.ws
"""
## get version string from "autobahntestsuite/_version.py"
## See: http://stackoverflow.com/a/7071358/884770
##
import re
VERSIONFILE="autobahntestsuite/_version.py"
verstrline = open(VERSIONFILE, "rt").read()
VSRE = r"^__version__ = ['\"]([^'\"]*)['\"]"
mo = re.search(VSRE, verstrline, re.M)
if mo:
verstr = mo.group(1)
else:
raise RuntimeError("Unable to find version string in %s." % (VERSIONFILE,))
setup (
name = 'autobahntestsuite',
version = verstr,
description = 'AutobahnTestSuite - WebSocket/WAMP protocol implementation test suite.',
long_description = LONGSDESC,
license = 'Apache License 2.0',
author = 'Tavendo GmbH',
author_email = 'autobahnws@googlegroups.com',
url = 'http://autobahn.ws/testsuite',
platforms = ('Any'),
install_requires = ['setuptools',
'txaio<=2.1.0', # https://github.com/crossbario/autobahn-testsuite/issues/55
'autobahn[twisted,accelerate]>=0.9.2,<0.11',
'jinja2>=2.6',
'markupsafe>=0.19',
'Werkzeug>=0.9.4',
'klein>=0.2.1',
'pyopenssl>=0.14',
'service_identity>=14.0.0',
'unittest2>=1.1.0'],
packages = find_packages(),
#packages = ['autobahntestsuite'],
include_package_data = True,
package_data = {
'': ['templates/*.html'],
},
zip_safe = False,
entry_points = {
'console_scripts': [
'wstest = autobahntestsuite.wstest:run'
]},
## http://pypi.python.org/pypi?%3Aaction=list_classifiers
##
classifiers = ["License :: OSI Approved :: Apache Software License",
"Development Status :: 5 - Production/Stable",
"Environment :: Console",
"Framework :: Twisted",
"Intended Audience :: Developers",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Topic :: Internet",
"Topic :: Software Development :: Testing"],
keywords = 'autobahn autobahn.ws websocket wamp realtime test testsuite rfc6455 wstest wsperf'
)
|
apache-2.0
|
OLR-xray/XRay-NEW
|
XRay/xr_3da/xrRender_R2/PSLibrary.cpp
|
4701
|
//----------------------------------------------------
// file: PSLibrary.cpp
//----------------------------------------------------
#include "stdafx.h"
#pragma hdrstop
#include "PSLibrary.h"
#include "ParticleEffect.h"
#define _game_data_ "$game_data$"
bool ped_sort_pred (const PS::CPEDef* a, const PS::CPEDef* b) { return xr_strcmp(a->Name(),b->Name())<0;}
bool pgd_sort_pred (const PS::CPGDef* a, const PS::CPGDef* b) { return xr_strcmp(a->m_Name,b->m_Name)<0;}
bool ped_find_pred (const PS::CPEDef* a, LPCSTR b) { return xr_strcmp(a->Name(),b)<0;}
bool pgd_find_pred (const PS::CPGDef* a, LPCSTR b) { return xr_strcmp(a->m_Name,b)<0;}
//----------------------------------------------------
void CPSLibrary::OnCreate()
{
string256 fn;
FS.update_path(fn,_game_data_,PSLIB_FILENAME);
if (FS.exist(fn)){
if (!Load(fn)) Msg("PS Library: Unsupported version.");
}else{
Msg("Can't find file: '%s'",fn);
}
for (PS::PEDIt e_it = m_PEDs.begin(); e_it!=m_PEDs.end(); e_it++)
(*e_it)->CreateShader();
}
void CPSLibrary::OnDestroy()
{
for (PS::PEDIt e_it = m_PEDs.begin(); e_it!=m_PEDs.end(); e_it++)
(*e_it)->DestroyShader();
for (PS::PEDIt e_it = m_PEDs.begin(); e_it!=m_PEDs.end(); e_it++)
xr_delete (*e_it);
m_PEDs.clear ();
for (PS::PGDIt g_it = m_PGDs.begin(); g_it!=m_PGDs.end(); g_it++)
xr_delete (*g_it);
m_PGDs.clear ();
}
//----------------------------------------------------
PS::PEDIt CPSLibrary::FindPEDIt(LPCSTR Name)
{
if (!Name) return m_PEDs.end();
#ifdef _EDITOR
for (PS::PEDIt it=m_PEDs.begin(); it!=m_PEDs.end(); it++)
if (0==xr_strcmp((*it)->Name(),Name)) return it;
return m_PEDs.end();
#else
PS::PEDIt I = std::lower_bound(m_PEDs.begin(),m_PEDs.end(),Name,ped_find_pred);
if (I==m_PEDs.end() || (0!=xr_strcmp((*I)->m_Name,Name))) return m_PEDs.end();
else return I;
#endif
}
PS::CPEDef* CPSLibrary::FindPED(LPCSTR Name)
{
PS::PEDIt it = FindPEDIt(Name);
return (it==m_PEDs.end())?0:*it;
}
PS::PGDIt CPSLibrary::FindPGDIt(LPCSTR Name)
{
if (!Name) return m_PGDs.end();
#ifdef _EDITOR
for (PS::PGDIt it=m_PGDs.begin(); it!=m_PGDs.end(); it++)
if (0==xr_strcmp((*it)->m_Name,Name)) return it;
return m_PGDs.end();
#else
PS::PGDIt I = std::lower_bound(m_PGDs.begin(),m_PGDs.end(),Name,pgd_find_pred);
if (I==m_PGDs.end() || (0!=xr_strcmp((*I)->m_Name,Name))) return m_PGDs.end();
else return I;
#endif
}
PS::CPGDef* CPSLibrary::FindPGD(LPCSTR Name)
{
PS::PGDIt it = FindPGDIt(Name);
return (it==m_PGDs.end())?0:*it;
}
void CPSLibrary::RenamePED(PS::CPEDef* src, LPCSTR new_name)
{
R_ASSERT(src&&new_name&&new_name[0]);
src->SetName(new_name);
}
void CPSLibrary::RenamePGD(PS::CPGDef* src, LPCSTR new_name)
{
R_ASSERT(src&&new_name&&new_name[0]);
src->SetName(new_name);
}
void CPSLibrary::Remove(const char* nm)
{
PS::PEDIt it = FindPEDIt(nm);
if (it!=m_PEDs.end()){
(*it)->DestroyShader();
xr_delete (*it);
m_PEDs.erase (it);
}else{
PS::PGDIt it = FindPGDIt(nm);
if (it!=m_PGDs.end()){
xr_delete (*it);
m_PGDs.erase(it);
}
}
}
//----------------------------------------------------
bool CPSLibrary::Load(const char* nm)
{
IReader* F = FS.r_open(nm);
bool bRes = true;
R_ASSERT(F->find_chunk(PS_CHUNK_VERSION));
u16 ver = F->r_u16();
if (ver!=PS_VERSION) return false;
// second generation
IReader* OBJ;
OBJ = F->open_chunk(PS_CHUNK_SECONDGEN);
if (OBJ){
IReader* O = OBJ->open_chunk(0);
for (int count=1; O; count++) {
PS::CPEDef* def = xr_new<PS::CPEDef>();
if (def->Load(*O)) m_PEDs.push_back(def);
else{ bRes = false; xr_delete(def); }
O->close();
if (!bRes) break;
O = OBJ->open_chunk(count);
}
OBJ->close();
}
// second generation
OBJ = F->open_chunk(PS_CHUNK_THIRDGEN);
if (OBJ){
IReader* O = OBJ->open_chunk(0);
for (int count=1; O; count++) {
PS::CPGDef* def = xr_new<PS::CPGDef>();
if (def->Load(*O)) m_PGDs.push_back(def);
else{ bRes = false; xr_delete(def); }
O->close();
if (!bRes) break;
O = OBJ->open_chunk(count);
}
OBJ->close();
}
// final
FS.r_close (F);
std::sort (m_PEDs.begin(),m_PEDs.end(),ped_sort_pred);
std::sort (m_PGDs.begin(),m_PGDs.end(),pgd_sort_pred);
return bRes;
}
//----------------------------------------------------
void CPSLibrary::Reload()
{
OnDestroy();
OnCreate();
Msg( "PS Library was succesfully reloaded." );
}
//----------------------------------------------------
|
apache-2.0
|
thr0w/galen
|
src/test/java/net/mindengine/galen/tests/parser/GalenSuiteReaderTest.java
|
18941
|
/*******************************************************************************
* Copyright 2015 Ivan Shubin http://mindengine.net
*
* 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 net.mindengine.galen.tests.parser;
import static java.util.Arrays.asList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import java.awt.Dimension;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import net.mindengine.galen.browser.BrowserFactory;
import net.mindengine.galen.browser.SeleniumGridBrowserFactory;
import net.mindengine.galen.parser.FileSyntaxException;
import net.mindengine.galen.suite.GalenPageAction;
import net.mindengine.galen.suite.GalenPageActions;
import net.mindengine.galen.suite.GalenPageTest;
import net.mindengine.galen.suite.reader.GalenSuiteReader;
import net.mindengine.galen.tests.GalenBasicTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class GalenSuiteReaderTest {
private static final Object EMPTY_TAGS = new LinkedList<String>();
@Test
public void shouldRead_simpleSuite_successfully() throws IOException {
GalenSuiteReader reader = new GalenSuiteReader();
List<GalenBasicTest> galenSuites = reader.read(new File(getClass().getResource("/suites/suite-simple.test").getFile()));
assertThat("Amount of suites should be", galenSuites.size(), is(2));
/* Checking suite 1*/
{
GalenBasicTest suite = galenSuites.get(0);
assertThat(suite.getName(), is("This is a name of suite"));
assertThat("Amount of pages for 1st suite should be", suite.getPageTests().size(), is(2));
// Checking page 1
{
GalenPageTest page = suite.getPageTests().get(0);
assertThat(page.getTitle(), is("This is title for page"));
assertThat(page.getUrl(), is("http://example.com/page1"));
assertThat(page.getScreenSize(), is(new Dimension(640, 480)));
assertThat(page.getActions(), is(actions(GalenPageActions.injectJavascript("javascript.js"),
GalenPageActions.check(asList("page1.spec")).withIncludedTags(asList("mobile", "tablet")).withExcludedTags(asList("nomobile")),
GalenPageActions.injectJavascript("javascript2.js"),
GalenPageActions.runJavascript("selenium/loginToMyProfile.js").withArguments("{\"login\":\"user1\", \"password\": \"test123\"}"),
GalenPageActions.check(asList("page1_1.spec", "page1_2.spec", "page1_3.spec")).withIncludedTags(asList("sometag"))
)));
}
//Checking page 2
{
GalenPageTest page = suite.getPageTests().get(1);
assertThat(page.getTitle(), is("http://example.com/page2 1024x768"));
assertThat(page.getUrl(), is("http://example.com/page2"));
assertThat(page.getScreenSize(), is(new Dimension(1024, 768)));
assertThat(page.getActions(), is(actions(GalenPageActions.check(asList("page2.spec")),
(GalenPageAction)GalenPageActions.check(asList("page3.spec")))));
}
}
// Checking suite 2
{
GalenBasicTest suite = galenSuites.get(1);
assertThat(suite.getName(), is("This is another suite name"));
assertThat("Amount of pages for 1st suite should be", suite.getPageTests().size(), is(1));
GalenPageTest page = suite.getPageTests().get(0);
assertThat(page.getUrl(), is("http://example.com/page3"));
assertThat(page.getScreenSize(), is(new Dimension(320, 240)));
assertThat(page.getActions(), is(actions(GalenPageActions.check(asList("page3.spec")))));
}
}
@Test
public void shouldRead_allPageActions() throws IOException {
GalenSuiteReader reader = new GalenSuiteReader();
List<GalenBasicTest> galenSuites = reader.read(new File(getClass().getResource("/suites/suite-all-page-actions.test").getFile()));
assertThat(galenSuites.size(), is(1));
List<GalenPageAction> pageActions = galenSuites.get(0).getPageTests().get(0).getActions();
assertThat(pageActions.size(), is(6));
assertThat(pageActions.get(0), is((GalenPageAction)GalenPageActions.open("http://example.com")));
assertThat(pageActions.get(1), is((GalenPageAction)GalenPageActions.resize(640, 480)));
assertThat(pageActions.get(2), is((GalenPageAction)GalenPageActions.cookie("cookie1=somevalue; path=/")));
assertThat(pageActions.get(3), is((GalenPageAction)GalenPageActions.runJavascript("script.js")));
assertThat(pageActions.get(4), is((GalenPageAction)GalenPageActions.injectJavascript("script.js")));
assertThat(pageActions.get(5), is((GalenPageAction)GalenPageActions.check(asList("homepage.spec"))));
}
@Test
public void shouldRead_suiteWithVariables_successfully() throws IOException {
System.setProperty("some.system.property", "custom property");
GalenSuiteReader reader = new GalenSuiteReader();
List<GalenBasicTest> galenSuites = reader.read(new File(getClass().getResource("/suites/suite-variables.txt").getFile()));
assertThat("Amount of suites should be", galenSuites.size(), is(2));
/* Checking suite 1*/
{
GalenBasicTest suite = galenSuites.get(0);
assertThat(suite.getName(), is("This is a name of suite"));
assertThat("Amount of pages for 1st suite should be", suite.getPageTests().size(), is(1));
// Checking page 1
GalenPageTest page = suite.getPageTests().get(0);
assertThat(page.getUrl(), is("http://example.com/some-page.html"));
assertThat(page.getScreenSize(), is(new Dimension(640, 480)));
assertThat(page.getActions(), is(actions(
GalenPageActions.runJavascript("selenium/loginToMyProfile.js").withArguments("{\"myvar\" : \"suite\", \"var_concat\" : \"some-page.html and 640x480\"}")
)));
}
// Checking suite 2
{
GalenBasicTest suite = galenSuites.get(1);
assertThat(suite.getName(), is("This is a name of suite 2 and also custom property"));
assertThat("Amount of pages for 1st suite should be", suite.getPageTests().size(), is(1));
GalenPageTest page = suite.getPageTests().get(0);
assertThat(page.getUrl(), is("http://example.com/some-page.html"));
assertThat(page.getScreenSize(), is(new Dimension(640, 480)));
assertThat(page.getActions(), is(actions(
GalenPageActions.runJavascript("selenium/loginToMyProfile.js").withArguments("{\"myvar\" : \"suite 2\"}")
)));
}
}
@SuppressWarnings("unchecked")
@Test
public void shouldRead_suiteWithParameterizations_successfully() throws IOException {
GalenSuiteReader reader = new GalenSuiteReader();
List<GalenBasicTest> galenSuites = reader.read(new File(getClass().getResource("/suites/suite-parameterized.test").getFile()));
assertThat("Amount of suites should be", galenSuites.size(), is(11));
/* Checking first group of suites */
{
Object [][] table = new Object[][]{
{new Dimension(320, 240), asList("mobile"), "Phone", asList("nomobile")},
{new Dimension(640, 480), asList("tablet"), "Tablet", EMPTY_TAGS}
};
for (int i=0; i<2; i++) {
GalenBasicTest suite = galenSuites.get(i);
assertThat(suite.getName(), is("Test for " + table[i][2]));
assertThat("Amount of pages for 1st suite should be", suite.getPageTests().size(), is(1));
// Checking page 1
GalenPageTest page = suite.getPageTests().get(0);
assertThat(page.getUrl(), is("http://example.com/page1"));
assertThat(page.getScreenSize(), is((Dimension)table[i][0]));
assertThat(page.getActions(), is(actions(
GalenPageActions.check(asList("page1.spec")).withIncludedTags((List<String>) table[i][1]).withExcludedTags((List<String>) table[i][3])
)));
}
}
/* Checking second group of suites */
{
Object [][] table = new Object[][]{
{new Dimension(320, 240), asList("mobile"), "Phone", asList("nomobile"), "page1"},
{new Dimension(640, 480), asList("tablet"), "Tablet", EMPTY_TAGS, "page2"},
{new Dimension(1024, 768), asList("desktop"), "Desktop", asList("nodesktop"), "page3"}
};
for (int i=2; i<5; i++) {
int j = i - 2;
GalenBasicTest suite = galenSuites.get(i);
assertThat(suite.getName(), is("Test combining 2 tables for " + table[j][2]));
assertThat("Amount of pages for 1st suite should be", suite.getPageTests().size(), is(1));
// Checking page 1
GalenPageTest page = suite.getPageTests().get(0);
assertThat(page.getUrl(), is("http://example.com/" + table[j][4]));
assertThat(page.getScreenSize(), is((Dimension)table[j][0]));
assertThat(page.getActions(), is(actions(
GalenPageActions.check(asList("page1.spec")).withIncludedTags((List<String>) table[j][1]).withExcludedTags((List<String>) table[j][3])
)));
}
}
/* Checking 3rd group of suites */
{
Object[][] table = new Object[][]{
{new Dimension(320, 240), asList("mobile"), "Phone", asList("nomobile"), "page1", "firefox", "Firefox", "any"},
{new Dimension(640, 480), asList("tablet"), "Tablet", EMPTY_TAGS, "page2", "firefox", "Firefox", "any"},
{new Dimension(320, 240), asList("mobile"), "Phone", asList("nomobile"), "page1", "ie", "IE 8", "8"},
{new Dimension(640, 480), asList("tablet"), "Tablet", EMPTY_TAGS, "page2", "ie", "IE 8", "8"},
{new Dimension(320, 240), asList("mobile"), "Phone", asList("nomobile"), "page1", "ie", "IE 9", "9"},
{new Dimension(640, 480), asList("tablet"), "Tablet", EMPTY_TAGS, "page2", "ie", "IE 9", "9"},
};
for (int i=5; i<11; i++) {
int j = i - 5;
GalenBasicTest suite = galenSuites.get(i);
assertThat(suite.getName(), is("Test using 2 layer tables in browser " + table[j][6] + " for type " + table[j][2]));
assertThat("Amount of pages for 1st suite should be", suite.getPageTests().size(), is(1));
// Checking page 1
GalenPageTest page = suite.getPageTests().get(0);
assertThat(page.getBrowserFactory(), is((BrowserFactory)new SeleniumGridBrowserFactory("http://mygrid:8080/wd/hub")
.withBrowser((String)table[j][5])
.withBrowserVersion((String)table[j][7])
));
assertThat(page.getUrl(), is("http://example.com/" + table[j][4]));
assertThat(page.getScreenSize(), is((Dimension)table[j][0]));
assertThat(page.getActions(), is(actions(
GalenPageActions.check(asList("page1.spec")).withIncludedTags((List<String>) table[j][1]).withExcludedTags((List<String>) table[j][3])
)));
}
}
}
@Test
public void shouldParse_suitesWithEmptyUrls() throws IOException {
GalenSuiteReader reader = new GalenSuiteReader();
List<GalenBasicTest> galenSuites = reader.read(new File(getClass().getResource("/suites/suite-empty-url.test").getFile()));
assertThat("Amount of suites should be", galenSuites.size(), is(4));
for (int i = 0; i < 4; i++) {
assertThat(galenSuites.get(i).getName(), is("Suite " + (i+1)));
GalenPageTest pageTest = galenSuites.get(i).getPageTests().get(0);
assertThat(pageTest.getUrl(), is(nullValue()));
}
assertThat(galenSuites.get(0).getPageTests().get(0).getScreenSize(), is(new Dimension(640, 480)));
assertThat(galenSuites.get(1).getPageTests().get(0).getScreenSize(), is(nullValue()));
assertThat(galenSuites.get(2).getPageTests().get(0).getScreenSize(), is(new Dimension(320, 240)));
assertThat(galenSuites.get(3).getPageTests().get(0).getScreenSize(), is(nullValue()));
}
@Test
public void shouldNotInclude_disabledSuites() throws IOException {
GalenSuiteReader reader = new GalenSuiteReader();
List<GalenBasicTest> galenSuites = reader.read(new File(getClass().getResource("/suites/suite-disabled.test").getFile()));
assertThat("Amount of suites should be", galenSuites.size(), is(3));
assertThat(galenSuites.get(0).getName(), is("Suite 1"));
assertThat(galenSuites.get(1).getName(), is("Suite 2"));
assertThat(galenSuites.get(2).getName(), is("Suite 3"));
}
@Test
public void shouldIncludeEverything_forImportedTestSuites() throws IOException {
GalenSuiteReader reader = new GalenSuiteReader();
List<GalenBasicTest> galenSuites = reader.read(new File(getClass().getResource("/suites/suite-import.test").getFile()));
assertThat("Amount of suites should be", galenSuites.size(), is(3));
assertThat(galenSuites.get(0).getName(), is("Suite 1"));
assertThat(galenSuites.get(1).getName(), is("Suite 2"));
assertThat(galenSuites.get(2).getName(), is("Suite 3 imported test suite name"));
}
@Test
public void shouldRead_testGroups() throws IOException {
GalenSuiteReader reader = new GalenSuiteReader();
List<GalenBasicTest> galenTests = reader.read(new File(getClass().getResource("/suites/suite-with-groups.test").getFile()));
assertThat("Amount of tests should be", galenTests.size(), is(5));
assertThat(galenTests.get(0).getName(), is("Test 1"));
assertThat(galenTests.get(0).getGroups(), contains("mobile"));
assertThat(galenTests.get(1).getName(), is("Test 2"));
assertThat(galenTests.get(1).getGroups(), is(nullValue()));
assertThat(galenTests.get(2).getName(), is("Test 3"));
assertThat(galenTests.get(2).getGroups(), contains("tablet", "desktop", "HOMEPAGE"));
assertThat(galenTests.get(3).getName(), is("Test on firefox browser"));
assertThat(galenTests.get(3).getGroups(), contains("mobile", "tablet"));
assertThat(galenTests.get(4).getName(), is("Test on chrome browser"));
assertThat(galenTests.get(4).getGroups(), contains("mobile", "tablet"));
}
private List<GalenPageAction> actions(GalenPageAction...actions) {
List<GalenPageAction> list = new LinkedList<GalenPageAction>();
for (GalenPageAction action : actions) {
list.add(action);
}
return list;
}
@Test(dataProvider="provideBadSamples") public void shouldGiveError_withLineNumberInformation_whenParsingIncorrectSuite(String filePath, int expectedLine, String expectedMessage) throws IOException {
FileSyntaxException exception = null;
try {
new GalenSuiteReader().read(new File(getClass().getResource(filePath).getFile()));
}
catch (FileSyntaxException e) {
exception = e;
System.out.println("***************");
e.printStackTrace();
}
String fullPath = getClass().getResource(filePath).getFile();
assertThat("Exception should be thrown", exception, notNullValue());
assertThat("Message should be", exception.getMessage(), is(expectedMessage + "\n in " + fullPath + ":" + expectedLine));
assertThat("Line should be", exception.getLine(), is(expectedLine));
}
@DataProvider public Object[][] provideBadSamples() {
return new Object[][]{
{"/suites/suite-with-error-unknown-table-in-parameterized.test", 16, "Table with name \"some_unknown_table\" does not exist"},
{"/suites/suite-with-error-page-error.test", 3, "Incorrect amount of arguments: selenium http://"},
{"/suites/suite-with-error-action-inject-error.test", 3, "Cannot parse: inject"},
{"/suites/suite-with-error-table-wrong-amount-of-columns-1.test", 5, "Amount of cells in a row is not the same in header"},
{"/suites/suite-with-error-table-wrong-amount-of-columns-2.test", 4, "Incorrect format. Should end with '|'"},
{"/suites/suite-with-error-table-wrong-amount-of-columns-3.test", 4, "Incorrect format. Should start with '|'"},
{"/suites/suite-with-error-parameterization-merge-tables.test", 12, "Cannot merge table \"table2\". Perhaps it has different amount of columns"},
{"/suites/suite-with-error-parameterization-wrong-amount-of-columns.test", 5, "Amount of cells in a row is not the same in header"},
{"/suites/suite-with-error-wrong-indentation-1.test", 8, "Incorrect indentation. Amount of spaces in indentation should be the same within one level"},
{"/suites/suite-with-error-wrong-indentation-2.test", 6, "Incorrect indentation. Should use from 1 to 8 spaces"}
};
}
}
|
apache-2.0
|
jivesoftware/upena
|
upena-deployable/src/main/java/com/jivesoftware/os/upena/deployable/region/RepoPluginRegion.java
|
8003
|
package com.jivesoftware.os.upena.deployable.region;
import com.google.common.collect.Maps;
import com.jivesoftware.os.mlogger.core.MetricLogger;
import com.jivesoftware.os.mlogger.core.MetricLoggerFactory;
import com.jivesoftware.os.upena.deployable.UpenaHealth;
import com.jivesoftware.os.upena.deployable.region.RepoPluginRegion.RepoPluginRegionInput;
import com.jivesoftware.os.upena.deployable.soy.SoyRenderer;
import com.jivesoftware.os.upena.service.UpenaStore;
import com.jivesoftware.os.upena.shared.PathToRepo;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.mutable.MutableLong;
import org.apache.logging.log4j.util.Strings;
import org.apache.shiro.SecurityUtils;
/**
*
*/
// soy.page.repoPluginRegion
public class RepoPluginRegion implements PageRegion<RepoPluginRegionInput> {
private static final MetricLogger LOG = MetricLoggerFactory.getLogger();
private final String template;
private final SoyRenderer renderer;
private final UpenaStore upenaStore;
private final PathToRepo localPathToRepo;
public RepoPluginRegion(String template,
SoyRenderer renderer,
UpenaStore upenaStore,
PathToRepo localPathToRepo) {
this.template = template;
this.renderer = renderer;
this.upenaStore = upenaStore;
this.localPathToRepo = localPathToRepo;
}
@Override
public String getRootPath() {
return "/ui/repo";
}
public static class RepoPluginRegionInput implements PluginInput {
final String groupIdFilter;
final String artifactIdFilter;
final String versionFilter;
String fileNameFilter;
final String action;
public RepoPluginRegionInput(String groupIdFilter, String artifactIdFilter, String versionFilter, String fileNameFilter, String action) {
this.groupIdFilter = groupIdFilter;
this.artifactIdFilter = artifactIdFilter;
this.versionFilter = versionFilter;
this.fileNameFilter = fileNameFilter;
this.action = action;
}
@Override
public String name() {
return "Repo";
}
}
@Override
public String render(String user, RepoPluginRegionInput input) {
SecurityUtils.getSubject().checkPermission("write");
Map<String, Object> data = Maps.newHashMap();
try {
File repoFile = localPathToRepo.get();
List<Map<String, Object>> repo = new ArrayList<>();
if (input.action != null) {
if (input.action.equals("remove") && input.fileNameFilter != null && input.fileNameFilter.length() > 0) {
SecurityUtils.getSubject().checkPermission("write");
File f = new File(repoFile, input.fileNameFilter);
if (f.exists()) {
FileUtils.forceDelete(f);
data.put("message", "Deleted " + f.getAbsolutePath());
} else {
data.put("message", "Doesn''t exists " + f.getAbsolutePath());
}
input.fileNameFilter = !Strings.isNotBlank(input.groupIdFilter)
|| !Strings.isNotBlank(input.artifactIdFilter)
|| !Strings.isNotBlank(input.versionFilter)
|| !Strings.isNotBlank(input.fileNameFilter) ? "filter" : "";
}
if (input.action.equals("filter")) {
MutableLong fileCount = new MutableLong();
if (repoFile.exists() && repoFile.isDirectory()) {
buildTree(input, repoFile, repoFile, repo, fileCount);
}
}
}
Map<String, String> filter = new HashMap<>();
filter.put("groupIdFilter", input.groupIdFilter);
filter.put("artifactIdFilter", input.artifactIdFilter);
filter.put("versionFilter", input.versionFilter);
filter.put("fileNameFilter", input.fileNameFilter);
data.put("filters", filter);
if (!repo.isEmpty()) {
data.put("repo", repo);
}
} catch (Exception e) {
LOG.error("Unable to retrieve data", e);
}
return renderer.render(template, data);
}
@Override
public String getTitle() {
return "Upena Repo";
}
public static void buildTree(RepoPluginRegionInput input, File root, File folder, List<Map<String, Object>> output, MutableLong fileCount) {
if (!folder.isDirectory()) {
throw new IllegalArgumentException("folder is not a Directory");
}
int indent = 0;
printDirectoryTree(input, root, folder, indent, output, fileCount);
}
private static void printDirectoryTree(RepoPluginRegionInput input,
File root,
File folder,
int indent,
List<Map<String, Object>> output,
MutableLong fileCount) {
if (!folder.isDirectory()) {
throw new IllegalArgumentException("folder is not a Directory");
}
output.add(fileToMap(root, folder, indent));
long currentFileCount = fileCount.longValue();
for (File file : folder.listFiles()) {
if (file.isDirectory()) {
printDirectoryTree(input, root, file, indent + 1, output, fileCount);
} else {
printFile(input, root, file, indent + 1, output, fileCount);
}
}
if (currentFileCount == fileCount.longValue()) {
output.remove(output.size() - 1);
}
}
private static void printFile(RepoPluginRegionInput input, File root, File file, int indent, List<Map<String, Object>> output, MutableLong fileCount) {
String relativePath = getRelativePath(root, file);
if (input.groupIdFilter != null && input.groupIdFilter.length() > 0) {
if (!relativePath.contains(input.groupIdFilter.replace(".", "/"))) {
return;
}
}
if (input.artifactIdFilter != null && input.artifactIdFilter.length() > 0) {
if (!relativePath.contains(input.artifactIdFilter.replace(".", "/"))) {
return;
}
}
if (input.versionFilter != null && input.versionFilter.length() > 0) {
if (!relativePath.contains(input.versionFilter)) {
return;
}
}
if (input.fileNameFilter != null && input.fileNameFilter.length() > 0) {
if (!file.getName().contains(input.fileNameFilter)) {
return;
}
}
fileCount.add(1);
output.add(fileToMap(root, file, indent));
}
private static String getIndentString(int indent) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < indent; i++) {
sb.append("| ");
}
return sb.toString();
}
private static Map<String, Object> fileToMap(File root, File file, int indent) {
boolean isDir = file.isDirectory();
Map<String, Object> map = new HashMap<>();
map.put("name", getIndentString(indent) + "+--" + file.getName() + ((isDir) ? "/" : ""));
map.put("path", getRelativePath(root, file));
map.put("lastModified", isDir ? "" : UpenaHealth.humanReadableUptime(System.currentTimeMillis() - file.lastModified()));
return map;
}
public static String getRelativePath(File root, File file) {
String home = root.getAbsolutePath();
String path = file.getAbsolutePath();
if (!path.startsWith(home)) {
return null;
}
if (path.length() > home.length()) {
return path.substring(home.length() + 1);
} else {
return null;
}
}
}
|
apache-2.0
|
GoogleCloudPlatform/getting-started-dotnet
|
Bookshelf/ViewModels/Books/Form.cs
|
1336
|
// Copyright(c) 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.
namespace Bookshelf.ViewModels.Books
{
public class Form
{
/// <summary>
/// The book to be displayed in the form.
/// </summary>
public Models.Book Book;
/// <summary>
/// The string displayed to the user. Either "Edit" or "Create".
/// </summary>
public string Action;
/// <summary>
/// False when the user tried entering a bad field value. For example, they entered
/// "yesterday" for Date Published.
/// </summary>
public bool IsValid;
/// <summary>
/// The target of submit form. Fills asp-action="".
/// </summary>
public string FormAction;
}
}
|
apache-2.0
|
groupe-sii/ogham
|
ogham-spring-boot-common-autoconfigure/src/main/java/fr/sii/ogham/spring/template/thymeleaf/ThymeleafRequestContextWrapper.java
|
1635
|
package fr.sii.ogham.spring.template.thymeleaf;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.support.RequestContext;
import org.thymeleaf.spring5.context.IThymeleafRequestContext;
/**
* This aim of this interface is to be able to handle different versions of
* Thymeleaf in a Spring context.
*
* In Thymeleaf v2, there is no need to wrap the {@link RequestContext} into a
* wrapper and register it as another variable in the model.
*
* In Thymeleaf v3, the {@link RequestContext} is wrapped into a
* {@link IThymeleafRequestContext} and registered as a variable in the model.
* Since Spring WebFlux, we also have to handle both Spring Web and Spring
* WebFlux.
*
*
* @author Aurélien Baudet
*
*/
public interface ThymeleafRequestContextWrapper {
/**
* Wrap the {@link RequestContext} and current Web context
* ({@link HttpServletRequest}, {@link HttpServletResponse} and
* {@link ServletContext}) into a new object and register it into the
* provided model.
*
* @param requestContext
* the request context
* @param request
* the current HTTP request
* @param response
* the current HTTP response
* @param servletContext
* the servlet execution context
* @param springModel
* the model to fill
*/
void wrapAndRegister(RequestContext requestContext, HttpServletRequest request, HttpServletResponse response, ServletContext servletContext, Map<String, Object> springModel);
}
|
apache-2.0
|
yunify/qingcloud-cli
|
qingcloud/cli/iaas_client/actions/vxnet/describe_vxnet_instances.py
|
2703
|
# =========================================================================
# Copyright 2012-present Yunify, Inc.
# -------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this work except in compliance with the License.
# You may obtain a copy of the License in the LICENSE file, or at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# =========================================================================
from qingcloud.cli.misc.utils import explode_array
from qingcloud.cli.iaas_client.actions.base import BaseAction
class DescribeVxnetInstancesAction(BaseAction):
action = 'DescribeVxnetInstances'
command = 'describe-vxnet-instances'
usage = '%(prog)s -v <vxnet_id> [-f <conf_file>]'
@classmethod
def add_ext_arguments(cls, parser):
parser.add_argument('-v', '--vxnet', dest='vxnet',
action='store', type=str, default='',
help='ID of vxnet whose instances you want to list.')
parser.add_argument('-m', '--image', dest='image',
action='store', type=str, default='',
help='filter by ID of image that instance based')
parser.add_argument('-i', '--instances', dest='instances',
action='store', type=str, default='',
help='filter by comma separated IDs of instances')
parser.add_argument('-t', '--instance_type', dest='instance_type',
action='store', type=str, default='',
help='filter by instance type')
parser.add_argument('-s', '--status', dest='status',
action='store', type=str, default='',
help='filter by instance status: pending, running, stopped, suspended, terminated, ceased')
@classmethod
def build_directive(cls, options):
if not options.vxnet:
print('[vxnet] should be provided')
return None
return {
'vxnet': options.vxnet,
'image': explode_array(options.image),
'instances': explode_array(options.instances),
'instance_type': explode_array(options.instance_type),
'status': explode_array(options.status),
'offset':options.offset,
'limit': options.limit,
}
|
apache-2.0
|
griffon/griffon
|
subprojects/griffon-core-api/src/main/java/griffon/core/events/WindowShownEvent.java
|
1573
|
/*
* SPDX-License-Identifier: Apache-2.0
*
* Copyright 2008-2022 the original author or 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 griffon.core.events;
import griffon.annotations.core.Nonnull;
import griffon.core.event.Event;
import static griffon.util.StringUtils.requireNonBlank;
import static java.util.Objects.requireNonNull;
/**
* @author Andres Almiray
* @since 3.0.0
*/
public class WindowShownEvent<W> extends Event {
private final String name;
private final W window;
public WindowShownEvent(@Nonnull String name, @Nonnull W window) {
this.name = requireNonBlank(name, "Argument 'name' must not be blank");
this.window = requireNonNull(window, "Argument 'window' must not be null");
}
@Nonnull
public W getWindow() {
return window;
}
@Nonnull
public String getName() {
return name;
}
@Nonnull
public static <W> WindowShownEvent of(@Nonnull String name, @Nonnull W window) {
return new WindowShownEvent<>(name, window);
}
}
|
apache-2.0
|
google/grr
|
grr/server/grr_response_server/check_lib/checks_test_lib_test.py
|
8405
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""Tests for checks_test_lib."""
from typing import IO
from typing import Iterator
from absl import app
from grr_response_core.lib import parsers
from grr_response_core.lib.rdfvalues import anomaly as rdf_anomaly
from grr_response_core.lib.rdfvalues import client as rdf_client
from grr_response_core.lib.rdfvalues import client_fs as rdf_client_fs
from grr_response_core.lib.rdfvalues import paths as rdf_paths
from grr_response_server.check_lib import checks
from grr_response_server.check_lib import checks_test_lib
from grr.test_lib import test_lib
class CheckHelperTests(checks_test_lib.HostCheckTest):
"""Tests for common Check Helper methods."""
def testAssertCheckUndetected(self):
"""Tests for the asertCheckUndetected() method."""
anomaly = {
"finding": ["Adware 2.1.1 is installed"],
"symptom": "Found: Malicious software.",
"type": "ANALYSIS_ANOMALY"
}
# Simple no anomaly case.
no_anomaly = {"SW-CHECK": checks.CheckResult(check_id="SW-CHECK")}
self.assertCheckUndetected("SW-CHECK", no_anomaly)
# The case were there is an anomaly in the results, just not the check
# we are looking for.
other_anomaly = {
"SW-CHECK":
checks.CheckResult(check_id="SW-CHECK"),
"OTHER":
checks.CheckResult(
check_id="OTHER", anomaly=[rdf_anomaly.Anomaly(**anomaly)])
}
self.assertCheckUndetected("SW-CHECK", other_anomaly)
# Check the simple failure case works.
has_anomaly = {
"SW-CHECK":
checks.CheckResult(
check_id="SW-CHECK", anomaly=[rdf_anomaly.Anomaly(**anomaly)])
}
self.assertRaises(AssertionError, self.assertCheckUndetected, "SW-CHECK",
has_anomaly)
def testAssertRanChecks(self):
"""Tests for the assertRanChecks() method."""
no_checks = {}
some_checks = {"EXISTS": checks.CheckResult(check_id="EXISTS")}
self.assertRanChecks(["EXISTS"], some_checks)
self.assertRaises(AssertionError, self.assertRanChecks, ["EXISTS"],
no_checks)
self.assertRaises(AssertionError, self.assertRanChecks, ["FOOBAR"],
some_checks)
def testAssertChecksNotRun(self):
"""Tests for the assertChecksNotRun() method."""
no_checks = {}
some_checks = {"EXISTS": checks.CheckResult(check_id="EXISTS")}
self.assertChecksNotRun(["FOOBAR"], no_checks)
self.assertChecksNotRun(["FOO", "BAR"], no_checks)
self.assertChecksNotRun(["FOOBAR"], some_checks)
self.assertChecksNotRun(["FOO", "BAR"], some_checks)
self.assertRaises(AssertionError, self.assertChecksNotRun, ["EXISTS"],
some_checks)
self.assertRaises(AssertionError, self.assertChecksNotRun,
["FOO", "EXISTS", "BAR"], some_checks)
def testAssertCheckDetectedAnom(self):
"""Tests for the assertCheckDetectedAnom() method."""
# Check we fail when our checkid isn't in the results.
no_checks = {}
self.assertRaises(
AssertionError,
self.assertCheckDetectedAnom,
"UNICORN",
no_checks,
sym=None,
findings=None)
# Check we fail when our checkid is in the results but hasn't
# produced an anomaly.
passing_checks = {"EXISTS": checks.CheckResult(check_id="EXISTS")}
self.assertRaises(
AssertionError,
self.assertCheckDetectedAnom,
"EXISTS",
passing_checks,
sym=None,
findings=None)
# On to a 'successful' cases.
anomaly = {
"finding": ["Finding"],
"symptom": "Found: An issue.",
"type": "ANALYSIS_ANOMALY"
}
failing_checks = {
"EXISTS":
checks.CheckResult(
check_id="EXISTS", anomaly=[rdf_anomaly.Anomaly(**anomaly)])
}
# Check we pass when our check produces an anomaly and we don't care
# about the details.
self.assertCheckDetectedAnom(
"EXISTS", failing_checks, sym=None, findings=None)
# When we do care only about the 'symptom'.
self.assertCheckDetectedAnom(
"EXISTS", failing_checks, sym="Found: An issue.", findings=None)
# And when we also care about the findings.
self.assertCheckDetectedAnom(
"EXISTS", failing_checks, sym="Found: An issue.", findings=["Finding"])
# And check we match substrings of a 'finding'.
self.assertCheckDetectedAnom(
"EXISTS", failing_checks, sym="Found: An issue.", findings=["Fin"])
# Check we complain when the symptom doesn't match.
self.assertRaises(
AssertionError,
self.assertCheckDetectedAnom,
"EXISTS",
failing_checks,
sym="wrong symptom",
findings=None)
# Check we complain when the symptom matches but the findings don't.
self.assertRaises(
AssertionError,
self.assertCheckDetectedAnom,
"EXISTS",
failing_checks,
sym="Found: An issue.",
findings=["Not found"])
# Lastly, if there is a finding in the anomaly we didn't expect, we consider
# that a problem.
self.assertRaises(
AssertionError,
self.assertCheckDetectedAnom,
"EXISTS",
failing_checks,
sym="Found: An issue.",
findings=[])
def testGenProcessData(self):
"""Test for the GenProcessData() method."""
# Trivial empty case.
art_name = "ListProcessesGrr"
context = "RAW"
result = self.GenProcessData([])
self.assertIn("KnowledgeBase", result)
self.assertIn(art_name, result)
self.assertDictEqual(self.SetArtifactData(), result[art_name])
# Now with data.
result = self.GenProcessData([("proc1", 1, ["/bin/foo"]),
("proc2", 2, ["/bin/bar"])])
self.assertEqual("proc1", result[art_name][context][0].name)
self.assertEqual(1, result[art_name][context][0].pid)
self.assertEqual(["/bin/foo"], result[art_name][context][0].cmdline)
self.assertEqual("proc2", result[art_name][context][1].name)
self.assertEqual(2, result[art_name][context][1].pid)
self.assertEqual(["/bin/bar"], result[art_name][context][1].cmdline)
def testGenFileData(self):
"""Test for the GenFileData() method."""
# Need a parser
self.assertRaises(ValueError, self.GenFileData, "EMPTY", [])
class VoidParser(parsers.SingleFileParser[None]):
def ParseFile(
self,
knowledge_base: rdf_client.KnowledgeBase,
pathspec: rdf_paths.PathSpec,
filedesc: IO[bytes],
) -> Iterator[None]:
del knowledge_base, pathspec, filedesc # Unused.
return iter([])
# Trivial empty case.
result = self.GenFileData("EMPTY", [], VoidParser())
self.assertIn("KnowledgeBase", result)
self.assertIn("EMPTY", result)
self.assertDictEqual(self.SetArtifactData(), result["EMPTY"])
# Now with data.
result = self.GenFileData("FILES", {
"/tmp/foo": """blah""",
"/tmp/bar": """meh"""
}, VoidParser())
self.assertIn("FILES", result)
# No parser information should be generated.
self.assertEqual([], result["FILES"]["PARSER"])
# Two stat entries under raw (stat entries should exist)
self.assertLen(result["FILES"]["RAW"], 2)
# Walk the result till we find the item we want.
# This is to avoid a flakey test.
statentry = None
for r in result["FILES"]["RAW"]:
if r.pathspec.path == "/tmp/bar":
statentry = r
self.assertIsInstance(statentry, rdf_client_fs.StatEntry)
self.assertEqual(33188, statentry.st_mode)
def testGenSysVInitData(self):
"""Test for the GenSysVInitData() method."""
# Trivial empty case.
result = self.GenSysVInitData([])
self.assertIn("KnowledgeBase", result)
self.assertIn("LinuxServices", result)
self.assertDictEqual(self.SetArtifactData(), result["LinuxServices"])
# Now with data.
result = self.GenSysVInitData(["/etc/rc2.d/S99testing"])
self.assertIn("LinuxServices", result)
self.assertLen(result["LinuxServices"]["PARSER"], 1)
result = result["LinuxServices"]["PARSER"][0]
self.assertEqual("testing", result.name)
self.assertEqual([2], result.start_on)
self.assertTrue(result.starts)
def main(argv):
# Run the full test suite
test_lib.main(argv)
if __name__ == "__main__":
app.run(main)
|
apache-2.0
|
ConclusionMC/puppetlabs-dsc
|
lib/puppet/type/dsc_xwaitforcluster.rb
|
3854
|
require 'pathname'
Puppet::Type.newtype(:dsc_xwaitforcluster) do
require Pathname.new(__FILE__).dirname + '../../' + 'puppet/type/base_dsc'
require Pathname.new(__FILE__).dirname + '../../puppet_x/puppetlabs/dsc_type_helpers'
@doc = %q{
The DSC xWaitForCluster resource type.
Automatically generated from
'xFailOverCluster/DSCResources/MSFT_xWaitForCluster/MSFT_xWaitForCluster.schema.mof'
To learn more about PowerShell Desired State Configuration, please
visit https://technet.microsoft.com/en-us/library/dn249912.aspx.
For more information about built-in DSC Resources, please visit
https://technet.microsoft.com/en-us/library/dn249921.aspx.
For more information about xDsc Resources, please visit
https://github.com/PowerShell/DscResources.
}
validate do
fail('dsc_name is a required attribute') if self[:dsc_name].nil?
end
def dscmeta_resource_friendly_name; 'xWaitForCluster' end
def dscmeta_resource_name; 'MSFT_xWaitForCluster' end
def dscmeta_module_name; 'xFailOverCluster' end
def dscmeta_module_version; '1.8.0.0' end
newparam(:name, :namevar => true ) do
end
ensurable do
newvalue(:exists?) { provider.exists? }
newvalue(:present) { provider.create }
defaultto { :present }
end
# Name: PsDscRunAsCredential
# Type: MSFT_Credential
# IsMandatory: False
# Values: None
newparam(:dsc_psdscrunascredential) do
def mof_type; 'MSFT_Credential' end
def mof_is_embedded?; true end
desc "PsDscRunAsCredential"
validate do |value|
unless value.kind_of?(Hash)
fail("Invalid value '#{value}'. Should be a hash")
end
PuppetX::Dsc::TypeHelpers.validate_MSFT_Credential("Credential", value)
end
end
# Name: Name
# Type: string
# IsMandatory: True
# Values: None
newparam(:dsc_name) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "Name - Name of the cluster to wait for."
isrequired
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: RetryIntervalSec
# Type: uint64
# IsMandatory: False
# Values: None
newparam(:dsc_retryintervalsec) do
def mof_type; 'uint64' end
def mof_is_embedded?; false end
desc "RetryIntervalSec - Interval to check for cluster existence. Default values is 10 seconds."
validate do |value|
unless (value.kind_of?(Numeric) && value >= 0) || (value.to_i.to_s == value && value.to_i >= 0)
fail("Invalid value #{value}. Should be a unsigned Integer")
end
end
munge do |value|
PuppetX::Dsc::TypeHelpers.munge_integer(value)
end
end
# Name: RetryCount
# Type: uint32
# IsMandatory: False
# Values: None
newparam(:dsc_retrycount) do
def mof_type; 'uint32' end
def mof_is_embedded?; false end
desc "RetryCount - Maximum number of retries to check for cluster existence. Default value is 50 retries."
validate do |value|
unless (value.kind_of?(Numeric) && value >= 0) || (value.to_i.to_s == value && value.to_i >= 0)
fail("Invalid value #{value}. Should be a unsigned Integer")
end
end
munge do |value|
PuppetX::Dsc::TypeHelpers.munge_integer(value)
end
end
def builddepends
pending_relations = super()
PuppetX::Dsc::TypeHelpers.ensure_reboot_relationship(self, pending_relations)
end
end
Puppet::Type.type(:dsc_xwaitforcluster).provide :powershell, :parent => Puppet::Type.type(:base_dsc).provider(:powershell) do
confine :true => (Gem::Version.new(Facter.value(:powershell_version)) >= Gem::Version.new('5.0.10240.16384'))
defaultfor :operatingsystem => :windows
mk_resource_methods
end
|
apache-2.0
|
GoogleCloudPlatform/cloud-foundation-toolkit
|
cli/report/cmd.go
|
3391
|
// Copyright 2019 Google LLC
//
// 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 report
import (
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var flags struct {
queryPath string
outputPath string
reportFormat string
bucketName string
dirName string
}
func init() {
viper.AutomaticEnv()
Cmd.Flags().StringVar(&flags.queryPath, "query-path", "", "Path to directory containing inventory queries")
Cmd.MarkFlagRequired("query-path")
Cmd.Flags().StringVar(&flags.outputPath, "output-path", "", "Path to directory to contain report outputs")
Cmd.MarkFlagRequired("output-path")
//Cmd.Flags().StringVar(&flags.bucketName, "bucket", "", "GCS bucket name for storing inventory (conflicts with --dir-path)")
Cmd.Flags().StringVar(&flags.dirName, "dir-path", "", "Local directory path for storing inventory ")
Cmd.MarkFlagRequired("dir-path")
Cmd.Flags().StringVar(&flags.reportFormat, "report-format", "", "Format of inventory report outputs, can be json or csv, default is csv")
viper.SetDefault("report-format", "csv")
viper.BindPFlag("report-format", Cmd.Flags().Lookup("report-format"))
Cmd.AddCommand(listCmd)
listCmd.Flags().StringVar(&flags.queryPath, "query-path", "", "Path to directory containing inventory queries")
listCmd.MarkFlagRequired("query-path")
}
// Cmd represents the base report command
var Cmd = &cobra.Command{
Use: "report",
Short: "Generate inventory reports based on CAI outputs in a directory.",
Long: `Generate inventory reports for resources in Cloud Asset Inventory (CAI) output files, with reports defined in rego (in '<path_to_cloud-foundation-toolkit>/reports/sample' folder).
Example:
cft report --query-path <path_to_cloud-foundation-toolkit>/reports/sample \
--dir-path <path-to-directory-containing-cai-export> \
--report-path <path-to-directory-for-report-output>
`,
Args: cobra.NoArgs,
/*
PreRunE: func(c *cobra.Command, args []string) error {
if (flags.bucketName == "" && flags.dirName == "") ||
(flags.bucketName != "" && flags.dirName != "") {
return errors.New("Either bucket or dir-path should be set")
}
return nil
},
*/
RunE: func(cmd *cobra.Command, args []string) error {
err := GenerateReports(flags.dirName, flags.queryPath, flags.outputPath, viper.GetString("report-format"))
if err != nil {
return err
}
return nil
},
}
var listCmd = &cobra.Command{
Use: "list-available-reports",
Short: "List available inventory report queries.",
Long: `List available inventory report queries for resources in Cloud Asset Inventory (CAI).
Example:
cft report list-available-reports --query-path <path_to_cloud-foundation-toolkit>/reports/sample
`,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
err := ListAvailableReports(flags.queryPath)
if err != nil {
return err
}
return nil
},
}
|
apache-2.0
|
mediascape/named-websocket-proxy
|
background/src/proxy.js
|
652
|
var debug = require('./debug')('Proxy');
var Channel = require('./channel');
Proxy = {
close: function (proxy, proxies, localPeers, remotePeers) {
// Find all remote peers using this channel
var remotes = _.filter(remotePeers, { ip: proxy.ip });
// Disconnect local peers
_.forEach(remotes, function (r) {
var locals = Channel.peers({ name: r.channel }, localPeers);
Channel.disconnectPeers(r, locals);
_.remove(remotePeers, { id: r.id });
});
// Remove proxy
_.remove(proxies, { ip: proxy.ip });
return {
proxies: proxies,
remotes: remotePeers
};
}
}
module.exports = Proxy;
|
apache-2.0
|
ruspl-afed/dbeaver
|
plugins/org.jkiss.dbeaver.ext.postgresql/src/org/jkiss/dbeaver/ext/postgresql/model/PostgreOperatorClass.java
|
3761
|
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2017 Serge Rider (serge@jkiss.org)
*
* 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.jkiss.dbeaver.ext.postgresql.model;
import org.jkiss.code.NotNull;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.ext.postgresql.PostgreUtils;
import org.jkiss.dbeaver.model.impl.jdbc.JDBCUtils;
import org.jkiss.dbeaver.model.meta.Property;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* PostgreOperatorClass
*/
public class PostgreOperatorClass extends PostgreInformation {
private long oid;
private PostgreAccessMethod accessMethod;
private String name;
private long namespaceId;
private long ownerId;
private long familyId;
private long typeId;
private boolean isDefault;
private long keyTypeId;
public PostgreOperatorClass(PostgreAccessMethod accessMethod, ResultSet dbResult)
throws SQLException
{
super(accessMethod.getDatabase());
this.accessMethod = accessMethod;
this.loadInfo(dbResult);
}
private void loadInfo(ResultSet dbResult)
throws SQLException
{
this.oid = JDBCUtils.safeGetLong(dbResult, "oid");
this.name = JDBCUtils.safeGetString(dbResult, "opcname");
this.namespaceId = JDBCUtils.safeGetLong(dbResult, "opcnamespace");
this.ownerId = JDBCUtils.safeGetLong(dbResult, "opcowner");
this.familyId = JDBCUtils.safeGetLong(dbResult, "opcfamily");
this.typeId = JDBCUtils.safeGetLong(dbResult, "opcintype");
this.isDefault = JDBCUtils.safeGetBoolean(dbResult, "opcdefault");
this.keyTypeId = JDBCUtils.safeGetLong(dbResult, "opckeytype");
}
@NotNull
@Override
@Property(viewable = true, order = 1)
public String getName()
{
return name;
}
@Property(viewable = true, order = 2)
@Override
public long getObjectId() {
return oid;
}
@Property(viewable = true, order = 3)
public PostgreSchema getNamespace(DBRProgressMonitor monitor) throws DBException {
return accessMethod.getDatabase().getSchema(monitor, namespaceId);
}
@Property(viewable = true, order = 4)
public PostgreRole getOwner(DBRProgressMonitor monitor) throws DBException {
return PostgreUtils.getObjectById(monitor, accessMethod.getDatabase().roleCache, accessMethod.getDatabase(), ownerId);
}
@Property(viewable = true, order = 5)
public PostgreOperatorFamily getFamily(DBRProgressMonitor monitor) throws DBException {
return accessMethod.getOperatorFamily(monitor, familyId);
}
@Property(viewable = true, order = 6)
public PostgreDataType getType(DBRProgressMonitor monitor) {
return accessMethod.getDatabase().getDataType(typeId);
}
@Property(viewable = true, order = 7)
public boolean isDefault() {
return isDefault;
}
@Property(viewable = true, order = 8)
public PostgreDataType getKeyType(DBRProgressMonitor monitor) {
if (keyTypeId == 0) {
return getType(monitor);
}
return accessMethod.getDatabase().getDataType(keyTypeId);
}
}
|
apache-2.0
|
opetrovski/development
|
oscm-portal-unittests/javasrc/org/oscm/ui/model/MarketplaceTest.java
|
8559
|
/*******************************************************************************
* Copyright FUJITSU LIMITED 2017
*******************************************************************************/
package org.oscm.ui.model;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.math.BigDecimal;
import org.junit.Test;
import org.oscm.internal.pricing.PORevenueShare;
public class MarketplaceTest {
@Test
public void assignedOrgChanged_negative() {
Marketplace m = new Marketplace();
m.setOwningOrganizationId("owningOrganizationId");
m.setOriginalOrgId(m.getOwningOrganizationId());
assertFalse(m.assignedOrgChanged());
}
@Test
public void assignedOrgChanged_null() {
Marketplace m = new Marketplace();
m.setOwningOrganizationId(null);
m.setOriginalOrgId(null);
assertFalse(m.assignedOrgChanged());
}
@Test
public void assignedOrgChanged() {
Marketplace m = new Marketplace();
m.setOwningOrganizationId("owningOrganizationId");
m.setOriginalOrgId("originalOrgId");
assertTrue(m.assignedOrgChanged());
}
@Test
public void assignedOrgChanged_emptt() {
Marketplace m = new Marketplace();
m.setOwningOrganizationId(" ");
m.setOriginalOrgId(null);
assertFalse(m.assignedOrgChanged());
}
@Test
public void getMarketplaceRevenueShare() {
Marketplace m = new Marketplace();
assertNull(m.getMarketplaceRevenueShare());
}
@Test
public void setMarketplaceRevenueShare() {
Marketplace m = new Marketplace();
m.setMarketplaceRevenueShare(BigDecimal.TEN);
assertEquals(BigDecimal.TEN, m.getMarketplaceRevenueShare());
}
@Test
public void setMarketplaceRevenueShare_Null() {
Marketplace m = new Marketplace();
m.setMarketplaceRevenueShare(null);
assertNull(m.getMarketplaceRevenueShare());
}
@Test
public void setMarketplaceRevenueShare_NotNull() {
Marketplace m = new Marketplace();
m.setMarketplaceRevenueShare(BigDecimal.TEN);
assertEquals(BigDecimal.TEN, m.getMarketplaceRevenueShare());
}
@Test
public void setMarketplaceRevenueShareObject_Null() {
Marketplace m = new Marketplace();
m.setMarketplaceRevenueShareObject(null);
assertNull(m.getMarketplaceRevenueShareObject());
assertNull(m.getMarketplaceRevenueShare());
}
@Test
public void getResellerRevenueShare() {
Marketplace m = new Marketplace();
assertNull(m.getResellerRevenueShare());
}
@Test
public void setResellerRevenueShare() {
Marketplace m = new Marketplace();
m.setResellerRevenueShare(BigDecimal.TEN);
assertEquals(BigDecimal.TEN, m.getResellerRevenueShare());
}
@Test
public void setResellerRevenueShare_Null() {
Marketplace m = new Marketplace();
m.setResellerRevenueShare(null);
assertNull(m.getResellerRevenueShare());
}
@Test
public void setResellerRevenueShare_NotNull() {
Marketplace m = new Marketplace();
m.setResellerRevenueShare(BigDecimal.TEN);
assertEquals(BigDecimal.TEN, m.getResellerRevenueShare());
}
@Test
public void setResellerRevenueShareObject_Null() {
Marketplace m = new Marketplace();
m.setResellerRevenueShareObject(null);
assertNull(m.getResellerRevenueShareObject());
assertNull(m.getResellerRevenueShare());
}
@Test
public void getBrokerRevenueShare() {
Marketplace m = new Marketplace();
assertNull(m.getBrokerRevenueShare());
}
@Test
public void setBrokerRevenueShare() {
Marketplace m = new Marketplace();
m.setBrokerRevenueShare(BigDecimal.TEN);
assertEquals(BigDecimal.TEN, m.getBrokerRevenueShare());
}
@Test
public void setBrokerRevenueShare_Null() {
Marketplace m = new Marketplace();
m.setBrokerRevenueShare(null);
assertNull(m.getBrokerRevenueShare());
}
@Test
public void setBrokerRevenueShare_NotNull() {
Marketplace m = new Marketplace();
m.setBrokerRevenueShare(BigDecimal.TEN);
assertEquals(BigDecimal.TEN, m.getBrokerRevenueShare());
}
@Test
public void setBrokerRevenueShareObject_Null() {
Marketplace m = new Marketplace();
m.setBrokerRevenueShareObject(null);
assertNull(m.getBrokerRevenueShareObject());
assertNull(m.getBrokerRevenueShare());
}
@Test
public void setRevenueSharesReadOnly_true() {
Marketplace m = new Marketplace();
m.setRevenueSharesReadOnly(true);
assertTrue(m.isRevenueSharesReadOnly());
}
@Test
public void setRevenueSharesReadOnly_false() {
Marketplace m = new Marketplace();
m.setRevenueSharesReadOnly(false);
assertFalse(m.isRevenueSharesReadOnly());
}
@Test
public void isMarketplaceRevenueSharePercentVisible() {
Marketplace m = new Marketplace();
m.setRevenueSharesReadOnly(true);
m.setMarketplaceRevenueShareObject(new PORevenueShare());
assertTrue(m.isMarketplaceRevenueShareVisible());
}
@Test
public void isMarketplaceRevenueSharePercentVisible_notReadonly() {
Marketplace m = new Marketplace();
m.setRevenueSharesReadOnly(false);
m.setMarketplaceRevenueShareObject(new PORevenueShare());
assertFalse(m.isMarketplaceRevenueShareVisible());
}
@Test
public void isMarketplaceRevenueSharePercentVisible_noRevenueShare() {
Marketplace m = new Marketplace();
m.setRevenueSharesReadOnly(true);
m.setMarketplaceRevenueShareObject(null);
assertFalse(m.isMarketplaceRevenueShareVisible());
}
@Test
public void isMarketplaceRevenueSharePercentVisible_notReadonly_noRevenueShare() {
Marketplace m = new Marketplace();
m.setRevenueSharesReadOnly(true);
m.setMarketplaceRevenueShareObject(null);
assertFalse(m.isMarketplaceRevenueShareVisible());
}
@Test
public void isResellerRevenueSharePercentVisible() {
Marketplace m = new Marketplace();
m.setRevenueSharesReadOnly(true);
m.setResellerRevenueShareObject(new PORevenueShare());
assertTrue(m.isResellerRevenueShareVisible());
}
@Test
public void isResellerRevenueSharePercentVisible_notReadonly() {
Marketplace m = new Marketplace();
m.setRevenueSharesReadOnly(false);
m.setResellerRevenueShareObject(new PORevenueShare());
assertFalse(m.isResellerRevenueShareVisible());
}
@Test
public void isResellerRevenueSharePercentVisible_noRevenueShare() {
Marketplace m = new Marketplace();
m.setRevenueSharesReadOnly(true);
m.setResellerRevenueShareObject(null);
assertFalse(m.isResellerRevenueShareVisible());
}
@Test
public void isResellerRevenueSharePercentVisible_notReadonly_noRevenueShare() {
Marketplace m = new Marketplace();
m.setRevenueSharesReadOnly(true);
m.setResellerRevenueShareObject(null);
assertFalse(m.isResellerRevenueShareVisible());
}
@Test
public void isBrokerRevenueSharePercentVisible() {
Marketplace m = new Marketplace();
m.setRevenueSharesReadOnly(true);
m.setBrokerRevenueShareObject(new PORevenueShare());
assertTrue(m.isBrokerRevenueShareVisible());
}
@Test
public void isBrokerRevenueSharePercentVisible_notReadonly() {
Marketplace m = new Marketplace();
m.setRevenueSharesReadOnly(false);
m.setBrokerRevenueShareObject(new PORevenueShare());
assertFalse(m.isBrokerRevenueShareVisible());
}
@Test
public void isBrokerRevenueSharePercentVisible_noRevenueShare() {
Marketplace m = new Marketplace();
m.setRevenueSharesReadOnly(true);
m.setBrokerRevenueShareObject(null);
assertFalse(m.isBrokerRevenueShareVisible());
}
@Test
public void isBrokerRevenueSharePercentVisible_notReadonly_noRevenueShare() {
Marketplace m = new Marketplace();
m.setRevenueSharesReadOnly(true);
m.setBrokerRevenueShareObject(null);
assertFalse(m.isBrokerRevenueShareVisible());
}
}
|
apache-2.0
|
spotify/annoy
|
test/holes_test.py
|
2095
|
# Copyright (c) 2013 Spotify AB
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
import numpy
import random
from common import TestCase
from annoy import AnnoyIndex
class HolesTest(TestCase):
def test_random_holes(self):
f = 10
index = AnnoyIndex(f, 'angular')
valid_indices = random.sample(range(2000), 1000) # leave holes
for i in valid_indices:
v = numpy.random.normal(size=(f,))
index.add_item(i, v)
index.build(10)
for i in valid_indices:
js = index.get_nns_by_item(i, 10000)
for j in js:
self.assertTrue(j in valid_indices)
for i in range(1000):
v = numpy.random.normal(size=(f,))
js = index.get_nns_by_vector(v, 10000)
for j in js:
self.assertTrue(j in valid_indices)
def _test_holes_base(self, n, f=100, base_i=100000):
annoy = AnnoyIndex(f, 'angular')
for i in range(n):
annoy.add_item(base_i + i, numpy.random.normal(size=(f,)))
annoy.build(100)
res = annoy.get_nns_by_item(base_i, n)
self.assertEqual(set(res), set([base_i + i for i in range(n)]))
def test_root_one_child(self):
# See https://github.com/spotify/annoy/issues/223
self._test_holes_base(1)
def test_root_two_children(self):
self._test_holes_base(2)
def test_root_some_children(self):
# See https://github.com/spotify/annoy/issues/295
self._test_holes_base(10)
def test_root_many_children(self):
self._test_holes_base(1000)
|
apache-2.0
|
gaxnys/pixflaw_redux
|
src/components/Player.js
|
2908
|
import { Component } from './index'
import constants from '../constants'
class Player extends Component {
shouldCanvasUpdate(previousValue, currentValue) {
if(previousValue === undefined) {
return true
}
return this.updateCanvas = (
previousValue.player.posAngle !== currentValue.player.posAngle ||
previousValue.player.posR !== currentValue.player.posR
)
}
shouldPositionUpdate(previousValue, currentValue) {
if(previousValue === undefined) {
return true
}
return this.updatePosition = (
previousValue.player.posAngle !== currentValue.player.posAngle ||
previousValue.player.posR !== currentValue.player.posR ||
previousValue.player.cameraAngle !== currentValue.player.cameraAngle ||
previousValue.player.cameraR !== currentValue.player.cameraR
)
}
render() {
const state = this.getState()
if(this.updateCanvas) {
this.context.fillStyle = "#007DFF"
const canvas = this.context.canvas
this.context.clearRect(0, 0, canvas.width, canvas.height)
this.context.save()
this.context.translate(
constants.PLAYER_WIDTH * 2,
constants.PLAYER_HEIGHT * 2
)
this.context.rotate(state.player.posAngle)
this.context.fillRect(
- constants.PLAYER_HEIGHT / 2,
- constants.PLAYER_WIDTH / 2,
constants.PLAYER_HEIGHT,
constants.PLAYER_WIDTH
)
this.context.restore()
}
return {
canvas: this.context.canvas,
angle: state.player.posAngle,
r: state.player.posR,
offsetX: constants.PLAYER_WIDTH * 2,
offsetY: constants.PLAYER_HEIGHT * 2
}
}
renderToContext(context, state, scale) {
const wins = state.level.wins
context.save()
context.fillStyle = "#007DFF"
context.rotate(state.player.posAngle)
context.translate(state.player.posR * scale, 0)
context.fillRect(
- constants.PLAYER_HEIGHT / 2 * scale,
- constants.PLAYER_WIDTH / 2 * scale,
constants.PLAYER_HEIGHT * scale,
constants.PLAYER_WIDTH * scale
)
context.fillStyle = "#FFFFFF"
for(var i = 0; i < wins; i++) {
var y = Math.floor(i / 2 + 1)
var x = Math.floor(i % 2 + 1)
context.fillRect(
- (constants.PLAYER_HEIGHT / 2 - constants.PLAYER_HEIGHT / 4 * y + 2) * scale,
- (constants.PLAYER_WIDTH / 2 - constants.PLAYER_WIDTH / 3 * x + 2) * scale,
4 * scale,
4 * scale
)
}
context.restore()
}
}
export default Player
|
apache-2.0
|
rocknamx8/rocknamx8.github.io
|
node_modules/urllib/lib/urllib.js
|
30798
|
'use strict';
var debug = require('debug')('urllib');
var http = require('http');
var https = require('https');
var urlutil = require('url');
var util = require('util');
var qs = require('querystring');
var zlib = require('zlib');
var ua = require('default-user-agent');
var digestAuthHeader = require('digest-header');
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var ms = require('humanize-ms');
var statuses = require('statuses');
var contentTypeParser = require('content-type');
var _Promise;
var _iconv;
var pkg = require('../package.json');
var USER_AGENT = exports.USER_AGENT = ua('node-urllib', pkg.version);
// change Agent.maxSockets to 1000
exports.agent = new http.Agent();
exports.agent.maxSockets = 1000;
exports.httpsAgent = new https.Agent();
exports.httpsAgent.maxSockets = 1000;
/**
* The default request timeout(in milliseconds).
* @type {Number}
* @const
*/
exports.TIMEOUT = ms('5s');
exports.TIMEOUTS = [ms('5s'), ms('5s')];
var REQUEST_ID = 0;
var MAX_VALUE = Math.pow(2, 31) - 10;
var isOldVersionNode = /^v0\.10\.\d+$/.test(process.version);
/**
* support data types
* will auto decode response body
* @type {Array}
*/
var TEXT_DATA_TYPES = [
'json',
'text'
];
var PROTO_RE = /^https?:\/\//i;
/**
* Handle all http request, both http and https support well.
*
* @example
*
* // GET http://httptest.cnodejs.net
* urllib.request('http://httptest.cnodejs.net/test/get', function(err, data, res) {});
* // POST http://httptest.cnodejs.net
* var args = { type: 'post', data: { foo: 'bar' } };
* urllib.request('http://httptest.cnodejs.net/test/post', args, function(err, data, res) {});
*
* @param {String|Object} url
* @param {Object} [args], optional
* - {Object} [data]: request data, will auto be query stringify.
* - {String|Buffer} [content]: optional, if set content, `data` will ignore.
* - {ReadStream} [stream]: read stream to sent.
* - {WriteStream} [writeStream]: writable stream to save response data.
* If you use this, callback's data should be null.
* We will just `pipe(ws, {end: true})`.
* - {consumeWriteStream} [true]: consume the writeStream, invoke the callback after writeStream close.
* - {String} [method]: optional, could be GET | POST | DELETE | PUT, default is GET
* - {String} [contentType]: optional, request data type, could be `json`, default is undefined
* - {String} [dataType]: optional, response data type, could be `text` or `json`, default is buffer
* - {Boolean} [fixJSONCtlChars]: optional, fix the control characters (U+0000 through U+001F)
* before JSON parse response. Default is `false`
* - {Object} [headers]: optional, request headers
* - {Number|Array} [timeout]: request timeout(in milliseconds), default is `exports.TIMEOUTS containing connect timeout and response timeout`
* - {Agent} [agent]: optional, http agent. Set `false` if you does not use agent.
* - {Agent} [httpsAgent]: optional, https agent. Set `false` if you does not use agent.
* - {String} [auth]: Basic authentication i.e. 'user:password' to compute an Authorization header.
* - {String} [digestAuth]: Digest authentication i.e. 'user:password' to compute an Authorization header.
* - {String|Buffer|Array} [ca]: An array of strings or Buffers of trusted certificates.
* If this is omitted several well known "root" CAs will be used, like VeriSign.
* These are used to authorize connections.
* Notes: This is necessary only if the server uses the self-signed certificate
* - {Boolean} [rejectUnauthorized]: If true, the server certificate is verified against the list of supplied CAs.
* An 'error' event is emitted if verification fails. Default: true.
* - {String|Buffer} [pfx]: A string or Buffer containing the private key,
* certificate and CA certs of the server in PFX or PKCS12 format.
* - {String|Buffer} [key]: A string or Buffer containing the private key of the client in PEM format.
* Notes: This is necessary only if using the client certificate authentication
* - {String|Buffer} [cert]: A string or Buffer containing the certificate key of the client in PEM format.
* Notes: This is necessary only if using the client certificate authentication
* - {String} [passphrase]: A string of passphrase for the private key or pfx.
* - {String} [ciphers]: A string describing the ciphers to use or exclude.
* - {String} [secureProtocol]: The SSL method to use, e.g. SSLv3_method to force SSL version 3.
* The possible values depend on your installation of OpenSSL and are defined in the constant SSL_METHODS.
* - {Boolean} [followRedirect]: Follow HTTP 3xx responses as redirects. defaults to false.
* - {Number} [maxRedirects]: The maximum number of redirects to follow, defaults to 10.
* - {Function(from, to)} [formatRedirectUrl]: Format the redirect url by your self. Default is `url.resolve(from, to)`
* - {Function(options)} [beforeRequest]: Before request hook, you can change every thing here.
* - {Boolean} [streaming]: let you get the res object when request connected, default is `false`. alias `customResponse`
* - {Boolean} [gzip]: Accept gzip response content and auto decode it, default is `false`.
* - {Boolean} [timing]: Enable timing or not, default is `false`.
* - {Function} [lookup]: Custom DNS lookup function, default is `dns.lookup`.
* Require node >= 4.0.0 and only work on `http` protocol.
* @param {Function} [callback], callback(error, data, res). If missing callback, will return a promise object.
* @return {HttpRequest} req object.
* @api public
*/
exports.request = function request(url, args, callback) {
// request(url, callback)
if (arguments.length === 2 && typeof args === 'function') {
callback = args;
args = null;
}
if (typeof callback === 'function') {
return exports.requestWithCallback(url, args, callback);
}
// Promise
if (!_Promise) {
_Promise = require('any-promise');
}
return new _Promise(function (resolve, reject) {
exports.requestWithCallback(url, args, makeCallback(resolve, reject));
});
};
// alias to curl
exports.curl = exports.request;
function makeCallback(resolve, reject) {
return function (err, data, res) {
if (err) {
return reject(err);
}
resolve({
data: data,
status: res.statusCode,
headers: res.headers,
res: res
});
};
}
// yield urllib.requestThunk(url, args)
exports.requestThunk = function requestThunk(url, args) {
return function (callback) {
exports.requestWithCallback(url, args, function (err, data, res) {
if (err) {
return callback(err);
}
callback(null, {
data: data,
status: res.statusCode,
headers: res.headers,
res: res
});
});
};
};
exports.requestWithCallback = function requestWithCallback(url, args, callback) {
// requestWithCallback(url, callback)
if (!url || (typeof url !== 'string' && typeof url !== 'object')) {
var msg = util.format('expect request url to be a string or a http request options, but got %j', url);
throw new Error(msg);
}
if (arguments.length === 2 && typeof args === 'function') {
callback = args;
args = null;
}
args = args || {};
if (REQUEST_ID >= MAX_VALUE) {
REQUEST_ID = 0;
}
var reqId = ++REQUEST_ID;
args.requestUrls = args.requestUrls || [];
if (args.emitter) {
args.emitter.emit('request', {
requestId: reqId,
url: url,
args: args,
ctx: args.ctx,
});
}
args.timeout = args.timeout || exports.TIMEOUTS;
args.maxRedirects = args.maxRedirects || 10;
args.streaming = args.streaming || args.customResponse;
var requestStartTime = Date.now();
var parsedUrl;
if (typeof url === 'string') {
if (!PROTO_RE.test(url)) {
// Support `request('www.server.com')`
url = 'http://' + url;
}
parsedUrl = urlutil.parse(url);
} else {
parsedUrl = url;
}
var method = (args.type || args.method || parsedUrl.method || 'GET').toUpperCase();
var port = parsedUrl.port || 80;
var httplib = http;
var agent = getAgent(args.agent, exports.agent);
var fixJSONCtlChars = !!args.fixJSONCtlChars;
if (parsedUrl.protocol === 'https:') {
httplib = https;
agent = getAgent(args.httpsAgent, exports.httpsAgent);
if (!parsedUrl.port) {
port = 443;
}
}
var options = {
host: parsedUrl.hostname || parsedUrl.host || 'localhost',
path: parsedUrl.path || '/',
method: method,
port: port,
agent: agent,
headers: args.headers || {},
// default is dns.lookup
// https://github.com/nodejs/node/blob/master/lib/net.js#L986
// custom dnslookup require node >= 4.0.0
// https://github.com/nodejs/node/blob/archived-io.js-v0.12/lib/net.js#L952
lookup: args.lookup,
};
var sslNames = [
'pfx',
'key',
'passphrase',
'cert',
'ca',
'ciphers',
'rejectUnauthorized',
'secureProtocol',
'secureOptions',
];
for (var i = 0; i < sslNames.length; i++) {
var name = sslNames[i];
if (args.hasOwnProperty(name)) {
options[name] = args[name];
}
}
// don't check ssl
if (options.rejectUnauthorized === false && !options.hasOwnProperty('secureOptions')) {
options.secureOptions = require('constants').SSL_OP_NO_TLSv1_2;
}
var auth = args.auth || parsedUrl.auth;
if (auth) {
options.auth = auth;
}
var body = args.content || args.data;
var isReadAction = method === 'GET' || method === 'HEAD';
if (!args.content) {
if (body && !(typeof body === 'string' || Buffer.isBuffer(body))) {
if (isReadAction) {
// read: GET, HEAD, use query string
body = qs.stringify(body);
} else {
var contentType = options.headers['Content-Type'] || options.headers['content-type'];
// auto add application/x-www-form-urlencoded when using urlencode form request
if (!contentType) {
if (args.contentType === 'json') {
contentType = 'application/json';
} else {
contentType = 'application/x-www-form-urlencoded';
}
options.headers['Content-Type'] = contentType;
}
if (parseContentType(contentType).type === 'application/json') {
body = JSON.stringify(body);
} else {
// 'application/x-www-form-urlencoded'
body = qs.stringify(body);
}
}
}
}
// if it's a GET or HEAD request, data should be sent as query string
if (isReadAction && body) {
options.path += (parsedUrl.query ? '&' : '?') + body;
body = null;
}
var requestSize = 0;
if (body) {
var length = body.length;
if (!Buffer.isBuffer(body)) {
length = Buffer.byteLength(body);
}
requestSize = options.headers['Content-Length'] = length;
}
if (args.dataType === 'json') {
options.headers.Accept = 'application/json';
}
if (typeof args.beforeRequest === 'function') {
// you can use this hook to change every thing.
args.beforeRequest(options);
}
var connectTimer = null;
var responseTimer = null;
var __err = null;
var connected = false; // socket connected or not
var keepAliveSocket = false; // request with keepalive socket
var responseSize = 0;
var statusCode = -1;
var responseAborted = false;
var remoteAddress = '';
var remotePort = '';
var timing = null;
if (args.timing) {
timing = {
// socket assigned
queuing: 0,
// dns lookup time
dnslookup: 0,
// socket connected
connected: 0,
// request sent
requestSent: 0,
// Time to first byte (TTFB)
waiting: 0,
contentDownload: 0,
};
}
function cancelConnectTimer() {
if (connectTimer) {
clearTimeout(connectTimer);
connectTimer = null;
}
}
function cancelResponseTimer() {
if (responseTimer) {
clearTimeout(responseTimer);
responseTimer = null;
}
}
function done(err, data, res) {
cancelResponseTimer();
if (!callback) {
console.warn('[urllib:warn] [%s] [worker:%s] %s %s callback twice!!!',
Date(), process.pid, options.method, url);
// https://github.com/node-modules/urllib/pull/30
if (err) {
console.warn('[urllib:warn] [%s] [worker:%s] %s: %s\nstack: %s',
Date(), process.pid, err.name, err.message, err.stack);
}
return;
}
var cb = callback;
callback = null;
var headers = {};
if (res) {
statusCode = res.statusCode;
headers = res.headers;
}
// handle digest auth
if (statusCode === 401 && headers['www-authenticate']
&& (!args.headers || !args.headers.Authorization) && args.digestAuth) {
var authenticate = headers['www-authenticate'];
if (authenticate.indexOf('Digest ') >= 0) {
debug('Request#%d %s: got digest auth header WWW-Authenticate: %s', reqId, url, authenticate);
args.headers = args.headers || {};
args.headers.Authorization = digestAuthHeader(options.method, options.path, authenticate, args.digestAuth);
debug('Request#%d %s: auth with digest header: %s', reqId, url, args.headers.Authorization);
if (res.headers['set-cookie']) {
args.headers.Cookie = res.headers['set-cookie'].join(';');
}
return exports.requestWithCallback(url, args, cb);
}
}
var requestUseTime = Date.now() - requestStartTime;
if (timing) {
timing.contentDownload = requestUseTime;
}
debug('[%sms] done, %s bytes HTTP %s %s %s %s, keepAliveSocket: %s, timing: %j',
requestUseTime, responseSize, statusCode, options.method, options.host, options.path,
keepAliveSocket, timing);
var response = {
status: statusCode,
statusCode: statusCode,
headers: headers,
size: responseSize,
aborted: responseAborted,
rt: requestUseTime,
keepAliveSocket: keepAliveSocket,
data: data,
requestUrls: args.requestUrls,
timing: timing,
remoteAddress: remoteAddress,
remotePort: remotePort,
};
if (err) {
var agentStatus = '';
if (agent && typeof agent.getCurrentStatus === 'function') {
// add current agent status to error message for logging and debug
agentStatus = ', agent status: ' + JSON.stringify(agent.getCurrentStatus());
}
err.message += ', ' + options.method + ' ' + url + ' ' + statusCode
+ ' (connected: ' + connected + ', keepalive socket: ' + keepAliveSocket + agentStatus + ')'
+ '\nheaders: ' + JSON.stringify(headers);
err.data = data;
err.path = options.path;
err.status = statusCode;
err.headers = headers;
err.res = response;
}
cb(err, data, args.streaming ? res : response);
if (args.emitter) {
args.emitter.emit('response', {
requestId: reqId,
error: err,
ctx: args.ctx,
req: {
url: url,
socket: req && req.connection,
options: options,
size: requestSize,
},
res: response
});
}
}
function handleRedirect(res) {
var err = null;
if (args.followRedirect && statuses.redirect[res.statusCode]) { // handle redirect
args._followRedirectCount = (args._followRedirectCount || 0) + 1;
var location = res.headers.location;
if (!location) {
err = new Error('Got statusCode ' + res.statusCode + ' but cannot resolve next location from headers');
err.name = 'FollowRedirectError';
} else if (args._followRedirectCount > args.maxRedirects) {
err = new Error('Exceeded maxRedirects. Probably stuck in a redirect loop ' + url);
err.name = 'MaxRedirectError';
} else {
var newUrl = args.formatRedirectUrl ? args.formatRedirectUrl(url, location) : urlutil.resolve(url, location);
debug('Request#%d %s: `redirected` from %s to %s', reqId, options.path, url, newUrl);
// make sure timer stop
cancelResponseTimer();
// should clean up headers.Host on `location: http://other-domain/url`
if (args.headers && args.headers.Host && PROTO_RE.test(location)) {
args.headers.Host = null;
}
// avoid done will be execute in the future change.
var cb = callback;
callback = null;
exports.requestWithCallback(newUrl, args, cb);
return {
redirect: true,
error: null
};
}
}
return {
redirect: false,
error: err
};
}
// set user-agent
if (!options.headers['User-Agent'] && !options.headers['user-agent']) {
options.headers['User-Agent'] = USER_AGENT;
}
if (args.gzip) {
if (!options.headers['Accept-Encoding'] && !options.headers['accept-encoding']) {
options.headers['Accept-Encoding'] = 'gzip';
}
}
function decodeContent(res, body, cb) {
var encoding = res.headers['content-encoding'];
if (body.length === 0) {
return cb(null, body, encoding);
}
if (!encoding || encoding.toLowerCase() !== 'gzip') {
return cb(null, body, encoding);
}
debug('gunzip %d length body', body.length);
zlib.gunzip(body, cb);
}
var writeStream = args.writeStream;
debug('Request#%d %s %s with headers %j, options.path: %s',
reqId, method, url, options.headers, options.path);
args.requestUrls.push(url);
function onResponse(res) {
if (timing) {
timing.waiting = Date.now() - requestStartTime;
}
debug('Request#%d %s `req response` event emit: status %d, headers: %j',
reqId, url, res.statusCode, res.headers);
if (args.streaming) {
var result = handleRedirect(res);
if (result.redirect) {
res.resume();
return;
}
if (result.error) {
res.resume();
return done(result.error, null, res);
}
return done(null, null, res);
}
if (writeStream) {
// If there's a writable stream to recieve the response data, just pipe the
// response stream to that writable stream and call the callback when it has
// finished writing.
//
// NOTE that when the response stream `res` emits an 'end' event it just
// means that it has finished piping data to another stream. In the
// meanwhile that writable stream may still writing data to the disk until
// it emits a 'close' event.
//
// That means that we should not apply callback until the 'close' of the
// writable stream is emited.
//
// See also:
// - https://github.com/TBEDP/urllib/commit/959ac3365821e0e028c231a5e8efca6af410eabb
// - http://nodejs.org/api/stream.html#stream_event_end
// - http://nodejs.org/api/stream.html#stream_event_close_1
var result = handleRedirect(res);
if (result.redirect) {
res.resume();
return;
}
if (result.error) {
res.resume();
// end ths stream first
writeStream.end();
return done(result.error, null, res);
}
// you can set consumeWriteStream false that only wait response end
if (args.consumeWriteStream === false) {
res.on('end', done.bind(null, null, null, res));
} else {
writeStream.on('close', done.bind(null, null, null, res));
}
return res.pipe(writeStream);
}
// Otherwise, just concat those buffers.
//
// NOTE that the `chunk` is not a String but a Buffer. It means that if
// you simply concat two chunk with `+` you're actually converting both
// Buffers into Strings before concating them. It'll cause problems when
// dealing with multi-byte characters.
//
// The solution is to store each chunk in an array and concat them with
// 'buffer-concat' when all chunks is recieved.
//
// See also:
// http://cnodejs.org/topic/4faf65852e8fb5bc65113403
var chunks = [];
res.on('data', function (chunk) {
debug('Request#%d %s: `res data` event emit, size %d', reqId, url, chunk.length);
responseSize += chunk.length;
chunks.push(chunk);
});
// res.on('close', function () {
// debug('Request#%d %s: `res close` event emit, total size %d',
// reqId, url, responseSize);
// });
// res.on('error', function () {
// debug('Request#%d %s: `res error` event emit, total size %d',
// reqId, url, responseSize);
// });
res.on('aborted', function () {
responseAborted = true;
debug('Request#%d %s: `res aborted` event emit, total size %d',
reqId, url, responseSize);
});
res.on('end', function () {
var body = Buffer.concat(chunks, responseSize);
debug('Request#%d %s: `res end` event emit, total size %d, _dumped: %s',
reqId, url, responseSize, res._dumped);
if (__err) {
// req.abort() after `res data` event emit.
return done(__err, body, res);
}
var result = handleRedirect(res);
if (result.error) {
return done(result.error, body, res);
}
if (result.redirect) {
return;
}
decodeContent(res, body, function (err, data, encoding) {
if (err) {
return done(err, body, res);
}
// if body not decode, dont touch it
if (!encoding && TEXT_DATA_TYPES.indexOf(args.dataType) >= 0) {
// try to decode charset
try {
data = decodeBodyByCharset(data, res);
} catch (e) {
debug('decodeBodyByCharset error: %s', e);
// if error, dont touch it
return done(null, data, res);
}
if (args.dataType === 'json') {
if (responseSize === 0) {
data = null;
} else {
var r = parseJSON(data, fixJSONCtlChars);
if (r.error) {
err = r.error;
} else {
data = r.data;
}
}
}
}
if (responseAborted) {
// err = new Error('Remote socket was terminated before `response.end()` was called');
// err.name = 'RemoteSocketClosedError';
debug('Request#%d %s: Remote socket was terminated before `response.end()` was called', reqId, url);
}
done(err, data, res);
});
});
}
var connectTimeout, responseTimeout;
if (Array.isArray(args.timeout)) {
connectTimeout = ms(args.timeout[0]);
responseTimeout = ms(args.timeout[1]);
} else { // set both timeout equal
connectTimeout = responseTimeout = ms(args.timeout);
}
debug('ConnectTimeout: %d, ResponseTimeout: %d', connectTimeout, responseTimeout);
function startConnectTimer() {
debug('Connect timer ticking, timeout: %d', connectTimeout);
connectTimer = setTimeout(function () {
connectTimer = null;
if (statusCode === -1) {
statusCode = -2;
}
var msg = 'Connect timeout for ' + connectTimeout + 'ms';
var errorName = 'ConnectionTimeoutError';
if (!req.socket) {
errorName = 'SocketAssignTimeoutError';
msg += ', working sockets is full';
}
__err = new Error(msg);
__err.name = errorName;
__err.requestId = reqId;
debug('ConnectTimeout: Request#%d %s %s: %s, connected: %s', reqId, url, __err.name, msg, connected);
abortRequest();
}, connectTimeout);
}
function startResposneTimer() {
debug('Response timer ticking, timeout: %d', responseTimeout);
responseTimer = setTimeout(function () {
responseTimer = null;
var msg = 'Response timeout for ' + responseTimeout + 'ms';
var errorName = 'ResponseTimeoutError';
__err = new Error(msg);
__err.name = errorName;
__err.requestId = reqId;
debug('ResponseTimeout: Request#%d %s %s: %s, connected: %s', reqId, url, __err.name, msg, connected);
abortRequest();
}, responseTimeout);
}
var req;
// request headers checker will throw error
try {
req = httplib.request(options, onResponse);
} catch (err) {
return done(err);
}
// start connect timer just after `request` return
startConnectTimer();
function abortRequest() {
debug('Request#%d %s abort, connected: %s', reqId, url, connected);
// it wont case error event when req haven't been assigned a socket yet.
if (!req.socket) {
__err.noSocket = true;
done(__err);
}
req.abort();
}
if (timing) {
// request sent
req.on('finish', function() {
timing.requestSent = Date.now() - requestStartTime;
});
}
req.once('socket', function (socket) {
if (timing) {
// socket queuing time
timing.queuing = Date.now() - requestStartTime;
}
// https://github.com/nodejs/node/blob/master/lib/net.js#L377
// https://github.com/nodejs/node/blob/v0.10.40-release/lib/net.js#L352
// should use socket.socket on 0.10.x
if (isOldVersionNode && socket.socket) {
socket = socket.socket;
}
var readyState = socket.readyState;
if (readyState === 'opening') {
socket.once('lookup', function(err, ip, addressType) {
debug('Request#%d %s lookup: %s, %s, %s', reqId, url, err, ip, addressType);
if (timing) {
timing.dnslookup = Date.now() - requestStartTime;
}
if (ip) {
remoteAddress = ip;
}
});
socket.once('connect', function() {
if (timing) {
// socket connected
timing.connected = Date.now() - requestStartTime;
}
// cancel socket timer at first and start tick for TTFB
cancelConnectTimer();
startResposneTimer();
debug('Request#%d %s new socket connected', reqId, url);
connected = true;
if (!remoteAddress) {
remoteAddress = socket.remoteAddress;
}
remotePort = socket.remotePort;
});
return;
}
debug('Request#%d %s reuse socket connected, readyState: %s', reqId, url, readyState);
connected = true;
keepAliveSocket = true;
if (!remoteAddress) {
remoteAddress = socket.remoteAddress;
}
remotePort = socket.remotePort;
// reuse socket, timer should be canceled.
cancelConnectTimer();
startResposneTimer();
});
req.on('error', function (err) {
if (err.name === 'Error') {
err.name = connected ? 'ResponseError' : 'RequestError';
}
err.message += ' (req "error")';
debug('Request#%d %s `req error` event emit, %s: %s', reqId, url, err.name, err.message);
done(__err || err);
});
if (writeStream) {
writeStream.once('error', function (err) {
err.message += ' (writeStream "error")';
__err = err;
debug('Request#%d %s `writeStream error` event emit, %s: %s', reqId, url, err.name, err.message);
abortRequest();
});
}
if (args.stream) {
args.stream.pipe(req);
args.stream.once('error', function (err) {
err.message += ' (stream "error")';
__err = err;
debug('Request#%d %s `readStream error` event emit, %s: %s', reqId, url, err.name, err.message);
abortRequest();
});
} else {
req.end(body);
}
req.requestId = reqId;
return req;
};
var JSONCtlCharsMap = {
'"': '\\"', // \u0022
'\\': '\\\\', // \u005c
'\b': '\\b', // \u0008
'\f': '\\f', // \u000c
'\n': '\\n', // \u000a
'\r': '\\r', // \u000d
'\t': '\\t' // \u0009
};
var JSONCtlCharsRE = /[\u0000-\u001F\u005C]/g;
function _replaceOneChar(c) {
return JSONCtlCharsMap[c] || '\\u' + (c.charCodeAt(0) + 0x10000).toString(16).substr(1);
}
function replaceJSONCtlChars(str) {
return str.replace(JSONCtlCharsRE, _replaceOneChar);
}
function parseJSON(data, fixJSONCtlChars) {
var result = {
error: null,
data: null
};
if (fixJSONCtlChars) {
// https://github.com/node-modules/urllib/pull/77
// remote the control characters (U+0000 through U+001F)
data = replaceJSONCtlChars(data);
}
try {
result.data = JSON.parse(data);
} catch (err) {
if (err.name === 'SyntaxError') {
err.name = 'JSONResponseFormatError';
}
if (data.length > 1024) {
// show 0~512 ... -512~end data
err.message += ' (data json format: ' +
JSON.stringify(data.slice(0, 512)) + ' ...skip... ' + JSON.stringify(data.slice(data.length - 512)) + ')';
} else {
err.message += ' (data json format: ' + JSON.stringify(data) + ')';
}
result.error = err;
}
return result;
}
function HttpClient(options) {
EventEmitter.call(this);
options = options || {};
if (options.agent !== undefined) {
this.agent = options.agent;
this.hasCustomAgent = true;
} else {
this.agent = exports.agent;
this.hasCustomAgent = false;
}
if (options.httpsAgent !== undefined) {
this.httpsAgent = options.httpsAgent;
this.hasCustomHttpsAgent = true;
} else {
this.httpsAgent = exports.httpsAgent;
this.hasCustomHttpsAgent = false;
}
}
util.inherits(HttpClient, EventEmitter);
HttpClient.prototype.request = HttpClient.prototype.curl = function (url, args, callback) {
if (typeof args === 'function') {
callback = args;
args = null;
}
args = args || {};
args.emitter = this;
args.agent = getAgent(args.agent, this.agent);
args.httpsAgent = getAgent(args.httpsAgent, this.httpsAgent);
return exports.request(url, args, callback);
};
HttpClient.prototype.requestThunk = function (url, args) {
args = args || {};
args.emitter = this;
args.agent = getAgent(args.agent, this.agent);
args.httpsAgent = getAgent(args.httpsAgent, this.httpsAgent);
return exports.requestThunk(url, args);
};
exports.HttpClient = HttpClient;
exports.create = function (options) {
return new HttpClient(options);
};
/**
* decode response body by parse `content-type`'s charset
* @param {Buffer} data
* @param {Http(s)Response} res
* @return {String}
*/
function decodeBodyByCharset(data, res) {
var type = res.headers['content-type'];
if (!type) {
return data.toString();
}
var type = parseContentType(type);
var charset = type.parameters.charset || 'utf-8';
if (!Buffer.isEncoding(charset)) {
if (!_iconv) {
_iconv = require('iconv-lite');
}
return _iconv.decode(data, charset);
}
return data.toString(charset);
}
function getAgent(agent, defaultAgent) {
return agent === undefined ? defaultAgent : agent;
}
function parseContentType(str) {
try {
return contentTypeParser.parse(str);
} catch (err) {
// ignore content-type error, tread as default
return { parameters: {} };
}
}
|
apache-2.0
|
steveswinsburg/sakai-learning-object-repository
|
tool/src/java/org/sakaiproject/content/repository/tool/components/EditorButton.java
|
789
|
package org.sakaiproject.content.repository.tool.components;
import java.util.List;
import org.apache.wicket.markup.html.form.Button;
public abstract class EditorButton extends Button
{
private transient ListItem< ? > parent;
public EditorButton(String id)
{
super(id);
}
protected final ListItem< ? > getItem()
{
if (parent == null)
{
parent = findParent(ListItem.class);
}
return parent;
}
protected final List< ? > getList()
{
return getEditor().items;
}
protected final ListEditor< ? > getEditor()
{
return (ListEditor< ? >)getItem().getParent();
}
@Override
protected void onDetach()
{
parent = null;
super.onDetach();
}
}
|
apache-2.0
|
langbat/webservice
|
application/models/users.php
|
2547
|
<?php
class Users extends CI_Model {
protected $table = 'users';
/**
* Verify if an api is valid and assigned to a subscriber
* @param int $subscriber_id
* @param string $key
* @param string $secret
* @return bool
*/
public function validate_api($subscriber_id, $key, $secret) {
$res = $this->db->select('*')
->from($this->table)
->where('subscriberId', $subscriber_id)
->where('api_key', $key)
->where('api_secret', $secret)
->where('userStatus', 'ACTIVE')
->get();
return $res->num_rows() > 0;
}
/**
* Verify if an api is valid and assigned to a subscriber
* @param int $subscriber_id
* @param string $username
* @param string $password
* @return bool
*/
public function validate_user($subscriber_id, $username, $password) {
$res = $this->db->select('*')
->from($this->table)
->where('subscriberId', $subscriber_id)
->where('username', $username)
->where('pass', md5($password))
->where('userStatus', 'ACTIVE')
->get();
return $res->num_rows() > 0;
}
/**
* Gets one user by subscriber
* @param int $subscriber_id
* @return array|bool
*/
public function get_by_subscriber($subscriber_id) {
$res = $this->db->select('*')
->from($this->table)
->where('subscriberId', $subscriber_id)
->where('userStatus', 'ACTIVE')
->get();
return ($res->num_rows() > 0) ? $res->row_array() : false;
}
/**
* Returns a unique api key and secret
* @return array
*/
public function generate_api() {
do {
$key = $this->_generate_rand();
$res = $this->db->select('*')
->from($this->table)
->where('api_key', $key)
->get();
} while ($res->num_rows() > 0);
do {
$secret = $this->_generate_rand();
$res = $this->db->select('*')
->from($this->table)
->where('api_secret', $secret)
->get();
} while ($res->num_rows() > 0);
return array('api_key' => $key, 'api_secret' => $secret);
}
private function _generate_rand() {
$ran = random_string('alnum', 32);
return strtolower($ran);
}
}
|
apache-2.0
|
bobo159357456/bobo
|
android_project/L62/app/src/main/java/cn/eoe/l62/MainActivity.java
|
2068
|
package cn.eoe.l62;
import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.GridLayout;
public class MainActivity extends Activity {
GridLayout gridLayout;
//定义16个按钮的文本
String[] chars = new String[]{
"7","8","9","/",
"4","5","6","x",
"1","2","3","-",
".","0","=","+",
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridLayout = (GridLayout) findViewById(R.id.root);
for (int i = 0;i<chars.length;i++){
Button bn =new Button(this);
bn.setText(chars[i]);
//设置该按钮的字号大小
bn.setTextSize(70);
//指定组件所在的行
GridLayout.Spec rowSpec = GridLayout.spec(i/4+2);
//指定该组件所在的列
GridLayout.Spec columnSpec = GridLayout.spec(i%4);
GridLayout.LayoutParams params = new GridLayout.LayoutParams(rowSpec,columnSpec);
//指定该组件占满父容器
params.setGravity(Gravity.FILL);
gridLayout.addView(bn,params);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
apache-2.0
|
aws/aws-sdk-java
|
aws-java-sdk-glue/src/main/java/com/amazonaws/services/glue/model/transform/UpdateUserDefinedFunctionRequestProtocolMarshaller.java
|
2824
|
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.glue.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.glue.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.protocol.*;
import com.amazonaws.protocol.Protocol;
import com.amazonaws.annotation.SdkInternalApi;
/**
* UpdateUserDefinedFunctionRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class UpdateUserDefinedFunctionRequestProtocolMarshaller implements
Marshaller<Request<UpdateUserDefinedFunctionRequest>, UpdateUserDefinedFunctionRequest> {
private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.AWS_JSON).requestUri("/")
.httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true)
.operationIdentifier("AWSGlue.UpdateUserDefinedFunction").serviceName("AWSGlue").build();
private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory;
public UpdateUserDefinedFunctionRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<UpdateUserDefinedFunctionRequest> marshall(UpdateUserDefinedFunctionRequest updateUserDefinedFunctionRequest) {
if (updateUserDefinedFunctionRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
final ProtocolRequestMarshaller<UpdateUserDefinedFunctionRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(
SDK_OPERATION_BINDING, updateUserDefinedFunctionRequest);
protocolMarshaller.startMarshalling();
UpdateUserDefinedFunctionRequestMarshaller.getInstance().marshall(updateUserDefinedFunctionRequest, protocolMarshaller);
return protocolMarshaller.finishMarshalling();
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
|
apache-2.0
|
respawner/peering-manager
|
users/api/views.py
|
1673
|
from django.contrib.auth.models import Group, User
from django.db.models import Count
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.routers import APIRootView
from peering.models import AutonomousSystem
from peering_manager.api.views import ModelViewSet
from users.filters import GroupFilterSet, UserFilterSet
from .serializers import GroupSerializer, UserSerializer
class UsersRootView(APIRootView):
def get_view_name(self):
return "Users"
class GroupViewSet(ModelViewSet):
queryset = Group.objects.all().annotate(user_count=Count("user")).order_by("name")
serializer_class = GroupSerializer
filterset_class = GroupFilterSet
class UserViewSet(ModelViewSet):
queryset = User.objects.all().prefetch_related("groups").order_by("username")
serializer_class = UserSerializer
filterset_class = UserFilterSet
@action(detail=True, methods=["patch"], url_path="set-context-as")
def set_context_as(self, request, pk=None):
preferences = self.get_object().preferences
try:
autonomous_system = AutonomousSystem.objects.get(
pk=int(request.data["as_id"]), affiliated=True
)
preferences.set("context.as", autonomous_system.pk, commit=True)
except AutonomousSystem.DoesNotExist:
return Response(
{
"error": f"affiliated autonomous system with id {request.data['as_id']} not found"
},
status=status.HTTP_404_NOT_FOUND,
)
return Response({"status": "success"})
|
apache-2.0
|
Falldog/moneydog
|
moneydog/urls.py
|
1687
|
from moneydog import app
from moneydog import views
from moneydog import views_admin
app.add_url_rule('/', 'index', views.index)
#app.add_url_rule('/login', 'login', views.login)
app.add_url_rule('/list/trade/<c_type>', 'list_trade', views.list_trade)
app.add_url_rule('/list/trade/by_category/<url_key>', 'list_trade_by_category', views.list_trade_by_category)
app.add_url_rule('/edit/trade/<url_key>', 'edit_trade', views.edit_trade, methods=['GET', 'POST'])
app.add_url_rule('/add/trade/<c_type>', 'add_trade', views.add_trade, methods=['GET', 'POST'])
app.add_url_rule('/remove/trade/<url_key>', 'remove_trade', views.remove_trade)
app.add_url_rule('/list/category/<c_type>', 'list_category', views.list_category)
app.add_url_rule('/edit/category/<url_key>', 'edit_category', views.edit_category, methods=['GET', 'POST'])
app.add_url_rule('/remove/category/<url_key>', 'remove_category', views.remove_category)
app.add_url_rule('/add/category', 'add_category', views.add_category, methods=['GET', 'POST'])
app.add_url_rule('/analytics/trade/year/<c_type>', 'analytics_trade_by_year', views.analytics_trade_by_year)
app.add_url_rule('/search/', 'search_text', views.search_text)
app.add_url_rule('/ajax/hello', 'ajax_hello', views.ajax_hello, methods=['POST'])
app.add_url_rule('/api/category', 'api_category', views.api_category, methods=['GET', 'POST'])
app.add_url_rule('/api/add/trade', 'api_add_trade', views.api_add_trade, methods=['POST'])
# admin control view
app.add_url_rule('/admin/dump', 'dump', views_admin.dump)
app.add_url_rule('/admin/push_ancient_data', 'push_ancient_data', views_admin.push_ancient_data, methods=['GET', 'POST'])
|
apache-2.0
|
AlexandrSurkov/PKStudio
|
PKStudio/Helpers/MSBuildHelper.cs
|
2405
|
using System;
using System.Collections.Generic;
using Microsoft.Build.Framework;
using Microsoft.Build.Evaluation;
using System.Diagnostics;
using System.ComponentModel;
namespace PKStudio.Helpers
{
class MSBuildHelper : IDisposable
{
private List<ILogger> mLoggers = new List<ILogger>();
private BackgroundWorker m_worker;
private class WorkerRunArgument
{
public string Path { get; set; }
public string Target { get; set; }
public string BuildType { get; set; }
public string MediaType { get; set; }
}
public MSBuildHelper()
{
this.m_worker = new BackgroundWorker();
this.m_worker.DoWork += new DoWorkEventHandler(m_worker_DoWork);
this.m_worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(m_worker_RunWorkerCompleted);
//this.m_worker.WorkerReportsProgress = true;
}
void m_worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//throw new NotImplementedException();
}
void m_worker_DoWork(object sender, DoWorkEventArgs e)
{
WorkerRunArgument argument = (WorkerRunArgument)e.Argument;
using (ProjectCollection BuildCollection = new ProjectCollection())
{
Project BuildProject = BuildCollection.LoadProject(PK.Wrapper.ExpandEnvVars(argument.Path, ""));
BuildProject.SetProperty("flavor", argument.BuildType);
BuildProject.SetProperty("memory", argument.MediaType);
BuildProject.Build(argument.Target, mLoggers);
}
}
public void Build(string Path, string target, string buildType, string mediaType)
{
if (m_worker.IsBusy == false)
{
WorkerRunArgument argument = new WorkerRunArgument();
argument.Path = Path;
argument.Target = target;
argument.BuildType = buildType;
argument.MediaType = mediaType;
m_worker.RunWorkerAsync(argument);
}
}
public List<ILogger> Loggers { get { return this.mLoggers; } }
#region IDisposable Members
public void Dispose()
{
m_worker.Dispose();
}
#endregion
}
}
|
apache-2.0
|
LindaLawton/Google-Dotnet-Samples
|
Samples/DCM/DFA Reporting And Trafficking API/v2.7/ContentCategoriesSample.cs
|
13688
|
// Copyright 2017 DAIMTO ([Linda Lawton](https://twitter.com/LindaLawtonDK)) : [www.daimto.com](http://www.daimto.com/)
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
// an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by DAIMTO-Google-apis-Sample-generator 1.0.0
// Template File Name: methodTemplate.tt
// Build date: 2017-10-08
// C# generater version: 1.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
// About
//
// Unoffical sample for the Dfareporting v2.7 API for C#.
// This sample is designed to be used with the Google .Net client library. (https://github.com/google/google-api-dotnet-client)
//
// API Description: Manages your DoubleClick Campaign Manager ad campaigns and reports.
// API Documentation Link https://developers.google.com/doubleclick-advertisers/
//
// Discovery Doc https://www.googleapis.com/discovery/v1/apis/Dfareporting/v2_7/rest
//
//------------------------------------------------------------------------------
// Installation
//
// This sample code uses the Google .Net client library (https://github.com/google/google-api-dotnet-client)
//
// NuGet package:
//
// Location: https://www.nuget.org/packages/Google.Apis.Dfareporting.v2_7/
// Install Command: PM> Install-Package Google.Apis.Dfareporting.v2_7
//
//------------------------------------------------------------------------------
using Google.Apis.Dfareporting.v2_7;
using Google.Apis.Dfareporting.v2_7.Data;
using System;
namespace GoogleSamplecSharpSample.Dfareportingv2_7.Methods
{
public static class ContentCategoriesSample
{
/// <summary>
/// Deletes an existing content category.
/// Documentation https://developers.google.com/dfareporting/v2.7/reference/contentCategories/delete
/// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong.
/// </summary>
/// <param name="service">Authenticated Dfareporting service.</param>
/// <param name="profileId">User profile ID associated with this request.</param>
/// <param name="id">Content category ID.</param>
public static void Delete(DfareportingService service, string profileId, string id)
{
try
{
// Initial validation.
if (service == null)
throw new ArgumentNullException("service");
if (profileId == null)
throw new ArgumentNullException(profileId);
if (id == null)
throw new ArgumentNullException(id);
// Make the request.
service.ContentCategories.Delete(profileId, id).Execute();
}
catch (Exception ex)
{
throw new Exception("Request ContentCategories.Delete failed.", ex);
}
}
/// <summary>
/// Gets one content category by ID.
/// Documentation https://developers.google.com/dfareporting/v2.7/reference/contentCategories/get
/// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong.
/// </summary>
/// <param name="service">Authenticated Dfareporting service.</param>
/// <param name="profileId">User profile ID associated with this request.</param>
/// <param name="id">Content category ID.</param>
/// <returns>ContentCategoryResponse</returns>
public static ContentCategory Get(DfareportingService service, string profileId, string id)
{
try
{
// Initial validation.
if (service == null)
throw new ArgumentNullException("service");
if (profileId == null)
throw new ArgumentNullException(profileId);
if (id == null)
throw new ArgumentNullException(id);
// Make the request.
return service.ContentCategories.Get(profileId, id).Execute();
}
catch (Exception ex)
{
throw new Exception("Request ContentCategories.Get failed.", ex);
}
}
/// <summary>
/// Inserts a new content category.
/// Documentation https://developers.google.com/dfareporting/v2.7/reference/contentCategories/insert
/// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong.
/// </summary>
/// <param name="service">Authenticated Dfareporting service.</param>
/// <param name="profileId">User profile ID associated with this request.</param>
/// <param name="body">A valid Dfareporting v2.7 body.</param>
/// <returns>ContentCategoryResponse</returns>
public static ContentCategory Insert(DfareportingService service, string profileId, ContentCategory body)
{
try
{
// Initial validation.
if (service == null)
throw new ArgumentNullException("service");
if (body == null)
throw new ArgumentNullException("body");
if (profileId == null)
throw new ArgumentNullException(profileId);
// Make the request.
return service.ContentCategories.Insert(body, profileId).Execute();
}
catch (Exception ex)
{
throw new Exception("Request ContentCategories.Insert failed.", ex);
}
}
public class ContentCategoriesListOptionalParms
{
/// Select only content categories with these IDs.
public string Ids { get; set; }
/// Maximum number of results to return.
public int? MaxResults { get; set; }
/// Value of the nextPageToken from the previous result page.
public string PageToken { get; set; }
/// Allows searching for objects by name or ID. Wildcards (*) are allowed. For example, "contentcategory*2015" will return objects with names like "contentcategory June 2015", "contentcategory April 2015", or simply "contentcategory 2015". Most of the searches also add wildcards implicitly at the start and the end of the search string. For example, a search string of "contentcategory" will match objects with name "my contentcategory", "contentcategory 2015", or simply "contentcategory".
public string SearchString { get; set; }
/// Field by which to sort the list.
public string SortField { get; set; }
/// Order of sorted results.
public string SortOrder { get; set; }
}
/// <summary>
/// Retrieves a list of content categories, possibly filtered. This method supports paging.
/// Documentation https://developers.google.com/dfareporting/v2.7/reference/contentCategories/list
/// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong.
/// </summary>
/// <param name="service">Authenticated Dfareporting service.</param>
/// <param name="profileId">User profile ID associated with this request.</param>
/// <param name="optional">Optional paramaters.</param>
/// <returns>ContentCategoriesListResponseResponse</returns>
public static ContentCategoriesListResponse List(DfareportingService service, string profileId, ContentCategoriesListOptionalParms optional = null)
{
try
{
// Initial validation.
if (service == null)
throw new ArgumentNullException("service");
if (profileId == null)
throw new ArgumentNullException(profileId);
// Building the initial request.
var request = service.ContentCategories.List(profileId);
// Applying optional parameters to the request.
request = (ContentCategoriesResource.ListRequest)SampleHelpers.ApplyOptionalParms(request, optional);
// Requesting data.
return request.Execute();
}
catch (Exception ex)
{
throw new Exception("Request ContentCategories.List failed.", ex);
}
}
/// <summary>
/// Updates an existing content category. This method supports patch semantics.
/// Documentation https://developers.google.com/dfareporting/v2.7/reference/contentCategories/patch
/// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong.
/// </summary>
/// <param name="service">Authenticated Dfareporting service.</param>
/// <param name="profileId">User profile ID associated with this request.</param>
/// <param name="id">Content category ID.</param>
/// <param name="body">A valid Dfareporting v2.7 body.</param>
/// <returns>ContentCategoryResponse</returns>
public static ContentCategory Patch(DfareportingService service, string profileId, string id, ContentCategory body)
{
try
{
// Initial validation.
if (service == null)
throw new ArgumentNullException("service");
if (body == null)
throw new ArgumentNullException("body");
if (profileId == null)
throw new ArgumentNullException(profileId);
if (id == null)
throw new ArgumentNullException(id);
// Make the request.
return service.ContentCategories.Patch(body, profileId, id).Execute();
}
catch (Exception ex)
{
throw new Exception("Request ContentCategories.Patch failed.", ex);
}
}
/// <summary>
/// Updates an existing content category.
/// Documentation https://developers.google.com/dfareporting/v2.7/reference/contentCategories/update
/// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong.
/// </summary>
/// <param name="service">Authenticated Dfareporting service.</param>
/// <param name="profileId">User profile ID associated with this request.</param>
/// <param name="body">A valid Dfareporting v2.7 body.</param>
/// <returns>ContentCategoryResponse</returns>
public static ContentCategory Update(DfareportingService service, string profileId, ContentCategory body)
{
try
{
// Initial validation.
if (service == null)
throw new ArgumentNullException("service");
if (body == null)
throw new ArgumentNullException("body");
if (profileId == null)
throw new ArgumentNullException(profileId);
// Make the request.
return service.ContentCategories.Update(body, profileId).Execute();
}
catch (Exception ex)
{
throw new Exception("Request ContentCategories.Update failed.", ex);
}
}
}
public static class SampleHelpers
{
/// <summary>
/// Using reflection to apply optional parameters to the request.
///
/// If the optonal parameters are null then we will just return the request as is.
/// </summary>
/// <param name="request">The request. </param>
/// <param name="optional">The optional parameters. </param>
/// <returns></returns>
public static object ApplyOptionalParms(object request, object optional)
{
if (optional == null)
return request;
System.Reflection.PropertyInfo[] optionalProperties = (optional.GetType()).GetProperties();
foreach (System.Reflection.PropertyInfo property in optionalProperties)
{
// Copy value from optional parms to the request. They should have the same names and datatypes.
System.Reflection.PropertyInfo piShared = (request.GetType()).GetProperty(property.Name);
if (property.GetValue(optional, null) != null) // TODO Test that we do not add values for items that are null
piShared.SetValue(request, property.GetValue(optional, null), null);
}
return request;
}
}
}
|
apache-2.0
|
google/vectorio
|
vectorio_buffered.go
|
3433
|
/*
Copyright 2015 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 vectorio
import (
"errors"
"net"
"os"
"sync"
"syscall"
)
// 1024 is the max size of an Iovec on Linux
const defaultBufSize = 1024
// just an alias so users don't have to import syscall to use this
//type Iovec syscall.Iovec
// BufferedWritev is similar to bufio.Writer.
// after all data has been written, the client should call Flush to make sure everything is written.
// Note: this is NOT concurrency safe. Concurrent access should use the embedded Lock object (w.Lock.Lock() /
// w.Lock.Unlock()), or wrap this in a single goroutine that handles a channel of []byte.
type BufferedWritev struct {
buf []syscall.Iovec
Lock *sync.Mutex
fd uintptr
}
// NewBufferedWritev makes a new BufferedWritev from a net.TCPConn, os.File, or file descriptor (FD).
func NewBufferedWritev(targetIn interface{}) (bw *BufferedWritev, err error) {
switch target := targetIn.(type) {
case *net.TCPConn:
var f *os.File
f, err = target.File()
if err != nil {
return
}
bw, err = NewBufferedWritev(f)
case *os.File:
bw, err = NewBufferedWritev(uintptr(target.Fd()))
case uintptr:
// refactor: make buffer size user-specified?
bw = &BufferedWritev{buf: make([]syscall.Iovec, 0, defaultBufSize), Lock: new(sync.Mutex), fd: target}
default:
err = errors.New("NewBufferedWritev called with invalid type")
}
return
}
// Write implements the io.Writer interface.
// Number of bytes written (nw) is usually 0 except for the times we flush the buffer, which will reflect the quantity of all bytes written in that writev() call
func (bw *BufferedWritev) Write(p []byte) (nw int, err error) {
nw, err = bw.WriteIovec(syscall.Iovec{&p[0], uint64(len(p))})
return
}
// WriteIovec takes a user-composed syscall.Iovec struct instead of []byte; functionally the same as Write
func (bw *BufferedWritev) WriteIovec(iov syscall.Iovec) (nw int, err error) {
//bw.lock.Lock()
// normally append will reallocate a slice if it exceeds its cap, but that should not happen here because of our logic below
bw.buf = append(bw.buf, iov)
if len(bw.buf) == cap(bw.buf) {
// maxed out the slice; write it and reset the slice
nw, err = bw.flush()
}
//bw.lock.Unlock()
return
}
// Flush writes the contents of buffer to underlying file handle and resets buffer.
// This must be called at the end of writing before closing the underlying file, or data will be lost.
func (bw *BufferedWritev) Flush() (nw int, err error) {
// TODO: if we're not going to use a lock, collapse Flush() and flush()
//bw.Lock.Lock()
nw, err = bw.flush()
//bw.Lock.Unlock()
return
}
// FUTURE: check to make sure the number of bytes written matches the sum of the iovec's
// Note: must be wrapped in a mutex to be concurrency safe
func (bw *BufferedWritev) flush() (nw int, err error) {
nw, err = WritevRaw(bw.fd, bw.buf)
bw.buf = bw.buf[:0]
return
}
|
apache-2.0
|
minnal/minnal
|
minnal-jaxrs/minnal-instrumentation-jaxrs/src/main/java/org/minnal/instrument/entity/metadata/handler/SearchableAnnotationHandler.java
|
1330
|
/**
*
*/
package org.minnal.instrument.entity.metadata.handler;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.minnal.instrument.entity.Searchable;
import org.minnal.instrument.entity.metadata.EntityMetaData;
import org.minnal.instrument.entity.metadata.ParameterMetaData;
import com.google.common.base.Strings;
/**
* @author ganeshs
*
*/
public class SearchableAnnotationHandler extends AbstractEntityAnnotationHandler {
@Override
public void handle(EntityMetaData metaData, Annotation annotation, Method method) {
String value = ((Searchable)annotation).value();
value = Strings.isNullOrEmpty(value) ? getGetterName(method, true) : value;
ParameterMetaData parameterMetaData = new ParameterMetaData(value, value, method.getReturnType());
metaData.addSearchField(parameterMetaData);
}
@Override
public void handle(EntityMetaData metaData, Annotation annotation, Field field) {
String value = ((Searchable)annotation).value();
if (Strings.isNullOrEmpty(value)) {
value = field.getName();
}
ParameterMetaData parameterMetaData = new ParameterMetaData(value, field.getName(), field.getType());
metaData.addSearchField(parameterMetaData);
}
@Override
public Class<?> getAnnotationType() {
return Searchable.class;
}
}
|
apache-2.0
|
cristiani/encuestame
|
enme-persistence/enme-model/src/main/java/org/encuestame/persistence/utils/EncodingUtils.java
|
3943
|
/*
************************************************************************************
* Copyright (C) 2001-2011 encuestame: system online surveys Copyright (C) 2011
* encuestame Development Team.
* Licensed under the Apache Software License version 2.0
* 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.encuestame.persistence.utils;
import java.io.UnsupportedEncodingException;
/**
* Helper to Encode Strings.
* @author Picado, Juan juanATencuestame.org
* @since Dec 24, 2010 4:01:40 PM
* @version $Id:$
*/
public class EncodingUtils {
/**
* Encode the byte array into a hex String.
*/
public static String hexEncode(byte[] bytes) {
StringBuilder result = new StringBuilder();
char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
for (int i = 0; i < bytes.length; ++i) {
byte b = bytes[i];
result.append(digits[(b & 0xf0) >> 4]);
result.append(digits[b & 0x0f]);
}
return result.toString();
}
/**
* Decode the hex String into a byte array.
*/
public static byte[] hexDecode(String s) {
int len = s.length();
byte[] r = new byte[len / 2];
for (int i = 0; i < r.length; i++) {
int digit1 = s.charAt(i * 2), digit2 = s.charAt(i * 2 + 1);
if ((digit1 >= '0') && (digit1 <= '9')) {
digit1 -= '0';
} else if ((digit1 >= 'a') && (digit1 <= 'f')) {
digit1 -= 'a' - 10;
}
if ((digit2 >= '0') && (digit2 <= '9')) {
digit2 -= '0';
} else if ((digit2 >= 'a') && (digit2 <= 'f')) {
digit2 -= 'a' - 10;
}
r[i] = (byte) ((digit1 << 4) + digit2);
}
return r;
}
/**
* Get the bytes of the String in UTF-8 encoded form.
*/
public static byte[] utf8Encode(String string) {
try {
return string.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw encodingException(e);
}
}
/**
* Decode the bytes in UTF-8 form into a String.
*/
public static String utf8Decode(byte[] bytes) {
try {
return new String(bytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw encodingException(e);
}
}
/**
* Combine the individual byte arrays into one array.
*/
public static byte[] concatenate(byte[]... arrays) {
int length = 0;
for (byte[] array : arrays) {
length += array.length;
}
byte[] newArray = new byte[length];
int destPos = 0;
for (byte[] array : arrays) {
System.arraycopy(array, 0, newArray, destPos, array.length);
destPos += array.length;
}
return newArray;
}
/**
* Extract a sub array of bytes out of the byte array.
*/
public static byte[] subArray(byte[] array, int beginIndex, int endIndex) {
int length = endIndex - beginIndex;
byte[] subarray = new byte[length];
System.arraycopy(array, beginIndex, subarray, 0, length);
return subarray;
}
private EncodingUtils() {
}
private static RuntimeException encodingException(UnsupportedEncodingException e) {
return new IllegalStateException("UTF-8 is not an available char set", e);
}
}
|
apache-2.0
|
pdalbora/gosu-lang
|
gosu-xml/src/main/java/gw/internal/schema/gw/xsd/w3c/soap12/enums/UseChoice.java
|
2037
|
package gw.internal.schema.gw.xsd.w3c.soap12.enums;
/***************************************************************************/
/* THIS IS AUTOGENERATED CODE - DO NOT MODIFY OR YOUR CHANGES WILL BE LOST */
/* THIS CODE CAN BE REGENERATED USING 'xsd-codegen' */
/***************************************************************************/
public enum UseChoice implements gw.lang.reflect.gs.IGosuObject, gw.lang.reflect.IEnumValue, gw.xml.IXmlSchemaEnumValue, gw.internal.xml.IXmlGeneratedClass {
Literal( "literal" ), Encoded( "encoded" );
public static final gw.util.concurrent.LockingLazyVar<gw.lang.reflect.IType> TYPE = new gw.util.concurrent.LockingLazyVar<gw.lang.reflect.IType>( gw.lang.reflect.TypeSystem.getGlobalLock() ) {
@Override
protected gw.lang.reflect.IType init() {
return gw.lang.reflect.TypeSystem.getByFullName( "gw.xsd.w3c.soap12.enums.UseChoice" );
}
};
private final java.lang.String _serializedValue;
private UseChoice( java.lang.String serializedValue ) {
_serializedValue = serializedValue;
}
@Override
public gw.lang.reflect.IType getIntrinsicType() {
return TYPE.get();
}
@Override
public java.lang.String toString() {
return _serializedValue;
}
@Override
public java.lang.Object getValue() {
return this;
}
@Override
public java.lang.String getCode() {
return name();
}
@Override
public int getOrdinal() {
return ordinal();
}
@Override
public java.lang.String getDisplayName() {
return name();
}
public java.lang.String getGosuValue() {
return (java.lang.String) TYPE.get().getTypeInfo().getProperty( "GosuValue" ).getAccessor().getValue( this );
}
public java.lang.String getSerializedValue() {
return (java.lang.String) TYPE.get().getTypeInfo().getProperty( "SerializedValue" ).getAccessor().getValue( this );
}
@SuppressWarnings( {"UnusedDeclaration"} )
private static final long FINGERPRINT = 2571638017947858241L;
}
|
apache-2.0
|
ShaneKing/sk-js
|
src/Window0.js
|
2183
|
import Proxy0 from './Proxy0';
import SK from './SK';
export default class Window0 {
/**
* the url of page or sub frame page
*
* @returns {string}
*/
static getCurrentHref() {
if (window && window.location) {
return window.location.href;
}
}
/**
* window.location.origin
*
* @returns {string}
*/
static getCurrentOrigin() {
if (window && window.location) {
return window.location.origin;
}
}
/**
* /a/b -> /a/b
* /a/b/c.html -> /a/b/c
* /context/a -> /a
*
* @returns {string}
*/
static getCurrentPath() {
if (window && window.location) {
let path = window.location.pathname;
path = path.substring(SK.DEFAULT_CONTEXT_PATH.length, path.length);
path = Proxy0._.endsWith(path, SK.FILE_TYPE_HTML_WITH_POINT) ? path.substring(0, path.length - 5) : path;
return path;
}
}
/**
* ?a=1&b=2
*
* @returns {*}
*/
static getCurrentSearch() {
if (window && window.location) {
return window.location.search;
}
}
/**
* (a,?a=1&b=2) -> 1
*
* @param param
* @param search
* @returns {*}
*/
static getRequestParameter(param, search = SK.getCurrentSearch()) {
return SK.getRequestParameter(param, search);
}
/**
* localStorage
*
* @param key
* @param value
*/
static local(key, value) {
if (localStorage) {
if (arguments.length > 1) {
localStorage.removeItem(key);
if (!Proxy0._.isNil(value)) {
return localStorage.setItem(key, value);
}
} else {
return localStorage.getItem(key);
}
}
}
/**
* web redirect
*
* @param url
*/
static redirect(url) {
if (window && window.location) {
window.location.href = url;
}
}
/**
* sessionStorage
*
* @param key
* @param value
*/
static session(key, value) {
if (sessionStorage) {
if (arguments.length > 1) {
sessionStorage.removeItem(key);
if (!Proxy0._.isNil(value)) {
return sessionStorage.setItem(key, value);
}
} else {
return sessionStorage.getItem(key);
}
}
}
}
|
apache-2.0
|
lvydra/syndesis-e2e-tests
|
utilities/src/main/java/io/syndesis/qe/utils/DbUtils.java
|
3525
|
package io.syndesis.qe.utils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class DbUtils {
private Connection dbConnection;
public DbUtils(Connection dbConnection) {
this.dbConnection = dbConnection;
}
/**
* Execute given SQL command on sampledb in syndesis-db pod.
*
* @param sqlCommnad
* @return
*/
public ResultSet readSqlOnSampleDb(String sqlCommnad) {
ResultSet resultSet = null;
final PreparedStatement preparedStatement;
try {
preparedStatement = dbConnection.prepareStatement(sqlCommnad);
resultSet = preparedStatement.executeQuery();
} catch (SQLException ex) {
log.error("Error: " + ex);
}
return resultSet;
}
public int updateSqlOnSampleDb(String sqlCommnad) {
int result = -2;
final PreparedStatement preparedStatement;
try {
preparedStatement = dbConnection.prepareStatement(sqlCommnad);
result = preparedStatement.executeUpdate();
} catch (SQLException ex) {
log.error("Error: " + ex);
}
return result;
}
/**
* Get number of records in table.
*
* @param tableName - name of the table, of which we want the number of items.
* @return
*/
public int getNumberOfRecordsInTable(String tableName) {
int records = 0;
final PreparedStatement preparedStatement;
try {
preparedStatement = dbConnection.prepareStatement("SELECT COUNT(*) FROM " + tableName);
final ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
records = resultSet.getInt(1);
}
} catch (SQLException ex) {
log.error("Error: " + ex);
}
log.debug("Number of records: " + records);
return records;
}
/**
* Get number of records in table specified.
*
* @param tableName - name of the DB table.
* @param columnName - name of column in that table.
* @param value - value of the parameter.
* @return
*/
public int getNumberOfRecordsInTable(String tableName, String columnName, String value) {
int records = 0;
final PreparedStatement preparedStatement;
try {
String sql = "SELECT COUNT(*) FROM " + tableName + " WHERE " + columnName + " LIKE '" + value + "'";
log.info("SQL: *{}*", sql);
preparedStatement = dbConnection.prepareStatement(sql);
final ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
records = resultSet.getInt(1);
}
} catch (SQLException ex) {
log.error("Error: " + ex);
}
log.debug("Number of records: " + records);
return records;
}
/**
* Removes all data from specified table.
*
* @param tableName
*/
public void deleteRecordsInTable(String tableName) {
final PreparedStatement preparedStatement;
try {
preparedStatement = dbConnection.prepareStatement("Delete FROM " + tableName);
preparedStatement.executeUpdate();
log.debug("Cleared table: " + tableName);
} catch (SQLException ex) {
log.error("Error: " + ex);
}
}
}
|
apache-2.0
|
vmuzikar/keycloak
|
model/jpa/src/main/java/org/keycloak/models/jpa/session/JpaUserSessionPersisterProvider.java
|
15504
|
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.keycloak.models.jpa.session;
import org.jboss.logging.Logger;
import org.keycloak.common.util.Time;
import org.keycloak.models.AuthenticatedClientSessionModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.UserSessionModel;
import org.keycloak.models.session.PersistentAuthenticatedClientSessionAdapter;
import org.keycloak.models.session.PersistentClientSessionModel;
import org.keycloak.models.session.PersistentUserSessionAdapter;
import org.keycloak.models.session.PersistentUserSessionModel;
import org.keycloak.models.session.UserSessionPersisterProvider;
import org.keycloak.models.utils.SessionTimeoutHelper;
import org.keycloak.storage.StorageId;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.persistence.LockModeType;
import static org.keycloak.models.jpa.PaginationUtils.paginateQuery;
import static org.keycloak.utils.StreamsUtil.closing;
/**
* @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
*/
public class JpaUserSessionPersisterProvider implements UserSessionPersisterProvider {
private static final Logger logger = Logger.getLogger(JpaUserSessionPersisterProvider.class);
private final KeycloakSession session;
private final EntityManager em;
public JpaUserSessionPersisterProvider(KeycloakSession session, EntityManager em) {
this.session = session;
this.em = em;
}
@Override
public void createUserSession(UserSessionModel userSession, boolean offline) {
PersistentUserSessionAdapter adapter = new PersistentUserSessionAdapter(userSession);
PersistentUserSessionModel model = adapter.getUpdatedModel();
PersistentUserSessionEntity entity = new PersistentUserSessionEntity();
entity.setUserSessionId(model.getUserSessionId());
entity.setCreatedOn(model.getStarted());
entity.setRealmId(adapter.getRealm().getId());
entity.setUserId(adapter.getUser().getId());
String offlineStr = offlineToString(offline);
entity.setOffline(offlineStr);
entity.setLastSessionRefresh(model.getLastSessionRefresh());
entity.setData(model.getData());
em.persist(entity);
em.flush();
}
@Override
public void createClientSession(AuthenticatedClientSessionModel clientSession, boolean offline) {
PersistentAuthenticatedClientSessionAdapter adapter = new PersistentAuthenticatedClientSessionAdapter(session, clientSession);
PersistentClientSessionModel model = adapter.getUpdatedModel();
PersistentClientSessionEntity entity = new PersistentClientSessionEntity();
StorageId clientStorageId = new StorageId(clientSession.getClient().getId());
if (clientStorageId.isLocal()) {
entity.setClientId(clientStorageId.getId());
entity.setClientStorageProvider(PersistentClientSessionEntity.LOCAL);
entity.setExternalClientId(PersistentClientSessionEntity.LOCAL);
} else {
entity.setClientId(PersistentClientSessionEntity.EXTERNAL);
entity.setClientStorageProvider(clientStorageId.getProviderId());
entity.setExternalClientId(clientStorageId.getExternalId());
}
entity.setTimestamp(clientSession.getTimestamp());
String offlineStr = offlineToString(offline);
entity.setOffline(offlineStr);
entity.setUserSessionId(clientSession.getUserSession().getId());
entity.setData(model.getData());
em.persist(entity);
em.flush();
}
@Override
public void removeUserSession(String userSessionId, boolean offline) {
String offlineStr = offlineToString(offline);
em.createNamedQuery("deleteClientSessionsByUserSession")
.setParameter("userSessionId", userSessionId)
.setParameter("offline", offlineStr)
.executeUpdate();
PersistentUserSessionEntity sessionEntity = em.find(PersistentUserSessionEntity.class, new PersistentUserSessionEntity.Key(userSessionId, offlineStr), LockModeType.PESSIMISTIC_WRITE);
if (sessionEntity != null) {
em.remove(sessionEntity);
em.flush();
}
}
@Override
public void removeClientSession(String userSessionId, String clientUUID, boolean offline) {
String offlineStr = offlineToString(offline);
StorageId clientStorageId = new StorageId(clientUUID);
String clientId = PersistentClientSessionEntity.EXTERNAL;
String clientStorageProvider = PersistentClientSessionEntity.LOCAL;
String externalId = PersistentClientSessionEntity.LOCAL;
if (clientStorageId.isLocal()) {
clientId = clientUUID;
} else {
clientStorageProvider = clientStorageId.getProviderId();
externalId = clientStorageId.getExternalId();
}
PersistentClientSessionEntity sessionEntity = em.find(PersistentClientSessionEntity.class, new PersistentClientSessionEntity.Key(userSessionId, clientId, clientStorageProvider, externalId, offlineStr), LockModeType.PESSIMISTIC_WRITE);
if (sessionEntity != null) {
em.remove(sessionEntity);
// Remove userSession if it was last clientSession
List<PersistentClientSessionEntity> clientSessions = getClientSessionsByUserSession(sessionEntity.getUserSessionId(), offline);
if (clientSessions.size() == 0) {
offlineStr = offlineToString(offline);
PersistentUserSessionEntity userSessionEntity = em.find(PersistentUserSessionEntity.class, new PersistentUserSessionEntity.Key(sessionEntity.getUserSessionId(), offlineStr), LockModeType.PESSIMISTIC_WRITE);
if (userSessionEntity != null) {
em.remove(userSessionEntity);
}
}
em.flush();
}
}
private List<PersistentClientSessionEntity> getClientSessionsByUserSession(String userSessionId, boolean offline) {
String offlineStr = offlineToString(offline);
TypedQuery<PersistentClientSessionEntity> query = em.createNamedQuery("findClientSessionsByUserSession", PersistentClientSessionEntity.class);
query.setParameter("userSessionId", userSessionId);
query.setParameter("offline", offlineStr);
return query.getResultList();
}
@Override
public void onRealmRemoved(RealmModel realm) {
int num = em.createNamedQuery("deleteClientSessionsByRealm").setParameter("realmId", realm.getId()).executeUpdate();
num = em.createNamedQuery("deleteUserSessionsByRealm").setParameter("realmId", realm.getId()).executeUpdate();
}
@Override
public void onClientRemoved(RealmModel realm, ClientModel client) {
onClientRemoved(client.getId());
}
private void onClientRemoved(String clientUUID) {
int num = 0;
StorageId clientStorageId = new StorageId(clientUUID);
if (clientStorageId.isLocal()) {
num = em.createNamedQuery("deleteClientSessionsByClient").setParameter("clientId", clientUUID).executeUpdate();
} else {
num = em.createNamedQuery("deleteClientSessionsByExternalClient")
.setParameter("clientStorageProvider", clientStorageId.getProviderId())
.setParameter("externalClientId", clientStorageId.getExternalId())
.executeUpdate();
}
}
@Override
public void onUserRemoved(RealmModel realm, UserModel user) {
onUserRemoved(realm, user.getId());
}
private void onUserRemoved(RealmModel realm, String userId) {
int num = em.createNamedQuery("deleteClientSessionsByUser").setParameter("userId", userId).executeUpdate();
num = em.createNamedQuery("deleteUserSessionsByUser").setParameter("userId", userId).executeUpdate();
}
@Override
public void updateLastSessionRefreshes(RealmModel realm, int lastSessionRefresh, Collection<String> userSessionIds, boolean offline) {
String offlineStr = offlineToString(offline);
int us = em.createNamedQuery("updateUserSessionLastSessionRefresh")
.setParameter("lastSessionRefresh", lastSessionRefresh)
.setParameter("realmId", realm.getId())
.setParameter("offline", offlineStr)
.setParameter("userSessionIds", userSessionIds)
.executeUpdate();
logger.debugf("Updated lastSessionRefresh of %d user sessions in realm '%s'", us, realm.getName());
}
@Override
public void removeExpired(RealmModel realm) {
int expiredOffline = Time.currentTime() - realm.getOfflineSessionIdleTimeout() - SessionTimeoutHelper.PERIODIC_CLEANER_IDLE_TIMEOUT_WINDOW_SECONDS;
String offlineStr = offlineToString(true);
logger.tracef("Trigger removing expired user sessions for realm '%s'", realm.getName());
int cs = em.createNamedQuery("deleteExpiredClientSessions")
.setParameter("realmId", realm.getId())
.setParameter("lastSessionRefresh", expiredOffline)
.setParameter("offline", offlineStr)
.executeUpdate();
int us = em.createNamedQuery("deleteExpiredUserSessions")
.setParameter("realmId", realm.getId())
.setParameter("lastSessionRefresh", expiredOffline)
.setParameter("offline", offlineStr)
.executeUpdate();
logger.debugf("Removed %d expired user sessions and %d expired client sessions in realm '%s'", us, cs, realm.getName());
}
@Override
public Stream<UserSessionModel> loadUserSessionsStream(Integer firstResult, Integer maxResults, boolean offline,
Integer lastCreatedOn, String lastUserSessionId) {
String offlineStr = offlineToString(offline);
TypedQuery<PersistentUserSessionEntity> query = em.createNamedQuery("findUserSessions", PersistentUserSessionEntity.class);
query.setParameter("offline", offlineStr);
query.setParameter("lastCreatedOn", lastCreatedOn);
query.setParameter("lastSessionId", lastUserSessionId);
List<PersistentUserSessionAdapter> result = closing(paginateQuery(query, firstResult, maxResults).getResultStream()
.map(this::toAdapter))
.collect(Collectors.toList());
Map<String, PersistentUserSessionAdapter> sessionsById = result.stream()
.collect(Collectors.toMap(UserSessionModel::getId, Function.identity()));
Set<String> userSessionIds = sessionsById.keySet();
Set<String> removedClientUUIDs = new HashSet<>();
if (!userSessionIds.isEmpty()) {
TypedQuery<PersistentClientSessionEntity> query2 = em.createNamedQuery("findClientSessionsByUserSessions", PersistentClientSessionEntity.class);
query2.setParameter("userSessionIds", userSessionIds);
query2.setParameter("offline", offlineStr);
closing(query2.getResultStream()).forEach(clientSession -> {
PersistentUserSessionAdapter userSession = sessionsById.get(clientSession.getUserSessionId());
PersistentAuthenticatedClientSessionAdapter clientSessAdapter = toAdapter(userSession.getRealm(), userSession, clientSession);
Map<String, AuthenticatedClientSessionModel> currentClientSessions = userSession.getAuthenticatedClientSessions();
// Case when client was removed in the meantime
if (clientSessAdapter.getClient() == null) {
removedClientUUIDs.add(clientSession.getClientId());
} else {
currentClientSessions.put(clientSession.getClientId(), clientSessAdapter);
}
});
}
for (String clientUUID : removedClientUUIDs) {
onClientRemoved(clientUUID);
}
return result.stream().map(UserSessionModel.class::cast);
}
private PersistentUserSessionAdapter toAdapter(PersistentUserSessionEntity entity) {
RealmModel realm = session.realms().getRealm(entity.getRealmId());
return toAdapter(realm, entity);
}
private PersistentUserSessionAdapter toAdapter(RealmModel realm, PersistentUserSessionEntity entity) {
PersistentUserSessionModel model = new PersistentUserSessionModel();
model.setUserSessionId(entity.getUserSessionId());
model.setStarted(entity.getCreatedOn());
model.setLastSessionRefresh(entity.getLastSessionRefresh());
model.setData(entity.getData());
model.setOffline(offlineFromString(entity.getOffline()));
Map<String, AuthenticatedClientSessionModel> clientSessions = new HashMap<>();
return new PersistentUserSessionAdapter(session, model, realm, entity.getUserId(), clientSessions);
}
private PersistentAuthenticatedClientSessionAdapter toAdapter(RealmModel realm, PersistentUserSessionAdapter userSession, PersistentClientSessionEntity entity) {
String clientId = entity.getClientId();
if (!entity.getExternalClientId().equals("local")) {
clientId = new StorageId(entity.getClientId(), entity.getExternalClientId()).getId();
}
ClientModel client = realm.getClientById(clientId);
PersistentClientSessionModel model = new PersistentClientSessionModel();
model.setClientId(clientId);
model.setUserSessionId(userSession.getId());
model.setUserId(userSession.getUserId());
model.setTimestamp(entity.getTimestamp());
model.setData(entity.getData());
return new PersistentAuthenticatedClientSessionAdapter(session, model, realm, client, userSession);
}
@Override
public int getUserSessionsCount(boolean offline) {
String offlineStr = offlineToString(offline);
Query query = em.createNamedQuery("findUserSessionsCount");
query.setParameter("offline", offlineStr);
Number n = (Number) query.getSingleResult();
return n.intValue();
}
@Override
public void close() {
}
private String offlineToString(boolean offline) {
return offline ? "1" : "0";
}
private boolean offlineFromString(String offlineStr) {
return "1".equals(offlineStr);
}
}
|
apache-2.0
|
sai-pullabhotla/catatumbo
|
src/test/java/com/jmethods/catatumbo/entities/StringListIndex2.java
|
2644
|
/*
* Copyright 2016 Sai Pullabhotla.
*
* 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.jmethods.catatumbo.entities;
import java.util.LinkedList;
import java.util.List;
import com.jmethods.catatumbo.Entity;
import com.jmethods.catatumbo.Identifier;
import com.jmethods.catatumbo.Property;
import com.jmethods.catatumbo.PropertyIndexer;
import com.jmethods.catatumbo.SecondaryIndex;
import com.jmethods.catatumbo.indexers.UpperCaseStringListIndexer;
/**
* @author Sai Pullabhotla
*
*/
@Entity(kind = "StringListIndex")
public class StringListIndex2 {
@Identifier
private long id;
@SecondaryIndex
private List<String> colors;
@SecondaryIndex
@PropertyIndexer(UpperCaseStringListIndexer.class)
private LinkedList<String> sizes;
@Property(name = "$colors")
private List<String> colorsIndex;
@Property(name = "$sizes")
private LinkedList<String> sizesIndex;
/**
* @return the id
*/
public long getId() {
return id;
}
/**
* @param id
* the id to set
*/
public void setId(long id) {
this.id = id;
}
/**
* @return the colors
*/
public List<String> getColors() {
return colors;
}
/**
* @param colors
* the colors to set
*/
public void setColors(List<String> colors) {
this.colors = colors;
}
/**
* @return the sizes
*/
public LinkedList<String> getSizes() {
return sizes;
}
/**
* @param sizes
* the sizes to set
*/
public void setSizes(LinkedList<String> sizes) {
this.sizes = sizes;
}
/**
* @return the colorsIndex
*/
public List<String> getColorsIndex() {
return colorsIndex;
}
/**
* @param colorsIndex
* the colorsIndex to set
*/
public void setColorsIndex(List<String> colorsIndex) {
this.colorsIndex = colorsIndex;
}
/**
* @return the sizesIndex
*/
public LinkedList<String> getSizesIndex() {
return sizesIndex;
}
/**
* @param sizesIndex
* the sizesIndex to set
*/
public void setSizesIndex(LinkedList<String> sizesIndex) {
this.sizesIndex = sizesIndex;
}
}
|
apache-2.0
|
stitchfix/flotilla-os
|
ui/src/components/__tests__/ListRequest.spec.tsx
|
8182
|
import * as React from "react"
import { mount, ReactWrapper } from "enzyme"
import { ListRequest, Props, ChildProps } from "../ListRequest"
import { RequestStatus } from "../Request"
import { SortOrder } from "../../types"
const DEFAULT_PROPS: Props<any, any> = {
requestStatus: RequestStatus.NOT_READY,
data: null,
isLoading: false,
error: null,
query: {},
request: (args: any) => {},
setQuery: (query: object, shouldReplace?: boolean) => {},
initialQuery: {},
getRequestArgs: (query: object) => {},
children: (props: ChildProps<any, any>) => <span />,
receivedAt: new Date(),
}
describe("ListRequest", () => {
it("calls props.setQuery w/ props.initialQuery if props.query is empty on componentDidMount", () => {
const realReq = ListRequest.prototype.request
ListRequest.prototype.request = jest.fn()
const setQuery = jest.fn()
const initialQuery = { foo: "bar" }
expect(setQuery).toHaveBeenCalledTimes(0)
mount(
<ListRequest
{...DEFAULT_PROPS}
initialQuery={initialQuery}
query={{}}
setQuery={setQuery}
>
{() => <span />}
</ListRequest>
)
expect(setQuery).toHaveBeenCalledTimes(1)
expect(setQuery).toHaveBeenCalledWith(initialQuery, true)
expect(ListRequest.prototype.request).toHaveBeenCalledTimes(0)
ListRequest.prototype.request = realReq
})
it("calls this.request if props.query is not empty on componentDidMount", () => {
const realReq = ListRequest.prototype.request
ListRequest.prototype.request = jest.fn()
const setQuery = jest.fn()
expect(setQuery).toHaveBeenCalledTimes(0)
expect(ListRequest.prototype.request).toHaveBeenCalledTimes(0)
const wrapper = mount(
<ListRequest
{...DEFAULT_PROPS}
query={{ foo: "bar" }}
setQuery={setQuery}
>
{() => <span />}
</ListRequest>
)
expect(setQuery).toHaveBeenCalledTimes(0)
expect(ListRequest.prototype.request).toHaveBeenCalledTimes(1)
ListRequest.prototype.request = realReq
})
it("calls this.request if prevProps.query and props.query are not equal on componentDidUpdate", () => {
const realReq = ListRequest.prototype.request
ListRequest.prototype.request = jest.fn()
expect(ListRequest.prototype.request).toHaveBeenCalledTimes(0)
const wrapper = mount(
<ListRequest {...DEFAULT_PROPS} query={{ foo: "bar" }}>
{() => <span />}
</ListRequest>
)
// Should have been called once when the component mounts.
expect(ListRequest.prototype.request).toHaveBeenCalledTimes(1)
wrapper.setProps({ query: { foo: "not-bar" } })
expect(ListRequest.prototype.request).toHaveBeenCalledTimes(2)
ListRequest.prototype.request = realReq
})
it("calls props.request with the correct args", () => {
const request = jest.fn()
const getRequestArgs = jest.fn(q => q)
const query = { foo: "bar" }
const wrapper = mount<ListRequest<any, any>>(
<ListRequest
{...DEFAULT_PROPS}
request={request}
getRequestArgs={getRequestArgs}
query={query}
>
{() => <span />}
</ListRequest>
)
const inst = wrapper.instance()
expect(request).toHaveBeenCalledTimes(1)
inst.request()
expect(request).toHaveBeenCalledTimes(2)
expect(request).toHaveBeenCalledWith(getRequestArgs(query))
})
it("calls props.children with the correct args", () => {
const realUpdateSort = ListRequest.prototype.updateSort
const realUpdatePage = ListRequest.prototype.updatePage
const realUpdateFilter = ListRequest.prototype.updateFilter
ListRequest.prototype.updateSort = jest.fn()
ListRequest.prototype.updatePage = jest.fn()
ListRequest.prototype.updateFilter = jest.fn()
const wrapper = mount<ListRequest<any, any>>(
<ListRequest {...DEFAULT_PROPS}>
{(props: ChildProps<any, any>) => (
<span>
<button
id="filter-btn"
onClick={() => {
props.updateFilter("foo", "bar")
}}
/>
<button
id="page-btn"
onClick={() => {
props.updatePage(10)
}}
/>
<button
id="sort-btn"
onClick={() => {
props.updateSort("a")
}}
/>
</span>
)}
</ListRequest>
)
// Test sort
expect(ListRequest.prototype.updateSort).toHaveBeenCalledTimes(0)
const sortButton = wrapper.find("#sort-btn")
sortButton.simulate("click")
expect(ListRequest.prototype.updateSort).toHaveBeenCalledTimes(1)
expect(ListRequest.prototype.updateSort).toHaveBeenCalledWith("a")
// Test page
expect(ListRequest.prototype.updateFilter).toHaveBeenCalledTimes(0)
const filterButton = wrapper.find("#filter-btn")
filterButton.simulate("click")
expect(ListRequest.prototype.updateFilter).toHaveBeenCalledTimes(1)
expect(ListRequest.prototype.updateFilter).toHaveBeenCalledWith(
"foo",
"bar"
)
// Test filter
expect(ListRequest.prototype.updatePage).toHaveBeenCalledTimes(0)
const pageButton = wrapper.find("#page-btn")
pageButton.simulate("click")
expect(ListRequest.prototype.updatePage).toHaveBeenCalledTimes(1)
expect(ListRequest.prototype.updatePage).toHaveBeenCalledWith(10)
ListRequest.prototype.updateSort = realUpdateSort
ListRequest.prototype.updatePage = realUpdatePage
ListRequest.prototype.updateFilter = realUpdateFilter
})
describe("query update methods", () => {
const setQuery = jest.fn()
let wrapper: ReactWrapper<any>
let instance: any
beforeEach(() => {
wrapper = mount<ListRequest<any, any>>(
<ListRequest {...DEFAULT_PROPS} setQuery={setQuery} query={{ a: 1 }}>
{() => <span />}
</ListRequest>
)
instance = wrapper.instance() as ListRequest<any, any>
})
afterEach(() => {
setQuery.mockReset()
})
it("updateSort calls setQuery with the correct arguments", () => {
// Note: we're manually setting the wrapper's query prop since we're
// mocking setQuery and it won't actually update the query.
expect(setQuery).toHaveBeenCalledTimes(0)
instance.updateSort("x")
expect(setQuery).toHaveBeenCalledTimes(1)
expect(setQuery).toHaveBeenCalledWith({
...wrapper.prop("query"),
page: 1,
sort_by: "x",
order: SortOrder.ASC,
})
wrapper.setProps({ query: { sort_by: "x", order: SortOrder.ASC } })
instance.updateSort("x")
expect(setQuery).toHaveBeenCalledTimes(2)
expect(setQuery).toHaveBeenCalledWith({
...wrapper.prop("query"),
page: 1,
sort_by: "x",
order: SortOrder.DESC,
})
wrapper.setProps({ query: { sort_by: "x", order: SortOrder.DESC } })
instance.updateSort("x")
expect(setQuery).toHaveBeenCalledTimes(3)
expect(setQuery).toHaveBeenCalledWith({
...wrapper.prop("query"),
page: 1,
sort_by: "x",
order: SortOrder.ASC,
})
wrapper.setProps({ query: { sort_by: "x", order: SortOrder.ASC } })
instance.updateSort("y")
expect(setQuery).toHaveBeenCalledTimes(4)
expect(setQuery).toHaveBeenCalledWith({
...wrapper.prop("query"),
page: 1,
sort_by: "y",
order: SortOrder.ASC,
})
})
it("updatePage calls setQuery with the correct arguments", () => {
expect(setQuery).toHaveBeenCalledTimes(0)
instance.updatePage(5000)
expect(setQuery).toHaveBeenCalledTimes(1)
expect(setQuery).toHaveBeenCalledWith({
...wrapper.prop("query"),
page: 5000,
})
})
it("updateFilter calls setQuery with the correct arguments", () => {
expect(setQuery).toHaveBeenCalledTimes(0)
instance.updateFilter("foo", "bar")
expect(setQuery).toHaveBeenCalledTimes(1)
expect(setQuery).toHaveBeenCalledWith({
...wrapper.prop("query"),
page: 1,
foo: "bar",
})
})
})
})
|
apache-2.0
|
AMWA-TV/maj
|
src/main/java/tv/amwa/maj/union/DefinitionCriteria.java
|
1618
|
/*
* Copyright 2016 Richard Cartwright
*
* 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.
*/
/*
* $Log: DefinitionCriteria.java,v $
* Revision 1.4 2011/01/04 10:39:03 vizigoth
* Refactor all package names to simpler forms more consistent with typical Java usage.
*
* Revision 1.3 2008/01/14 16:07:34 vizigoth
* Changed terminology for interfaces so that they all specify something.
*
* Revision 1.2 2008/01/09 12:24:53 vizigoth
* Edited javadoc comments to a release standard.
*
* Revision 1.1 2007/11/13 22:15:11 vizigoth
* Public release of MAJ API.
*/
package tv.amwa.maj.union;
/**
* <p>Specifies a criteria for matching a {@linkplain tv.amwa.maj.model.DefinitionObject definition} as
* determined by class, kind, name etc..</p>
*
* @see DefinitionCriteriaType
*
*
*/
public abstract interface DefinitionCriteria {
/**
* <p>Returns the type of definition criteria, which corresponds to the type of value used to
* define the criteria.</p>
*
* @return Definition criteria type.
*/
public DefinitionCriteriaType getDefinitionType();
}
|
apache-2.0
|
mingxinkejian/EGEngine
|
DB/EGIDB.php
|
939
|
<?php
namespace DB;
interface EGIDB {
/**
* 初始化数据库连接
* @param string $isMaster
*/
public function initConnection($isMaster=true);
/**
* 连接数据库
*/
public function connection($config,$connId=0);
/**
* 默认采用主库写,从库读,可以在配置文件中设置
* 分布式数据库连接
*/
public function multiConnection($isMaster=true);
/**
* 选择默认数据库
* @param string $dbName
*/
public function selectDB($dbName);
/**
* 释放查询结果
*/
public function freeResult();
/**
* 关闭数据库连接
*/
public function close();
/**
* 获取数据库错误
*/
public function getDBError();
/**
* 获取上一次执行sql的语句
*/
public function getLastSql();
/**
* 获取上一次插入数据的主键Id
*/
public function getLastId();
/**
* 取得当前数据库的表信息
*/
public function getTables();
}
|
apache-2.0
|
Wireless-Innovation-Forum/Spectrum-Access-System
|
src/harness/reference_models/tools/studies/dpa_margin_sim.py
|
38972
|
# Copyright 2018 SAS Project 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.
"""DPA move list and TH interference check simulator based on IPR configs.
This is a simulation of the DPA test harness process for purpose of analyzing
the pass/fail criteria of the test harness.
It has 2 modes of operations:
- standalone simulator: analysis of a IPR/MCP or reg/grant configuration.
- test harness log analyzer: analysis of DPA CSV logs produced during IPR/MCP runs.
Disclaimer:
====================
This simulator/analyzer is a tool provided for helping in the analyzis of the DPA
interference checks between reference model and SAS UUT.
Those interference checks have an inherently randomness to them, and this tool cannot
provide definite conclusion: it only provides some hints on why a test can fail
for randomness reasons although the SAS UUT perfectly implement a procedure fully in
compliance with Winnforum specification.
Extension of this tool may be required for a complete and proper analysis and in any
case engineering due diligence is still required before drawing meaningful conclusions.
Standard Simulator
==============================
This mode is selected when no "--log_file" option.
Under this mode it performs 2 type of analysis:
1. Standard single worst-case analysis (always).
Performs a "worst-case" interference check, and generates all related disk logs.
Because it looks at worst case, the SAS UUT is assumed to be a ref_model-like
move list algorithm providing the smallest move list (ie the most optimal one).
The 'ref model' move list can be chosen to be the biggest move list (default),
the median size move list or a composite "intersection based" move list.
2. Extensive interference analysis (optional with --do_extensive)
Performs many interference check without logs, and create scatter plots
analysing the required linear margin.
In that mode, the UUT move list is compared against each of the synthesized
ref move list, and all individual interference check displayed in scatter plots
and histogram.
Example simulation:
------------------
python dpa_margin_sim.py --num_process=3 --num_ml 20 --dpa West14 \
--dpa_builder "default(18,0,0,0)" \
--dpa_builder_uut "default(25,0,0,0)" \
--do_extensive \
--uut_ml_method min --uut_ml_num 10 \
data/ipr7_1kCBSDs.config
: Extensive simulation, on West14, with higher number of protected points in
UUT (UUT is best move list of 10), while reference move list spans all
20 randomly generated ones.
Test Harness Log Analyzer
===============================
This mode is entered when specifying the "--log_file" option.
Performs the analysis of results obtained during a test exercising the
DPA interference check.
Plots the move list and keep list of the SAS UUT versus reference models. Also
creates scatter and CDF plots of UUT vs reference margin for 3 types of analysis:
1. The reference move list versus the SAS UUT move list (ie as obtained during the test):
This is done by repeating many times the CheckInterference test and analyzing the
results variability and test success/failure caused by the Monte Carlo randomness
during that CheckInterference procedure.
If the original test has failed, but this check shows a small failure rate, this
original failure is most likely a false negative, just caused by the particular
Monte Carlo random draw.
2. Many newly generated reference move list versus the SAS UUT move list:
This is done by regenerating many reference move list (--num_ml), and then
analysing the failure/success statistics of each one of those versus the SAS UUT
move list.
This goes further from case 1, as it can detect "bad luck" scenarios where the
reference move list is not statistically representative.
3. Many newly generated reference move list versus a best case SAS UUT move list:
Similar to 2), but the SAS UUT move list is now generated by taking the smallest
size reference move list. This allows to get some hints when a SAS UUT move list
procedure seems to differ significantly from the Winnforum spec.
Note: Analysis 2 and 3 are only performed in `--do_extensive` option. In that case
a direct plot of the best case UUT versus real UUT is also provided in terms of
statistical behavior in terms of required margin.
Example analysis
------------------
python dpa_margin_sim.py \
--num_process=3 --num_ml 100 --do_extensive \
--log="output/2018-11-14 13_05_16 DPA=West14 channel=(3620.0, 3630.0) (neighbor list).csv" \
data/ipr5_5kCBSDs.config
: Analysis of log files of a test.
Internal statistical analysis will use 100 different regenerated ref move lists.
Notes on modeling capabilties:
===================================
By default will use the exact configuration of the json file for DPA. However
this can be overriden using some options:
--dpa <dpa_name>: specify an alternative DPA to use from the standard E-DPA/P-DPA KMLs.
--dpa_builder <"default(18,0,0,0,0)">: an alternative protected points builder.
Required if using --dpa option
--dpa_builder_uut <"default(25,0,0,0,0)">: an alternative builder for UUT only.
This is to further simulate a different UUT implementation using different
protected points.
Note that --dpa and --dpa_builder are required if using a grant-only config file.
Other parameters:
-----------------
--num_ml <10>: number of internal move list for variability analysing.
--ref_ml_method <method>: method used to generate the reference move list:
'min': use the minimum size move list
'max': use the maximum size move list
'med' or 'median': use the median size move list
'inter' or 'intersect': use the intersection of move lists (NIST method)
--ref_ml_num <num>: number of move lists to consider in above method. If 0,
then use --num_ml
--uut_ml_method and --uut_ml_num: same for UUT.
--do_extensive: extensive variability analysis mode. Produces advanced scatter
plots of UUT versus reference interference (across points and azimuth).
Misc notes:
-----------
- multiprocessing facility not tested on Windows. Use single process if experiencing
issues: `-num_process 1`.
- if warning reported on cached tiles swapping, increase the cache size with
option `--size_tile_cache XX`.
- use --seed <1234>: to specify a new random seed.
- in simulation mode, use --cache_file <filename>: to generate a pickled file
containing the DPA and move lists (as a tuple). This allows to reload this later
and rerun detailed analysis with different parameters in interactive sessions
(advanced use only).
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import copy
from six.moves import cPickle
import logging
import sys
import time
from absl import app
import matplotlib.pyplot as plt
import numpy as np
import shapely.geometry as sgeo
from six.moves import range
from reference_models.common import mpool
from reference_models.dpa import dpa_mgr
from reference_models.dpa import dpa_builder
from reference_models.dpa import move_list as ml
from reference_models.geo import drive
from reference_models.geo import zones
from reference_models.tools import sim_utils
# Utility functions
Db2Lin = dpa_mgr.Db2Lin
Lin2Db = dpa_mgr.Lin2Db
#----------------------------------------
# Setup the command line arguments
parser = argparse.ArgumentParser(description='DPA Simulator')
# - Generic config.
parser.add_argument('--seed', type=int, default=12, help='Random seed.')
parser.add_argument('--num_process', type=int, default=-1,
help='Number of parallel process. -2=all-1, -1=50%.')
parser.add_argument('--size_tile_cache', type=int, default=40,
help='Number of parallel process. -2=all-1, -1=50%.')
parser.add_argument('--log_level', type=str, default='info',
help='Logging level: debug, info, warning, error.')
# - DPA configuration
parser.add_argument('--dpa', type=str, default='',
help='Optional: override DPA to consider. Needs to specify '
'also the --dpa_builder')
parser.add_argument('--dpa_builder', type=str, default='',
help='Optional: override DPA builder to use '
'for generating DPA protected points. See BuildDpa().')
parser.add_argument('--dpa_builder_uut', type=str, default='',
help='Optional: override DPA builder to use '
'for generating DPA protected points for UUT.')
parser.add_argument('--dpa_kml', type=str, default='',
help='Optional: override DPA KML (use with --dpa only).')
parser.add_argument('--margin_db', type=str, default='',
help='Optional: override `movelistMargin`, for ex:`linear(1.5)`.')
parser.add_argument('--channel_freq_mhz', type=int, default=0,
help='Optional: the channel frequency to analyze (lower freq).')
# - Move list building methods
parser.add_argument('--ref_ml_method', type=str, default='max',
help='Method of reference move list: '
'`max`: max size move list, `med`: median size move list, '
'`min`: min size move list, `inter`: intersection of move lists')
parser.add_argument('--ref_ml_num', type=int, default=0,
help='Number of move list to use in --ref_ml_method.'
'0 means all, otherwise the specified number.')
parser.add_argument('--uut_ml_method', type=str, default='min',
help='Method of UUT move list: '
'`max`: max size move list, `med`: median size move list, '
'`min`: min size move list, `inter`: intersection of move lists')
parser.add_argument('--uut_ml_num', type=int, default=0,
help='Number of move list to use in --uut_ml_method.'
'0 means all, otherwise the specified number.')
# - Simulation/Analyzis parameters
parser.add_argument('--do_extensive', action='store_true',
help='Do extensive aggregate interference analysis '
'by checking all possible ref move list')
parser.add_argument('--num_ml', type=int, default=100,
help='Number of move list to compute.')
parser.add_argument('--cache_file', type=str, default='',
help='If defined, save simulation data to file. '
'Allows to rerun later detailed analysis')
parser.add_argument('config_file', type=str, default='',
help='The configuration file (IPR or MCP)')
# - Analyze mode
parser.add_argument('--log_file', type=str, default='',
help='The configuration file (IPR or MCP)')
_LOGGER_MAP = {
'info': logging.INFO,
'debug': logging.DEBUG,
'warning': logging.WARNING,
'error': logging.ERROR
}
# Simulation data saved to cache file when using --cache-file
def SaveDataToCache(cache_file, sim_data):
"""Save simulation data to pickled file."""
with open(cache_file, 'w') as fd:
cPickle.dump(sim_data, fd)
print('Simulation data saved to %s' % cache_file)
def SyntheticMoveList(ml_list, method, num, chan_idx):
"""Gets a synthetic move list from a list of them according to some criteria.
See options `ref_ml_method` and `ref_ml_num`.
"""
if num == 0: num = len(ml_list)
ml_size = [len(ml[chan_idx]) for ml in ml_list]
if method.startswith('med'):
# Median method (median size keep list)
median_idx = ml_size.index(np.percentile(ml_size[:num], 50,
interpolation='nearest'))
ref_ml = ml_list[median_idx]
elif method.startswith('max'):
# Max method (bigger move list, ie smallest keep list).
max_idx = np.argmax(ml_size[:num])
ref_ml = ml_list[max_idx]
elif method.startswith('min'):
# Min method (smaller move list, ie bigger keep list).
min_idx = np.argmin(ml_size[:num])
ref_ml = ml_list[min_idx]
elif method.startswith('int'):
# Intersection method (similar to method of Michael Souryal - NIST).
# One difference is that we do not remove xx% of extrema.
ref_ml = []
for chan in range(len(ml_list[0])):
ref_ml.append(set.intersection(*[ml_list[k][chan]
for k in range(num)]))
elif method.startswith('idx'):
idx = int(method.split('idx')[1])
ref_ml = ml_list[idx]
else:
raise ValueError('Ref ML method %d unsupported' % method)
return ref_ml
def ScatterAnalyze(ref_levels, diff_levels, threshold_db, tag):
"""Plots scatter graph of interference variation."""
if not ref_levels: return
ref_levels, diff_levels = np.asarray(ref_levels), np.asarray(diff_levels)
# Find the maximum variation in mW
diff_mw = Db2Lin(ref_levels + diff_levels) - Db2Lin(ref_levels)
max_diff_mw = np.max(diff_mw)
max_margin_db = Lin2Db(max_diff_mw + Db2Lin(threshold_db)) - threshold_db
print('Max difference: %g mw ==> %.3fdB (norm to %.0fdBm)' % (
max_diff_mw, max_margin_db, threshold_db))
print('Statistics: ')
max_diff_1_5 = Db2Lin(threshold_db + 1.5) - Db2Lin(threshold_db)
print(' < 1.5dB norm: %.4f%%' % (
np.count_nonzero(diff_mw < Db2Lin(threshold_db+1.5)-Db2Lin(threshold_db))
/ float(len(diff_mw)) * 100.))
print(' < 2.0dB norm: %.4f%%' % (
np.count_nonzero(diff_mw < Db2Lin(threshold_db+2.0)-Db2Lin(threshold_db))
/ float(len(diff_mw)) * 100.))
print(' < 2.5dB norm: %.4f%%' % (
np.count_nonzero(diff_mw < Db2Lin(threshold_db+2.5)-Db2Lin(threshold_db))
/ float(len(diff_mw)) * 100.))
print(' < 3.0dB norm: %.4f%%' % (
np.count_nonzero(diff_mw < Db2Lin(threshold_db+3.0)-Db2Lin(threshold_db))
/ float(len(diff_mw)) * 100.))
print(' < 3.5dB norm: %.4f%%' % (
np.count_nonzero(diff_mw < Db2Lin(threshold_db+3.5)-Db2Lin(threshold_db))
/ float(len(diff_mw)) * 100.))
# Plot the scatter plot
plt.figure()
plt.suptitle('Aggr Interf Delta - %s' % tag)
plt.subplot(211)
plt.grid(True)
plt.xlabel('Reference aggregate interference (dBm/10MHz)')
plt.ylabel('SAS UUT difference (dB)')
plt.scatter(ref_levels, diff_levels, c = 'r', marker='.', s=10)
margin_mw = Db2Lin(threshold_db + 1.5) - Db2Lin(threshold_db)
x_data = np.arange(min(ref_levels), max(ref_levels), 0.01)
plt.plot(x_data, Lin2Db(Db2Lin(x_data) + margin_mw) - x_data, 'b',
label='Fixed Linear Margin @1.5dB')
plt.plot(x_data, Lin2Db(Db2Lin(x_data) + max_diff_mw) - x_data, 'g',
label='Fixed Linear Margin @%.3fdB' % max_margin_db)
plt.legend()
plt.subplot(212)
margins_db = Lin2Db(diff_mw + Db2Lin(threshold_db)) - threshold_db
plt.grid(True)
plt.ylabel('Complement Log-CDF')
plt.xlabel('SAS UUT Normalized diff (dB to %ddBm)' % threshold_db)
sorted_margins_db = np.sort(margins_db)
sorted_margins_db = sorted_margins_db[sorted_margins_db > -5]
y_val = 1 - np.arange(len(margins_db), dtype=float) / len(margins_db)
if len(sorted_margins_db):
plt.plot(sorted_margins_db, y_val[-len(sorted_margins_db):])
plt.yscale('log', nonposy='clip')
def ExtensiveInterferenceCheck(dpa,
uut_keep_list, ref_move_lists,
ref_ml_num, ref_ml_method,
channel, chan_idx, tag=''):
"""Performs extensive interference check of UUT vs many reference move lists.
Args:
dpa: A reference |dpa_mgr.Dpa|.
uut_keep_list: The UUT keep list for the given channel.
ref_move_lists: A list of reference move lists.
ref_ml_num & ref_ml_method: The method for building the reference move list
used for interference check. See module documentation.
channel & chan_idx: The channels info.
Returns:
A tuple of 2 lists (ref_level, diff_levels) holding all the interference
results over each points, each azimuth and each synthesized reference move list.
"""
num_success = 0
ref_levels = []
diff_levels = []
start_time = time.time()
num_synth_ml = 1 if not ref_ml_num else ref_ml_num
num_check = len(ref_move_lists) - num_synth_ml + 1
for k in range(num_check):
dpa.move_lists = SyntheticMoveList(ref_move_lists[k:],
ref_ml_method, ref_ml_num,
chan_idx)
interf_results = []
num_success += dpa.CheckInterference(uut_keep_list, dpa.margin_db,
channel=channel,
extensive_print=False,
output_data=interf_results)
sys.stdout.write('.'); sys.stdout.flush()
for pt_res in interf_results:
if not pt_res.A_DPA_ref.shape: continue
ref_levels.extend(pt_res.A_DPA_ref)
diff_levels.extend(pt_res.A_DPA - pt_res.A_DPA_ref)
print(' Computation time: %.1fs' % (time.time() - start_time))
print('Extensive Interference Check: %d success / %d (%.3f%%)' % (
num_success, num_check, (100. * num_success) / num_check))
if not ref_levels:
print('Empty interference - Please check your setup')
ScatterAnalyze(ref_levels, diff_levels, dpa.threshold,
tag + 'DPA: %s' % dpa.name)
return np.asarray(ref_levels), np.asarray(diff_levels)
def PlotMoveListHistogram(move_lists, chan_idx):
"""Plots an histogram of move lists size."""
ref_ml_size = [len(ml[chan_idx]) for ml in move_lists]
plt.figure()
plt.hist(ref_ml_size)
plt.grid(True)
plt.xlabel('Count')
plt.ylabel('')
plt.title('Histogram of move list size across %d runs' % len(ref_ml_size))
def GetMostUsedChannel(dpa):
"""Gets the (channel, chan_idx) of the most used channel in |dpa_mgr.Dpa|."""
chan_idx = np.argmax([len(dpa.GetNeighborList(chan)) for chan in dpa._channels])
channel = dpa._channels[chan_idx]
return channel, chan_idx
def FindOrBuildDpa(dpas, options, grants):
"""Find or build DPA for simulation purpose.
If several DPA, select the one with most grants around (but DPA simulation
options always override the logic).
"""
if options.dpa:
dpa_kml_file = options.dpa_kml or None
dpa = None
if dpas:
for d in dpas:
if d.name.lower() == options.dpa.lower():
dpa = d
break
if not dpa:
print('Cannot find DPA in config - creating a default one')
dpa = dpa_mgr.BuildDpa(options.dpa, None, portal_dpa_filename=dpa_kml_file)
else:
if not dpas:
raise ValueError('Config file not defining a DPA and no --dpa option used.')
if len(dpas) == 1:
dpa = dpas[0]
else:
# Roughly find the DPA wth most CBSD within 200km
all_cbsds = sgeo.MultiPoint([(g.longitude, g.latitude) for g in grants])
num_cbsds_inside = [len(dpa.geometry.buffer(2.5).intersection(all_cbsds))
for dpa in dpas]
dpa = dpas[np.argmax(num_cbsds_inside)]
try: dpa.margin_db
except AttributeError:
dpa.margin_db = 'linear(1.5)'
try: dpa.geometry
except AttributeError:
try: dpa_geometry = zones.GetCoastalDpaZones()[dpa.name]
except KeyError: dpa_geometry = zones.GetPortalDpaZones(kml_path=dpa_kml_file)[dpa.name]
dpa.geometry = dpa_geometry.geometry
if options.dpa_builder:
dpa.protected_points = dpa_builder.DpaProtectionPoints(
dpa.name, dpa.geometry, options.dpa_builder)
if options.margin_db: # Override `movelistMargin` directive.
try: dpa.margin_db = float(options.margin_db)
except ValueError: dpa.margin_db = options.margin_db
return dpa
def SetupSimProcessor(num_process, size_tile_cache, geo_points, load_cache=False):
print('== Setup simulator resources - loading all terrain tiles..')
# Make sure terrain tiles loaded in main process memory.
# Then forking will make sure worker reuse those from shared memory (instead of
# reallocating and reloading the tiles) on copy-on-write system (Linux).
# TODO(sbdt): review this as it does not seem to really work.
# - disable workers
if load_cache:
num_workers = sim_utils.ConfigureRunningEnv(
num_process=0, size_tile_cache=size_tile_cache)
# - read some altitudes just to load the terrain tiles in main process memory
junk_alt = drive.terrain_driver.GetTerrainElevation(
[g.latitude for g in geo_points], [g.longitude for g in geo_points],
do_interp=False)
# - enable the workers
num_workers = sim_utils.ConfigureRunningEnv(
num_process=options.num_process, size_tile_cache=size_tile_cache)
if load_cache:
# Check cache is ok
sim_utils.CheckTerrainTileCacheOk() # Cache analysis and report
time.sleep(1)
return num_workers
#----------------------------------------------
# Utility routines for re-analyse from cache pickle dumps (advanced mode only).
# Usage:
# import dpa_margin_sim as dms
# sim_utils.ConfigureRunningEnv(-1, 40)
# sim_data = LoadDataFromCache(cache_file)
# CacheAnalyze(sim_data, 'max', 1, 'min', 100)
def LoadDataFromCache(cache_file):
"""Load simulation data from pickled file."""
with open(cache_file, 'r') as fd:
return cPickle.load(fd)
def CacheAnalyze(sim_data,
ref_ml_method, ref_ml_num,
uut_ml_method, uut_ml_num):
"""Extensive analyze from loaded simulation data. See module doc."""
dpa_ref = sim_data[0]
dpa_uut = sim_data[2]
channel, chan_idx = GetMostUsedChannel(dpa_ref)
dpa_uut.move_lists = SyntheticMoveList(sim_data[3],
uut_ml_method, uut_ml_num,
chan_idx)
uut_keep_list = dpa_uut.GetKeepList(channel)
ExtensiveInterferenceCheck(dpa_ref, uut_keep_list,
sim_data[1],
ref_ml_num, ref_ml_method,
channel, chan_idx)
plt.show(block=False)
#-----------------------------------------------------
# DPA aggregate interference variation simulator
def DpaSimulate(config_file, options):
"""Performs the DPA simulation."""
if options.seed is not None:
# reset the random seed
np.random.seed(options.seed)
logging.getLogger().setLevel(logging.WARNING)
# Read the input config file into ref model entities.
grants, dpas = sim_utils.ReadTestHarnessConfigFile(config_file)
# Select appropriate DPA or buid one from options.
dpa = FindOrBuildDpa(dpas, options, grants)
# Setup the simulator processor: number of processor and cache.
num_workers = SetupSimProcessor(options.num_process, options.size_tile_cache,
grants)
# Simulation start
print('Simulation with DPA `%s` (ref: %d pts):\n'
' %d granted CBSDs: %d CatB - %d CatA_out - %d CatA_in' % (
dpa.name, len(dpa.protected_points),
len(grants),
len([grant for grant in grants if grant.cbsd_category == 'B']),
len([grant for grant in grants
if grant.cbsd_category == 'A' and not grant.indoor_deployment]),
len([grant for grant in grants
if grant.cbsd_category == 'A' and grant.indoor_deployment])))
# Plot the entities.
ax, _ = sim_utils.CreateCbrsPlot(grants, dpa=dpa)
plt.show(block=False)
# Set the grants into DPA.
dpa.SetGrantsFromList(grants)
# Manages the number of move list to compute.
if options.dpa_builder_uut == options.dpa_builder:
options.dpa_builder_uut = ''
num_ref_ml = options.ref_ml_num or options.num_ml
num_uut_ml = options.uut_ml_num or options.num_ml
num_base_ml = (num_ref_ml if options.dpa_builder_uut
else max(num_ref_ml, num_uut_ml))
if options.do_extensive:
num_base_ml = max(num_base_ml, options.num_ml)
# Run the move list N times on ref DPA
print('Running Move List algorithm (%d workers): %d times' % (
num_workers, num_ref_ml))
start_time = time.time()
ref_move_list_runs = [] # Save the move list of each run
for k in range(num_base_ml):
dpa.ComputeMoveLists()
ref_move_list_runs.append(copy.copy(dpa.move_lists))
sys.stdout.write('.'); sys.stdout.flush()
# Plot the last move list on map.
for channel in dpa._channels:
move_list = dpa.GetMoveList(channel)
sim_utils.PlotGrants(ax, move_list, color='r')
# Now build the UUT dpa and move lists
dpa_uut = copy.copy(dpa)
uut_move_list_runs = ref_move_list_runs[:num_uut_ml]
if options.dpa_builder_uut:
dpa_uut.protected_points = dpa_builder.DpaProtectionPoints(
dpa_uut.name, dpa_uut.geometry, options.dpa_builder_uut)
# If UUT has its own parameters, simulate it by running it,
# otherwise reuse the move lists of the ref model.
uut_move_list_runs = []
for k in range(num_uut_ml):
dpa_uut.ComputeMoveLists()
uut_move_list_runs.append(copy.copy(dpa_uut.move_lists))
sys.stdout.write('+'); sys.stdout.flush()
ref_move_list_runs = ref_move_list_runs[:num_ref_ml]
print('\n Computation time: %.1fs' % (time.time() - start_time))
# Save data
if options.cache_file:
SaveDataToCache(options.cache_file,
(dpa, ref_move_list_runs,
dpa_uut, uut_move_list_runs,
options))
# Find a good channel to check: the one with maximum CBSDs.
channel, chan_idx = GetMostUsedChannel(dpa)
# Plot the move list sizes histogram for that channel.
PlotMoveListHistogram(ref_move_list_runs, chan_idx)
# Analyze aggregate interference. By default:
# + uut: taking smallest move list (ie bigger keep list)
# + ref: taking biggest move list (ie smallest keep list)
# or taking a median or intersection move list
# Hopefully (!) this is a good proxy for worst case scenarios.
#
# - enable log level - usually 'info' allows concise report.
logging.getLogger().setLevel(_LOGGER_MAP[options.log_level])
# - The ref case first
dpa.move_lists = SyntheticMoveList(ref_move_list_runs,
options.ref_ml_method, options.ref_ml_num,
chan_idx)
# - The UUT case
dpa_uut.move_lists = SyntheticMoveList(uut_move_list_runs,
options.uut_ml_method, options.uut_ml_num,
chan_idx)
uut_keep_list = dpa_uut.GetKeepList(channel)
start_time = time.time()
print('***** BASIC INTERFERENCE CHECK: size ref_ML=%d vs %d *****' % (
len(dpa.move_lists[chan_idx]), len(dpa_uut.move_lists[chan_idx])))
success = dpa.CheckInterference(uut_keep_list, dpa.margin_db, channel=channel,
extensive_print=True)
print(' Computation time: %.1fs' % (time.time() - start_time))
# Note: disable extensive logging for further extensive interference check
logging.getLogger().setLevel(logging.ERROR)
# Extensive mode: compare UUT against many ref model move list
if options.do_extensive:
print('***** EXTENSIVE INTERFERENCE CHECK *****')
ExtensiveInterferenceCheck(dpa, uut_keep_list, ref_move_list_runs,
options.ref_ml_num, options.ref_ml_method,
channel, chan_idx)
# Simulation finalization
print('')
sim_utils.CheckTerrainTileCacheOk() # Cache analysis and report
#-----------------------------------------------------
# DPA logs analyzer
def DpaAnalyzeLogs(config_file, log_file, options):
"""Analyze DPA logs through simulation."""
if options.seed is not None:
# reset the random seed
np.random.seed(options.seed)
logging.getLogger().setLevel(logging.WARNING)
# Read the input files: config and logs
if not log_file and config_file:
log_file = config_file
config_file = None
ref_nbor_list, ref_keep_list, uut_keep_list = sim_utils.ReadDpaLogFile(log_file)
if config_file:
grants, dpas = sim_utils.ReadTestHarnessConfigFile(config_file)
# For best robustness, make sure all coordinates are properly rounded, so the
# 2 sources of data can be exactly compared.
grants = [sim_utils.CleanGrant(g) for g in grants]
ref_nbor_list = [sim_utils.CleanGrant(g) for g in ref_nbor_list]
ref_keep_list = [sim_utils.CleanGrant(g) for g in ref_keep_list]
uut_keep_list = [sim_utils.CleanGrant(g) for g in uut_keep_list]
else:
grants, dpas = ref_nbor_list, []
ref_nbor_list = set(ref_nbor_list)
ref_keep_list = set(ref_keep_list)
uut_keep_list = set(uut_keep_list)
no_peers = not ref_nbor_list and uut_keep_list
if no_peers:
print('NOTE: MCP test with no peer SAS.')
if options.dpa_builder_uut and options.dpa_builder_uut != options.dpa_builder:
print(' Option --dpa_builder_uut unsupported in analyze mode: Ignored.')
if not grants:
raise ValueError('No grants specified - use a valid config file.')
# Find reference DPA for analyzis.
dpa = FindOrBuildDpa(dpas, options, grants)
# Setup the simulator processor: number of processor and cache.
num_workers = SetupSimProcessor(options.num_process, options.size_tile_cache,
uut_keep_list)
# Set the grants into DPA.
print('== Initialize DPA, one reference move list and misc.')
print(' Num grants in cfg: %s' % (len(grants) if config_file else 'No Cfg'))
print(' Num grants in logs: nbor_l=%d ref_kl_all=%d uut_kl=%d' % (
len(ref_nbor_list), len(ref_keep_list), len(uut_keep_list)))
dpa.SetGrantsFromList(grants)
if options.channel_freq_mhz:
dpa.ResetFreqRange([(options.channel_freq_mhz, options.channel_freq_mhz+10)])
dpa.ComputeMoveLists()
# Note: disable extensive logging for further extensive interference check.
logging.getLogger().setLevel(logging.ERROR)
# Find a good channel to check: the one with maximum CBSDs.
channel, chan_idx = GetMostUsedChannel(dpa)
nbor_list = dpa.GetNeighborList(channel)
move_list = dpa.GetMoveList(channel)
keep_list = dpa.GetKeepList(channel)
print(' DPA for analyze: %s' % dpa.name)
print(' Channel for analyze: %s' % (channel,))
print(' Recalc on chan: nbor_l=%d kl=%d' % (len(nbor_list), len(keep_list)))
# Initial step - plot CBSD on maps: UUT keep list vs ref model keep list
print('== Plot relevant lists on map.')
# Plot the entities.
print(' Plotting Map: Nbor list and keep list for channel %s' % (channel,))
uut_move_list_uut = [g for g in nbor_list
if g.is_managed_grant and g not in uut_keep_list]
move_list_uut = [g for g in move_list if g.is_managed_grant]
move_list_other = [g for g in move_list if not g.is_managed_grant]
if len(ref_nbor_list):
ref_move_list = nbor_list.difference(ref_keep_list)
ref_move_list_uut = [g for g in ref_move_list if g.is_managed_grant]
ref_move_list_other = [g for g in ref_move_list if not g.is_managed_grant]
ax1, fig = sim_utils.CreateCbrsPlot(nbor_list, dpa=dpa, tag='Test Ref ', subplot=121)
sim_utils.PlotGrants(ax1, ref_move_list_other, color='m')
sim_utils.PlotGrants(ax1, ref_move_list_uut, color='r')
ax2, _ = sim_utils.CreateCbrsPlot(nbor_list, dpa=dpa, tag='Test UUT ', subplot=122, fig=fig)
sim_utils.PlotGrants(ax2, ref_move_list_other, color='m')
sim_utils.PlotGrants(ax2, uut_move_list_uut, color='r')
fig.suptitle('Neighbor and move list from Test Log - Chan %s' % (channel,))
ax1, fig = sim_utils.CreateCbrsPlot(nbor_list, dpa=dpa, tag='Calc Ref ', subplot=121)
sim_utils.PlotGrants(ax1, move_list_other, color='m')
sim_utils.PlotGrants(ax1, move_list_uut, color='r')
ax2, _ = sim_utils.CreateCbrsPlot(nbor_list, dpa=dpa, tag='Test UUT ', subplot=122, fig=fig)
sim_utils.PlotGrants(ax2, ref_move_list_other, color='m')
sim_utils.PlotGrants(ax2, uut_move_list_uut, color='r')
fig.suptitle('Neighbor and move list from Calc + UUT Log - Chan %s' % (channel,))
plt.show(block=False)
# Manages the number of move list to compute.
num_ref_ml = options.ref_ml_num or options.num_ml
num_uut_ml = options.num_ml
num_base_ml = max(num_ref_ml, num_uut_ml)
# Summary of the analyze.
print('== Analysing DPA `%s` (ref: %d pts) on Channel %s:\n'
' %d total grants (all channels)\n'
' %d CBSDs in neighbor list: %d CatB - %d CatA_out - %d CatA_in\n' % (
dpa.name, len(dpa.protected_points), channel,
len(grants),
len(nbor_list),
len([grant for grant in nbor_list if grant.cbsd_category == 'B']),
len([grant for grant in nbor_list
if grant.cbsd_category == 'A' and not grant.indoor_deployment]),
len([grant for grant in nbor_list
if grant.cbsd_category == 'A' and grant.indoor_deployment])))
# Analyze aggregate interference of TEST-REF vs SAS_UUT keep list
# ie we repeat the Check N times but with the same ML
if len(ref_nbor_list):
start_time = time.time()
num_check = max(10, num_base_ml // 2)
print('***** Re-testing REAL SAS UUT vs %d TEST-REF move list *****' % (num_check))
print(' Same ref move list each time from TEST - only interference check is random. ')
full_ref_move_list_runs = [None] * len(dpa._channels)
full_ref_move_list_runs[chan_idx] = nbor_list.difference(ref_keep_list)
many_ref_move_list_runs = [full_ref_move_list_runs] * num_check
ExtensiveInterferenceCheck(dpa, uut_keep_list, many_ref_move_list_runs,
1, 'max', channel, chan_idx,
tag='REAL-REF vs REAL-UUT (%dML) - ' % num_check)
print(' Computation time: %.1fs' % (time.time() - start_time))
if not options.do_extensive:
return
# Run the move list N times on ref DPA
print('***** From now on: analysing against fresh ref move lists *****')
print('Modes of operation:\n'
' UUT ref - Real or best of %d (smallest size)\n'
' Against %d different ref move list obtained through method: %s of %d\n' % (
num_uut_ml, num_ref_ml, options.ref_ml_method, max(options.ref_ml_num, 1)))
print('First computing %d reference move lists (%d workers)' % (num_ref_ml, num_workers))
start_time = time.time()
ref_move_list_runs = [] # Save the move list of each run
for k in range(num_base_ml):
dpa.ComputeMoveLists()
ref_move_list_runs.append(copy.copy(dpa.move_lists))
sys.stdout.write('.'); sys.stdout.flush()
# Now build the UUT dpa and move lists
dpa_uut = copy.copy(dpa)
uut_move_list_runs = ref_move_list_runs[:num_uut_ml]
ref_move_list_runs = ref_move_list_runs[:num_ref_ml]
print('\n Computation time: %.1fs' % (time.time() - start_time))
# Save data
if options.cache_file:
SaveDataToCache(options.cache_file,
(dpa, ref_move_list_runs,
dpa_uut, uut_move_list_runs,
options))
# Plot the move list sizes histogram for that channel.
PlotMoveListHistogram(ref_move_list_runs, chan_idx)
# Analyze aggregate interference of SAS_UUT keep list vs new reference
# ie we check the SAS UUT versus many recomputed reference ML
start_time = time.time()
print('***** REAL SAS UUT vs %d random reference move list *****' % num_ref_ml)
print(' Every ref move list regenerated through move list process (+ %s of %d method)' % (
options.ref_ml_method, max(options.ref_ml_num, 1)))
real_levels, real_diffs = ExtensiveInterferenceCheck(
dpa, uut_keep_list, ref_move_list_runs,
options.ref_ml_num, options.ref_ml_method,
channel, chan_idx,
tag='Rand-Ref vs REAL-UUT (%dML) - ' % num_ref_ml)
print(' Computation time: %.1fs' % (time.time() - start_time))
# Analyze aggregate interference of best SAS_UUT keep list vs new reference
# ie we smallest size ML versus many recomputed reference ML (like in std simulation).
start_time = time.time()
print('***** GOOD SAS UUT vs %d random reference move list *****' % num_ref_ml)
print(' Every ref move list regenerated through move list process (+ %s of %d method)' % (
options.ref_ml_method, max(options.ref_ml_num, 1)))
print(' SAS UUT move list taken with method: %s of %d' % (
options.uut_ml_method, options.uut_ml_num or len(ref_move_list_runs)))
dpa_uut.move_lists = SyntheticMoveList(ref_move_list_runs,
options.uut_ml_method, options.uut_ml_num,
chan_idx)
uut_keep_list = dpa_uut.GetKeepList(channel)
good_levels, good_diffs = ExtensiveInterferenceCheck(
dpa, uut_keep_list, ref_move_list_runs,
options.ref_ml_num, options.ref_ml_method,
channel, chan_idx,
tag='Rand-Ref vs Good UUT (%dML) - ' % num_ref_ml)
print(' Computation time: %.1fs' % (time.time() - start_time))
# Show on same graph the Real UUT CDF vs Good UUT CDF
real_diff_mw = Db2Lin(real_levels + real_diffs) - Db2Lin(real_levels)
real_margins_db = Lin2Db(real_diff_mw + Db2Lin(dpa.threshold)) - dpa.threshold
sorted_real_margins_db = np.sort(real_margins_db)
good_diff_mw = Db2Lin(good_levels + good_diffs) - Db2Lin(good_levels)
good_margins_db = Lin2Db(good_diff_mw + Db2Lin(dpa.threshold)) - dpa.threshold
sorted_good_margins_db = np.sort(good_margins_db)
plt.figure()
plt.title('CDF of Agg Interf Delta: REAL UUT vs GOOD UUT')
plt.grid(True)
plt.ylabel('Complement Log-CDF')
plt.xlabel('SAS UUT Normalized diff (dB to %ddBm)' % dpa.threshold)
y_val = 1 - np.arange(len(real_levels), dtype=float) / len(real_levels)
sorted_good_margins_db = sorted_good_margins_db[sorted_good_margins_db > -1]
sorted_real_margins_db = sorted_real_margins_db[sorted_real_margins_db > -1]
if len(sorted_good_margins_db):
plt.plot(sorted_good_margins_db, y_val[-len(sorted_good_margins_db):],
color='g', label='Good ML')
if len(sorted_real_margins_db):
plt.plot(sorted_real_margins_db, y_val[-len(sorted_real_margins_db):],
color='b', label='Real ML')
plt.yscale('log', nonposy='clip')
plt.legend()
#---------------------------
# The simulation
if __name__ == '__main__':
options = parser.parse_args()
if options.log_file or options.config_file.endswith('csv'):
print('Analyzing log files')
DpaAnalyzeLogs(options.config_file, options.log_file, options)
else:
print('Running DPA simulator')
DpaSimulate(options.config_file, options)
plt.show(block=True)
|
apache-2.0
|
Pkcs11Interop/Pkcs11Interop
|
src/Pkcs11Interop/HighLevelAPI41/MechanismParams/CkPkcs5Pbkd2Params.cs
|
6134
|
/*
* Copyright 2012-2021 The Pkcs11Interop 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.
*/
/*
* Written for the Pkcs11Interop project by:
* Jaroslav IMRICH <jimrich@jimrich.sk>
*/
using System;
using Net.Pkcs11Interop.Common;
using Net.Pkcs11Interop.HighLevelAPI.MechanismParams;
using Net.Pkcs11Interop.LowLevelAPI41.MechanismParams;
using NativeULong = System.UInt32;
// Note: Code in this file is maintained manually.
namespace Net.Pkcs11Interop.HighLevelAPI41.MechanismParams
{
/// <summary>
/// Parameters for the CKM_PKCS5_PBKD2 mechanism
/// </summary>
public class CkPkcs5Pbkd2Params : ICkPkcs5Pbkd2Params
{
/// <summary>
/// Flag indicating whether instance has been disposed
/// </summary>
private bool _disposed = false;
/// <summary>
/// Low level mechanism parameters
/// </summary>
private CK_PKCS5_PBKD2_PARAMS _lowLevelStruct = new CK_PKCS5_PBKD2_PARAMS();
/// <summary>
/// Initializes a new instance of the CkPkcs5Pbkd2Params class.
/// </summary>
/// <param name='saltSource'>Source of the salt value (CKZ)</param>
/// <param name='saltSourceData'>Data used as the input for the salt source</param>
/// <param name='iterations'>Number of iterations to perform when generating each block of random data</param>
/// <param name='prf'>Pseudo-random function to used to generate the key (CKP)</param>
/// <param name='prfData'>Data used as the input for PRF in addition to the salt value</param>
/// <param name='password'>Password to be used in the PBE key generation</param>
public CkPkcs5Pbkd2Params(NativeULong saltSource, byte[] saltSourceData, NativeULong iterations, NativeULong prf, byte[] prfData, byte[] password)
{
_lowLevelStruct.SaltSource = 0;
_lowLevelStruct.SaltSourceData = IntPtr.Zero;
_lowLevelStruct.SaltSourceDataLen = 0;
_lowLevelStruct.Iterations = 0;
_lowLevelStruct.Prf = 0;
_lowLevelStruct.PrfData = IntPtr.Zero;
_lowLevelStruct.PrfDataLen = 0;
_lowLevelStruct.Password = IntPtr.Zero;
_lowLevelStruct.PasswordLen = IntPtr.Zero;
_lowLevelStruct.SaltSource = saltSource;
if (saltSourceData != null)
{
_lowLevelStruct.SaltSourceData = UnmanagedMemory.Allocate(saltSourceData.Length);
UnmanagedMemory.Write(_lowLevelStruct.SaltSourceData, saltSourceData);
_lowLevelStruct.SaltSourceDataLen = ConvertUtils.UInt32FromInt32(saltSourceData.Length);
}
_lowLevelStruct.Iterations = iterations;
_lowLevelStruct.Prf = prf;
if (prfData != null)
{
_lowLevelStruct.PrfData = UnmanagedMemory.Allocate(prfData.Length);
UnmanagedMemory.Write(_lowLevelStruct.PrfData, prfData);
_lowLevelStruct.PrfDataLen = ConvertUtils.UInt32FromInt32(prfData.Length);
}
if (password != null)
{
_lowLevelStruct.Password = UnmanagedMemory.Allocate(password.Length);
UnmanagedMemory.Write(_lowLevelStruct.Password, password);
NativeULong passwordLength = ConvertUtils.UInt32FromInt32(password.Length);
_lowLevelStruct.PasswordLen = UnmanagedMemory.Allocate(UnmanagedMemory.SizeOf(typeof(NativeULong)));
UnmanagedMemory.Write(_lowLevelStruct.PasswordLen, BitConverter.GetBytes(passwordLength));
}
}
#region IMechanismParams
/// <summary>
/// Returns managed object that can be marshaled to an unmanaged block of memory
/// </summary>
/// <returns>A managed object holding the data to be marshaled. This object must be an instance of a formatted class.</returns>
public object ToMarshalableStructure()
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
return _lowLevelStruct;
}
#endregion
#region IDisposable
/// <summary>
/// Disposes object
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes object
/// </summary>
/// <param name="disposing">Flag indicating whether managed resources should be disposed</param>
protected virtual void Dispose(bool disposing)
{
if (!this._disposed)
{
if (disposing)
{
// Dispose managed objects
}
// Dispose unmanaged objects
UnmanagedMemory.Free(ref _lowLevelStruct.SaltSourceData);
_lowLevelStruct.SaltSourceDataLen = 0;
UnmanagedMemory.Free(ref _lowLevelStruct.PrfData);
_lowLevelStruct.PrfDataLen = 0;
UnmanagedMemory.Free(ref _lowLevelStruct.Password);
UnmanagedMemory.Free(ref _lowLevelStruct.PasswordLen);
_disposed = true;
}
}
/// <summary>
/// Class destructor that disposes object if caller forgot to do so
/// </summary>
~CkPkcs5Pbkd2Params()
{
Dispose(false);
}
#endregion
}
}
|
apache-2.0
|
chiaming0914/awe-cpp-sdk
|
aws-cpp-sdk-appstream/source/AppStreamErrors.cpp
|
3193
|
/*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/core/client/AWSError.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/appstream/AppStreamErrors.h>
using namespace Aws::Client;
using namespace Aws::AppStream;
using namespace Aws::Utils;
namespace Aws
{
namespace AppStream
{
namespace AppStreamErrorMapper
{
static const int RESOURCE_IN_USE_HASH = HashingUtils::HashString("ResourceInUseException");
static const int RESOURCE_ALREADY_EXISTS_HASH = HashingUtils::HashString("ResourceAlreadyExistsException");
static const int LIMIT_EXCEEDED_HASH = HashingUtils::HashString("LimitExceededException");
static const int INVALID_ROLE_HASH = HashingUtils::HashString("InvalidRoleException");
static const int CONCURRENT_MODIFICATION_HASH = HashingUtils::HashString("ConcurrentModificationException");
static const int INCOMPATIBLE_IMAGE_HASH = HashingUtils::HashString("IncompatibleImageException");
static const int RESOURCE_NOT_AVAILABLE_HASH = HashingUtils::HashString("ResourceNotAvailableException");
static const int OPERATION_NOT_PERMITTED_HASH = HashingUtils::HashString("OperationNotPermittedException");
AWSError<CoreErrors> GetErrorForName(const char* errorName)
{
int hashCode = HashingUtils::HashString(errorName);
if (hashCode == RESOURCE_IN_USE_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(AppStreamErrors::RESOURCE_IN_USE), false);
}
else if (hashCode == RESOURCE_ALREADY_EXISTS_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(AppStreamErrors::RESOURCE_ALREADY_EXISTS), false);
}
else if (hashCode == LIMIT_EXCEEDED_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(AppStreamErrors::LIMIT_EXCEEDED), false);
}
else if (hashCode == INVALID_ROLE_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(AppStreamErrors::INVALID_ROLE), false);
}
else if (hashCode == CONCURRENT_MODIFICATION_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(AppStreamErrors::CONCURRENT_MODIFICATION), false);
}
else if (hashCode == INCOMPATIBLE_IMAGE_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(AppStreamErrors::INCOMPATIBLE_IMAGE), false);
}
else if (hashCode == RESOURCE_NOT_AVAILABLE_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(AppStreamErrors::RESOURCE_NOT_AVAILABLE), false);
}
else if (hashCode == OPERATION_NOT_PERMITTED_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(AppStreamErrors::OPERATION_NOT_PERMITTED), false);
}
return AWSError<CoreErrors>(CoreErrors::UNKNOWN, false);
}
} // namespace AppStreamErrorMapper
} // namespace AppStream
} // namespace Aws
|
apache-2.0
|
ifnul/ums-backend
|
is-lnu-service/src/main/java/org/lnu/is/extractor/department/specialty/DepartmentSpecialtyParametersExtractor.java
|
1179
|
package org.lnu.is.extractor.department.specialty;
import java.util.Map;
import javax.annotation.Resource;
import org.lnu.is.annotations.ParametersExtractor;
import org.lnu.is.dao.dao.Dao;
import org.lnu.is.domain.department.Department;
import org.lnu.is.domain.department.specialty.DepartmentSpecialty;
import org.lnu.is.domain.specialty.Specialty;
import org.lnu.is.extractor.AbstractParametersExtractor;
/**
* Department Specialty parameters parameters extractor.
* @author ivanursul
*
*/
@ParametersExtractor("departmentSpecialtyParametersExtractor")
public class DepartmentSpecialtyParametersExtractor extends AbstractParametersExtractor<DepartmentSpecialty> {
@Resource(name = "departmentDao")
private Dao<Department, Department, Long> departmentDao;
@Resource(name = "specialtyDao")
private Dao<Specialty, Specialty, Long> specialtyDao;
@Override
protected Map<String, Object> getParameters(final DepartmentSpecialty entity, final Map<String, Object> parameters) {
addParameter(entity.getDepartment(), departmentDao, "department", parameters);
addParameter(entity.getSpecialty(), specialtyDao, "specialty", parameters);
return parameters;
}
}
|
apache-2.0
|
googleapis/google-cloud-go
|
pubsublite/internal/wire/errors.go
|
2276
|
// Copyright 2020 Google LLC
//
// 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
//
// https://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
package wire
import (
"errors"
"fmt"
"golang.org/x/xerrors"
)
// Errors exported from this package.
var (
// ErrOverflow indicates that the publish buffers have overflowed. See
// comments for PublishSettings.BufferedByteLimit.
ErrOverflow = errors.New("pubsublite: client-side publish buffers have overflowed")
// ErrOversizedMessage indicates that the user published a message over the
// allowed serialized byte size limit. It is wrapped in another error.
ErrOversizedMessage = fmt.Errorf("maximum allowed message size is MaxPublishRequestBytes (%d)", MaxPublishRequestBytes)
// ErrServiceUninitialized indicates that a service (e.g. publisher or
// subscriber) cannot perform an operation because it is uninitialized.
ErrServiceUninitialized = errors.New("pubsublite: service must be started")
// ErrServiceStarting indicates that a service (e.g. publisher or subscriber)
// cannot perform an operation because it is starting up.
ErrServiceStarting = errors.New("pubsublite: service is starting up")
// ErrServiceStopped indicates that a service (e.g. publisher or subscriber)
// cannot perform an operation because it has stopped or is in the process of
// stopping.
ErrServiceStopped = errors.New("pubsublite: service has stopped or is stopping")
// ErrBackendUnavailable indicates that the backend service has been
// unavailable for a period of time. The timeout can be configured using
// PublishSettings.Timeout or ReceiveSettings.Timeout.
ErrBackendUnavailable = errors.New("pubsublite: backend service is unavailable")
)
func wrapError(context, resource string, err error) error {
if err != nil {
return xerrors.Errorf("%s(%s): %w", context, resource, err)
}
return err
}
|
apache-2.0
|
jaxio/celerio
|
celerio-engine/src/test/java/com/jaxio/celerio/aspects/GraphPredicateAspect.java
|
1520
|
/*
* Copyright 2015 JAXIO http://www.jaxio.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jaxio.celerio.aspects;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import static org.springframework.beans.factory.config.BeanDefinition.SCOPE_PROTOTYPE;
@Service
@Scope(SCOPE_PROTOTYPE)
@Slf4j
public class GraphPredicateAspect {
private static int depth = 0;
@Around("com.jaxio.celerio.aspects.PredicatesAspect.methods()")
public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
depth++;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < depth; i++) {
sb.append(' ');
}
sb.append(pjp.getSignature());
log.info(sb.toString());
Object retVal = pjp.proceed();
depth--;
return retVal;
}
}
|
apache-2.0
|
LindaLawton/Google-Dotnet-Samples
|
Samples/Drive API/v2/PermissionsSample.cs
|
18201
|
// Copyright 2017 DAIMTO ([Linda Lawton](https://twitter.com/LindaLawtonDK)) : [www.daimto.com](http://www.daimto.com/)
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
// an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by DAIMTO-Google-apis-Sample-generator 1.0.0
// Template File Name: methodTemplate.tt
// Build date: 2017-10-08
// C# generater version: 1.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
// About
//
// Unoffical sample for the Drive v2 API for C#.
// This sample is designed to be used with the Google .Net client library. (https://github.com/google/google-api-dotnet-client)
//
// API Description: Manages files in Drive including uploading, downloading, searching, detecting changes, and updating sharing permissions.
// API Documentation Link https://developers.google.com/drive/
//
// Discovery Doc https://www.googleapis.com/discovery/v1/apis/Drive/v2/rest
//
//------------------------------------------------------------------------------
// Installation
//
// This sample code uses the Google .Net client library (https://github.com/google/google-api-dotnet-client)
//
// NuGet package:
//
// Location: https://www.nuget.org/packages/Google.Apis.Drive.v2/
// Install Command: PM> Install-Package Google.Apis.Drive.v2
//
//------------------------------------------------------------------------------
using Google.Apis.Drive.v2;
using Google.Apis.Drive.v2.Data;
using System;
namespace GoogleSamplecSharpSample.Drivev2.Methods
{
public static class PermissionsSample
{
public class PermissionsDeleteOptionalParms
{
/// Whether the requesting application supports Team Drives.
public bool? SupportsTeamDrives { get; set; }
}
/// <summary>
/// Deletes a permission from a file or Team Drive.
/// Documentation https://developers.google.com/drive/v2/reference/permissions/delete
/// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong.
/// </summary>
/// <param name="service">Authenticated Drive service.</param>
/// <param name="fileId">The ID for the file or Team Drive.</param>
/// <param name="permissionId">The ID for the permission.</param>
/// <param name="optional">Optional paramaters.</param>
public static void Delete(DriveService service, string fileId, string permissionId, PermissionsDeleteOptionalParms optional = null)
{
try
{
// Initial validation.
if (service == null)
throw new ArgumentNullException("service");
if (fileId == null)
throw new ArgumentNullException(fileId);
if (permissionId == null)
throw new ArgumentNullException(permissionId);
// Building the initial request.
var request = service.Permissions.Delete(fileId, permissionId);
// Applying optional parameters to the request.
request = (PermissionsResource.DeleteRequest)SampleHelpers.ApplyOptionalParms(request, optional);
// Requesting data.
request.Execute();
}
catch (Exception ex)
{
throw new Exception("Request Permissions.Delete failed.", ex);
}
}
public class PermissionsGetOptionalParms
{
/// Whether the requesting application supports Team Drives.
public bool? SupportsTeamDrives { get; set; }
}
/// <summary>
/// Gets a permission by ID.
/// Documentation https://developers.google.com/drive/v2/reference/permissions/get
/// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong.
/// </summary>
/// <param name="service">Authenticated Drive service.</param>
/// <param name="fileId">The ID for the file or Team Drive.</param>
/// <param name="permissionId">The ID for the permission.</param>
/// <param name="optional">Optional paramaters.</param>
/// <returns>PermissionResponse</returns>
public static Permission Get(DriveService service, string fileId, string permissionId, PermissionsGetOptionalParms optional = null)
{
try
{
// Initial validation.
if (service == null)
throw new ArgumentNullException("service");
if (fileId == null)
throw new ArgumentNullException(fileId);
if (permissionId == null)
throw new ArgumentNullException(permissionId);
// Building the initial request.
var request = service.Permissions.Get(fileId, permissionId);
// Applying optional parameters to the request.
request = (PermissionsResource.GetRequest)SampleHelpers.ApplyOptionalParms(request, optional);
// Requesting data.
return request.Execute();
}
catch (Exception ex)
{
throw new Exception("Request Permissions.Get failed.", ex);
}
}
/// <summary>
/// Returns the permission ID for an email address.
/// Documentation https://developers.google.com/drive/v2/reference/permissions/getIdForEmail
/// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong.
/// </summary>
/// <param name="service">Authenticated Drive service.</param>
/// <param name="email">The email address for which to return a permission ID</param>
/// <returns>PermissionIdResponse</returns>
public static PermissionId GetIdForEmail(DriveService service, string email)
{
try
{
// Initial validation.
if (service == null)
throw new ArgumentNullException("service");
if (email == null)
throw new ArgumentNullException(email);
// Make the request.
return service.Permissions.GetIdForEmail(email).Execute();
}
catch (Exception ex)
{
throw new Exception("Request Permissions.GetIdForEmail failed.", ex);
}
}
public class PermissionsInsertOptionalParms
{
/// A custom message to include in notification emails.
public string EmailMessage { get; set; }
/// Whether to send notification emails when sharing to users or groups. This parameter is ignored and an email is sent if the role is owner.
public bool? SendNotificationEmails { get; set; }
/// Whether the requesting application supports Team Drives.
public bool? SupportsTeamDrives { get; set; }
}
/// <summary>
/// Inserts a permission for a file or Team Drive.
/// Documentation https://developers.google.com/drive/v2/reference/permissions/insert
/// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong.
/// </summary>
/// <param name="service">Authenticated Drive service.</param>
/// <param name="fileId">The ID for the file or Team Drive.</param>
/// <param name="body">A valid Drive v2 body.</param>
/// <param name="optional">Optional paramaters.</param>
/// <returns>PermissionResponse</returns>
public static Permission Insert(DriveService service, string fileId, Permission body, PermissionsInsertOptionalParms optional = null)
{
try
{
// Initial validation.
if (service == null)
throw new ArgumentNullException("service");
if (body == null)
throw new ArgumentNullException("body");
if (fileId == null)
throw new ArgumentNullException(fileId);
// Building the initial request.
var request = service.Permissions.Insert(body, fileId);
// Applying optional parameters to the request.
request = (PermissionsResource.InsertRequest)SampleHelpers.ApplyOptionalParms(request, optional);
// Requesting data.
return request.Execute();
}
catch (Exception ex)
{
throw new Exception("Request Permissions.Insert failed.", ex);
}
}
public class PermissionsListOptionalParms
{
/// The maximum number of permissions to return per page. When not set for files in a Team Drive, at most 100 results will be returned. When not set for files that are not in a Team Drive, the entire list will be returned.
public int? MaxResults { get; set; }
/// The token for continuing a previous list request on the next page. This should be set to the value of 'nextPageToken' from the previous response.
public string PageToken { get; set; }
/// Whether the requesting application supports Team Drives.
public bool? SupportsTeamDrives { get; set; }
}
/// <summary>
/// Lists a file's or Team Drive's permissions.
/// Documentation https://developers.google.com/drive/v2/reference/permissions/list
/// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong.
/// </summary>
/// <param name="service">Authenticated Drive service.</param>
/// <param name="fileId">The ID for the file or Team Drive.</param>
/// <param name="optional">Optional paramaters.</param>
/// <returns>PermissionListResponse</returns>
public static PermissionList List(DriveService service, string fileId, PermissionsListOptionalParms optional = null)
{
try
{
// Initial validation.
if (service == null)
throw new ArgumentNullException("service");
if (fileId == null)
throw new ArgumentNullException(fileId);
// Building the initial request.
var request = service.Permissions.List(fileId);
// Applying optional parameters to the request.
request = (PermissionsResource.ListRequest)SampleHelpers.ApplyOptionalParms(request, optional);
// Requesting data.
return request.Execute();
}
catch (Exception ex)
{
throw new Exception("Request Permissions.List failed.", ex);
}
}
public class PermissionsPatchOptionalParms
{
/// Whether to remove the expiration date.
public bool? RemoveExpiration { get; set; }
/// Whether the requesting application supports Team Drives.
public bool? SupportsTeamDrives { get; set; }
/// Whether changing a role to 'owner' downgrades the current owners to writers. Does nothing if the specified role is not 'owner'.
public bool? TransferOwnership { get; set; }
}
/// <summary>
/// Updates a permission using patch semantics.
/// Documentation https://developers.google.com/drive/v2/reference/permissions/patch
/// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong.
/// </summary>
/// <param name="service">Authenticated Drive service.</param>
/// <param name="fileId">The ID for the file or Team Drive.</param>
/// <param name="permissionId">The ID for the permission.</param>
/// <param name="body">A valid Drive v2 body.</param>
/// <param name="optional">Optional paramaters.</param>
/// <returns>PermissionResponse</returns>
public static Permission Patch(DriveService service, string fileId, string permissionId, Permission body, PermissionsPatchOptionalParms optional = null)
{
try
{
// Initial validation.
if (service == null)
throw new ArgumentNullException("service");
if (body == null)
throw new ArgumentNullException("body");
if (fileId == null)
throw new ArgumentNullException(fileId);
if (permissionId == null)
throw new ArgumentNullException(permissionId);
// Building the initial request.
var request = service.Permissions.Patch(body, fileId, permissionId);
// Applying optional parameters to the request.
request = (PermissionsResource.PatchRequest)SampleHelpers.ApplyOptionalParms(request, optional);
// Requesting data.
return request.Execute();
}
catch (Exception ex)
{
throw new Exception("Request Permissions.Patch failed.", ex);
}
}
public class PermissionsUpdateOptionalParms
{
/// Whether to remove the expiration date.
public bool? RemoveExpiration { get; set; }
/// Whether the requesting application supports Team Drives.
public bool? SupportsTeamDrives { get; set; }
/// Whether changing a role to 'owner' downgrades the current owners to writers. Does nothing if the specified role is not 'owner'.
public bool? TransferOwnership { get; set; }
}
/// <summary>
/// Updates a permission.
/// Documentation https://developers.google.com/drive/v2/reference/permissions/update
/// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong.
/// </summary>
/// <param name="service">Authenticated Drive service.</param>
/// <param name="fileId">The ID for the file or Team Drive.</param>
/// <param name="permissionId">The ID for the permission.</param>
/// <param name="body">A valid Drive v2 body.</param>
/// <param name="optional">Optional paramaters.</param>
/// <returns>PermissionResponse</returns>
public static Permission Update(DriveService service, string fileId, string permissionId, Permission body, PermissionsUpdateOptionalParms optional = null)
{
try
{
// Initial validation.
if (service == null)
throw new ArgumentNullException("service");
if (body == null)
throw new ArgumentNullException("body");
if (fileId == null)
throw new ArgumentNullException(fileId);
if (permissionId == null)
throw new ArgumentNullException(permissionId);
// Building the initial request.
var request = service.Permissions.Update(body, fileId, permissionId);
// Applying optional parameters to the request.
request = (PermissionsResource.UpdateRequest)SampleHelpers.ApplyOptionalParms(request, optional);
// Requesting data.
return request.Execute();
}
catch (Exception ex)
{
throw new Exception("Request Permissions.Update failed.", ex);
}
}
}
public static class SampleHelpers
{
/// <summary>
/// Using reflection to apply optional parameters to the request.
///
/// If the optonal parameters are null then we will just return the request as is.
/// </summary>
/// <param name="request">The request. </param>
/// <param name="optional">The optional parameters. </param>
/// <returns></returns>
public static object ApplyOptionalParms(object request, object optional)
{
if (optional == null)
return request;
System.Reflection.PropertyInfo[] optionalProperties = (optional.GetType()).GetProperties();
foreach (System.Reflection.PropertyInfo property in optionalProperties)
{
// Copy value from optional parms to the request. They should have the same names and datatypes.
System.Reflection.PropertyInfo piShared = (request.GetType()).GetProperty(property.Name);
if (property.GetValue(optional, null) != null) // TODO Test that we do not add values for items that are null
piShared.SetValue(request, property.GetValue(optional, null), null);
}
return request;
}
}
}
|
apache-2.0
|
vmware/tosca-vcloud-plugin
|
tests/unittests/test_mock_base.py
|
12694
|
# Copyright (c) 2014 GigaSpaces Technologies Ltd. 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.
import mock
import unittest
from cloudify import mocks as cfy_mocks
from network_plugin import BUSY_MESSAGE, NAT_ROUTED
class TestBase(unittest.TestCase):
ERROR_PLACE = "ERROR_MESSAGE_PLACE_HOLDER"
def generate_task(self, status):
task = mock.Mock()
error = mock.Mock()
error.get_message = mock.MagicMock(return_value="Some Error")
task.get_Error = mock.MagicMock(return_value=error)
task.get_status = mock.MagicMock(return_value=status)
return task
def set_services_conf_result(self, gateway, result):
"""
set result for save configuration
"""
task = None
if result:
task = self.generate_task(result)
gateway.save_services_configuration = mock.MagicMock(
return_value=task
)
def set_gateway_busy(self, gateway):
message = gateway.response.content
message = message.replace(
self.ERROR_PLACE, BUSY_MESSAGE
)
gateway.response.content = message
def prepare_retry(self, ctx):
"""
set fake retry operation
"""
ctx.operation.retry = mock.MagicMock(
return_value=None
)
def check_retry_realy_called(self, ctx):
"""
check that we really call retry
"""
ctx.operation.retry.assert_called_with(
message='Waiting for gateway.',
retry_after=10
)
def generate_gateway(
self, vdc_name="vdc", vms_networks=None, vdc_networks=None
):
gate = mock.Mock()
gate.get_dhcp_pools = mock.MagicMock(return_value=[
self.genarate_pool(
vdc_name, '127.0.0.1', '127.0.0.255'
)
])
gate.add_dhcp_pool = mock.MagicMock(return_value=None)
self.set_services_conf_result(gate, None)
gate.response = mock.Mock()
gate.response.content = ('''
<?xml version="1.0" encoding="UTF-8"?>
<Error
xmlns="http://www.vmware.com/vcloud/v1.5"
status="stoped"
name="error"
message="''' + self.ERROR_PLACE + '''"
/>''').replace("\n", " ").strip()
# list of interfaces
interfaces = []
if vms_networks:
for network in vms_networks:
interface = mock.Mock()
interface.get_Name = mock.MagicMock(
return_value=network.get(
'network_name', 'unknowNet'
)
)
interfaces.append(interface)
gate.get_interfaces = mock.MagicMock(
return_value=interfaces
)
# firewall enabled
gate.is_fw_enabled = mock.MagicMock(return_value=True)
# dont have any nat rules
gate.get_nat_rules = mock.MagicMock(return_value=[])
# cant deallocate ip
gate.deallocate_public_ip = mock.MagicMock(return_value=None)
# public ips not exist
gate.get_public_ips = mock.MagicMock(return_value=[])
return gate
def generate_fake_client_network(
self, fenceMode=None, name="some", start_ip="127.1.1.1",
end_ip="127.1.1.255"
):
"""
generate network for vca client
"""
network = mock.Mock()
# generate ip
network._ip = mock.Mock()
network._ip.get_StartAddress = mock.MagicMock(return_value=start_ip)
network._ip.get_EndAddress = mock.MagicMock(return_value=end_ip)
# generate ipRange
network._ip_range = mock.Mock()
network._ip_range.IpRanges.IpRange = [network._ip]
# network get_network_configuration
network._network_config = mock.Mock()
network._network_config.get_FenceMode = mock.MagicMock(
return_value=fenceMode
)
# network scope
network.Configuration.IpScopes.IpScope = [network._ip_range]
# network
network.get_name = mock.MagicMock(return_value=name)
network.get_Configuration = mock.MagicMock(
return_value=network._network_config
)
return network
def generate_nat_rule(
self, rule_type, original_ip, original_port, translated_ip,
translated_port, protocol
):
rule = mock.Mock()
rule.get_OriginalIp = mock.MagicMock(return_value=original_ip)
rule.get_OriginalPort = mock.MagicMock(return_value=original_port)
rule.get_TranslatedIp = mock.MagicMock(return_value=translated_ip)
rule.get_TranslatedPort = mock.MagicMock(return_value=translated_port)
rule.get_Protocol = mock.MagicMock(return_value=protocol)
rule_inlist = mock.Mock()
rule_inlist.get_RuleType = mock.MagicMock(return_value=rule_type)
rule_inlist.get_GatewayNatRule = mock.MagicMock(return_value=rule)
return rule_inlist
def genarate_pool(self, name, low_ip, high_ip):
pool = mock.Mock()
pool.Network = mock.Mock()
pool.Network.name = name
pool.get_LowIpAddress = mock.MagicMock(return_value=low_ip)
pool.get_HighIpAddress = mock.MagicMock(return_value=high_ip)
# network in pool
network = mock.Mock()
network.get_href = mock.MagicMock(
return_value="_href" + name
)
pool.get_Network = mock.MagicMock(return_value=network)
return pool
def set_network_routed_in_client(self, fake_client):
"""
set any network as routed
"""
network = self.generate_fake_client_network(NAT_ROUTED)
fake_client.get_network = mock.MagicMock(return_value=network)
def generate_fake_client_disk(self, name="some_disk"):
"""
generate fake disk for fake client,
have used in client.get_disks
"""
disk = mock.Mock()
disk.name = name
return disk
def generate_fake_client_disk_ref(self, name):
"""
generate ref for disk,
have used for client.get_diskRefs
"""
ref = mock.Mock()
ref.name = name
return ref
def generate_fake_vms_disk(self, name="some_disk"):
"""
generate attached vms for disk,
have used for client.get_disks
"""
vms = mock.Mock()
vms._disk = name
return vms
def generate_client(self, vms_networks=None, vdc_networks=None):
def _generate_fake_client_network(vdc_name, network_name):
return self.generate_fake_client_network(network_name)
def _get_admin_network_href(vdc_name, network_name):
return "_href" + network_name
def _get_gateway(vdc_name="vdc"):
return self.generate_gateway(
vdc_name,
vms_networks,
vdc_networks
)
def _get_gateways(vdc_name):
return [_get_gateway(vdc_name)]
def _get_vdc(networks):
vdc = mock.Mock()
vdc.AvailableNetworks = mock.Mock()
vdc.AvailableNetworks.Network = []
if networks:
for net in networks:
networkEntity = mock.Mock()
networkEntity.name = net
vdc.AvailableNetworks.Network.append(networkEntity)
return vdc
template = mock.Mock()
template.get_name = mock.MagicMock(return_value='secret')
catalogItems = mock.Mock()
catalogItems.get_CatalogItem = mock.MagicMock(
return_value=[template]
)
catalog = mock.Mock()
catalog.get_name = mock.MagicMock(return_value='public')
catalog.get_CatalogItems = mock.MagicMock(
return_value=catalogItems
)
client = mock.Mock()
client.get_catalogs = mock.MagicMock(return_value=[catalog])
client.get_network = _generate_fake_client_network
client.get_networks = mock.MagicMock(return_value=[])
client.get_admin_network_href = _get_admin_network_href
client._vdc_gateway = _get_gateway()
client.get_gateway = mock.MagicMock(
return_value=client._vdc_gateway
)
client.get_gateways = _get_gateways
client._vapp = self.generate_vapp(vms_networks)
client.get_vapp = mock.MagicMock(return_value=client._vapp)
client._app_vdc = _get_vdc(vdc_networks)
client.get_vdc = mock.MagicMock(return_value=client._app_vdc)
client.delete_vdc_network = mock.MagicMock(
return_value=(False, None)
)
client.create_vdc_network = mock.MagicMock(
return_value=(False, None)
)
# disks for client
client.add_disk = mock.MagicMock(
return_value=(False, None)
)
client.get_disks = mock.MagicMock(return_value=[])
client.add_disk = mock.MagicMock(
return_value=(False, None)
)
client.delete_disk = mock.MagicMock(
return_value=(False, None)
)
client.get_diskRefs = mock.MagicMock(return_value=[])
# login authification
client.login = mock.MagicMock(
return_value=False
)
client.logout = mock.MagicMock(
return_value=False
)
client.get_instances = mock.MagicMock(
return_value=[]
)
client.login_to_instance = mock.MagicMock(
return_value=False
)
client.login_to_org = mock.MagicMock(
return_value=False
)
return client
def generate_vca(self):
return mock.MagicMock(return_value=self.generate_client())
def generate_vapp(self, vms_networks=None):
def _get_vms_network_info():
return [vms_networks]
vapp = mock.Mock()
vapp.me = mock.Mock()
vapp.get_vms_network_info = _get_vms_network_info
# disk for vapp
vapp.attach_disk_to_vm = mock.MagicMock(
return_value=None
)
vapp.detach_disk_from_vm = mock.MagicMock(
return_value=None
)
# mememory/cpu customize
vapp.modify_vm_memory = mock.MagicMock(
return_value=None
)
vapp.modify_vm_cpu = mock.MagicMock(
return_value=None
)
return vapp
def generate_relation_context(self):
source = mock.Mock()
source.node = mock.Mock()
target = mock.Mock()
target.node = mock.Mock()
target.instance.runtime_properties = {}
fake_ctx = cfy_mocks.MockCloudifyContext(
source=source, target=target
)
return fake_ctx
def generate_node_context(
self, relation_node_properties=None, properties=None,
runtime_properties=None
):
class MockInstanceContext(cfy_mocks.MockNodeInstanceContext):
self._relationships = None
@property
def relationships(self):
return self._relationships
if not properties:
properties = {
'management_network': '_management_network',
'vcloud_config': {
'vdc': 'vdc_name'
}
}
if not runtime_properties:
runtime_properties = {
'vcloud_vapp_name': 'vapp_name'
}
fake_ctx = cfy_mocks.MockCloudifyContext(
node_id='test',
node_name='test',
properties=properties,
provider_context={},
runtime_properties=runtime_properties
)
fake_ctx._instance = MockInstanceContext(
fake_ctx.instance._id, fake_ctx.instance._runtime_properties
)
relationship = self.generate_relation_context()
relationship._target.node.properties = relation_node_properties
fake_ctx.instance._relationships = [relationship]
return fake_ctx
|
apache-2.0
|
pacogomez/pyvcloud
|
pyvcloud/vcd/vdc.py
|
33031
|
# VMware vCloud Director Python SDK
# Copyright (c) 2014 VMware, 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.
from lxml import etree
from pyvcloud.vcd.client import E
from pyvcloud.vcd.client import get_links
from pyvcloud.vcd.client import E_OVF
from pyvcloud.vcd.client import EntityType
from pyvcloud.vcd.client import NSMAP
from pyvcloud.vcd.client import RelationType
from pyvcloud.vcd.client import find_link
from pyvcloud.vcd.org import Org
from pyvcloud.vcd.utils import access_control_settings_to_dict
from pyvcloud.vcd.utils import get_admin_extension_href
from pyvcloud.vcd.utils import get_admin_href
import pprint
class VDC(object):
def __init__(self, client, name=None, href=None, resource=None):
self.client = client
self.name = name
self.href = href
self.resource = resource
if resource is not None:
self.name = resource.get('name')
self.href = resource.get('href')
self.href_admin = get_admin_href(self.href)
def get_resource(self):
if self.resource is None:
self.resource = self.client.get_resource(self.href)
return self.resource
def get_resource_href(self, name, entity_type=EntityType.VAPP):
if self.resource is None:
self.resource = self.client.get_resource(self.href)
result = []
if hasattr(self.resource, 'ResourceEntities') and \
hasattr(self.resource.ResourceEntities, 'ResourceEntity'):
for vapp in self.resource.ResourceEntities.ResourceEntity:
if entity_type is None or \
entity_type.value == vapp.get('type'):
if vapp.get('name') == name:
result.append(vapp.get('href'))
if len(result) == 0:
raise Exception('not found')
elif len(result) > 1:
raise Exception('more than one found, use the vapp-id')
return result[0]
def reload(self):
self.resource = self.client.get_resource(self.href)
if self.resource is not None:
self.name = self.resource.get('name')
self.href = self.resource.get('href')
def get_vapp(self, name):
return self.client.get_resource(self.get_resource_href(name))
def delete_vapp(self, name, force=False):
href = self.get_resource_href(name)
return self.client.delete_resource(href, force)
# NOQA refer to http://pubs.vmware.com/vcd-820/index.jsp?topic=%2Fcom.vmware.vcloud.api.sp.doc_27_0%2FGUID-BF9B790D-512E-4EA1-99E8-6826D4B8E6DC.html
def instantiate_vapp(self,
name,
catalog,
template,
network=None,
fence_mode='bridged',
ip_allocation_mode='dhcp',
deploy=True,
power_on=True,
accept_all_eulas=False,
memory=None,
cpu=None,
disk_size=None,
password=None,
cust_script=None,
vm_name=None,
hostname=None,
storage_profile=None):
"""Instantiate a vApp from a vApp template in a catalog.
If customization parameters are provided, it will customize the VM and
guest OS, taking some assumptions.
See each parameter for details.
:param name: (str): The name of the new vApp.
:param catalog: (str): The name of the catalog.
:param template: (str): The name of the vApp template.
:param network: (str): The name of a VDC network.
When provided, connects the VM to the network.
It assumes one VM in the vApp and one NIC in the VM.
:param fence_mode: (str): Fence mode.
Possible values are `bridged` and `natRouted`
:param ip_allocation_mode: (str): IP allocation mode.
Possible values are `pool`, `dhcp` and `static`
:param deploy: (bool):
:param power_on: (bool):
:param accept_all_eulas: (bool): True confirms acceptance of all EULAs
in a vApp template.
:param memory: (int):
:param cpu: (int):
:param disk_size: (int):
:param password: (str):
:param cust_script: (str):
:param vm_name: (str): When provided, set the name of the VM.
It assumes one VM in the vApp.
:param hostname: (str): When provided, set the hostname of the guest
OS. It assumes one VM in the vApp.
:param storage_profile: (str):
:return: A :class:`lxml.objectify.StringElement` object describing the
new vApp.
"""
if self.resource is None:
self.resource = self.client.get_resource(self.href)
# Get hold of the template
org_href = find_link(self.resource, RelationType.UP,
EntityType.ORG.value).href
org = Org(self.client, href=org_href)
catalog_item = org.get_catalog_item(catalog, template)
template_resource = self.client.get_resource(
catalog_item.Entity.get('href'))
# If network is not specified by user then default to
# vApp network name specified in the template
template_networks = template_resource.xpath(
'//ovf:NetworkSection/ovf:Network',
namespaces={
'ovf': NSMAP['ovf']
})
assert len(template_networks) > 0
network_name_from_template = template_networks[0].get(
'{' + NSMAP['ovf'] + '}name')
if ((network is None) and (network_name_from_template != 'none')):
network = network_name_from_template
# Find the network in vdc referred to by user, using
# name of the network
network_href = network_name = None
if network is not None:
if hasattr(self.resource, 'AvailableNetworks') and \
hasattr(self.resource.AvailableNetworks, 'Network'):
for n in self.resource.AvailableNetworks.Network:
if network == n.get('name'):
network_href = n.get('href')
network_name = n.get('name')
break
if network_href is None:
raise Exception(
'Network \'%s\' not found in the Virtual Datacenter.' %
network)
# Configure the network of the vApp
vapp_instantiation_param = None
if network_name is not None:
network_configuration = E.Configuration(
E.ParentNetwork(href=network_href), E.FenceMode(fence_mode))
if fence_mode == 'natRouted':
# TODO(need to find the vm_id)
vm_id = None
network_configuration.append(
E.Features(
E.NatService(
E.IsEnabled('true'), E.NatType('ipTranslation'),
E.Policy('allowTraffic'),
E.NatRule(
E.OneToOneVmRule(
E.MappingMode('automatic'),
E.VAppScopedVmId(vm_id), E.VmNicId(0))))))
vapp_instantiation_param = E.InstantiationParams(
E.NetworkConfigSection(
E_OVF.Info('Configuration for logical networks'),
E.NetworkConfig(
network_configuration, networkName=network_name)))
# Get all vms in the vapp template
vms = template_resource.xpath(
'//vcloud:VAppTemplate/vcloud:Children/vcloud:Vm',
namespaces=NSMAP)
assert len(vms) > 0
vm_instantiation_param = E.InstantiationParams()
# Configure network of the first vm
if network_name is not None:
primary_index = int(vms[
0].NetworkConnectionSection.PrimaryNetworkConnectionIndex.text)
vm_instantiation_param.append(
E.NetworkConnectionSection(
E_OVF.Info(
'Specifies the available VM network connections'),
E.NetworkConnection(
E.NetworkConnectionIndex(primary_index),
E.IsConnected('true'),
E.IpAddressAllocationMode(ip_allocation_mode.upper()),
network=network_name)))
# Configure cpu, memory, disk of the first vm
cpu_params = memory_params = disk_params = None
if memory is not None or cpu is not None or disk_size is not None:
virtual_hardware_section = E_OVF.VirtualHardwareSection(
E_OVF.Info('Virtual hardware requirements'))
items = vms[0].xpath(
'//ovf:VirtualHardwareSection/ovf:Item',
namespaces={
'ovf': NSMAP['ovf']
})
for item in items:
if memory is not None and memory_params is None:
if item['{' + NSMAP['rasd'] + '}ResourceType'] == 4:
item['{' + NSMAP['rasd'] +
'}ElementName'] = '%s MB of memory' % memory
item['{' + NSMAP['rasd'] + '}VirtualQuantity'] = memory
memory_params = item
virtual_hardware_section.append(memory_params)
if cpu is not None and cpu_params is None:
if item['{' + NSMAP['rasd'] + '}ResourceType'] == 3:
item['{' + NSMAP['rasd'] +
'}ElementName'] = '%s virtual CPU(s)' % cpu
item['{' + NSMAP['rasd'] + '}VirtualQuantity'] = cpu
cpu_params = item
virtual_hardware_section.append(cpu_params)
if disk_size is not None and disk_params is None:
if item['{' + NSMAP['rasd'] + '}ResourceType'] == 17:
item['{' + NSMAP['rasd'] + '}Parent'] = None
item['{' + NSMAP['rasd'] + '}HostResource'].attrib[
'{' + NSMAP['vcloud'] +
'}capacity'] = '%s' % disk_size
item['{' + NSMAP['rasd'] +
'}VirtualQuantity'] = disk_size * 1024 * 1024
disk_params = item
virtual_hardware_section.append(disk_params)
vm_instantiation_param.append(virtual_hardware_section)
# Configure guest customization for the vm
if password is not None or cust_script is not None or \
hostname is not None:
guest_customization_param = E.GuestCustomizationSection(
E_OVF.Info('Specifies Guest OS Customization Settings'),
E.Enabled('true'),
)
if password is None:
guest_customization_param.append(
E.AdminPasswordEnabled('false'))
else:
guest_customization_param.append(
E.AdminPasswordEnabled('true'))
guest_customization_param.append(E.AdminPasswordAuto('false'))
guest_customization_param.append(E.AdminPassword(password))
guest_customization_param.append(
E.ResetPasswordRequired('false'))
if cust_script is not None:
guest_customization_param.append(
E.CustomizationScript(cust_script))
if hostname is not None:
guest_customization_param.append(E.ComputerName(hostname))
vm_instantiation_param.append(guest_customization_param)
# Craft the <SourcedItem> element for the first VM
sourced_item = E.SourcedItem(
E.Source(
href=vms[0].get('href'),
id=vms[0].get('id'),
name=vms[0].get('name'),
type=vms[0].get('type')))
vm_general_params = E.VmGeneralParams()
if vm_name is not None:
vm_general_params.append(E.Name(vm_name))
# TODO(check if it needs customization if network, cpu or memory...)
if disk_size is None and \
password is None and \
cust_script is None and \
hostname is None:
needs_customization = 'false'
else:
needs_customization = 'true'
vm_general_params.append(E.NeedsCustomization(needs_customization))
sourced_item.append(vm_general_params)
sourced_item.append(vm_instantiation_param)
if storage_profile is not None:
sp = self.get_storage_profile(storage_profile)
vapp_storage_profile = E.StorageProfile(
href=sp.get('href'),
id=sp.get('href').split('/')[-1],
type=sp.get('type'),
name=sp.get('name'))
sourced_item.append(vapp_storage_profile)
# Cook the entire vApp Template instantiation element
deploy_param = 'true' if deploy else 'false'
power_on_param = 'true' if power_on else 'false'
all_eulas_accepted = 'true' if accept_all_eulas else 'false'
vapp_template_params = E.InstantiateVAppTemplateParams(
name=name, deploy=deploy_param, powerOn=power_on_param)
if vapp_instantiation_param is not None:
vapp_template_params.append(vapp_instantiation_param)
vapp_template_params.append(
E.Source(href=catalog_item.Entity.get('href')))
vapp_template_params.append(sourced_item)
vapp_template_params.append(E.AllEULAsAccepted(all_eulas_accepted))
# TODO(use post_linked_resource?)
return self.client.post_resource(
self.href + '/action/instantiateVAppTemplate',
vapp_template_params,
EntityType.INSTANTIATE_VAPP_TEMPLATE_PARAMS.value)
def list_resources(self, entity_type=None):
if self.resource is None:
self.resource = self.client.get_resource(self.href)
result = []
if hasattr(self.resource, 'ResourceEntities') and \
hasattr(self.resource.ResourceEntities, 'ResourceEntity'):
for vapp in self.resource.ResourceEntities.ResourceEntity:
if entity_type is None or \
entity_type.value == vapp.get('type'):
result.append({'name': vapp.get('name')})
return result
def list_edge_gateways(self):
"""
Request a list of edge gateways defined in a vdc.
:return: An array of the existing edge gateways.
""" # NOQA
if self.resource is None:
self.resource = self.client.get_resource(self.href)
links = self.client.get_linked_resource(self.resource,
RelationType.EDGE_GATEWAYS,
EntityType.RECORDS.value)
edge_gateways = []
for e in links.EdgeGatewayRecord:
edge_gateways.append({'name': e.get('name'), 'href': e.get('href')})
return edge_gateways
def create_disk(self,
name,
size,
bus_type=None,
bus_sub_type=None,
description=None,
storage_profile_name=None,
iops=None):
"""Request the creation of an indendent disk.
:param name: (str): The name of the new disk.
:param size: (int): The size of the new disk in bytes.
:param bus_type: (str): The bus type of the new disk.
:param bus_subtype: (str): The bus subtype of the new disk.
:param description: (str): A description of the new disk.
:param storage_profile_name: (str): The name of an existing \
storage profile to be used by the new disk.
:param iops: (int): Iops requirement of the new disk.
:return: A :class:`lxml.objectify.StringElement` object containing \
the sparse representation of the new disk and the asynchronus \
Task that is creating the disk.
"""
if self.resource is None:
self.resource = self.client.get_resource(self.href)
disk_params = E.DiskCreateParams(E.Disk(name=name, size=str(size)))
if iops is not None:
disk_params.Disk.set('iops', iops)
if description is not None:
disk_params.Disk.append(E.Description(description))
if bus_type is not None and bus_sub_type is not None:
disk_params.Disk.set('busType', bus_type)
disk_params.Disk.set('busSubType', bus_sub_type)
if storage_profile_name is not None:
storage_profile = self.get_storage_profile(storage_profile_name)
disk_params.Disk.append(E.StorageProfile(
name=storage_profile_name,
href=storage_profile.get('href'),
type=storage_profile.get('type')))
return self.client.post_linked_resource(
self.resource, RelationType.ADD,
EntityType.DISK_CREATE_PARMS.value, disk_params)
def update_disk(self,
name=None,
disk_id=None,
new_name=None,
new_size=None,
new_description=None,
new_storage_profile_name=None,
new_iops=None):
"""Update an existing independent disk.
:param name: (str): The name of the existing disk.
:param disk_id: (str): The id of the existing disk.
:param new_name: (str): The new name of the disk
:param new_size: (int): The new size of the disk in bytes.
:param new_description: (str): The new description of the disk.
:param new_storage_profile_name: (str): The new storage profile that \
the disk will be moved to.
:param new_iops: (int): The new iops requirement of the disk.
:return: A :class:`lxml.objectify.StringElement` object describing \
the asynchronous Task updating the disk.
:raises: Exception: If the named disk cannot be located or some \
other error occurs.
"""
if self.resource is None:
self.resource = self.client.get_resource(self.href)
if disk_id is not None:
disk = self.get_disk(disk_id=disk_id)
else:
disk = self.get_disk(name=name)
disk_params = E.Disk()
if new_name is not None:
disk_params.set('name', new_name)
else:
disk_params.set('name', disk.get('name'))
if new_size is not None:
disk_params.set('size', str(new_size))
else:
disk_params.set('size', disk.get('size'))
if new_description is not None:
disk_params.append(E.Description(new_description))
if new_storage_profile_name is not None:
new_sp = self.get_storage_profile(new_storage_profile_name)
disk_params.append(E.StorageProfile(
name=new_storage_profile_name,
href=new_sp.get('href'),
type=new_sp.get('type')))
if new_iops is not None:
disk_params.set('iops', str(new_iops))
return self.client.put_linked_resource(
disk, RelationType.EDIT, EntityType.DISK.value, disk_params)
def delete_disk(self, name=None, disk_id=None):
"""Delete an existing independent disk.
:param name: (str): The name of the Disk to delete.
:param disk_id: (str): The id of the disk to delete.
:return: A :class:`lxml.objectify.StringElement` object describing \
the asynchronous Task deleting the disk.
:raises: Exception: If the named disk cannot be located or some \
other error occurs.
"""
if self.resource is None:
self.resource = self.client.get_resource(self.href)
if disk_id is not None:
disk = self.get_disk(disk_id=disk_id)
else:
disk = self.get_disk(name=name)
return self.client.delete_linked_resource(disk, RelationType.REMOVE,
None)
def get_disks(self):
"""Request a list of independent disks defined in a vdc.
:return: An array of :class:`lxml.objectify.StringElement` \
objects describing the existing Disks.
"""
if self.resource is None:
self.resource = self.client.get_resource(self.href)
disks = []
if hasattr(self.resource, 'ResourceEntities') and \
hasattr(self.resource.ResourceEntities, 'ResourceEntity'):
for resourceEntity in \
self.resource.ResourceEntities.ResourceEntity:
if resourceEntity.get('type') == EntityType.DISK.value:
disk = self.client.get_resource(resourceEntity.get('href'))
attached_vms = self.client.get_linked_resource(
disk, RelationType.DOWN, EntityType.VMS.value)
disk['attached_vms'] = attached_vms
disks.append(disk)
return disks
def get_disk(self, name=None, disk_id=None):
"""Return information for an independent disk.
:param name: (str): The name of the disk.
:param disk_id: (str): The id of the disk.
:return: A :class:`lxml.objectify.StringElement` object describing \
the existing disk.
:raises: Exception: If the named disk cannot be located or some \
other error occurs.
"""
if name is None and disk_id is None:
raise Exception('Unable to idendify disk without name or id.')
if self.resource is None:
self.resource = self.client.get_resource(self.href)
disks = self.get_disks()
result = None
if disk_id is not None:
if not disk_id.startswith('urn:vcloud:disk:'):
disk_id = 'urn:vcloud:disk:' + disk_id
for disk in disks:
if disk.get('id') == disk_id:
result = disk
# disk-id's are unique so it's ok to break the loop
# and stop looking further.
break
elif name is not None:
for disk in disks:
if disk.get('name') == name:
if result is None:
result = disk
else:
raise Exception('Found multiple disks with name %s'
', please identify disk via disk-id.'
% disk.get('name'))
if result is None:
raise Exception('No disk found with the given name/id.')
else:
return result
def change_disk_owner(self, user_href, name=None, disk_id=None):
"""Change the ownership of an independent disk to a given user.
:param user_href: Href of the new owner (user).
:param name: Name of the independent disk.
:param disk_id: The id of the disk (required if there are multiple \
disks with same name).
:return: None
:raises: Exception: If the named disk cannot be located or some \
other error occurs.
"""
if self.resource is None:
self.resource = self.client.get_resource(self.href)
if disk_id is not None:
disk = self.get_disk(disk_id=disk_id)
else:
disk = self.get_disk(name=name)
new_owner = disk.Owner
new_owner.User.set('href', user_href)
etree.cleanup_namespaces(new_owner)
return self.client.put_resource(
disk.get('href') + '/owner/', new_owner, EntityType.OWNER.value)
def get_storage_profiles(self):
"""Request a list of the Storage Profiles defined in a VDC.
:return: An array of :class:`lxml.objectify.StringElement` objects
describing the existing Storage Profiles.
"""
profile_list = []
if self.resource is None:
self.resource = self.client.get_resource(self.href)
if hasattr(self.resource, 'VdcStorageProfiles') and \
hasattr(self.resource.VdcStorageProfiles, 'VdcStorageProfile'):
for profile in self.resource.VdcStorageProfiles.VdcStorageProfile:
profile_list.append(profile)
return profile_list
return None
def get_storage_profile(self, profile_name):
"""Request a specific Storage Profile within a Virtual Data Center.
:param profile_name: (str): The name of the requested storage profile.
:return: (VdcStorageProfileType)
A :class:`lxml.objectify.StringElement` object describing the
requested storage profile.
"""
if self.resource is None:
self.resource = self.client.get_resource(self.href)
if hasattr(self.resource, 'VdcStorageProfiles') and \
hasattr(self.resource.VdcStorageProfiles, 'VdcStorageProfile'):
for profile in self.resource.VdcStorageProfiles.VdcStorageProfile:
if profile.get('name') == profile_name:
return profile
raise Exception(
'Storage Profile named \'%s\' not found' % profile_name)
def enable_vdc(self, enable=True):
"""Enable current VDC
:param is_enabled: (bool): enable/disable the vdc
:return: (OrgVdcType) updated vdc object.
"""
resource_admin = self.client.get_resource(self.href_admin)
link = RelationType.ENABLE if enable else RelationType.DISABLE
return self.client.post_linked_resource(resource_admin, link, None,
None)
def delete_vdc(self):
"""Delete the current Organization vDC
:param vdc_name: The name of the org vdc to delete
:return:
"""
if self.resource is None:
self.resource = self.client.get_resource(self.href)
return self.client.delete_linked_resource(self.resource,
RelationType.REMOVE, None)
def get_access_control_settings(self):
"""Get the access control settings of the vdc.
:return: (dict): Access control settings of the vdc.
"""
vdc_resource = self.get_resource()
access_control_settings = self.client.get_linked_resource(
vdc_resource, RelationType.DOWN,
EntityType.CONTROL_ACCESS_PARAMS.value)
return access_control_settings_to_dict(access_control_settings)
def create_vapp(self,
name,
description=None,
network=None,
fence_mode='bridged',
accept_all_eulas=None):
"""Create a new vApp in this VDC
:param name: (str) Name of the new vApp
:param description: (str) Description of the new vApp
:param network: (str) Name of the OrgVDC network to connect the vApp to
:param fence_mode: (str): Network fence mode.
Possible values are `bridged` and `natRouted`
:param accept_all_eulas: (bool): True confirms acceptance of all EULAs
in a vApp template.
:return: A :class:`lxml.objectify.StringElement` object representing a
sparsely populated vApp element in the target VDC.
"""
if self.resource is None:
self.resource = self.client.get_resource(self.href)
network_href = network_name = None
if network is not None:
if hasattr(self.resource, 'AvailableNetworks') and \
hasattr(self.resource.AvailableNetworks, 'Network'):
for n in self.resource.AvailableNetworks.Network:
if network == n.get('name'):
network_href = n.get('href')
network_name = n.get('name')
break
if network_href is None:
raise Exception(
'Network \'%s\' not found in the Virtual Datacenter.' %
network)
vapp_instantiation_param = None
if network_name is not None:
network_configuration = E.Configuration(
E.ParentNetwork(href=network_href), E.FenceMode(fence_mode))
vapp_instantiation_param = E.InstantiationParams(
E.NetworkConfigSection(
E_OVF.Info('Configuration for logical networks'),
E.NetworkConfig(
network_configuration, networkName=network_name)))
params = E.ComposeVAppParams(name=name)
if description is not None:
params.append(E.Description(description))
if vapp_instantiation_param is not None:
params.append(vapp_instantiation_param)
if accept_all_eulas is not None:
params.append(E.AllEULAsAccepted(accept_all_eulas))
return self.client.post_linked_resource(
self.resource, RelationType.ADD,
EntityType.COMPOSE_VAPP_PARAMS.value, params)
def create_directly_connected_vdc_network(self,
network_name,
description,
parent_network_name,
is_shared=None):
"""Create a new directly connected OrgVdc network in this VDC.
:param network_name: (str): Name of the new network
:param description: (str): Description of the new network
:param parent_network_name: (str): Name of the external network
that the new network will be directly connected to
:param is_shared: (bool): True, is the network is shared with \
other VDC(s) in the organization else False
:return: A :class:`lxml.objectify.StringElement` object representing
a sparsely populated OrgVdcNetwork element.
"""
resource_admin = self.client.get_resource(self.href_admin)
parent_network_href = None
if hasattr(resource_admin, 'ProviderVdcReference'):
pvdc_admin_href = resource_admin.ProviderVdcReference.get('href')
pvdc_admin_ext_href = get_admin_extension_href(pvdc_admin_href)
pvdc_resource = self.client.get_resource(pvdc_admin_ext_href)
available_network_tag = '{' + NSMAP['vcloud'] + \
'}AvailableNetworks'
if hasattr(pvdc_resource, available_network_tag) and \
hasattr(pvdc_resource[available_network_tag], 'Network'):
for ext_net in pvdc_resource[available_network_tag].Network:
if parent_network_name == ext_net.get('name'):
parent_network_href = ext_net.get('href')
break
else:
raise Exception('User doesn\'t have enough permission to view '
'Provider Virtual Datacenter backing Virtual '
'Datacenter %s' % self.name)
if parent_network_href is None:
raise Exception('Network \'%s\' not found in the Provider '
'Virtual Datacenter.' % parent_network_name)
request_payload = E.OrgVdcNetwork(name=network_name)
request_payload.append(E.Description(description))
vdc_network_configuration = E.Configuration()
vdc_network_configuration.append(
E.ParentNetwork(href=parent_network_href))
vdc_network_configuration.append(E.FenceMode('bridged'))
request_payload.append(vdc_network_configuration)
if is_shared is not None:
request_payload.append(E.IsShared(is_shared))
return self.client.post_linked_resource(
resource_admin,
RelationType.ADD,
EntityType.ORG_VDC_NETWORK.value,
request_payload)
|
apache-2.0
|
liufeiit/lnk
|
lnk-api/src/main/java/io/lnk/api/registry/Registry.java
|
436
|
package io.lnk.api.registry;
import io.lnk.api.Address;
/**
* @author 刘飞 E-mail:liufei_it@126.com
*
* @version 1.0.0
* @since 2017年5月24日 上午11:49:43
*/
public interface Registry {
Address[] lookup(String serviceId, String version, int protocol);
void registry(String serviceId, String version, int protocol, Address addr);
void unregistry(String serviceId, String version, int protocol, Address addr);
}
|
apache-2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.