repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
vdenotaris/spring-boot-security-saml-sample | src/main/java/com/vdenotaris/spring/boot/security/saml/web/config/MvcConfig.java | 1978 | /*
* Copyright 2021 Vincenzo De Notaris
*
* 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.vdenotaris.spring.boot.security.saml.web.config;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import com.vdenotaris.spring.boot.security.saml.web.core.CurrentUserHandlerMethodArgumentResolver;
@Configuration
public class MvcConfig implements WebMvcConfigurer {
@Autowired
CurrentUserHandlerMethodArgumentResolver currentUserHandlerMethodArgumentResolver;
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("pages/index");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!registry.hasMappingForPattern("/static/**")) {
registry.addResourceHandler("/static/**")
.addResourceLocations("/static/");
}
}
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers){
argumentResolvers.add(currentUserHandlerMethodArgumentResolver);
}
} | apache-2.0 |
arangodb/arangodb | arangod/RocksDBEngine/Listeners/RocksDBMetricsListener.cpp | 3022 | ////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2022 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Matthew Von-Maszewski
////////////////////////////////////////////////////////////////////////////////
#include "RocksDBMetricsListener.h"
#include "ApplicationFeatures/ApplicationServer.h"
#include "Logger/LogMacros.h"
#include "Metrics/CounterBuilder.h"
#include "Metrics/MetricsFeature.h"
DECLARE_COUNTER(
arangodb_rocksdb_write_stalls_total,
"Number of times RocksDB has entered a stalled (slowed) write state");
DECLARE_COUNTER(arangodb_rocksdb_write_stops_total,
"Number of times RocksDB has entered a stopped write state");
namespace arangodb {
/// @brief Setup the object, clearing variables, but do no real work
RocksDBMetricsListener::RocksDBMetricsListener(ArangodServer& server)
: _writeStalls(server.getFeature<metrics::MetricsFeature>().add(
arangodb_rocksdb_write_stalls_total{})),
_writeStops(server.getFeature<metrics::MetricsFeature>().add(
arangodb_rocksdb_write_stops_total{})) {}
void RocksDBMetricsListener::OnStallConditionsChanged(
const rocksdb::WriteStallInfo& info) {
// we should only get here if there's an actual change
TRI_ASSERT(info.condition.cur != info.condition.prev);
// in the case that we go from normal to stalled or stopped, we count it;
// we also count a stall if we go from stopped to stall since it's a distinct
// state
if (info.condition.cur == rocksdb::WriteStallCondition::kDelayed) {
_writeStalls.count();
LOG_TOPIC("9123c", WARN, Logger::ENGINES)
<< "rocksdb is slowing incoming writes to column family '"
<< info.cf_name << "' to let background writes catch up";
} else if (info.condition.cur == rocksdb::WriteStallCondition::kStopped) {
_writeStops.count();
LOG_TOPIC("9123d", WARN, Logger::ENGINES)
<< "rocksdb has stopped incoming writes to column family '"
<< info.cf_name << "' to let background writes catch up";
} else {
TRI_ASSERT(info.condition.cur == rocksdb::WriteStallCondition::kNormal);
LOG_TOPIC("9123e", INFO, Logger::ENGINES)
<< "rocksdb is resuming normal writes for column family '"
<< info.cf_name << "'";
}
}
} // namespace arangodb
| apache-2.0 |
AmesianX/binnavi | src/main/java/com/google/security/zynamics/binnavi/Gui/GraphWindows/BottomPanel/InstructionHighlighter/CSpecialInstructionsModel.java | 3472 | /*
Copyright 2011-2016 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.google.security.zynamics.binnavi.Gui.GraphWindows.BottomPanel.InstructionHighlighter;
import com.google.security.zynamics.binnavi.CUtilityFunctions;
import com.google.security.zynamics.zylib.general.ListenerProvider;
import java.util.ArrayList;
import java.util.List;
/**
* Model that encapsulates the results of a special instruction search.
*/
public final class CSpecialInstructionsModel {
/**
* List of special instructions found in the search.
*/
private final List<CSpecialInstruction> m_instructions = new ArrayList<>();
/**
* Listeners that are notified about changes in the model.
*/
private final ListenerProvider<ISpecialInstructionsModelListener> m_listeners =
new ListenerProvider<>();
/**
* List of available special instruction descriptions.
*/
private final List<ITypeDescription> m_descriptions = new ArrayList<>();
/**
* Creates a new model object.
*/
public CSpecialInstructionsModel() {
m_descriptions.add(new CCallsDescription());
m_descriptions.add(new CReadsDescription());
m_descriptions.add(new CWritesDescription());
}
/**
* Adds a listener object that is notified about changes in the model.
*
* @param listener The listener object to add.
*/
public void addListener(final ISpecialInstructionsModelListener listener) {
m_listeners.addListener(listener);
}
/**
* Returns the available special instruction descriptions.
*
* @return The available special instruction descriptions.
*/
public List<ITypeDescription> getDescriptions() {
return new ArrayList<ITypeDescription>(m_descriptions);
}
/**
* Returns the search result with the given index.
*
* @param index The index of the search result.
*
* @return The search result with the given index.
*/
public CSpecialInstruction getInstruction(final int index) {
return m_instructions.get(index);
}
/**
* Returns all search results.
*
* @return All search results.
*/
public List<CSpecialInstruction> getInstructions() {
return new ArrayList<CSpecialInstruction>(m_instructions);
}
/**
* Removes a listener that was previously listening on the model.
*
* @param listener The listener object to remove.
*/
public void removeListener(final ISpecialInstructionsModelListener listener) {
m_listeners.removeListener(listener);
}
/**
* Updates the search results.
*
* @param instructions The new search result.
*/
public void setInstructions(final List<CSpecialInstruction> instructions) {
m_instructions.clear();
m_instructions.addAll(instructions);
for (final ISpecialInstructionsModelListener listener : m_listeners) {
try {
listener.changedInstructions();
} catch (final Exception exception) {
CUtilityFunctions.logException(exception);
}
}
}
}
| apache-2.0 |
csmoore/MyMiscellanea | CSharp/Testing2525D/MilSymbolPicker/Properties/Resources.Designer.cs | 2789 | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18444
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace MilSymbolPicker.Properties
{
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MilSymbolPicker.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
| apache-2.0 |
speedycontrol/googleapis | output/com/google/devtools/clouddebugger/v2/ListActiveBreakpointsRequestOrBuilder.java | 1889 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/devtools/clouddebugger/v2/controller.proto
package com.google.devtools.clouddebugger.v2;
public interface ListActiveBreakpointsRequestOrBuilder extends
// @@protoc_insertion_point(interface_extends:google.devtools.clouddebugger.v2.ListActiveBreakpointsRequest)
com.google.protobuf.MessageOrBuilder {
/**
* <pre>
* Identifies the debuggee.
* </pre>
*
* <code>optional string debuggee_id = 1;</code>
*/
java.lang.String getDebuggeeId();
/**
* <pre>
* Identifies the debuggee.
* </pre>
*
* <code>optional string debuggee_id = 1;</code>
*/
com.google.protobuf.ByteString
getDebuggeeIdBytes();
/**
* <pre>
* A wait token that, if specified, blocks the method call until the list
* of active breakpoints has changed, or a server selected timeout has
* expired. The value should be set from the last returned response.
* </pre>
*
* <code>optional string wait_token = 2;</code>
*/
java.lang.String getWaitToken();
/**
* <pre>
* A wait token that, if specified, blocks the method call until the list
* of active breakpoints has changed, or a server selected timeout has
* expired. The value should be set from the last returned response.
* </pre>
*
* <code>optional string wait_token = 2;</code>
*/
com.google.protobuf.ByteString
getWaitTokenBytes();
/**
* <pre>
* If set to `true`, returns `google.rpc.Code.OK` status and sets the
* `wait_expired` response field to `true` when the server-selected timeout
* has expired (recommended).
* If set to `false`, returns `google.rpc.Code.ABORTED` status when the
* server-selected timeout has expired (deprecated).
* </pre>
*
* <code>optional bool success_on_timeout = 3;</code>
*/
boolean getSuccessOnTimeout();
}
| apache-2.0 |
dbrimley/hazelcast | hazelcast/src/main/java/com/hazelcast/internal/nearcache/impl/invalidation/MetaDataContainer.java | 3519 | /*
* Copyright (c) 2008-2017, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.internal.nearcache.impl.invalidation;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import static java.util.concurrent.atomic.AtomicLongFieldUpdater.newUpdater;
import static java.util.concurrent.atomic.AtomicReferenceFieldUpdater.newUpdater;
/**
* Contains one partitions' invalidation metadata.
*/
public final class MetaDataContainer {
private static final AtomicLongFieldUpdater<MetaDataContainer> SEQUENCE
= newUpdater(MetaDataContainer.class, "sequence");
private static final AtomicLongFieldUpdater<MetaDataContainer> STALE_SEQUENCE
= newUpdater(MetaDataContainer.class, "staleSequence");
private static final AtomicLongFieldUpdater<MetaDataContainer> MISSED_SEQUENCE_COUNT =
newUpdater(MetaDataContainer.class, "missedSequenceCount");
private static final AtomicReferenceFieldUpdater<MetaDataContainer, UUID> UUID =
newUpdater(MetaDataContainer.class, java.util.UUID.class, "uuid");
/**
* Sequence number of last received invalidation event
*/
private volatile long sequence;
/**
* Holds the biggest sequence number that is lost, lower sequences from this sequence are accepted as stale
*
* @see StaleReadDetector
*/
private volatile long staleSequence;
/**
* Number of missed sequence count
*/
private volatile long missedSequenceCount;
/**
* UUID of the source partition that generates invalidation events
*/
private volatile UUID uuid;
public MetaDataContainer() {
}
public UUID getUuid() {
return uuid;
}
public void setUuid(UUID uuid) {
UUID.set(this, uuid);
}
public boolean casUuid(UUID prevUuid, UUID newUuid) {
return UUID.compareAndSet(this, prevUuid, newUuid);
}
public long getSequence() {
return sequence;
}
public void setSequence(long sequence) {
SEQUENCE.set(this, sequence);
}
public boolean casSequence(long currentSequence, long nextSequence) {
return SEQUENCE.compareAndSet(this, currentSequence, nextSequence);
}
public void resetSequence() {
SEQUENCE.set(this, 0);
}
public long getStaleSequence() {
return STALE_SEQUENCE.get(this);
}
public boolean casStaleSequence(long lastKnownStaleSequence, long lastReceivedSequence) {
return STALE_SEQUENCE.compareAndSet(this, lastKnownStaleSequence, lastReceivedSequence);
}
public void resetStaleSequence() {
STALE_SEQUENCE.set(this, 0);
}
public long addAndGetMissedSequenceCount(long missCount) {
return MISSED_SEQUENCE_COUNT.addAndGet(this, missCount);
}
public long getMissedSequenceCount() {
return missedSequenceCount;
}
}
| apache-2.0 |
markflyhigh/incubator-beam | runners/core-java/src/test/java/org/apache/beam/runners/core/metrics/SimpleExecutionStateTest.java | 3490 | /*
* 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.beam.runners.core.metrics;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.hasEntry;
import static org.junit.Assert.assertEquals;
import java.util.HashMap;
import org.joda.time.Duration;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link SimpleExecutionState}. */
@RunWith(JUnit4.class)
public class SimpleExecutionStateTest {
@Test
public void testLabelsAndNameAreExtracted() {
String stateName = "myState";
HashMap<String, String> labelsMetadata = new HashMap<String, String>();
labelsMetadata.put("k1", "v1");
labelsMetadata.put("k2", "v2");
SimpleExecutionState testObject = new SimpleExecutionState(stateName, null, labelsMetadata);
assertEquals(testObject.getStateName(), stateName);
assertEquals(2, testObject.getLabels().size());
assertThat(testObject.getLabels(), hasEntry("k1", "v1"));
assertThat(testObject.getLabels(), hasEntry("k2", "v2"));
}
@Test
public void testTakeSampleIncrementsTotal() {
SimpleExecutionState testObject = new SimpleExecutionState("myState", null, null);
assertEquals(0, testObject.getTotalMillis());
testObject.takeSample(10);
assertEquals(10, testObject.getTotalMillis());
testObject.takeSample(5);
assertEquals(15, testObject.getTotalMillis());
}
@Test
public void testGetLullReturnsARelevantMessageWithStepName() {
HashMap<String, String> labelsMetadata = new HashMap<String, String>();
labelsMetadata.put(MonitoringInfoConstants.Labels.PTRANSFORM, "myPTransform");
SimpleExecutionState testObject = new SimpleExecutionState("myState", null, labelsMetadata);
String message = testObject.getLullMessage(new Thread(), Duration.millis(100_000));
assertThat(message, containsString("myState"));
assertThat(message, containsString("myPTransform"));
}
@Test
public void testGetLullReturnsARelevantMessageWithoutStepNameWithNullLabels() {
SimpleExecutionState testObject = new SimpleExecutionState("myState", null, null);
String message = testObject.getLullMessage(new Thread(), Duration.millis(100_000));
assertThat(message, containsString("myState"));
}
@Test
public void testGetLullReturnsARelevantMessageWithoutStepName() {
HashMap<String, String> labelsMetadata = new HashMap<String, String>();
SimpleExecutionState testObject = new SimpleExecutionState("myState", null, labelsMetadata);
String message = testObject.getLullMessage(new Thread(), Duration.millis(100_000));
assertThat(message, containsString("myState"));
}
}
| apache-2.0 |
jasonwee/videoOnCloud | src/java/play/learn/java/design/double_dispatch/FlamingAsteroid.java | 325 | package play.learn.java.design.double_dispatch;
public class FlamingAsteroid extends Meteoroid {
public FlamingAsteroid(int left, int top, int right, int bottom) {
super(left, top, right, bottom);
setOnFire(true);
}
@Override
public void collision(GameObject gameObject) {
gameObject.collisionResolve(this);
}
}
| apache-2.0 |
markus1978/citygml4emf | de.hub.citygml.emf.ecore/src/net/opengis/gml/impl/AbstractGeometricAggregateTypeImpl.java | 909 | /**
* <copyright>
* </copyright>
*
* $Id$
*/
package net.opengis.gml.impl;
import net.opengis.gml.AbstractGeometricAggregateType;
import net.opengis.gml.GmlPackage;
import org.eclipse.emf.ecore.EClass;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Abstract Geometric Aggregate Type</b></em>'.
* <!-- end-user-doc -->
* <p>
* </p>
*
* @generated
*/
public abstract class AbstractGeometricAggregateTypeImpl extends AbstractGeometryTypeImpl implements AbstractGeometricAggregateType {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected AbstractGeometricAggregateTypeImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return GmlPackage.eINSTANCE.getAbstractGeometricAggregateType();
}
} //AbstractGeometricAggregateTypeImpl
| apache-2.0 |
nafae/developer | modules/dfp_axis/src/main/java/com/google/api/ads/dfp/axis/v201306/String_ValueMapEntry.java | 4955 | /**
* String_ValueMapEntry.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.dfp.axis.v201306;
/**
* This represents an entry in a map with a key of type String
* and value of type Value.
*/
public class String_ValueMapEntry implements java.io.Serializable {
private java.lang.String key;
private com.google.api.ads.dfp.axis.v201306.Value value;
public String_ValueMapEntry() {
}
public String_ValueMapEntry(
java.lang.String key,
com.google.api.ads.dfp.axis.v201306.Value value) {
this.key = key;
this.value = value;
}
/**
* Gets the key value for this String_ValueMapEntry.
*
* @return key
*/
public java.lang.String getKey() {
return key;
}
/**
* Sets the key value for this String_ValueMapEntry.
*
* @param key
*/
public void setKey(java.lang.String key) {
this.key = key;
}
/**
* Gets the value value for this String_ValueMapEntry.
*
* @return value
*/
public com.google.api.ads.dfp.axis.v201306.Value getValue() {
return value;
}
/**
* Sets the value value for this String_ValueMapEntry.
*
* @param value
*/
public void setValue(com.google.api.ads.dfp.axis.v201306.Value value) {
this.value = value;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof String_ValueMapEntry)) return false;
String_ValueMapEntry other = (String_ValueMapEntry) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
((this.key==null && other.getKey()==null) ||
(this.key!=null &&
this.key.equals(other.getKey()))) &&
((this.value==null && other.getValue()==null) ||
(this.value!=null &&
this.value.equals(other.getValue())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
if (getKey() != null) {
_hashCode += getKey().hashCode();
}
if (getValue() != null) {
_hashCode += getValue().hashCode();
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(String_ValueMapEntry.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201306", "String_ValueMapEntry"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("key");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201306", "key"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("value");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201306", "value"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201306", "Value"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| apache-2.0 |
coralnexus/corl | lib/core/util/puppet/resource_group.rb | 4408 |
module CORL
module Util
module Puppet
class ResourceGroup < Core
include Mixin::SubConfig
#-----------------------------------------------------------------------------
# Constructor / Destructor
def initialize(type_info, default = {})
super({
:info => hash(type_info),
:default => symbol_map(hash(default))
}, {}, true, true, false)
self.resources = {}
end
#---
def inspect
"#{self.class}#{info.to_s}[#{composite_resources.keys.length}]"
end
#-----------------------------------------------------------------------------
# Property accessors / modifiers
def info(default = {})
return hash(_get(:info, default))
end
#---
def info=info
_set(:info, hash(info))
end
#---
def default(default = {})
return hash(_get(:default, default))
end
#---
def default=default
_set(:default, symbol_map(hash(default)))
end
#---
def resources(default = {})
return hash(_get(:resources, default))
end
#---
def resources=resources
_set(:resources, symbol_map(hash(resources)))
end
#---
def composite_resources(default = {})
return hash(_get(:composite_resources, default))
end
#---
def composite_resources=resources
_set(:composite_resources, symbol_map(hash(resources)))
end
#---
def add(resources, options = {})
config = Config.ensure(options)
resources = normalize(info[:name], Data.clone(resources), config)
unless Data.empty?(resources)
collection = self.resources
resources.each do |title, resource|
Puppet.add_resource(info, title, resource.export, config)
collection[title] = resource
end
self.resources = collection
end
return self
end
#---
def add_composite_resource(name, resource_names)
name = name.to_sym
composite = self.composite_resources
composite[name] = [] unless composite[name].is_a?(Array)
unless resource_names.is_a?(Array)
resource_names = [ resource_names ]
end
resource_names.each do |r_name|
r_name = r_name.to_sym
unless composite[name].include?(r_name)
composite[name] << r_name
end
end
self.composite_resources = composite
end
protected :add_composite_resource
#-----------------------------------------------------------------------------
# Resource operations
def normalize(type_name, resources, options = {})
self.composite_resources = {}
config = Config.ensure(options)
resources = Data.value(resources)
unless Data.empty?(resources)
resource_names = {}
resources.keys.each do |name|
if ! resources[name] || resources[name].empty? || ! resources[name].is_a?(Hash)
resources.delete(name)
else
normalize = true
namevar = Puppet.namevar(type_name, name)
if resources[name].has_key?(namevar)
value = resources[name][namevar]
if Data.empty?(value)
resources.delete(name)
normalize = false
elsif value.is_a?(Array)
value.each do |item|
item_name = "#{name}_#{item}".gsub(/\-/, '_')
new_resource = resources[name].clone
new_resource[namevar] = item
resources[item_name] = Resource.new(self, info, item_name, new_resource).defaults(default, config)
add_composite_resource(name, item_name)
end
resources.delete(name)
normalize = false
end
end
if normalize
resource = Resource.new(self, info, name, resources[name]).defaults(default, config)
resource_names[name] = true
resources[name] = resource
end
end
end
config[:resource_names] = resource_names
resources.each do |name, resource|
resource.process(config)
end
end
return translate(resources, config)
end
protected :normalize
#---
def translate(resources, options = {})
config = Config.ensure(options)
results = {}
prefix = config.get(:resource_prefix, '')
resources.each do |name, resource|
unless prefix.empty?
name = "#{prefix}_#{name}"
end
results[name] = resource
end
return results
end
protected :translate
end
end
end
end
| apache-2.0 |
jmclark/capco | src/main/java/org/geoint/lbac/marking/SecurityMarkingBuilder.java | 3290 | package org.geoint.lbac.marking;
import org.geoint.lbac.policy.SecurityPolicy;
import org.geoint.lbac.impl.policy.restriction.SecurityRestrictionException;
/**
* API to create, or modify, a {@link SecurityMarking}.
*
*/
public interface SecurityMarkingBuilder {
/**
* Adds a {@link SecurityComponent} to a category within the
* {@link SecurityMarking}, first checking policy restrictions.
*
* This method if functionally equivalent to retrieving the control instance
* from the {@link SecurityPolicy} and calling
* {@link SecurityMarkingBuilder#addControl(SecurityComponent) }
*
* @param componentPath
* @return
* @throws UnknownSecurityComponentException if the control is unknown in
* the context of this policy
* @throws SecurityRestrictionException if a restriction prevents this
* action from happening
*/
SecurityMarkingBuilder addControl(String componentPath)
throws UnknownSecurityComponentException, SecurityRestrictionException;
/**
* Attempts to add a {@link Control} to the {@link SecurityMarking}.
*
* The {@link SecurityPolicy} is first checked for any restrictions that may
* morph the action taken by adding this control (based on those
* restrictions).
*
* @param component
* @return
* @throws UnknownSecurityComponentException if the control provided is not
* of the same policy, and the policy in this context does not contain that
* control
* @throws SecurityRestrictionException if a restriction prevents this
* action from happening
*/
SecurityMarkingBuilder addControl(Control component)
throws UnknownSecurityComponentException, SecurityRestrictionException;
/**
* Removes a {@link Control} to a category within the
* {@link SecurityMarking}, first checking policy restrictions.
*
* This method if functionally equivalent to retrieving the control instance
* from the {@link SecurityPolicy} and calling
* {@link SecurityMarkingBuilder#removeControl(SecurityControl) }
*
* @param componentPath
* @return
* @throws UnknownSecurityComponentException if the control is unknown in
* the context of this policy
* @throws SecurityRestrictionException if a restriction prevents this
* action from happening
*/
SecurityMarkingBuilder removeControl(String componentPath)
throws UnknownSecurityComponentException, SecurityRestrictionException;
/**
* Attempts to remove a {@link Control} from the
* {@link SecurityMarking}.
*
* The {@link SecurityPolicy} is first checked for any restrictions that may
* morph the action taken by adding this control (based on those
* restrictions).
*
* @param component
* @return
* @throws UnknownSecurityComponentException if the control provided is not
* of the same policy, and the policy in this context does not contain that
* control
* @throws SecurityRestrictionException if a restriction prevents this
* action from happening
*/
SecurityMarkingBuilder removeControl(Control component)
throws UnknownSecurityComponentException, SecurityRestrictionException;
}
| apache-2.0 |
Shenker93/playframework | framework/src/play-ahc-ws/src/test/scala/play/libs/ws/WSSpec.scala | 1443 | /*
* Copyright (C) 2009-2018 Lightbend Inc. <https://www.lightbend.com>
*/
package play.libs.ws
import akka.stream.Materializer
import play.api.mvc.Results._
import play.api.mvc._
import play.api.test._
import play.core.server.Server
import play.libs.ws.ahc.AhcWSClient
import play.shaded.ahc.org.asynchttpclient.AsyncHttpClient
class WSSpec extends PlaySpecification with WsTestClient {
sequential
"WSClient.url().post(InputStream)" should {
"uploads the stream" in {
var mat: Materializer = NoMaterializer
Server.withRouterFromComponents() { components =>
mat = components.materializer
import components.{ defaultActionBuilder => Action }
import play.api.routing.sird.{ POST => SirdPost, _ }
{
case SirdPost(p"/") => Action { req: Request[AnyContent] =>
req.body.asRaw.fold[Result](BadRequest) { raw =>
val size = raw.size
Ok(s"size=$size")
}
}
}
} { implicit port =>
withClient { ws =>
val javaWs = new AhcWSClient(ws.underlying[AsyncHttpClient], mat)
val input = this.getClass.getClassLoader.getResourceAsStream("play/libs/ws/play_full_color.png")
val rep = javaWs.url(s"http://localhost:$port/").post(input).toCompletableFuture.get()
rep.getStatus must ===(200)
rep.getBody must ===("size=20039")
}
}
}
}
}
| apache-2.0 |
tangfeixiong/go-to-exercise | vendor/github.com/cesanta/docker_auth/auth_server/authn/authn.go | 1824 | /*
Copyright 2015 Cesanta Software Ltd.
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 authn
import "errors"
type Labels map[string][]string
// Authentication plugin interface.
type Authenticator interface {
// Given a user name and a password (plain text), responds with the result or an error.
// Error should only be reported if request could not be serviced, not if it should be denied.
// A special NoMatch error is returned if the authorizer could not reach a decision,
// e.g. none of the rules matched.
// Another special WrongPass error is returned if the authorizer failed to authenticate.
// Implementations must be goroutine-safe.
Authenticate(user string, password PasswordString) (bool, Labels, error)
// Finalize resources in preparation for shutdown.
// When this call is made there are guaranteed to be no Authenticate requests in flight
// and there will be no more calls made to this instance.
Stop()
// Human-readable name of the authenticator.
Name() string
}
var NoMatch = errors.New("did not match any rule")
var WrongPass = errors.New("wrong password for user")
//go:generate go-bindata -pkg authn -modtime 1 -mode 420 -nocompress data/
type PasswordString string
func (ps PasswordString) String() string {
if len(ps) == 0 {
return ""
}
return "***"
}
| apache-2.0 |
sunfuchang/JavaLearn | src/main/java/com/belonk/crypt/AlgorithmData.java | 719 | package com.belonk.crypt;
public class AlgorithmData {
private String key;
private String dataMing;
private String dataMi;
private boolean doDisplay =true;//true-需要做显示处理,false-不需要做显示处理
public boolean isDoDisplay() {
return doDisplay;
}
public void setDoDisplay(boolean doDisplay) {
this.doDisplay = doDisplay;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getDataMing() {
return dataMing;
}
public void setDataMing(String dataMing) {
this.dataMing = dataMing;
}
public String getDataMi() {
return dataMi;
}
public void setDataMi(String dataMi) {
this.dataMi = dataMi;
}
}
| apache-2.0 |
hubrick/raml-maven-plugin | src/main/java/com/hubrick/raml/codegen/ReferencedPatternDefinition.java | 945 | /*
* Copyright 2015 Hubrick
*
* 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.hubrick.raml.codegen;
/**
* @author ahanin
* @since 1.0.0
*/
public class ReferencedPatternDefinition implements PatternDefinition {
private String reference;
public ReferencedPatternDefinition(String reference) {
this.reference = reference;
}
public String getReference() {
return reference;
}
}
| apache-2.0 |
bwsw/cloudstack-ui | src/app/vm-logs/vm-logs-token/vm-logs-token.component.ts | 814 | import { Component, Inject } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material';
import { VmLogToken } from '../models/vm-log-token.model';
import { SnackBarService } from '../../core/services';
@Component({
selector: 'cs-vm-logs-token',
templateUrl: 'vm-logs-token.component.html',
styleUrls: ['vm-logs-token.component.scss'],
})
export class VmLogsTokenComponent {
constructor(
public dialogRef: MatDialogRef<VmLogsTokenComponent>,
@Inject(MAT_DIALOG_DATA) public token: VmLogToken,
private notificationService: SnackBarService,
) {}
public onCopySuccess(): void {
this.notificationService.open('CLIPBOARD.COPY_SUCCESS').subscribe();
}
public onCopyFail(): void {
this.notificationService.open('CLIPBOARD.COPY_FAIL').subscribe();
}
}
| apache-2.0 |
wuxiatech/wuxia-common | src/main/java/cn/wuxia/common/express/ElUtil.java | 7177 | package cn.wuxia.common.express;
import cn.wuxia.common.util.ListUtil;
import org.nutz.el.El;
import org.nutz.el.opt.RunMethod;
import org.nutz.el.opt.custom.CustomMake;
import org.nutz.lang.Lang;
import org.nutz.lang.util.Context;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ElUtil {
/**
* @param str
* @return
* @description : 返回?{} 内的key,key允许的字符包括.#:[]*\/+-()
* @author songlin.li
*/
public static String[] getTemplateKey(String str) {
Pattern p = Pattern.compile("\\?+[{]+[\\w\\.\\#\\:\\[\\]\\*\\/\\+\\-\\(\\)\\s*]+[}]");
Matcher m = p.matcher(str);
List<String> value = new ArrayList<String>();
while (m.find()) {
String key = m.group();
key = key.substring(2, key.length() - 1);
value.add(key);
}
if (ListUtil.isEmpty(value)) {
return new String[] {};
}
value = ListUtil.removeDuplicateBySet(value);
return ListUtil.listToArray(value);
}
/**
* @param str
* @return
* @description : 返回[]内的内容
* @author songlin.li
*/
public static String[] getBracketsKey(String str) {
Pattern p = Pattern.compile("(\\[+[\\w\\.\\#\\:\\*\\/\\+\\-\\(\\)\\s*]+\\])");
Matcher m = p.matcher(str);
List<String> value = new ArrayList<String>();
while (m.find()) {
String key = m.group();
key = key.substring(1, key.length() - 1);
value.add(key);
}
if (ListUtil.isEmpty(value)) {
return new String[] {};
}
value = ListUtil.removeDuplicateBySet(value);
return ListUtil.listToArray(value);
}
/**
* @param str
* @return
* @description : 返回括号的内容
* @author songlin.li
*/
public static String[] getBracketKey(String str) {
Pattern p = Pattern.compile("[(]+[\\w\\.\\#\\:\\(\\)\\s*]+[)]");
Matcher m = p.matcher(str);
List<String> value = new ArrayList<String>();
while (m.find()) {
String key = m.group();
key = key.substring(1, key.length() - 1);
value.add(key);
}
if (ListUtil.isEmpty(value)) {
return new String[] {};
}
value = ListUtil.removeDuplicateBySet(value);
return ListUtil.listToArray(value);
}
/**
* @param str
* @return
* @description : 返回单词
* @author songlin.li
*/
public static String[] getWordKey(String str) {
Pattern p = Pattern.compile("\\w+");
Matcher m = p.matcher(str);
List<String> value = new ArrayList<String>();
while (m.find()) {
String key = m.group();
value.add(key);
}
if (ListUtil.isEmpty(value)) {
return new String[] {};
}
value = ListUtil.removeDuplicateBySet(value);
return ListUtil.listToArray(value);
}
/**
* @param str
* @return
* @description : 返回单词
* @author songlin.li
*/
public static String[] getNumberIndexKey(String str) {
Pattern p = Pattern.compile("\\d+#");
Matcher m = p.matcher(str);
List<String> value = new ArrayList<String>();
while (m.find()) {
String key = m.group();
value.add(key);
}
if (ListUtil.isEmpty(value)) {
return new String[] {};
}
value = ListUtil.removeDuplicateBySet(value);
return ListUtil.listToArray(value);
}
public static void main(String[] args) {
String temp = "jflasdjfl ${fasdf} #{fasdf} fkaslf<a > fasl</b> ?{666} lolofasdf 中文救场?{[1#].score} f ?{1:20#} fasldflll ?{[a]*[8#]} "
+ " f?{sum([1:20#].score)} fff++++fasd ?{(1#+20#+30#-5#)/2}";
String[] keys = getTemplateKey(temp);
int i = 0;
for (String key : keys) {
System.out.println(i++ + " == " + key);
}
String[] keys2 = getBracketsKey(temp);
int ii = 0;
for (String key : keys2) {
System.out.println(ii++ + " == " + key);
}
String[] keys3 = getBracketKey(temp);
int iii = 0;
for (String key : keys3) {
System.out.println(iii++ + " == " + key);
}
// 普通运算
System.out.println(El.eval("3+2*5"));
// 输出为 13
// 字符串操作
System.out.println(El.eval("trim(\" abc \")"));
// 输出为 abc
// Java 对象属性访问调用
Context context = Lang.context();
Testtext pet = new Testtext();
pet.setName("GFW");
context.set("pet", pet);
System.out.println(El.eval(context, "pet.name"));
// 输出为 GFW
// 函数调用
El.eval(context, "pet.setName('XiaoBai')");
System.out.println(El.eval(context, "pet.getName()"));
// 输出为 XiaoBai
// 数组访问
// context.set("x", Lang.array("A", "B", "C"));
//
// System.out.println(El.eval(context, "x[0].toLowerCase()"));
// 输出为 a
// 列表访问
// context.set("x", Lang.list("A", "B", "C"));
//
// System.out.println(El.eval(context, "x.get(0).toLowerCase()"));
// 输出为 a
// Map 访问
context.set("map", Lang.map("{x:10, y:5}"));
System.out.println(El.eval(context, "map['x'] * map['y']"));
// 输出为 50
// 判断
context.set("a", 5);
System.out.println(El.eval(context, "a>10"));
// 输出为 false
context.set("a", 20);
System.out.println(El.eval(context, "a>10"));
// 输出为 true
CustomMake.me().register("sum", new TestFunction());
System.out.println(El.eval(context, "sum(a+5)"));
context.set("10x", 10);
context.set("20x", 20);
System.out.println(El.eval(context, "10x+20x"));
}
public static class Testtext {
String name;
Object value;
public Testtext() {
}
public Testtext(String name, Object value) {
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
}
public static class TestFunction implements RunMethod {
@Override
public Object run(List<Object> fetchParam) {
Integer a = 0;
for (Object object : fetchParam) {
System.out.println("=====" + object);
a += (Integer) object;
}
return a;
}
@Override
public String fetchSelf() {
return null;
}
}
}
| apache-2.0 |
zheng-zy/zCore | src/main/java/com/ktvme/net/intercepter/NetInterceptor.java | 1694 | package com.ktvme.net.intercepter;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import java.io.IOException;
import java.util.UUID;
/**
* <p>模拟数据返回</p>
* Created by zhezhiyong@163.com on 2017/6/13.
*/
@Slf4j
public class NetInterceptor implements Interceptor {
// private static final String API_URL = "http://qxtsms.guodulink.net:8005/HttpQuickProcess/submitMessageAll";
private static final String API_URL = "/HttpQuickProcess/submitMessageAll";
@Override
public Response intercept(Chain chain) throws IOException {
Response response;
if (chain.request().url().toString().contains(API_URL)) {
String msgId = UUID.randomUUID().toString().replaceAll("-", "");
// {"time":"20170508103503","msgId":"17050810350326298","errorMsg":"","code":"0"}
// BaseDto dto = new BaseDto();
// SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
// String time = sdf.format(new Date());
// dto.put("time", time);
// dto.put("msgId", msgId);
// dto.put("errorMsg", "模拟数据返回");
// dto.put("code", "0");
String r = "00," + msgId;
response = new Response.Builder()
.code(200)
.addHeader("Content-Type", "text/plain")
.body(ResponseBody.create(MediaType.parse("text/plain"), r))
.message(r)
.request(chain.request())
.protocol(Protocol.HTTP_2)
.build();
} else {
response = chain.proceed(chain.request());
}
return response;
}
}
| apache-2.0 |
jwhonce/skopeo | vendor/github.com/containers/storage/containers.go | 15406 | package storage
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"time"
"github.com/containers/storage/pkg/idtools"
"github.com/containers/storage/pkg/ioutils"
"github.com/containers/storage/pkg/stringid"
"github.com/containers/storage/pkg/truncindex"
digest "github.com/opencontainers/go-digest"
"github.com/pkg/errors"
)
// A Container is a reference to a read-write layer with metadata.
type Container struct {
// ID is either one which was specified at create-time, or a random
// value which was generated by the library.
ID string `json:"id"`
// Names is an optional set of user-defined convenience values. The
// container can be referred to by its ID or any of its names. Names
// are unique among containers.
Names []string `json:"names,omitempty"`
// ImageID is the ID of the image which was used to create the container.
ImageID string `json:"image"`
// LayerID is the ID of the read-write layer for the container itself.
// It is assumed that the image's top layer is the parent of the container's
// read-write layer.
LayerID string `json:"layer"`
// Metadata is data we keep for the convenience of the caller. It is not
// expected to be large, since it is kept in memory.
Metadata string `json:"metadata,omitempty"`
// BigDataNames is a list of names of data items that we keep for the
// convenience of the caller. They can be large, and are only in
// memory when being read from or written to disk.
BigDataNames []string `json:"big-data-names,omitempty"`
// BigDataSizes maps the names in BigDataNames to the sizes of the data
// that has been stored, if they're known.
BigDataSizes map[string]int64 `json:"big-data-sizes,omitempty"`
// BigDataDigests maps the names in BigDataNames to the digests of the
// data that has been stored, if they're known.
BigDataDigests map[string]digest.Digest `json:"big-data-digests,omitempty"`
// Created is the datestamp for when this container was created. Older
// versions of the library did not track this information, so callers
// will likely want to use the IsZero() method to verify that a value
// is set before using it.
Created time.Time `json:"created,omitempty"`
// UIDMap and GIDMap are used for setting up a container's root
// filesystem for use inside of a user namespace where UID mapping is
// being used.
UIDMap []idtools.IDMap `json:"uidmap,omitempty"`
GIDMap []idtools.IDMap `json:"gidmap,omitempty"`
Flags map[string]interface{} `json:"flags,omitempty"`
}
// ContainerStore provides bookkeeping for information about Containers.
type ContainerStore interface {
FileBasedStore
MetadataStore
BigDataStore
FlaggableStore
// Create creates a container that has a specified ID (or generates a
// random one if an empty value is supplied) and optional names,
// based on the specified image, using the specified layer as its
// read-write layer.
// The maps in the container's options structure are recorded for the
// convenience of the caller, nothing more.
Create(id string, names []string, image, layer, metadata string, options *ContainerOptions) (*Container, error)
// SetNames updates the list of names associated with the container
// with the specified ID.
SetNames(id string, names []string) error
// Get retrieves information about a container given an ID or name.
Get(id string) (*Container, error)
// Exists checks if there is a container with the given ID or name.
Exists(id string) bool
// Delete removes the record of the container.
Delete(id string) error
// Wipe removes records of all containers.
Wipe() error
// Lookup attempts to translate a name to an ID. Most methods do this
// implicitly.
Lookup(name string) (string, error)
// Containers returns a slice enumerating the known containers.
Containers() ([]Container, error)
}
type containerStore struct {
lockfile Locker
dir string
containers []*Container
idindex *truncindex.TruncIndex
byid map[string]*Container
bylayer map[string]*Container
byname map[string]*Container
}
func copyContainer(c *Container) *Container {
return &Container{
ID: c.ID,
Names: copyStringSlice(c.Names),
ImageID: c.ImageID,
LayerID: c.LayerID,
Metadata: c.Metadata,
BigDataNames: copyStringSlice(c.BigDataNames),
BigDataSizes: copyStringInt64Map(c.BigDataSizes),
BigDataDigests: copyStringDigestMap(c.BigDataDigests),
Created: c.Created,
UIDMap: copyIDMap(c.UIDMap),
GIDMap: copyIDMap(c.GIDMap),
Flags: copyStringInterfaceMap(c.Flags),
}
}
func (r *containerStore) Containers() ([]Container, error) {
containers := make([]Container, len(r.containers))
for i := range r.containers {
containers[i] = *copyContainer(r.containers[i])
}
return containers, nil
}
func (r *containerStore) containerspath() string {
return filepath.Join(r.dir, "containers.json")
}
func (r *containerStore) datadir(id string) string {
return filepath.Join(r.dir, id)
}
func (r *containerStore) datapath(id, key string) string {
return filepath.Join(r.datadir(id), makeBigDataBaseName(key))
}
func (r *containerStore) Load() error {
needSave := false
rpath := r.containerspath()
data, err := ioutil.ReadFile(rpath)
if err != nil && !os.IsNotExist(err) {
return err
}
containers := []*Container{}
layers := make(map[string]*Container)
idlist := []string{}
ids := make(map[string]*Container)
names := make(map[string]*Container)
if err = json.Unmarshal(data, &containers); len(data) == 0 || err == nil {
idlist = make([]string, 0, len(containers))
for n, container := range containers {
idlist = append(idlist, container.ID)
ids[container.ID] = containers[n]
layers[container.LayerID] = containers[n]
for _, name := range container.Names {
if conflict, ok := names[name]; ok {
r.removeName(conflict, name)
needSave = true
}
names[name] = containers[n]
}
}
}
r.containers = containers
r.idindex = truncindex.NewTruncIndex(idlist)
r.byid = ids
r.bylayer = layers
r.byname = names
if needSave {
return r.Save()
}
return nil
}
func (r *containerStore) Save() error {
rpath := r.containerspath()
if err := os.MkdirAll(filepath.Dir(rpath), 0700); err != nil {
return err
}
jdata, err := json.Marshal(&r.containers)
if err != nil {
return err
}
defer r.Touch()
return ioutils.AtomicWriteFile(rpath, jdata, 0600)
}
func newContainerStore(dir string) (ContainerStore, error) {
if err := os.MkdirAll(dir, 0700); err != nil {
return nil, err
}
lockfile, err := GetLockfile(filepath.Join(dir, "containers.lock"))
if err != nil {
return nil, err
}
lockfile.Lock()
defer lockfile.Unlock()
cstore := containerStore{
lockfile: lockfile,
dir: dir,
containers: []*Container{},
byid: make(map[string]*Container),
bylayer: make(map[string]*Container),
byname: make(map[string]*Container),
}
if err := cstore.Load(); err != nil {
return nil, err
}
return &cstore, nil
}
func (r *containerStore) lookup(id string) (*Container, bool) {
if container, ok := r.byid[id]; ok {
return container, ok
} else if container, ok := r.byname[id]; ok {
return container, ok
} else if container, ok := r.bylayer[id]; ok {
return container, ok
} else if longid, err := r.idindex.Get(id); err == nil {
if container, ok := r.byid[longid]; ok {
return container, ok
}
}
return nil, false
}
func (r *containerStore) ClearFlag(id string, flag string) error {
container, ok := r.lookup(id)
if !ok {
return ErrContainerUnknown
}
delete(container.Flags, flag)
return r.Save()
}
func (r *containerStore) SetFlag(id string, flag string, value interface{}) error {
container, ok := r.lookup(id)
if !ok {
return ErrContainerUnknown
}
if container.Flags == nil {
container.Flags = make(map[string]interface{})
}
container.Flags[flag] = value
return r.Save()
}
func (r *containerStore) Create(id string, names []string, image, layer, metadata string, options *ContainerOptions) (container *Container, err error) {
if id == "" {
id = stringid.GenerateRandomID()
_, idInUse := r.byid[id]
for idInUse {
id = stringid.GenerateRandomID()
_, idInUse = r.byid[id]
}
}
if _, idInUse := r.byid[id]; idInUse {
return nil, ErrDuplicateID
}
names = dedupeNames(names)
for _, name := range names {
if _, nameInUse := r.byname[name]; nameInUse {
return nil, errors.Wrapf(ErrDuplicateName,
fmt.Sprintf("the container name \"%s\" is already in use by \"%s\". You have to remove that container to be able to reuse that name.", name, r.byname[name].ID))
}
}
if err == nil {
container = &Container{
ID: id,
Names: names,
ImageID: image,
LayerID: layer,
Metadata: metadata,
BigDataNames: []string{},
BigDataSizes: make(map[string]int64),
BigDataDigests: make(map[string]digest.Digest),
Created: time.Now().UTC(),
Flags: make(map[string]interface{}),
UIDMap: copyIDMap(options.UIDMap),
GIDMap: copyIDMap(options.GIDMap),
}
r.containers = append(r.containers, container)
r.byid[id] = container
r.idindex.Add(id)
r.bylayer[layer] = container
for _, name := range names {
r.byname[name] = container
}
err = r.Save()
container = copyContainer(container)
}
return container, err
}
func (r *containerStore) Metadata(id string) (string, error) {
if container, ok := r.lookup(id); ok {
return container.Metadata, nil
}
return "", ErrContainerUnknown
}
func (r *containerStore) SetMetadata(id, metadata string) error {
if container, ok := r.lookup(id); ok {
container.Metadata = metadata
return r.Save()
}
return ErrContainerUnknown
}
func (r *containerStore) removeName(container *Container, name string) {
container.Names = stringSliceWithoutValue(container.Names, name)
}
func (r *containerStore) SetNames(id string, names []string) error {
names = dedupeNames(names)
if container, ok := r.lookup(id); ok {
for _, name := range container.Names {
delete(r.byname, name)
}
for _, name := range names {
if otherContainer, ok := r.byname[name]; ok {
r.removeName(otherContainer, name)
}
r.byname[name] = container
}
container.Names = names
return r.Save()
}
return ErrContainerUnknown
}
func (r *containerStore) Delete(id string) error {
container, ok := r.lookup(id)
if !ok {
return ErrContainerUnknown
}
id = container.ID
toDeleteIndex := -1
for i, candidate := range r.containers {
if candidate.ID == id {
toDeleteIndex = i
break
}
}
delete(r.byid, id)
r.idindex.Delete(id)
delete(r.bylayer, container.LayerID)
for _, name := range container.Names {
delete(r.byname, name)
}
if toDeleteIndex != -1 {
// delete the container at toDeleteIndex
if toDeleteIndex == len(r.containers)-1 {
r.containers = r.containers[:len(r.containers)-1]
} else {
r.containers = append(r.containers[:toDeleteIndex], r.containers[toDeleteIndex+1:]...)
}
}
if err := r.Save(); err != nil {
return err
}
if err := os.RemoveAll(r.datadir(id)); err != nil {
return err
}
return nil
}
func (r *containerStore) Get(id string) (*Container, error) {
if container, ok := r.lookup(id); ok {
return copyContainer(container), nil
}
return nil, ErrContainerUnknown
}
func (r *containerStore) Lookup(name string) (id string, err error) {
if container, ok := r.lookup(name); ok {
return container.ID, nil
}
return "", ErrContainerUnknown
}
func (r *containerStore) Exists(id string) bool {
_, ok := r.lookup(id)
return ok
}
func (r *containerStore) BigData(id, key string) ([]byte, error) {
if key == "" {
return nil, errors.Wrapf(ErrInvalidBigDataName, "can't retrieve container big data value for empty name")
}
c, ok := r.lookup(id)
if !ok {
return nil, ErrContainerUnknown
}
return ioutil.ReadFile(r.datapath(c.ID, key))
}
func (r *containerStore) BigDataSize(id, key string) (int64, error) {
if key == "" {
return -1, errors.Wrapf(ErrInvalidBigDataName, "can't retrieve size of container big data with empty name")
}
c, ok := r.lookup(id)
if !ok {
return -1, ErrContainerUnknown
}
if c.BigDataSizes == nil {
c.BigDataSizes = make(map[string]int64)
}
if size, ok := c.BigDataSizes[key]; ok {
return size, nil
}
if data, err := r.BigData(id, key); err == nil && data != nil {
if r.SetBigData(id, key, data) == nil {
c, ok := r.lookup(id)
if !ok {
return -1, ErrContainerUnknown
}
if size, ok := c.BigDataSizes[key]; ok {
return size, nil
}
}
}
return -1, ErrSizeUnknown
}
func (r *containerStore) BigDataDigest(id, key string) (digest.Digest, error) {
if key == "" {
return "", errors.Wrapf(ErrInvalidBigDataName, "can't retrieve digest of container big data value with empty name")
}
c, ok := r.lookup(id)
if !ok {
return "", ErrContainerUnknown
}
if c.BigDataDigests == nil {
c.BigDataDigests = make(map[string]digest.Digest)
}
if d, ok := c.BigDataDigests[key]; ok {
return d, nil
}
if data, err := r.BigData(id, key); err == nil && data != nil {
if r.SetBigData(id, key, data) == nil {
c, ok := r.lookup(id)
if !ok {
return "", ErrContainerUnknown
}
if d, ok := c.BigDataDigests[key]; ok {
return d, nil
}
}
}
return "", ErrDigestUnknown
}
func (r *containerStore) BigDataNames(id string) ([]string, error) {
c, ok := r.lookup(id)
if !ok {
return nil, ErrContainerUnknown
}
return copyStringSlice(c.BigDataNames), nil
}
func (r *containerStore) SetBigData(id, key string, data []byte) error {
if key == "" {
return errors.Wrapf(ErrInvalidBigDataName, "can't set empty name for container big data item")
}
c, ok := r.lookup(id)
if !ok {
return ErrContainerUnknown
}
if err := os.MkdirAll(r.datadir(c.ID), 0700); err != nil {
return err
}
err := ioutils.AtomicWriteFile(r.datapath(c.ID, key), data, 0600)
if err == nil {
save := false
if c.BigDataSizes == nil {
c.BigDataSizes = make(map[string]int64)
}
oldSize, sizeOk := c.BigDataSizes[key]
c.BigDataSizes[key] = int64(len(data))
if c.BigDataDigests == nil {
c.BigDataDigests = make(map[string]digest.Digest)
}
oldDigest, digestOk := c.BigDataDigests[key]
newDigest := digest.Canonical.FromBytes(data)
c.BigDataDigests[key] = newDigest
if !sizeOk || oldSize != c.BigDataSizes[key] || !digestOk || oldDigest != newDigest {
save = true
}
addName := true
for _, name := range c.BigDataNames {
if name == key {
addName = false
break
}
}
if addName {
c.BigDataNames = append(c.BigDataNames, key)
save = true
}
if save {
err = r.Save()
}
}
return err
}
func (r *containerStore) Wipe() error {
ids := make([]string, 0, len(r.byid))
for id := range r.byid {
ids = append(ids, id)
}
for _, id := range ids {
if err := r.Delete(id); err != nil {
return err
}
}
return nil
}
func (r *containerStore) Lock() {
r.lockfile.Lock()
}
func (r *containerStore) Unlock() {
r.lockfile.Unlock()
}
func (r *containerStore) Touch() error {
return r.lockfile.Touch()
}
func (r *containerStore) Modified() (bool, error) {
return r.lockfile.Modified()
}
func (r *containerStore) IsReadWrite() bool {
return r.lockfile.IsReadWrite()
}
func (r *containerStore) TouchedSince(when time.Time) bool {
return r.lockfile.TouchedSince(when)
}
| apache-2.0 |
hazendaz/assertj-core | src/test/java/org/assertj/core/api/abstract_/AbstractAssert_asInstanceOf_with_InstanceOfAssertFactory_Test.java | 2795 | /*
* 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.
*
* Copyright 2012-2021 the original author or authors.
*/
package org.assertj.core.api.abstract_;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.assertj.core.api.BDDAssertions.then;
import static org.assertj.core.api.InstanceOfAssertFactories.LONG;
import static org.assertj.core.error.ShouldNotBeNull.shouldNotBeNull;
import static org.mockito.Mockito.verify;
import org.assertj.core.api.AbstractAssert;
import org.assertj.core.api.AbstractAssertBaseTest;
import org.assertj.core.api.AbstractLongAssert;
import org.assertj.core.api.ConcreteAssert;
import org.assertj.core.api.InstanceOfAssertFactory;
import org.assertj.core.api.NavigationMethodBaseTest;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
/**
* Tests for <code>{@link AbstractAssert#asInstanceOf(InstanceOfAssertFactory)}</code>.
*
* @author Stefano Cordio
*/
@DisplayName("AbstractAssert asInstanceOf(InstanceOfAssertFactory)")
class AbstractAssert_asInstanceOf_with_InstanceOfAssertFactory_Test extends AbstractAssertBaseTest
implements NavigationMethodBaseTest<ConcreteAssert> {
@Override
protected ConcreteAssert invoke_api_method() {
assertions.asInstanceOf(LONG);
return null;
}
@Override
protected void verify_internal_effects() {
verify(objects).assertIsInstanceOf(getInfo(assertions), getActual(assertions), Long.class);
}
@Override
public void should_return_this() {
// Test disabled since asInstanceOf does not return this.
}
@Override
public ConcreteAssert getAssertion() {
return assertions;
}
@Override
public AbstractAssert<?, ?> invoke_navigation_method(ConcreteAssert assertion) {
return assertion.asInstanceOf(LONG);
}
@Test
void should_throw_npe_if_no_factory_is_given() {
// WHEN
Throwable thrown = catchThrowable(() -> assertions.asInstanceOf(null));
// THEN
then(thrown).isInstanceOf(NullPointerException.class)
.hasMessage(shouldNotBeNull("instanceOfAssertFactory").create());
}
@Test
void should_return_narrowed_assert_type() {
// WHEN
AbstractAssert<?, ?> result = assertions.asInstanceOf(LONG);
// THEN
then(result).isInstanceOf(AbstractLongAssert.class);
}
}
| apache-2.0 |
marcuswr/elasticsearch-dateline | src/main/java/org/elasticsearch/search/aggregations/bucket/terms/TermsAggregatorFactory.java | 13808 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.search.aggregations.bucket.terms;
import org.apache.lucene.search.IndexSearcher;
import org.elasticsearch.ElasticsearchIllegalArgumentException;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.search.aggregations.*;
import org.elasticsearch.search.aggregations.bucket.terms.support.IncludeExclude;
import org.elasticsearch.search.aggregations.support.AggregationContext;
import org.elasticsearch.search.aggregations.support.ValuesSource;
import org.elasticsearch.search.aggregations.support.ValuesSourceAggregatorFactory;
import org.elasticsearch.search.aggregations.support.ValuesSourceConfig;
/**
*
*/
public class TermsAggregatorFactory extends ValuesSourceAggregatorFactory {
public enum ExecutionMode {
MAP(new ParseField("map")) {
@Override
Aggregator create(String name, AggregatorFactories factories, ValuesSource valuesSource, long estimatedBucketCount,
long maxOrd, InternalOrder order, int requiredSize, int shardSize, long minDocCount, IncludeExclude includeExclude,
AggregationContext aggregationContext, Aggregator parent) {
return new StringTermsAggregator(name, factories, valuesSource, estimatedBucketCount, order, requiredSize, shardSize, minDocCount, includeExclude, aggregationContext, parent);
}
@Override
boolean needsGlobalOrdinals() {
return false;
}
},
ORDINALS(new ParseField("ordinals")) {
@Override
Aggregator create(String name, AggregatorFactories factories, ValuesSource valuesSource, long estimatedBucketCount,
long maxOrd, InternalOrder order, int requiredSize, int shardSize, long minDocCount, IncludeExclude includeExclude,
AggregationContext aggregationContext, Aggregator parent) {
if (includeExclude != null) {
return MAP.create(name, factories, valuesSource, estimatedBucketCount, maxOrd, order, requiredSize, shardSize, minDocCount, includeExclude, aggregationContext, parent);
}
return new StringTermsAggregator.WithOrdinals(name, factories, (ValuesSource.Bytes.WithOrdinals) valuesSource, estimatedBucketCount, order, requiredSize, shardSize, minDocCount, aggregationContext, parent);
}
@Override
boolean needsGlobalOrdinals() {
return false;
}
},
GLOBAL_ORDINALS(new ParseField("global_ordinals")) {
@Override
Aggregator create(String name, AggregatorFactories factories, ValuesSource valuesSource, long estimatedBucketCount,
long maxOrd, InternalOrder order, int requiredSize, int shardSize, long minDocCount, IncludeExclude includeExclude,
AggregationContext aggregationContext, Aggregator parent) {
return new GlobalOrdinalsStringTermsAggregator(name, factories, (ValuesSource.Bytes.WithOrdinals.FieldData) valuesSource, estimatedBucketCount, maxOrd, order, requiredSize, shardSize, minDocCount, includeExclude, aggregationContext, parent);
}
@Override
boolean needsGlobalOrdinals() {
return true;
}
},
GLOBAL_ORDINALS_HASH(new ParseField("global_ordinals_hash")) {
@Override
Aggregator create(String name, AggregatorFactories factories, ValuesSource valuesSource, long estimatedBucketCount,
long maxOrd, InternalOrder order, int requiredSize, int shardSize, long minDocCount, IncludeExclude includeExclude,
AggregationContext aggregationContext, Aggregator parent) {
return new GlobalOrdinalsStringTermsAggregator.WithHash(name, factories, (ValuesSource.Bytes.WithOrdinals.FieldData) valuesSource, estimatedBucketCount, maxOrd, order, requiredSize, shardSize, minDocCount, includeExclude, aggregationContext, parent);
}
@Override
boolean needsGlobalOrdinals() {
return true;
}
},
GLOBAL_ORDINALS_LOW_CARDINALITY(new ParseField("global_ordinals_low_cardinality")) {
@Override
Aggregator create(String name, AggregatorFactories factories, ValuesSource valuesSource, long estimatedBucketCount,
long maxOrd, InternalOrder order, int requiredSize, int shardSize, long minDocCount, IncludeExclude includeExclude,
AggregationContext aggregationContext, Aggregator parent) {
if (includeExclude != null || factories != null) {
return GLOBAL_ORDINALS.create(name, factories, valuesSource, estimatedBucketCount, maxOrd, order, requiredSize, shardSize, minDocCount, includeExclude, aggregationContext, parent);
}
return new GlobalOrdinalsStringTermsAggregator.LowCardinality(name, factories, (ValuesSource.Bytes.WithOrdinals.FieldData) valuesSource, estimatedBucketCount, maxOrd, order, requiredSize, shardSize, minDocCount, aggregationContext, parent);
}
@Override
boolean needsGlobalOrdinals() {
return true;
}
};
public static ExecutionMode fromString(String value) {
for (ExecutionMode mode : values()) {
if (mode.parseField.match(value)) {
return mode;
}
}
throw new ElasticsearchIllegalArgumentException("Unknown `execution_hint`: [" + value + "], expected any of " + values());
}
private final ParseField parseField;
ExecutionMode(ParseField parseField) {
this.parseField = parseField;
}
abstract Aggregator create(String name, AggregatorFactories factories, ValuesSource valuesSource, long estimatedBucketCount,
long maxOrd, InternalOrder order, int requiredSize, int shardSize, long minDocCount,
IncludeExclude includeExclude, AggregationContext aggregationContext, Aggregator parent);
abstract boolean needsGlobalOrdinals();
@Override
public String toString() {
return parseField.getPreferredName();
}
}
private final InternalOrder order;
private final int requiredSize;
private final int shardSize;
private final long minDocCount;
private final IncludeExclude includeExclude;
private final String executionHint;
public TermsAggregatorFactory(String name, ValuesSourceConfig config, InternalOrder order, int requiredSize,
int shardSize, long minDocCount, IncludeExclude includeExclude, String executionHint) {
super(name, StringTerms.TYPE.name(), config);
this.order = order;
this.requiredSize = requiredSize;
this.shardSize = shardSize;
this.minDocCount = minDocCount;
this.includeExclude = includeExclude;
this.executionHint = executionHint;
}
@Override
protected Aggregator createUnmapped(AggregationContext aggregationContext, Aggregator parent) {
final InternalAggregation aggregation = new UnmappedTerms(name, order, requiredSize, minDocCount);
return new NonCollectingAggregator(name, aggregationContext, parent) {
@Override
public InternalAggregation buildEmptyAggregation() {
return aggregation;
}
};
}
public static long estimatedBucketCount(ValuesSource valuesSource, Aggregator parent) {
long estimatedBucketCount = valuesSource.metaData().maxAtomicUniqueValuesCount();
if (estimatedBucketCount < 0) {
// there isn't an estimation available.. 50 should be a good start
estimatedBucketCount = 50;
}
// adding an upper bound on the estimation as some atomic field data in the future (binary doc values) and not
// going to know their exact cardinality and will return upper bounds in AtomicFieldData.getNumberUniqueValues()
// that may be largely over-estimated.. the value chosen here is arbitrary just to play nice with typical CPU cache
//
// Another reason is that it may be faster to resize upon growth than to start directly with the appropriate size.
// And that all values are not necessarily visited by the matches.
estimatedBucketCount = Math.min(estimatedBucketCount, 512);
if (Aggregator.hasParentBucketAggregator(parent)) {
// There is a parent that creates buckets, potentially with a very long tail of buckets with few documents
// Let's be conservative with memory in that case
estimatedBucketCount = Math.min(estimatedBucketCount, 8);
}
return estimatedBucketCount;
}
@Override
protected Aggregator create(ValuesSource valuesSource, long expectedBucketsCount, AggregationContext aggregationContext, Aggregator parent) {
long estimatedBucketCount = estimatedBucketCount(valuesSource, parent);
if (valuesSource instanceof ValuesSource.Bytes) {
ExecutionMode execution = null;
if (executionHint != null) {
execution = ExecutionMode.fromString(executionHint);
}
// In some cases, using ordinals is just not supported: override it
if (!(valuesSource instanceof ValuesSource.Bytes.WithOrdinals)) {
execution = ExecutionMode.MAP;
}
final long maxOrd;
final double ratio;
if (execution == null || execution.needsGlobalOrdinals()) {
ValuesSource.Bytes.WithOrdinals valueSourceWithOrdinals = (ValuesSource.Bytes.WithOrdinals) valuesSource;
IndexSearcher indexSearcher = aggregationContext.searchContext().searcher();
maxOrd = valueSourceWithOrdinals.globalMaxOrd(indexSearcher);
ratio = maxOrd / ((double) indexSearcher.getIndexReader().numDocs());
} else {
maxOrd = -1;
ratio = -1;
}
// Let's try to use a good default
if (execution == null) {
// if there is a parent bucket aggregator the number of instances of this aggregator is going
// to be unbounded and most instances may only aggregate few documents, so use hashed based
// global ordinals to keep the bucket ords dense.
if (Aggregator.hasParentBucketAggregator(parent)) {
execution = ExecutionMode.GLOBAL_ORDINALS_HASH;
} else {
if (factories == AggregatorFactories.EMPTY) {
if (ratio <= 0.5 && maxOrd <= 2048) {
// 0.5: At least we need reduce the number of global ordinals look-ups by half
// 2048: GLOBAL_ORDINALS_LOW_CARDINALITY has additional memory usage, which directly linked to maxOrd, so we need to limit.
execution = ExecutionMode.GLOBAL_ORDINALS_LOW_CARDINALITY;
} else {
execution = ExecutionMode.GLOBAL_ORDINALS;
}
} else {
execution = ExecutionMode.GLOBAL_ORDINALS;
}
}
}
assert execution != null;
valuesSource.setNeedsGlobalOrdinals(execution.needsGlobalOrdinals());
return execution.create(name, factories, valuesSource, estimatedBucketCount, maxOrd, order, requiredSize, shardSize, minDocCount, includeExclude, aggregationContext, parent);
}
if (includeExclude != null) {
throw new AggregationExecutionException("Aggregation [" + name + "] cannot support the include/exclude " +
"settings as it can only be applied to string values");
}
if (valuesSource instanceof ValuesSource.Numeric) {
if (((ValuesSource.Numeric) valuesSource).isFloatingPoint()) {
return new DoubleTermsAggregator(name, factories, (ValuesSource.Numeric) valuesSource, config.format(), estimatedBucketCount, order, requiredSize, shardSize, minDocCount, aggregationContext, parent);
}
return new LongTermsAggregator(name, factories, (ValuesSource.Numeric) valuesSource, config.format(), estimatedBucketCount, order, requiredSize, shardSize, minDocCount, aggregationContext, parent);
}
throw new AggregationExecutionException("terms aggregation cannot be applied to field [" + config.fieldContext().field() +
"]. It can only be applied to numeric or string fields.");
}
}
| apache-2.0 |
suzaku-io/suzaku | webdemo/src/main/scala/perftest/PerfUIEntry.scala | 1547 | package perftest
import org.scalajs.dom
import org.scalajs.dom.raw.Worker
import suzaku.platform.web.{WebWorkerTransport, WorkerClientTransport}
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}
import scala.scalajs.js.typedarray.ArrayBuffer
@JSExportTopLevel("PerfUIEntry")
object PerfUIEntry {
var transport: WebWorkerTransport = _
@JSExport
def entry(workerScript: String): Unit = {
// create the worker to run our application in
val worker = new Worker(workerScript)
// create the transport
transport = new WorkerClientTransport(worker)
// listen to messages from worker
worker.onmessage = onMessage _
new PerfUI(transport)
}
private def debugPrint(data: Array[Byte]): Unit = {
data.grouped(16).foreach { d =>
val hex = d.map(c => "%02X " format (c & 0xFF)).mkString
val str = d
.collect {
case ascii if ascii >= 0x20 && ascii < 0x80 => ascii
case _ => '.'.toByte
}
.map(_.toChar)
.mkString
println(hex.padTo(16 * 3, ' ') + str)
}
}
def onMessage(msg: dom.MessageEvent) = {
msg.data match {
case buffer: ArrayBuffer =>
/*
val debugData = TypedArrayBuffer.wrap(buffer.slice(0))
val debugArray = Array.ofDim[Byte](debugData.limit())
debugData.get(debugArray)
println(s"UI Received:")
debugPrint(debugArray)
*/
transport.receive(buffer)
case _ => // ignore other messages
}
}
}
| apache-2.0 |
spheric/spheric.github.io | mail/contact_me.php | 1119 | <?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['phone']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
// Create the email and send the message
$to = 'roguespicecanteen@gmail.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply@roguespicecanteen.com.au\n"; // This is the email address the generated message will be from. We recommend using something like noreply@roguespicecanteen.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>
| apache-2.0 |
IBM-Bluemix/bluemix-cloud-connectors | samples/spring-cloud-connector-cloudant-test/src/main/java/org/terrence/testapp/TestappApplication.java | 753 | package org.terrence.testapp;
import org.ektorp.CouchDbConnector;
import org.ektorp.CouchDbInstance;
import org.ektorp.impl.StdCouchDbConnector;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class TestappApplication {
public static void main(String[] args) {
SpringApplication.run(TestappApplication.class, args);
}
@Bean
public CouchDbConnector couchDbConnector(CouchDbInstance couchDbInstance) {
CouchDbConnector connector = new StdCouchDbConnector("status", couchDbInstance);
connector.createDatabaseIfNotExists();
return connector;
}
}
| apache-2.0 |
rodbate/RpcComponent | src/main/java/com/rodbate/rpc/RpcService.java | 779 | package com.rodbate.rpc;
import com.rodbate.rpc.exception.RpcSendRequestException;
import com.rodbate.rpc.exception.RpcTimeoutException;
import com.rodbate.rpc.exception.RpcTooMuchRequestException;
import com.rodbate.rpc.netty.InvokeCallback;
import com.rodbate.rpc.netty.NettyRpcRequestProcessor;
import com.rodbate.rpc.protocol.RpcCommand;
import io.netty.channel.Channel;
import java.util.concurrent.ExecutorService;
public interface RpcService {
void start();
void shutdown();
void registerRpcHook(RpcHook rpcHook);
void registerProcessor(final int requestCode, final NettyRpcRequestProcessor processor, final ExecutorService service);
void registerDefaultProcessor(final NettyRpcRequestProcessor processor, final ExecutorService service);
}
| apache-2.0 |
stefanocke/japkit-examples | japkit-examples-roo-petclinic/src/main/java/de/japkit/roo/petclinic/web/PetControllerDef.java | 218 | package de.japkit.roo.petclinic.web;
import de.japkit.roo.japkit.web.JapkitWebScaffold;
import de.japkit.roo.petclinic.domain.Pet;
@JapkitWebScaffold(formBackingObject = Pet.class)
public class PetControllerDef {
}
| apache-2.0 |
Sargul/dbeaver | plugins/org.jkiss.dbeaver.ext.mssql/src/org/jkiss/dbeaver/ext/mssql/tasks/SQLServerToolTableRebuild.java | 1681 | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2021 DBeaver Corp and others
*
* 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.mssql.tasks;
import org.jkiss.dbeaver.ext.mssql.model.SQLServerTableBase;
import org.jkiss.dbeaver.model.DBPEvaluationContext;
import org.jkiss.dbeaver.model.edit.DBEPersistAction;
import org.jkiss.dbeaver.model.exec.DBCException;
import org.jkiss.dbeaver.model.exec.DBCSession;
import org.jkiss.dbeaver.model.impl.edit.SQLDatabasePersistAction;
import java.util.List;
public class SQLServerToolTableRebuild extends SQLServerToolWithStatus<SQLServerTableBase, SQLServerToolTableRebuildSettings> {
@Override
public SQLServerToolTableRebuildSettings createToolSettings() {
return new SQLServerToolTableRebuildSettings();
}
@Override
public void generateObjectQueries(DBCSession session, SQLServerToolTableRebuildSettings settings, List<DBEPersistAction> queries, SQLServerTableBase object) throws DBCException {
queries.add(new SQLDatabasePersistAction("ALTER INDEX ALL ON " + object.getFullyQualifiedName(DBPEvaluationContext.DDL) + " REBUILD "));
}
}
| apache-2.0 |
elharo/appengine-maven-archetypes-java | guestbook-archetype/src/main/resources/archetype-resources/src/test/java/GuestbookServletTest.java | 2442 | #set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
/**
* Copyright 2012 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 ${package};
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
import com.google.appengine.tools.development.testing.LocalUserServiceTestConfig;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class GuestbookServletTest {
private GuestbookServlet guestbookServlet;
private final LocalServiceTestHelper helper =
new LocalServiceTestHelper(new LocalUserServiceTestConfig())
.setEnvIsLoggedIn(true)
.setEnvAuthDomain("localhost")
.setEnvEmail("test@localhost");
@Before
public void setupGuestBookServlet() {
helper.setUp();
guestbookServlet = new GuestbookServlet();
}
@After
public void tearDownHelper() {
helper.tearDown();
}
@Test
public void testDoGet() throws IOException {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
StringWriter stringWriter = new StringWriter();
when(response.getWriter()).thenReturn(new PrintWriter(stringWriter));
guestbookServlet.doGet(request, response);
User currentUser = UserServiceFactory.getUserService().getCurrentUser();
assertEquals("Hello, " + currentUser.getNickname() + System.getProperty("line.separator"), stringWriter.toString());
}
}
| apache-2.0 |
gyankov/Goomer | Goomer/Goomer.Web/Models/Home/HomeViewModel.cs | 413 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Goomer.Web.Models.Home
{
public class HomeViewModel
{
public IEnumerable<TireViewModel> Tires { get; set; }
public IEnumerable<RimViewModel> Rims { get; set; }
public IEnumerable<RimWithTireViewModel> RimsWithTires { get; set; }
public int AdsCount { get; set; }
}
} | apache-2.0 |
googleapis/python-aiplatform | samples/generated_samples/aiplatform_generated_aiplatform_v1_metadata_service_list_metadata_stores_async.py | 1625 | # -*- coding: utf-8 -*-
# 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
#
# 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.
#
# Generated code. DO NOT EDIT!
#
# Snippet for ListMetadataStores
# NOTE: This snippet has been automatically generated for illustrative purposes only.
# It may require modifications to work in your environment.
# To install the latest published package dependency, execute the following:
# python3 -m pip install google-cloud-aiplatform
# [START aiplatform_generated_aiplatform_v1_MetadataService_ListMetadataStores_async]
from google.cloud import aiplatform_v1
async def sample_list_metadata_stores():
"""Snippet for list_metadata_stores"""
# Create a client
client = aiplatform_v1.MetadataServiceAsyncClient()
# Initialize request argument(s)
request = aiplatform_v1.ListMetadataStoresRequest(
parent="projects/{project}/locations/{location}",
)
# Make the request
page_result = client.list_metadata_stores(request=request)
async for response in page_result:
print(response)
# [END aiplatform_generated_aiplatform_v1_MetadataService_ListMetadataStores_async]
| apache-2.0 |
qtproject/qtqa-gerrit-plugin-replication | src/test/java/com/googlesource/gerrit/plugins/replication/ChainedSchedulerTest.java | 15363 | // Copyright (C) 2020 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.googlesource.gerrit.plugins.replication;
import static com.google.common.truth.Truth.assertThat;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import com.google.common.collect.ForwardingIterator;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;
import org.junit.Before;
import org.junit.Test;
public class ChainedSchedulerTest {
/** A simple {@link Runnable} that waits until the start() method is called. */
public class WaitingRunnable implements Runnable {
protected final CountDownLatch start;
public WaitingRunnable() {
this(new CountDownLatch(1));
}
public WaitingRunnable(CountDownLatch latch) {
this.start = latch;
}
@Override
public void run() {
try {
start.await();
} catch (InterruptedException e) {
missedAwaits.incrementAndGet();
}
}
public void start() {
start.countDown();
}
}
/** A simple {@link Runnable} that can be awaited to start to run. */
public static class WaitableRunnable implements Runnable {
protected final CountDownLatch started = new CountDownLatch(1);
@Override
public void run() {
started.countDown();
}
public boolean isStarted() {
return started.getCount() == 0;
}
public boolean awaitStart(int itemsBefore) {
try {
return started.await(SECONDS_SYNCHRONIZE * itemsBefore, SECONDS);
} catch (InterruptedException e) {
return false;
}
}
}
/** An {@link Iterator} wrapper which keeps track of how many times next() has been called. */
public static class CountingIterator extends ForwardingIterator<String> {
public volatile int count = 0;
protected Iterator<String> delegate;
public CountingIterator(Iterator<String> delegate) {
this.delegate = delegate;
}
@Override
public synchronized String next() {
count++;
return super.next();
}
@Override
protected Iterator<String> delegate() {
return delegate;
}
}
/** A {@link ChainedScheduler.Runner} which keeps track of completion and counts. */
public static class TestRunner implements ChainedScheduler.Runner<String> {
protected final AtomicInteger runCount = new AtomicInteger(0);
protected final CountDownLatch onDone = new CountDownLatch(1);
@Override
public void run(String item) {
incrementAndGet();
}
public int runCount() {
return runCount.get();
}
@Override
public void onDone() {
onDone.countDown();
}
public boolean isDone() {
return onDone.getCount() <= 0;
}
public boolean awaitDone(int items) {
try {
return onDone.await(items * SECONDS_SYNCHRONIZE, SECONDS);
} catch (InterruptedException e) {
return false;
}
}
protected int incrementAndGet() {
return runCount.incrementAndGet();
}
}
/**
* A {@link TestRunner} that can be awaited to start to run and additionally will wait until
* increment() or runOnewRandomStarted() is called to complete.
*/
public class WaitingRunner extends TestRunner {
protected class RunContext extends WaitableRunnable {
CountDownLatch run = new CountDownLatch(1);
CountDownLatch ran = new CountDownLatch(1);
int count;
@Override
public void run() {
super.run();
try {
run.await();
count = incrementAndGet();
ran.countDown();
} catch (InterruptedException e) {
missedAwaits.incrementAndGet();
}
}
public synchronized boolean startIfNotRunning() throws InterruptedException {
if (run.getCount() > 0) {
increment();
return true;
}
return false;
}
public synchronized int increment() throws InterruptedException {
run.countDown();
ran.await(); // no timeout needed as RunContext.run() calls countDown unless interrupted
return count;
}
}
protected final Map<String, RunContext> ctxByItem = new ConcurrentHashMap<>();
@Override
public void run(String item) {
context(item).run();
}
public void runOneRandomStarted() throws InterruptedException {
while (true) {
for (RunContext ctx : ctxByItem.values()) {
if (ctx.isStarted()) {
if (ctx.startIfNotRunning()) {
return;
}
}
}
MILLISECONDS.sleep(1);
}
}
public boolean awaitStart(String item, int itemsBefore) {
return context(item).awaitStart(itemsBefore);
}
public int increment(String item) throws InterruptedException {
return increment(item, 1);
}
public int increment(String item, int itemsBefore) throws InterruptedException {
awaitStart(item, itemsBefore);
return context(item).increment();
}
protected RunContext context(String item) {
return ctxByItem.computeIfAbsent(item, k -> new RunContext());
}
}
// Time for one synchronization event such as await(), or variable
// incrementing across threads to take
public static final int SECONDS_SYNCHRONIZE = 3;
public static final int MANY_ITEMS_SIZE = 1000;
public static String FIRST = item(1);
public static String SECOND = item(2);
public static String THIRD = item(3);
public final AtomicInteger missedAwaits = new AtomicInteger(0); // non-zero signals an error
@Before
public void setup() {
missedAwaits.set(0);
}
@Test
public void emptyCompletesImmediately() {
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
TestRunner runner = new TestRunner();
List<String> items = new ArrayList<>();
new ChainedScheduler<>(executor, items.iterator(), runner);
assertThat(runner.awaitDone(1)).isEqualTo(true);
assertThat(runner.runCount()).isEqualTo(0);
}
@Test
public void oneItemCompletes() throws Exception {
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
TestRunner runner = new TestRunner();
List<String> items = new ArrayList<>();
items.add(FIRST);
new ChainedScheduler<>(executor, items.iterator(), runner);
assertThat(runner.awaitDone(1)).isEqualTo(true);
assertThat(runner.runCount()).isEqualTo(1);
}
@Test
public void manyItemsAllComplete() throws Exception {
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
TestRunner runner = new TestRunner();
List<String> items = createManyItems();
new ChainedScheduler<>(executor, items.iterator(), runner);
assertThat(runner.awaitDone(items.size())).isEqualTo(true);
assertThat(runner.runCount()).isEqualTo(items.size());
}
@Test
public void exceptionInTaskDoesNotAbortIteration() throws Exception {
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
TestRunner runner =
new TestRunner() {
@Override
public void run(String item) {
super.run(item);
throw new RuntimeException();
}
};
List<String> items = new ArrayList<>();
items.add(FIRST);
items.add(SECOND);
items.add(THIRD);
new ChainedScheduler<>(executor, items.iterator(), runner);
assertThat(runner.awaitDone(items.size())).isEqualTo(true);
assertThat(runner.runCount()).isEqualTo(items.size());
}
@Test
public void onDoneNotCalledBeforeAllCompleted() throws Exception {
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
WaitingRunner runner = new WaitingRunner();
List<String> items = createManyItems();
new ChainedScheduler<>(executor, items.iterator(), runner);
for (int i = 1; i <= items.size(); i++) {
assertThat(runner.isDone()).isEqualTo(false);
runner.runOneRandomStarted();
}
assertThat(runner.awaitDone(items.size())).isEqualTo(true);
assertThat(runner.runCount()).isEqualTo(items.size());
assertThat(missedAwaits.get()).isEqualTo(0);
}
@Test
public void otherTasksOnlyEverWaitForAtMostOneRunningPlusOneWaiting() throws Exception {
for (int threads = 1; threads <= 10; threads++) {
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
WaitingRunner runner = new WaitingRunner();
List<String> items = createItems(threads + 1 /* Running */ + 1 /* Waiting */);
CountingIterator it = new CountingIterator(items.iterator());
new ChainedScheduler<>(executor, it, runner);
assertThat(runner.awaitStart(FIRST, 1)).isEqualTo(true); // Confirms at least one Running
assertThat(it.count).isGreaterThan(1); // Confirms at least one extra Waiting or Running
assertThat(it.count).isLessThan(items.size()); // Confirms at least one still not queued
WaitableRunnable external = new WaitableRunnable();
executor.execute(external);
assertThat(external.isStarted()).isEqualTo(false);
// Completes 2, (at most one Running + 1 Waiting)
assertThat(runner.increment(FIRST)).isEqualTo(1); // Was Running
assertThat(runner.increment(SECOND)).isEqualTo(2); // Was Waiting
// Asserts that the one that still needed to be queued is not blocking this external task
assertThat(external.awaitStart(1)).isEqualTo(true);
for (int i = 3; i <= items.size(); i++) {
runner.increment(item(i));
}
assertThat(missedAwaits.get()).isEqualTo(0);
}
}
@Test
public void saturatesManyFreeThreads() throws Exception {
int threads = 10;
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(threads);
WaitingRunner runner = new WaitingRunner();
List<String> items = createManyItems();
new ChainedScheduler<>(executor, items.iterator(), runner);
for (int j = 1; j <= MANY_ITEMS_SIZE; j += threads) {
// If #threads items can start before any complete, it proves #threads are
// running in parallel and saturating all available threads.
for (int i = j; i < j + threads; i++) {
assertThat(runner.awaitStart(item(i), threads)).isEqualTo(true);
}
for (int i = j; i < j + threads; i++) {
assertThat(runner.increment(item(i))).isEqualTo(i);
}
}
assertThat(runner.awaitDone(threads)).isEqualTo(true);
assertThat(runner.runCount()).isEqualTo(items.size());
assertThat(missedAwaits.get()).isEqualTo(0);
}
@Test
public void makesProgressEvenWhenSaturatedByOtherTasks() throws Exception {
int blockSize = 5; // how many batches to queue at once
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(blockSize);
List<String> items = createManyItems();
WaitingRunner runner = new WaitingRunner();
int batchSize = 5; // how many tasks are started concurrently
Queue<CountDownLatch> batches = new LinkedList<>();
for (int b = 0; b < blockSize; b++) {
batches.add(executeWaitingRunnableBatch(batchSize, executor));
}
new ChainedScheduler<>(executor, items.iterator(), runner);
for (int i = 1; i <= items.size(); i++) {
for (int b = 0; b < blockSize; b++) {
// Ensure saturation by always having at least a full thread count of
// other tasks waiting in the queue after the waiting item so that when
// one batch is executed, and the item then executes, there will still
// be at least a full batch waiting.
batches.add(executeWaitingRunnableBatch(batchSize, executor));
batches.remove().countDown();
}
assertThat(runner.increment(item(i), batchSize)).isEqualTo(i); // Assert progress can be made
}
assertThat(runner.runCount()).isEqualTo(items.size());
while (batches.size() > 0) {
batches.remove().countDown();
}
assertThat(missedAwaits.get()).isEqualTo(0);
}
@Test
public void forwardingRunnerForwards() throws Exception {
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
TestRunner runner = new TestRunner();
List<String> items = createManyItems();
new ChainedScheduler<>(
executor, items.iterator(), new ChainedScheduler.ForwardingRunner<>(runner));
assertThat(runner.awaitDone(items.size())).isEqualTo(true);
assertThat(runner.runCount()).isEqualTo(items.size());
}
@Test
public void streamSchedulerClosesStream() throws Exception {
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
WaitingRunner runner = new WaitingRunner();
List<String> items = new ArrayList<>();
items.add(FIRST);
items.add(SECOND);
final AtomicBoolean closed = new AtomicBoolean(false);
Object closeRecorder =
new Object() {
@SuppressWarnings("unused") // Called via reflection
public void close() {
closed.set(true);
}
};
@SuppressWarnings("unchecked") // Stream.class is converted to Stream<String>.class
Stream<String> stream = ForwardingProxy.create(Stream.class, items.stream(), closeRecorder);
new ChainedScheduler.StreamScheduler<>(executor, stream, runner);
assertThat(closed.get()).isEqualTo(false);
// Since there is only a single thread, the Stream cannot get closed before this runs
runner.increment(FIRST);
// The Stream should get closed as the last item (SECOND) runs, before its runner is called
runner.increment(SECOND); // Ensure the last item's runner has already been called
assertThat(runner.awaitDone(items.size())).isEqualTo(true);
assertThat(runner.runCount()).isEqualTo(items.size());
assertThat(closed.get()).isEqualTo(true);
}
protected CountDownLatch executeWaitingRunnableBatch(
int batchSize, ScheduledThreadPoolExecutor executor) {
CountDownLatch latch = new CountDownLatch(1);
for (int e = 0; e < batchSize; e++) {
executor.execute(new WaitingRunnable(latch));
}
return latch;
}
protected static List<String> createManyItems() {
return createItems(MANY_ITEMS_SIZE);
}
protected static List<String> createItems(int count) {
List<String> items = new ArrayList<>();
for (int i = 1; i <= count; i++) {
items.add(item(i));
}
return items;
}
protected static String item(int i) {
return "Item #" + i;
}
}
| apache-2.0 |
DanielGarcia-Carrillo/Beats-by-Dr-D | src/com/android/sampler/MusicSamplerActivity.java | 21975 | package com.android.sampler;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.*;
import android.media.AudioManager;
import android.media.MediaMetadataRetriever;
import android.media.SoundPool;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.*;
import com.android.sampler.audio.Decode;
import com.android.sampler.audio.FileTypeUtils;
import com.android.sampler.wireless.*;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class MusicSamplerActivity extends Activity {
private static final String PREFERENCES = "samplerActivityPreferences";
private static final int NUM_SAMPLES = 9;
private final Map<Integer, Sample> buttonSamples = new HashMap<Integer, Sample>(NUM_SAMPLES);
private final SoundPool songsPlaying = new SoundPool(NUM_SAMPLES + 1, AudioManager.STREAM_MUSIC, 0);
public static final int REQUEST_SAMPLE_CHOOSE = 2;
private int selectedButtonID;
private SampleTracker tracker;
private SamplerActivityState state;
private Context context = this;
private boolean jammin = false;
private ArrayAdapter<String> deviceListAdapter;
private BluetoothAdapter bluetoothAdapter;
private BluetoothServerThread server = null;
private BluetoothClientThread client = null;
private ConnectedSocketManager connectionSocketManager = null;
/**
* Setup button responsible for allowing button
*/
private void initEditButton() {
final Button edit = (Button) findViewById(R.id.edit);
edit.setOnClickListener(new View.OnClickListener() {
// Change text of edit button on press and set editmode
public void onClick(View v) {
if (!state.inEditMode()) {
state.setEditMode();
edit.setText(R.string.done);
} else {
state.disableAllModes();
edit.setText(R.string.edit);
}
}
});
Log.d("Sampler Edit", "Edit button successfully initialized");
}
private void initializeRecordButton() {
final Button record = (Button) findViewById(R.id.record);
record.setOnTouchListener(new View.OnTouchListener() {
Looper backgroundLooper;
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (state.isRecording()) {
if (backgroundLooper != null) {
backgroundLooper.stopExecution();
backgroundLooper = null;
}
tracker.stop(event.getEventTime());
state.disableAllModes();
record.setText(R.string.record);
} else {
if (!tracker.isFirstRecording()) {
backgroundLooper = new Looper(songsPlaying);
backgroundLooper.start();
}
tracker.start(event.getEventTime());
state.setRecording();
record.setText(R.string.done);
}
return true;
}
// We don't care about nonclicks so don't consume this operation
return false;
}
});
}
private void initializeLoopButton() {
final Button loop = (Button) findViewById(R.id.loop);
loop.setOnClickListener(new View.OnClickListener() {
Looper backgroundLooper;
@Override
public void onClick(View v) {
if (state.inLoopMode()) {
backgroundLooper.stopExecution();
backgroundLooper = null;
loop.setText(R.string.loop);
state.disableAllModes();
} else {
backgroundLooper = new Looper(songsPlaying);
backgroundLooper.start();
loop.setText(R.string.stop);
state.setLoopMode();
}
}
});
}
private void initializeResetButton() {
final Button reset = (Button) findViewById(R.id.reset);
reset.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
tracker.resetTracker();
state.reset();
}
});
}
private final BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
deviceListAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
};
private void initializeCoopSessionButtons() {
final Button hostJam = (Button) findViewById(R.id.jam);
final Button joinJam = (Button) findViewById(R.id.joinjam);
if (BluetoothUtils.isBluetoothSupported()) {
deviceListAdapter = new ArrayAdapter<String>(getApplication(), android.R.layout.simple_list_item_1);
hostJam.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
state.hostJam();
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
context.registerReceiver(bluetoothReceiver, filter);
// Called in case we are at the end of a prior discovery session
bluetoothAdapter.cancelDiscovery();
bluetoothAdapter.startDiscovery();
// Make dialog for choosing our bluetooth pair
showBluetoothDeviceDialog();
}
});
joinJam.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
state.joinJam();
// Despite this being the join option, we spawn a server thread...
connectionSocketManager = new ConnectedSocketManager();
server = new BluetoothServerThread(context, bluetoothAdapter, connectionSocketManager);
// Joining simply has us make the current device discoverable
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 30);
startActivity(discoverableIntent);
server.run();
jammin = true;
}
});
} else {
// Make jam button invisible and disabled
hostJam.setEnabled(false);
hostJam.setVisibility(View.GONE);
joinJam.setEnabled(false);
joinJam.setVisibility(View.GONE);
}
}
private void showBluetoothDeviceDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choose android device");
ListView foundDevices = new ListView(context);
foundDevices.setAdapter(deviceListAdapter);
foundDevices.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
// Any discovery that we are currently doing should be stopped because we're about to choose something
bluetoothAdapter.cancelDiscovery();
String deviceInfo = ((TextView) view).getText().toString();
// The info is newline delimited so I get the second line
String macAddress = deviceInfo.split("\n")[1];
// Awkwardly enough, this host will now spawn a "client" thread to connect to the joining "server"
BluetoothDevice remoteDevice = bluetoothAdapter.getRemoteDevice(macAddress);
connectionSocketManager = new ConnectedSocketManager();
client = new BluetoothClientThread(context, remoteDevice, bluetoothAdapter, connectionSocketManager);
client.run();
jammin = true;
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
state.disableAllModes();
}
});
builder.setView(foundDevices);
final Dialog dialog = builder.create();
dialog.show();
}
private void initializeSaveButton() {
final Button save = (Button) findViewById(R.id.save);
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
openNameDialog();
}
});
}
public void openNameDialog() {
AlertDialog.Builder nameDialog = new AlertDialog.Builder(this);
nameDialog.setTitle("Save project");
nameDialog.setMessage("Name dem fat beats");
final EditText input = new EditText(this);
nameDialog.setView(input);
nameDialog.setPositiveButton("Save", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
String projName = input.getText().toString();
// Figure out if we can even write to the external storage
String state = Environment.getExternalStorageState();
boolean mExternalStorageWritable = Environment.MEDIA_MOUNTED.equals(state);
if (!mExternalStorageWritable) {
Toast.makeText(getApplication(), "Storage not writable!", Toast.LENGTH_LONG).show();
return;
}
File soundFile = new File(getApplication().getExternalFilesDir(null), projName+".wav");
SampleSplicer splicer = new SampleSplicer(getApplication(), buttonSamples, soundFile);
try {
splicer.iterativelyWriteSamples();
} catch (IOException ioException) {
Toast.makeText(getApplication(), "Error writing out samples", Toast.LENGTH_LONG).show();
}
Toast.makeText(getApplication(), "File successively written to " + soundFile.getAbsolutePath(), Toast.LENGTH_LONG).show();
}
});
nameDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
return;
}
});
nameDialog.show();
}
/**
* Adds button to the current view, takes uri from last session and adds them or sets new ones
*/
private void initializeSampleButtons() {
// Get preferences to find which samples were set on the last session
final SharedPreferences sessionSamples = getSharedPreferences(PREFERENCES, 0);
for (int i = 0; i < 9; i++) {
String button_name = "Sample_" + i;
int button_ID = getResources().getIdentifier(button_name, "id", getPackageName());
final String sampleName = sessionSamples.getString("" + button_ID, null);
final int starting_id = R.raw.a;
final int defaultSampleId = starting_id + i;
// If user set sample not found, put default
if (sampleName == null) {
changeButtonSampleByResource(button_ID, defaultSampleId);
} else {
// Change button's audio from null to sampleFile
changeButtonSampleByName(button_ID, sampleName);
}
Log.d("button id: ", "" + button_ID);
final Button soundButton = (Button) findViewById(button_ID);
// Ontouch rather than onclick because I need the event time
soundButton.setOnTouchListener(new Button.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
final int buttonId = soundButton.getId();
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
if (state.inEditMode()) {
editCurrentButton(buttonId);
return true;
} else {
// Play file at button
final Sample sample = buttonSamples.get(buttonId);
int soundId = sample.getSoundID();
songsPlaying.play(soundId, 1.0f, 1.0f, 1, 0, 1.0f);
if (state.isRecording()) {
tracker.setSampleStart(buttonId, soundId, motionEvent.getEventTime(), sample.getDuration());
}
return true;
}
}
return false;
}
});
}
}
private void editCurrentButton(int buttonId) {
// Change file uri
// Start intent for android to show options for selecting audio files
Intent intent = new Intent();
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("audio/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// Save the current buttonId for the result
selectedButtonID = buttonId;
startActivityForResult(Intent.createChooser(intent, getText(R.string.select_file)), REQUEST_SAMPLE_CHOOSE);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tracker = SampleTracker.getInstance();
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
initEditButton();
initializeRecordButton();
initializeLoopButton();
initializeSaveButton();
initializeResetButton();
initializeCoopSessionButtons();
initializeSampleButtons();
state = new SamplerActivityState(
findViewById(R.id.edit),
findViewById(R.id.record),
findViewById(R.id.loop),
findViewById(R.id.save),
findViewById(R.id.reset),
findViewById(R.id.joinjam),
findViewById(R.id.jam)
);
state.cleanState();
}
@Override
public void onRestart() {
super.onRestart();
songsPlaying.autoResume();
}
@Override
protected void onStop() {
super.onStop();
songsPlaying.autoPause();
// Save which samples were used on the buttons
final SharedPreferences sessionSamples = getSharedPreferences(PREFERENCES, 0);
SharedPreferences.Editor editor = sessionSamples.edit();
for (Map.Entry<Integer, Sample> buttonSampleEntry : buttonSamples.entrySet()) {
final String elementID = buttonSampleEntry.getKey().toString();
final Sample buttonSample = buttonSampleEntry.getValue();
editor.putString(elementID, buttonSample.getSoundFilePath());
}
// Commit the changes to the buttons
editor.apply();
}
/**
* This method is for android to use when it shuts down the application for good, basically cleans up my threads and
* what not
*/
@Override
public void onDestroy() {
super.onDestroy();
// This is sufficient to check that bluetooth is supported and therefore a reciever has been set
if (findViewById(R.id.jam).hasOnClickListeners()) {
unregisterReceiver(bluetoothReceiver);
}
if (server != null) {
server.cancel();
server = null;
}
if (client != null) {
client.cancel();
client = null;
}
if (connectionSocketManager != null) {
connectionSocketManager.cancel();
connectionSocketManager = null;
}
songsPlaying.release();
}
/**
* This function gets called whenever I make an intent or specifically call another activity, only used for file
* browsing intent currently
* @param requestCode what we opened up the activity for in the first place
* @param resultCode did the filebrowser activity exit alright?
* @param filename an intent holding mainly just the filename
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent filename) {
super.onActivityResult(requestCode, resultCode, filename);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_SAMPLE_CHOOSE) {
if (filename != null) {
// Get the filename from the intent
String sampleFile = filename.getData().getEncodedPath();
if (!FileTypeUtils.isSupported(sampleFile)) {
Log.d("Samples", "Selected sample was not a supported mimetype");
Toast toast = Toast.makeText(getApplication(), "This audio file type is not supported", 2000);
toast.show();
return;
}
final int buttonID = selectedButtonID;
final String sampleWAV;
try {
sampleWAV = Decode.convertSupportedToWav(sampleFile);
} catch (Exception e) {
Log.e("Samples", "Sample failed to be converted to wav");
Toast toast = Toast.makeText(getApplication(), "An error occurred when setting this button", 2000);
toast.show();
return;
}
changeButtonSampleByName(buttonID, sampleWAV);
// Indicate the file that the user just selected
Toast toast = Toast.makeText(getApplicationContext(), sampleWAV, 1000);
toast.show();
Log.d("Samples", "Sample from file is: " + sampleWAV);
Log.d("Samples", "Button is: " + buttonID);
}
}
}
}
/**
* Sets a button to play based on a file in the android filesystem
*
* @param buttonID the identification of the button we'd like to change the sample for
* @param newFilename the pathname of the file we'd like to set for the sample
*/
private void changeButtonSampleByName(int buttonID, String newFilename) {
removeSampleIfPresent(buttonID);
// Load sample into soundPool and update map
int newSoundID = songsPlaying.load(newFilename, 1); // The 1 is set for future compatibility
// Get track information
MediaMetadataRetriever metadata = new MediaMetadataRetriever();
metadata.setDataSource(newFilename);
int duration = Integer.parseInt(metadata.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
Log.d("Duration", "The duration of this file is " + duration);
metadata.release();
Sample newSample = new Sample(newFilename, newSoundID, duration, -1);
buttonSamples.put(buttonID, newSample);
}
/**
* Sets a button to use a sample from the apk
*
* @param buttonID the identification of the button we'd like to change the sample for
* @param resId the apk resource we'd like to use for the sample
*/
private void changeButtonSampleByResource(int buttonID, int resId) {
removeSampleIfPresent(buttonID);
// Load sample into soundPool and update map
int newSoundID = songsPlaying.load(getApplication(), resId, 1); // The 1 is set for future compatibility
// Get Track information
MediaMetadataRetriever metadata = new MediaMetadataRetriever();
metadata.setDataSource(getApplication(), resourceUri(resId));
int duration = Integer.parseInt(metadata.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
metadata.release();
Sample newSample = new Sample(null, newSoundID, duration, resId);
buttonSamples.put(buttonID, newSample);
}
private void removeSampleIfPresent(int buttonID) {
Sample currentSample = buttonSamples.get(buttonID);
// Check if the button has had a sample assigned to it yet and remove that sample from soundpool
if (currentSample != null) {
final int currentSoundID = currentSample.getSoundID();
songsPlaying.unload(currentSoundID);
}
}
/**
* @param resId resource Id
* @return a Uri for the given resource id
*/
public static Uri resourceUri(int resId) {
return Uri.parse("android.resource://com.android.sampler/" + resId);
}
}
| apache-2.0 |
JimWiliam/coder | pat/B/1037.cpp | 965 | #include <bits/stdc++.h>
using namespace std;
struct SS {
int g, s, k;
} A{0, 0, 0}, B{0, 0, 0};
int compare(SS &A, SS &B) {
int f = A.g - B.g;
if (f != 0)return f;
f = A.s - B.s;
if (f != 0)return f;
f = A.k - B.k;
if (f != 0)return f;
}
void solve(SS &A, SS &B) {
SS result;
int flag = 1;
if (compare(A, B) < 0) {
swap(A, B);
flag = -1;
}
result.k = A.k - B.k;
if (result.k < 0) {
result.k += 29;
A.s--;
if (A.s < 0) {
A.s += 17;
A.g--;
}
}
result.s = A.s - B.s;
if (result.s < 0) {
result.s += 17;
A.g--;
}
result.g = A.g - B.g;
result.g *= flag;
printf("%d.%d.%d\n", result.g, result.s, result.k);
}
int main() {
freopen("data.txt", "r", stdin);
scanf("%d.%d.%d", &A.g, &A.s, &A.k);
scanf("%d.%d.%d", &B.g, &B.s, &B.k);
solve(B, A);
printf("\n");
return 0;
} | apache-2.0 |
MAMISHO/test_git | gemwebs-blogs/skins/base/dashboard/locale.php | 2847 | <?php
list($lang_token, $lang, $list, $tkn, $phraseid, $translate) = _GL('lang_token, lang, list, tkn, phraseid, translate');
$exid = REQ('exid');
cn_snippet_bc();
cn_snippet_messages();
?>
<!-- selection -->
<form action="<?php echo PHP_SELF; ?>" method="POST">
<?php cn_form_open('mod, opt'); ?>
<p>
Select language <sup><a href="#" title="Create new language file (e.g. fr.txt) in ./core/lang with 666, 664 or 644 permission" onclick="return(tiny_msg(this));">?</a></sup>
<select name="lang_token">
<?php foreach ($list as $token) { ?>
<option <?php if ($token == $lang_token) echo 'selected="selected"'; ?>><?php echo $token; ?></option>
<?php } ?>
</select>
<input type="submit" value="Select" />
</p>
</form>
<!-- operations -->
<?php if ($lang_token) { ?>
<form action="<?php echo PHP_SELF; ?>" method="POST">
<?php cn_form_open('mod, opt, lang_token, exid'); ?>
<input type="hidden" name="modifica" value="Y" />
<table class="panel" width="100%">
<?php if ($exid) { ?>
<tr>
<td align="right"><input type="checkbox" name="create_phrase" value="Y" /></td>
<td>Create new phrase</td>
</tr>
<?php } ?>
<tr>
<td align="right"><?php if ($exid) echo 'Phrase / ID'; else echo 'Phrase'; ?></td>
<td><input type="text" style="width: 450px;" name="phraseid" value="<?php echo $phraseid; ?>" /> </td>
</tr>
<tr>
<td align="right">Translate</td>
<td><input type="text" style="width: 650px;" name="translate" value="<?php echo $translate; ?>" /> </td>
</tr>
<?php if ($exid) { ?>
<tr>
<td align="right"><input type="checkbox" name="delete_phrase" value="Y" /></td>
<td>Delete phrase</td>
</tr>
<?php } ?>
<tr>
<td> </td>
<td><input type="submit" value="<?php if ($exid) echo 'Edit'; else echo 'Create'; ?>"/> </td>
</tr>
</table>
<br/>
<table class="std-table" width="100%">
<tr><th>ID</th> <th>Translate</th></tr>
<?php foreach ($tkn as $id => $tran) { ?>
<tr <?php if ($id == $exid) echo 'class="row_selected"'; ?>>
<td><a href="<?php echo cn_url_modify('lang_token='.$lang_token, 'exid='.$id); ?>"><?php echo $id; ?></a></td>
<td><?php echo cn_htmlspecialchars($tran); ?></td>
</tr>
<?php } ?>
</table>
<br/>
<div><input type="submit" name="submit" value="Submit" /></div>
</form>
<?php } ?> | apache-2.0 |
amplab/succinct | core/src/main/java/edu/berkeley/cs/succinct/buffers/SuccinctIndexedFileBuffer.java | 15599 | package edu.berkeley.cs.succinct.buffers;
import edu.berkeley.cs.succinct.StorageMode;
import edu.berkeley.cs.succinct.SuccinctIndexedFile;
import edu.berkeley.cs.succinct.regex.RegExMatch;
import edu.berkeley.cs.succinct.regex.parser.RegExParsingException;
import edu.berkeley.cs.succinct.util.Source;
import edu.berkeley.cs.succinct.util.SuccinctConfiguration;
import edu.berkeley.cs.succinct.util.SuccinctConstants;
import edu.berkeley.cs.succinct.util.container.Range;
import edu.berkeley.cs.succinct.util.iterator.SearchIterator;
import edu.berkeley.cs.succinct.util.iterator.SearchRecordIterator;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class SuccinctIndexedFileBuffer extends SuccinctFileBuffer implements SuccinctIndexedFile {
private static final long serialVersionUID = -8357331195541317163L;
protected transient int[] offsets;
/**
* Constructor to initialize SuccinctIndexedBuffer from input byte array and offsets corresponding to records.
*
* @param input The input byte array.
* @param offsets Offsets corresponding to records.
* @param conf SuccinctConfiguration
*/
public SuccinctIndexedFileBuffer(byte[] input, int[] offsets, SuccinctConfiguration conf) {
super(input, conf);
this.offsets = offsets;
}
/**
* Constructor to initialize SuccinctIndexedBuffer from input byte array and offsets corresponding to records.
*
* @param input The input byte array.
* @param offsets Offsets corresponding to records.
*/
public SuccinctIndexedFileBuffer(byte[] input, int[] offsets) {
super(input);
this.offsets = offsets;
}
/**
* Constructor to initialize SuccinctIndexedBuffer from input char array and offsets corresponding to records.
*
* @param input The input char array.
* @param offsets Offsets corresponding to records.
* @param conf SuccinctConfiguration
*/
public SuccinctIndexedFileBuffer(char[] input, int[] offsets, SuccinctConfiguration conf) {
super(input, conf);
this.offsets = offsets;
}
/**
* Constructor to initialize SuccinctIndexedBuffer from input char array and offsets corresponding to records.
*
* @param input The input char array.
* @param offsets Offsets corresponding to records.
*/
public SuccinctIndexedFileBuffer(char[] input, int[] offsets) {
super(input);
this.offsets = offsets;
}
/**
* Constructor to load the data from persisted Succinct data-structures.
*
* @param path Path to load data from.
* @param storageMode Mode in which data is stored (In-memory or Memory-mapped)
*/
public SuccinctIndexedFileBuffer(String path, StorageMode storageMode) {
super(path, storageMode);
}
/**
* Constructor to load the data from a DataInputStream.
*
* @param is Input stream to load the data from
*/
public SuccinctIndexedFileBuffer(DataInputStream is) {
try {
readFromStream(is);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Constructor to load the data from a ByteBuffer.
*
* @param buf Input buffer to load the data from
*/
public SuccinctIndexedFileBuffer(ByteBuffer buf) {
super(buf);
}
/**
* Default constructor.
*/
public SuccinctIndexedFileBuffer() {
super();
}
/**
* Construct SuccinctIndexedFile from input source and offsets, and write them to file.
*
* @param input The input source.
* @param offsets The offsets corresponding to records.
* @param os The data output stream.
* @throws IOException
*/
public static void construct(final char[] input, int[] offsets, DataOutputStream os,
SuccinctConfiguration conf) throws IOException {
construct(new Source() {
@Override public int length() {
return input.length;
}
@Override public int get(int i) {
return input[i];
}
}, offsets, os, conf);
}
/**
* Construct SuccinctIndexedFile from input source and offsets, and write them to file.
*
* @param input The input source.
* @param offsets The offsets corresponding to records.
* @param os The data output stream.
* @throws IOException
*/
public static void construct(final byte[] input, int[] offsets, DataOutputStream os,
SuccinctConfiguration conf)
throws IOException {
construct(new Source() {
@Override public int length() {
return input.length;
}
@Override public int get(int i) {
return input[i];
}
}, offsets, os, conf);
}
/**
* Construct SuccinctIndexedFile from input source and offsets, and write them to file.
*
* @param input The input source.
* @param offsets The offsets corresponding to records.
* @param os The data output stream.
* @throws IOException
*/
public static void construct(Source input, int[] offsets, DataOutputStream os,
SuccinctConfiguration conf)
throws IOException {
construct(input, os, conf);
os.writeInt(offsets.length);
for (int i = 0; i < offsets.length; i++) {
os.writeInt(offsets[i]);
}
}
/**
* Get the size of the Succinct compressed file.
*
* @return The size of the Succinct compressed file.
*/
@Override public int getCompressedSize() {
return super.getCompressedSize() + offsets.length * SuccinctConstants.INT_SIZE_BYTES;
}
/**
* Get the number of records.
*
* @return The number of records.
*/
@Override public int getNumRecords() {
return offsets.length;
}
/**
* Get the offset for a given recordId
*
* @param recordId The record id.
* @return The corresponding offset.
*/
@Override public int getRecordOffset(int recordId) {
if (recordId >= offsets.length || recordId < 0) {
throw new ArrayIndexOutOfBoundsException("Record does not exist: recordId = " + recordId);
}
return offsets[recordId];
}
/**
* Get the ith record.
*
* @param recordId The record index.
* @return The corresponding record.
*/
@Override public byte[] getRecordBytes(int recordId) {
if (recordId >= offsets.length || recordId < 0) {
throw new ArrayIndexOutOfBoundsException("Record does not exist: recordId = " + recordId);
}
int begOffset = offsets[recordId];
int endOffset =
(recordId == offsets.length - 1) ? getOriginalSize() - 1 : offsets[recordId + 1];
int len = (endOffset - begOffset - 1);
return extractBytes(begOffset, len);
}
@Override public byte[] extractRecordBytes(int recordId, int offset, int length) {
if (recordId >= offsets.length || recordId < 0) {
throw new ArrayIndexOutOfBoundsException("Record does not exist: recordId = " + recordId);
}
if (length == 0) {
return new byte[0];
}
int begOffset = offsets[recordId] + offset;
int nextRecordOffset =
(recordId == offsets.length - 1) ? getOriginalSize() - 1 : offsets[recordId + 1];
length = Math.min(nextRecordOffset - begOffset - 1, length);
return extractBytes(begOffset, length);
}
/**
* Get the record for a given recordId.
*
* @param recordId The record id.
* @return The corresponding record.
*/
@Override public String getRecord(int recordId) {
if (recordId >= offsets.length || recordId < 0) {
throw new ArrayIndexOutOfBoundsException("Record does not exist: recordId = " + recordId);
}
int begOffset = offsets[recordId];
int endOffset =
(recordId == offsets.length - 1) ? getOriginalSize() - 1 : offsets[recordId + 1];
int len = (endOffset - begOffset - 1);
return extract(begOffset, len);
}
/**
* Get random access into record.
*
* @param recordId The record id.
* @param offset Offset into record.
* @param length Number of bytes to fetch.
* @return The extracted data.
*/
@Override public String extractRecord(int recordId, int offset, int length) {
if (recordId >= offsets.length || recordId < 0) {
throw new ArrayIndexOutOfBoundsException("Record does not exist: recordId = " + recordId);
}
if (length == 0) {
return "";
}
int begOffset = offsets[recordId] + offset;
int nextRecordOffset =
(recordId == offsets.length - 1) ? getOriginalSize() - 1 : offsets[recordId + 1];
length = Math.min(nextRecordOffset - begOffset - 1, length);
return extract(begOffset, length);
}
/**
* Search for offset corresponding to a position in the input.
*
* @param pos Position in the input
* @return Offset corresponding to the position.
*/
@Override public int offsetToRecordId(int pos) {
int sp = 0, ep = offsets.length - 1;
int m;
while (sp <= ep) {
m = (sp + ep) / 2;
if (offsets[m] == pos) {
return m;
} else if (pos < offsets[m]) {
ep = m - 1;
} else {
sp = m + 1;
}
}
return ep;
}
/**
* Search for an input query and return ids of all matching records.
*
* @param query Input query.
* @return Ids of all matching records.
*/
@Override public Integer[] recordSearchIds(Source query) {
Set<Integer> results = new HashSet<>();
Range range = bwdSearch(query);
long sp = range.first, ep = range.second;
if (ep - sp + 1 <= 0) {
return new Integer[0];
}
for (long i = 0; i < ep - sp + 1; i++) {
results.add(offsetToRecordId((int) lookupSA(sp + i)));
}
return results.toArray(new Integer[results.size()]);
}
/**
* Search for an input query and return offsets of all matching records.
*
* @param query Input query.
* @return Offsets of all matching records.
*/
@Override public Integer[] recordSearchIds(final byte[] query) {
return recordSearchIds(new Source() {
@Override public int length() {
return query.length;
}
@Override public int get(int i) {
return query[i];
}
});
}
/**
* Search for an input query and return ids of all matching records.
*
* @param query Input query.
* @return Ids of all matching records.
*/
@Override public Integer[] recordSearchIds(final char[] query) {
return recordSearchIds(new Source() {
@Override public int length() {
return query.length;
}
@Override public int get(int i) {
return query[i];
}
});
}
/**
* Search for an input query and return an iterator over ids of all matching records.
*
* @param query Input query.
* @return Iterator over ids of all matching records
*/
@Override public Iterator<Integer> recordSearchIdIterator(Source query) {
SearchIterator searchIterator = (SearchIterator) searchIterator(query);
return new SearchRecordIterator(searchIterator, this);
}
/**
* Search for an input query and return an iterator over ids of all matching records.
*
* @param query Input query.
* @return Iterator over ids of all matching records
*/
@Override public Iterator<Integer> recordSearchIdIterator(final byte[] query) {
return recordSearchIdIterator(new Source() {
@Override public int length() {
return query.length;
}
@Override public int get(int i) {
return query[i];
}
});
}
/**
* Search for an input query and return an iterator over ids of all matching records.
*
* @param query Input query.
* @return Iterator over ids of all matching records
*/
@Override public Iterator<Integer> recordSearchIdIterator(final char[] query) {
return recordSearchIdIterator(new Source() {
@Override public int length() {
return query.length;
}
@Override public int get(int i) {
return query[i];
}
});
}
/**
* Check if the two offsets belong to the same record.
*
* @param firstOffset The first offset.
* @param secondOffset The second offset.
* @return True if the two offsets belong to the same record, false otherwise.
*/
@Override public boolean sameRecord(long firstOffset, long secondOffset) {
return offsetToRecordId((int) firstOffset) == offsetToRecordId((int) secondOffset);
}
/**
* Search for all records that contain a particular regular expression.
*
* @param query The regular expression (UTF-8 encoded).
* @return The records ids for records that contain the regular search expression.
* @throws RegExParsingException
*/
@Override public Integer[] recordSearchRegexIds(String query) throws RegExParsingException {
Set<RegExMatch> regexOffsetResults = regexSearch(query);
Set<Integer> recordIds = new HashSet<>();
for (RegExMatch m : regexOffsetResults) {
int recordId = offsetToRecordId((int) m.getOffset());
if (!recordIds.contains(recordId)) {
recordIds.add(recordId);
}
}
return recordIds.toArray(new Integer[recordIds.size()]);
}
/**
* Write SuccinctIndexedFile to file.
*
* @param path Path to file where Succinct data structures should be written.
* @throws IOException
*/
public void writeToFile(String path) throws IOException {
FileOutputStream fos = new FileOutputStream(path);
DataOutputStream os = new DataOutputStream(fos);
writeToStream(os);
}
/**
* Read SuccinctIndexedFile from file.
*
* @param path Path to serialized Succinct data structures.
* @throws IOException
*/
@Override public void readFromFile(String path) throws IOException {
FileInputStream fis = new FileInputStream(path);
DataInputStream is = new DataInputStream(fis);
readFromStream(is);
}
/**
* Write Succinct data structures to a DataOutputStream.
*
* @param os Output stream to write data to.
* @throws IOException
*/
@Override public void writeToStream(DataOutputStream os) throws IOException {
super.writeToStream(os);
os.writeInt(offsets.length);
for (int i = 0; i < offsets.length; i++) {
os.writeInt(offsets[i]);
}
}
/**
* Reads Succinct data structures from a DataInputStream.
*
* @param is Stream to read data structures from.
* @throws IOException
*/
@Override public void readFromStream(DataInputStream is) throws IOException {
super.readFromStream(is);
int len = is.readInt();
offsets = new int[len];
for (int i = 0; i < len; i++) {
offsets[i] = is.readInt();
}
}
/**
* Memory maps serialized Succinct data structures.
*
* @param path Path to serialized Succinct data structures.
* @throws IOException
*/
public void memoryMap(String path) throws IOException {
File file = new File(path);
long size = file.length();
FileChannel fileChannel = new RandomAccessFile(file, "r").getChannel();
ByteBuffer buf = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, size);
mapFromBuffer(buf);
int len = buf.getInt();
offsets = new int[len];
for (int i = 0; i < len; i++) {
offsets[i] = buf.getInt();
}
}
/**
* Serialize SuccinctIndexedBuffer to OutputStream.
*
* @param oos ObjectOutputStream to write to.
* @throws IOException
*/
private void writeObject(ObjectOutputStream oos) throws IOException {
oos.writeObject(offsets);
}
/**
* Deserialize SuccinctIndexedBuffer from InputStream.
*
* @param ois ObjectInputStream to read from.
* @throws IOException
*/
private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException {
offsets = (int[]) ois.readObject();
}
}
| apache-2.0 |
chanil1218/elasticsearch | src/test/java/org/elasticsearch/test/unit/cluster/routing/allocation/ShardVersioningTests.java | 6369 | /*
* Licensed to ElasticSearch and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. ElasticSearch 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.elasticsearch.test.unit.cluster.routing.allocation;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.routing.RoutingNodes;
import org.elasticsearch.cluster.routing.RoutingTable;
import org.elasticsearch.cluster.routing.allocation.AllocationService;
import org.elasticsearch.cluster.routing.allocation.decider.ClusterRebalanceAllocationDecider;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
import org.testng.annotations.Test;
import static org.elasticsearch.cluster.ClusterState.newClusterStateBuilder;
import static org.elasticsearch.cluster.metadata.IndexMetaData.newIndexMetaDataBuilder;
import static org.elasticsearch.cluster.metadata.MetaData.newMetaDataBuilder;
import static org.elasticsearch.cluster.node.DiscoveryNodes.newNodesBuilder;
import static org.elasticsearch.cluster.routing.RoutingBuilders.indexRoutingTable;
import static org.elasticsearch.cluster.routing.RoutingBuilders.routingTable;
import static org.elasticsearch.cluster.routing.ShardRoutingState.*;
import static org.elasticsearch.test.unit.cluster.routing.allocation.RoutingAllocationTests.newNode;
import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
@Test
public class ShardVersioningTests {
private final ESLogger logger = Loggers.getLogger(ShardVersioningTests.class);
@Test
public void simple() {
AllocationService strategy = new AllocationService(settingsBuilder().put("cluster.routing.allocation.allow_rebalance", ClusterRebalanceAllocationDecider.ClusterRebalanceType.ALWAYS.toString()).build());
MetaData metaData = newMetaDataBuilder()
.put(newIndexMetaDataBuilder("test1").numberOfShards(1).numberOfReplicas(1))
.put(newIndexMetaDataBuilder("test2").numberOfShards(1).numberOfReplicas(1))
.build();
RoutingTable routingTable = routingTable()
.add(indexRoutingTable("test1").initializeEmpty(metaData.index("test1")))
.add(indexRoutingTable("test2").initializeEmpty(metaData.index("test2")))
.build();
ClusterState clusterState = newClusterStateBuilder().metaData(metaData).routingTable(routingTable).build();
logger.info("start two nodes");
clusterState = newClusterStateBuilder().state(clusterState).nodes(newNodesBuilder().put(newNode("node1")).put(newNode("node2"))).build();
RoutingTable prevRoutingTable = routingTable;
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = newClusterStateBuilder().state(clusterState).routingTable(routingTable).build();
for (int i = 0; i < routingTable.index("test1").shards().size(); i++) {
assertThat(routingTable.index("test1").shard(i).shards().size(), equalTo(2));
assertThat(routingTable.index("test1").shard(i).primaryShard().state(), equalTo(INITIALIZING));
assertThat(routingTable.index("test1").shard(i).primaryShard().version(), equalTo(1l));
assertThat(routingTable.index("test1").shard(i).replicaShards().get(0).state(), equalTo(UNASSIGNED));
}
for (int i = 0; i < routingTable.index("test2").shards().size(); i++) {
assertThat(routingTable.index("test2").shard(i).shards().size(), equalTo(2));
assertThat(routingTable.index("test2").shard(i).primaryShard().state(), equalTo(INITIALIZING));
assertThat(routingTable.index("test2").shard(i).primaryShard().version(), equalTo(1l));
assertThat(routingTable.index("test2").shard(i).replicaShards().get(0).state(), equalTo(UNASSIGNED));
}
logger.info("start all the primary shards for test1, replicas will start initializing");
RoutingNodes routingNodes = clusterState.routingNodes();
prevRoutingTable = routingTable;
routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState("test1", INITIALIZING)).routingTable();
clusterState = newClusterStateBuilder().state(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
for (int i = 0; i < routingTable.index("test1").shards().size(); i++) {
assertThat(routingTable.index("test1").shard(i).shards().size(), equalTo(2));
assertThat(routingTable.index("test1").shard(i).primaryShard().state(), equalTo(STARTED));
assertThat(routingTable.index("test1").shard(i).primaryShard().version(), equalTo(2l));
assertThat(routingTable.index("test1").shard(i).replicaShards().get(0).state(), equalTo(INITIALIZING));
assertThat(routingTable.index("test1").shard(i).replicaShards().get(0).version(), equalTo(2l));
}
for (int i = 0; i < routingTable.index("test2").shards().size(); i++) {
assertThat(routingTable.index("test2").shard(i).shards().size(), equalTo(2));
assertThat(routingTable.index("test2").shard(i).primaryShard().state(), equalTo(INITIALIZING));
assertThat(routingTable.index("test2").shard(i).primaryShard().version(), equalTo(1l));
assertThat(routingTable.index("test2").shard(i).replicaShards().get(0).state(), equalTo(UNASSIGNED));
assertThat(routingTable.index("test2").shard(i).replicaShards().get(0).version(), equalTo(1l));
}
}
} | apache-2.0 |
Orange-OpenSource/matos-profiles | matos-android/src/main/java/com/google/android/util/Procedure.java | 775 | package com.google.android.util;
/*
* #%L
* Matos
* $Id:$
* $HeadURL:$
* %%
* Copyright (C) 2010 - 2014 Orange SA
* %%
* 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.
* #L%
*/
public interface Procedure<T>
{
// Methods
public void apply(T arg1);
}
| apache-2.0 |
chris115379/Recipr | presentation/src/main/java/de/androidbytes/recipr/presentation/overview/categories/view/adapter/SectionedCategoriesOverviewAdapter.java | 1007 | package de.androidbytes.recipr.presentation.overview.categories.view.adapter;
import android.content.Context;
import de.androidbytes.recipr.presentation.R;
import de.androidbytes.recipr.presentation.overview.core.view.OnRecipeClickListener;
import de.androidbytes.recipr.presentation.overview.core.view.adapter.SectionedGridRecyclerViewAdapter;
import javax.inject.Inject;
public class SectionedCategoriesOverviewAdapter extends SectionedGridRecyclerViewAdapter<CategoriesOverviewAdapter> {
@Inject
public SectionedCategoriesOverviewAdapter(Context context, CategoriesOverviewAdapter baseAdapter) {
super(
context,
R.layout.item_layout_categories_overview_section_header,
R.id.tv_section_header_title,
R.layout.item_layout_categories_overview_section_footer,
R.id.tv_section_footer_title,
R.string.section_footer_title,
baseAdapter
);
}
}
| apache-2.0 |
YuwenXiaodong/coolweather | app/src/main/java/com/coolcweather/app/model/County.java | 797 | package com.coolcweather.app.model;
/**
* Created by Administrator on 2016/6/21.
*/
public class County {
private int id;
private String countyName;
private String countyCode;
private int cityId;
public String getCountyName() {
return countyName;
}
public void setCountyName(String countyName) {
this.countyName = countyName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCountyCode() {
return countyCode;
}
public void setCountyCode(String countyCode) {
this.countyCode = countyCode;
}
public int getCityId() {
return cityId;
}
public void setCityId(int cityId) {
this.cityId = cityId;
}
}
| apache-2.0 |
bgrozev/jitsi-meet | react/features/toolbox/components/VideoMuteButton.js | 5444 | // @flow
import {
ACTION_SHORTCUT_TRIGGERED,
VIDEO_MUTE,
createShortcutEvent,
createToolbarEvent,
sendAnalytics
} from '../../analytics';
import { setAudioOnly } from '../../base/audio-only';
import { translate } from '../../base/i18n';
import {
VIDEO_MUTISM_AUTHORITY,
setVideoMuted
} from '../../base/media';
import { connect } from '../../base/redux';
import { AbstractVideoMuteButton } from '../../base/toolbox';
import type { AbstractButtonProps } from '../../base/toolbox';
import { getLocalVideoType, isLocalVideoTrackMuted } from '../../base/tracks';
import {
isPrejoinPageVisible,
isPrejoinVideoDisabled,
isPrejoinVideoMuted
} from '../../prejoin/functions';
import UIEvents from '../../../../service/UI/UIEvents';
declare var APP: Object;
/**
* The type of the React {@code Component} props of {@link VideoMuteButton}.
*/
type Props = AbstractButtonProps & {
/**
* Whether the current conference is in audio only mode or not.
*/
_audioOnly: boolean,
/**
* MEDIA_TYPE of the local video.
*/
_videoMediaType: string,
/**
* Whether video is currently muted or not.
*/
_videoMuted: boolean,
/**
* Whether video button is disabled or not.
*/
_videoDisabled: boolean,
/**
* The redux {@code dispatch} function.
*/
dispatch: Function
}
/**
* Component that renders a toolbar button for toggling video mute.
*
* @extends AbstractVideoMuteButton
*/
class VideoMuteButton extends AbstractVideoMuteButton<Props, *> {
accessibilityLabel = 'toolbar.accessibilityLabel.videomute';
label = 'toolbar.videomute';
tooltip = 'toolbar.videomute';
/**
* Initializes a new {@code VideoMuteButton} instance.
*
* @param {Props} props - The read-only React {@code Component} props with
* which the new instance is to be initialized.
*/
constructor(props: Props) {
super(props);
// Bind event handlers so they are only bound once per instance.
this._onKeyboardShortcut = this._onKeyboardShortcut.bind(this);
}
/**
* Registers the keyboard shortcut that toggles the video muting.
*
* @inheritdoc
* @returns {void}
*/
componentDidMount() {
typeof APP === 'undefined'
|| APP.keyboardshortcut.registerShortcut(
'V',
null,
this._onKeyboardShortcut,
'keyboardShortcuts.videoMute');
}
/**
* Unregisters the keyboard shortcut that toggles the video muting.
*
* @inheritdoc
* @returns {void}
*/
componentWillUnmount() {
typeof APP === 'undefined'
|| APP.keyboardshortcut.unregisterShortcut('V');
}
/**
* Indicates if video is currently disabled or not.
*
* @override
* @protected
* @returns {boolean}
*/
_isDisabled() {
return this.props._videoDisabled;
}
/**
* Indicates if video is currently muted ot nor.
*
* @override
* @protected
* @returns {boolean}
*/
_isVideoMuted() {
return this.props._videoMuted;
}
_onKeyboardShortcut: () => void;
/**
* Creates an analytics keyboard shortcut event and dispatches an action to
* toggle the video muting.
*
* @private
* @returns {void}
*/
_onKeyboardShortcut() {
sendAnalytics(
createShortcutEvent(
VIDEO_MUTE,
ACTION_SHORTCUT_TRIGGERED,
{ enable: !this._isVideoMuted() }));
super._handleClick();
}
/**
* Changes the muted state.
*
* @override
* @param {boolean} videoMuted - Whether video should be muted or not.
* @protected
* @returns {void}
*/
_setVideoMuted(videoMuted: boolean) {
sendAnalytics(createToolbarEvent(VIDEO_MUTE, { enable: videoMuted }));
if (this.props._audioOnly) {
this.props.dispatch(
setAudioOnly(false, /* ensureTrack */ true));
}
const mediaType = this.props._videoMediaType;
this.props.dispatch(
setVideoMuted(
videoMuted,
mediaType,
VIDEO_MUTISM_AUTHORITY.USER,
/* ensureTrack */ true));
// FIXME: The old conference logic still relies on this event being
// emitted.
typeof APP === 'undefined'
|| APP.UI.emitEvent(UIEvents.VIDEO_MUTED, videoMuted, true);
}
}
/**
* Maps (parts of) the redux state to the associated props for the
* {@code VideoMuteButton} component.
*
* @param {Object} state - The Redux state.
* @private
* @returns {{
* _audioOnly: boolean,
* _videoMuted: boolean
* }}
*/
function _mapStateToProps(state): Object {
const { enabled: audioOnly } = state['features/base/audio-only'];
const tracks = state['features/base/tracks'];
let _videoMuted = isLocalVideoTrackMuted(tracks);
let _videoDisabled = false;
if (isPrejoinPageVisible(state)) {
_videoMuted = isPrejoinVideoMuted(state);
_videoDisabled = isPrejoinVideoDisabled(state);
}
return {
_audioOnly: Boolean(audioOnly),
_videoDisabled,
_videoMediaType: getLocalVideoType(tracks),
_videoMuted
};
}
export default translate(connect(_mapStateToProps)(VideoMuteButton));
| apache-2.0 |
davidbwaikato/phonegap-fieldays-innovation | www/js/ConsiderView.js | 1045 |
var ConsiderView = function(homeView) {
this.homeView = homeView;
this.initialize = function() {
// 'div' wrapper to attach html and events to
this.el = $('<div/>');
};
this.render = function() {
if (!this.homeView) {
this.homeView = { enteredName: "" }
}
this.el.html(ConsiderView.template(this.homeView));
return this;
};
this.playVideo = function(callback) {
if (typeof VideoPlayer != 'undefined') {
VideoPlayer.play('file:///android_asset/www/video/startupVideo2Android.mp4',callback);
}
else {
console.log("StartPage: No VideoPlayer plugin. Going straight to callback()");
callback();
}
}
this.crossfade = function(delay) {
var self = this;
$("#svg-bubbles-div").delay(delay).animate({ opacity: 0 }, 700);
$("#after-bubbles").delay(delay).css("display","block").animate({ opacity: 1 }, 700);
};
this.initialize();
}
ConsiderView.template = Handlebars.compile($("#consider-tpl").html());
| apache-2.0 |
impactcloud/fact | box-service/boxTokenCache.js | 1737 | 'use strict';
const CacheService = require('../cache-service/cacheService');
const config = require('config');
const BoxSDKConfig = config.get('BoxSDKConfig');
const BoxOptions = config.get('BoxOptions');
const Promise = require('bluebird');
const asyncFunc = Promise.coroutine;
const BOX_ENTERPRISE = "enterprise";
const BOX_USER = "user";
const CACHE_KEY_PREFIX_ENTERPRISE_TOKEN = `${BoxSDKConfig.boxEnterpriseId}|${BOX_ENTERPRISE}`;
const CACHE_KEY_PREFIX_USER_TOKEN = `${BoxSDKConfig.boxEnterpriseId}|${BOX_USER}`;
//Implementation of a BoxCache: has getBoxToken and setBoxToken
class BoxTokenCache {
constructor() {
this.cache = new CacheService();
this.inMemoryStore = new Map();
this.cacheKeyPrefixEnterpriseToken = CACHE_KEY_PREFIX_ENTERPRISE_TOKEN;
this.cacheKeyPrefixUserToken = CACHE_KEY_PREFIX_USER_TOKEN;
}
getBoxToken(key) {
let self = this;
return asyncFunc(function* () {
let token = self.inMemoryStore.get(key);
if (token) {
return token;
} else {
let boxToken = yield self.cache.retrieveKey(key);
boxToken = (boxToken) ? JSON.parse(boxToken) : null;
clearInMemoryStore(self.inMemoryStore);
self.inMemoryStore.set(key, boxToken);
return boxToken;
}
})();
}
setBoxToken(key, boxToken, expiration) {
let self = this;
return asyncFunc(function* () {
clearInMemoryStore(self.inMemoryStore);
self.inMemoryStore.set(key, boxToken);
expiration = expiration || 3600;
boxToken = JSON.stringify(boxToken);
yield self.cache.setKeyWithExpiration(key, boxToken, expiration);
return true;
})();
}
}
function clearInMemoryStore(store) {
if (store.size > BoxOptions.inMemoryStoreSize) {
store.clear();
}
}
module.exports = new BoxTokenCache();
| apache-2.0 |
hawtio/hawtio | hawtio-system/src/main/java/io/hawt/web/kubernetes/PodServlet.java | 3489 | /**
* Copyright (C) 2013 the original author or authors.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* 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 io.hawt.web.kubernetes;
import javax.servlet.http.HttpServletRequest;
import io.hawt.util.Strings;
import io.hawt.web.proxy.ProxyAddress;
import io.hawt.web.proxy.ProxyServlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Proxies /pod/name/port/* to the pod IP/port for 'name' using the Kubernetes service lookup and then
* passes the rest of the URI to the underlying service.
*/
public class PodServlet extends ProxyServlet {
private static final transient Logger LOG = LoggerFactory.getLogger(PodServlet.class);
@Override
protected ProxyAddress parseProxyAddress(HttpServletRequest servletRequest) {
String reqQueryString = servletRequest.getQueryString();
String queryPostfix = "";
if (Strings.isNotBlank(reqQueryString)) {
queryPostfix = "?" + reqQueryString;
}
String userName = null;
String password = null;
String podName = servletRequest.getPathInfo();
if (podName == null) {
podName = "";
}
if (podName.startsWith("/")) {
podName = podName.substring(1);
}
int idx = podName.indexOf('/');
String podPort = "";
String podPath = "/";
if (idx > 0) {
podPath = podName.substring(idx);
podName = podName.substring(0, idx);
idx = podPath.indexOf('/', 1);
if (idx >= 0) {
podPort = podPath.substring(1, idx);
podPath = podPath.substring(idx);
}
}
if (podName.isEmpty()) {
// lets list the pods for /pod
String url = ServiceResolver.getSingleton().getServiceURL("kubernetes");
if (url == null) {
return null;
}
url += "/kubernetes/api/v1beta2/pods" + queryPostfix;
return new DefaultProxyAddress(url, userName, password);
}
String url = ServiceResolver.getSingleton().getPodUrl(podName, podPort);
if (url == null) {
if (LOG.isDebugEnabled()) {
LOG.debug("No pod for: " + podName + " port: " + podPort + " path: " + podPath);
}
System.out.println("No pod for: " + podName + " port: " + podPort + " path: " + podPath);
return null;
} else {
url += podPath + queryPostfix;
if (LOG.isDebugEnabled()) {
LOG.debug("Invoking: " + url + " from pod: " + podName + " port: " + podPort + " path: " + podPath);
}
System.out.println("Invoking: " + url + " from pod: " + podName + " port: " + podPort + " path: " + podPath);
return new DefaultProxyAddress(url, userName, password);
}
}
}
| apache-2.0 |
3ev0/rdns-monitor | setup.py | 352 | import setuptools
setuptools.setup(
name = "rDNS-Monitor",
version = "0.1",
packages = ["rdnsmonitor"],
author = "3v0o",
description = "Reverse DNS monitor. Queries and stores PTR records of all IPv4 addresses.",
license = "Apache",
entry_points = {
'console_scripts': ['rdnsmonitor = rdnsmonitor.cli:main']
}
)
| apache-2.0 |
traneio/ndbc | ndbc-core/src/main/java/io/trane/ndbc/proto/BufferReader.java | 730 | package io.trane.ndbc.proto;
import java.nio.charset.Charset;
public interface BufferReader {
int readableBytes();
int readInt();
byte readByte();
short readShort();
String readCString(Charset charset);
String readCString(int length, Charset charset);
String readString(Charset charset);
String readString(int length, Charset charset);
byte[] readBytes();
byte[] readBytes(int length);
int[] readInts();
int[] readInts(int length);
short[] readShorts();
short[] readShorts(int length);
BufferReader readSlice(int length);
void markReaderIndex();
void resetReaderIndex();
void retain();
void release();
Long readLong();
Float readFloat();
Double readDouble();
}
| apache-2.0 |
equella/Equella | Source/Plugins/Core/com.equella.core/src/com/tle/web/sections/standard/dialog/model/ControlsState.java | 1334 | /*
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* The Apereo Foundation 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 com.tle.web.sections.standard.dialog.model;
import com.tle.web.sections.standard.RendererConstants;
import com.tle.web.sections.standard.model.HtmlComponentState;
import java.util.List;
public class ControlsState extends HtmlComponentState {
private List<DialogControl> controls;
public ControlsState() {
super(RendererConstants.CONTROLS);
}
public List<DialogControl> getControls() {
return controls;
}
public void setControls(List<DialogControl> controls) {
this.controls = controls;
}
}
| apache-2.0 |
TakWolf/d2d-canvas-for-javascript | Lib/D2D_Engine.js | 28745 | //=======================================================
//
// EM-X for HTML5 Canvas - v0.0.3
//
// Powered by TakWolf - takgdx@gmail.com
// http://www.takgdx.com/emx-for-html5-canvas
//
//=======================================================
// -2013.10.22-
//=======================================================
// D2D_引擎类
//=======================================================
var D2D_Engine = (function() {
/**
* D2D_引擎类
* @param canvasId
* @param fps
* @param width
* @param height
* @constructor
*/
function D2D_Engine(canvasId,fps,width,height) {
//获取canvas
this.canvas = document.getElementById(canvasId);
this.canvas.width = width;
this.canvas.height = height;
this.context2D = this.canvas.getContext("2d");
//缓冲区
this.canvasBuffer = document.createElement("canvas");
this.canvasBuffer.width = width;
this.canvasBuffer.height = height;
this.contextBuffer2D = this.canvasBuffer.getContext("2d");
//帧率
this.fps = fps;
this.currentFps = 0;
this.frameCounter = 0;
this.timeCounter = 0;
/**
* 鼠标状态
* 注意:由于this关键字局限性,鼠标相关的状态注册在canvas对象内部
*/
this.canvas.mouseStates = {
//按键状态,支持三种按键
leftButton:{
down:false,
up:false,
click:false,
dblclick:false
},
rightButton:{
down:false,
up:false,
click:false,
dblclick:false
},
middleButton:{
down:false,
up:false,
click:false,
dblclick:false
},
//鼠标位置
pos:{
x:0,
y:0
},
//其他状态
wheel:false,
move:false,
out:false,
over:false,
//滚动方向
wheelDelta:0//0表示未滚动,1表示向上,-1表示向下
};
/**
* 定义回调函数
*/
//·鼠标按下·
function mouseDown(event) {
//兼容IE
event = event || window.event;
//检测IE
if(!-[1,]) {
switch(event.button) {
case 1:
this.mouseStates.leftButton.down = true;
break;
case 2:
this.mouseStates.rightButton.down = true;
break;
case 4:
this.mouseStates.middleButton.down = true;
break;
}
}
//非IE-W3C标准
else {
switch(event.which) {
case 1:
this.mouseStates.leftButton.down = true;
break;
case 2:
this.mouseStates.middleButton.down = true;
break;
case 3:
this.mouseStates.rightButton.down = true;
break;
}
}
//取消默认事件
event.preventDefault();
}
//·鼠标抬起·
function mouseUp(event) {
//兼容IE
event = event || window.event;
//检测IE
if(!-[1,]) {
switch(event.button) {
case 1:
this.mouseStates.leftButton.up = true;
this.mouseStates.leftButton.down = false;
break;
case 2:
this.mouseStates.rightButton.up = true;
this.mouseStates.rightButton.down = false;
break;
case 4:
this.mouseStates.middleButton.up = true;
this.mouseStates.middleButton.down = false;
break;
}
}
//非IE-W3C标准
else {
switch(event.which) {
case 1:
this.mouseStates.leftButton.up = true;
this.mouseStates.leftButton.down = false;
break;
case 2:
this.mouseStates.middleButton.up = true;
this.mouseStates.middleButton.down = false;
break;
case 3:
this.mouseStates.rightButton.up = true;
this.mouseStates.rightButton.down = false;
break;
}
}
//取消默认事件
event.preventDefault();
}
//·鼠标单击·
function mouseClick(event) {
//兼容IE
event = event || window.event;
//检测IE
if(!-[1,]) {
switch(event.button) {
case 1:
this.mouseStates.leftButton.click = true;
break;
case 2:
this.mouseStates.rightButton.click = true;
break;
case 4:
this.mouseStates.middleButton.click = true;
break;
}
}
//非IE-W3C标准
else {
switch(event.which) {
case 1:
this.mouseStates.leftButton.click = true;
break;
case 2:
this.mouseStates.middleButton.click = true;
break;
case 3:
this.mouseStates.rightButton.click = true;
break;
}
}
//取消默认事件
event.preventDefault();
}
//·鼠标双击·
function mouseDblclick(event) {
//兼容IE
event = event || window.event;
//检测IE
if(!-[1,]) {
switch(event.button) {
case 1:
this.mouseStates.leftButton.dblclick = true;
break;
case 2:
this.mouseStates.rightButton.dblclick = true;
break;
case 4:
this.mouseStates.middleButton.dblclick = true;
break;
}
}
//非IE-W3C标准
else {
switch(event.which) {
case 1:
this.mouseStates.leftButton.dblclick = true;
break;
case 2:
this.mouseStates.middleButton.dblclick = true;
break;
case 3:
this.mouseStates.rightButton.dblclick = true;
break;
}
}
//取消默认事件
event.preventDefault();
}
//·鼠标滚动·
function mouseWheel(event) {
//兼容IE
event = event || window.event;
//状态
this.mouseStates.wheel = true;
//设置滚动方向-IE/Opera/Chrome
if(event.wheelDelta) {
this.mouseStates.wheelDelta = event.wheelDelta/120;
}
//Firefox
else if(event.detail) {
this.mouseStates.wheelDelta = -event.detail/3;
}
//取消默认事件
event.preventDefault();
}
//·鼠标移动·
function mouseMove(event) {
//兼容IE
event = event || window.event;
//状态
this.mouseStates.move = true;
//判断是否为火狐浏览器
if(navigator.userAgent.indexOf("Firefox")>0) {
//FireFox鼠标坐标取法
var rect = this.getBoundingClientRect();//取出canvas矩形
this.mouseStates.pos.x = event.clientX-rect.left;
this.mouseStates.pos.y = event.clientY-rect.top;
} else {
//Chrome-Opera-Safari-鼠获取方法,firefox不兼容
this.mouseStates.pos.x = event.offsetX;
this.mouseStates.pos.y = event.offsetY;
}
//取消默认事件
event.preventDefault();
}
//·鼠标离开画布·
function mouseOut(event) {
//兼容IE
event = event || window.event;
//状态
this.mouseStates.out = true;
//取消所有down事件
this.mouseStates.leftButton.down = false;
this.mouseStates.rightButton.down = false;
this.mouseStates.middleButton.down = false;
//取消默认事件
event.preventDefault();
}
//·鼠标进入画布·
function mouseOver(event) {
//兼容IE
event = event || window.event;
//状态
this.mouseStates.over = true;
//取消默认事件
event.preventDefault();
}
//·鼠标右键菜单·
function contextMenu(event) {
//兼容IE
event = event || window.event;
//右键设置不返回菜单
event.returnValue = false;
//取消默认事件
event.preventDefault();
}
/**
* 鼠标事件回调适配-要求适配主流浏览器
*/
//W3C标准事件注册-使用该方法Chrome会报错
/*
if(this.canvas.addEventListener){
this.canvas.addEventListener("mousedown",mouseDown,false);
this.canvas.addEventListener("mouseup",mouseUp,false);
this.canvas.addEventListener("click",mouseClick,false);
this.canvas.addEventListener("dblclick",mouseDblclick,false);
this.canvas.addEventListener("mousewheel",mouseWheel,false);
this.canvas.addEventListener("mousemove",mouseMove,false);
this.canvas.addEventListener("mouseout",mouseOut,false);
this.canvas.addEventListener("mouseover",mouseOver,false);
this.canvas.addEventListener("contextmenu",contextMenu,false);
}*/
//反模式注册-Chrome、Opera、Safari、firefox
this.canvas.onmousedown = mouseDown;
this.canvas.onmouseup = mouseUp;
this.canvas.onclick = mouseClick;
this.canvas.ondblclick = mouseDblclick;
this.canvas.onmousewheel = mouseWheel;//firefox不支持
this.canvas.onmousemove = mouseMove;
this.canvas.onmouseout = mouseOut;
this.canvas.onmouseover = mouseOver;
this.canvas.oncontextmenu = contextMenu;
//firefox注册滚动事件-个性
this.canvas.addEventListener("DOMMouseScroll",mouseWheel,false);
/*
//IE事件注册-M$个性-IE8以下版本
if(this.canvas.attachEvent){
this.canvas.attachEvent("onmousedown",mouseDown);
this.canvas.attachEvent("onmouseup",mouseUp);
this.canvas.attachEvent("onclick",mouseClick);
this.canvas.attachEvent("ondblclick",mouseDblclick);
this.canvas.attachEvent("onmousewheel",mouseWheel);
this.canvas.attachEvent("onmousemove",mouseMove);
this.canvas.attachEvent("onmouseout",mouseOut);
this.canvas.attachEvent("onmouseover",mouseOver);
this.canvas.attachEvent("oncontextmenu",contextMenu);
}*/
/**
* 触摸事件状态-移动平台专用-浏览器支持差
* 不建议使用
* 注意:由于this关键字局限性,鼠标相关的状态注册在canvas对象内部
*/
this.canvas.touchStates = {
};
/**
* 触摸监听回调函数
* 根据浏览器情况判断
*/
/**
而每个触摸事件都包括了三个触摸列表,每个列表里包含了对应的一系列触摸点(用来实现多点触控):
touches:当前位于屏幕上的所有手指的列表。
targetTouches:位于当前DOM元素上手指的列表。
changedTouches:涉及当前事件手指的列表。
每个触摸点由包含了如下触摸信息(常用):
identifier:一个数值,唯一标识触摸会话(touch session)中的当前手指。一般为从0开始的流水号(android4.1,uc)
target:DOM元素,是动作所针对的目标。
pageX/pageX/clientX/clientY/screenX/screenY:一个数值,动作在屏幕上发生的位置(page包含滚动距离,client不包含滚动距离,screen则以屏幕为基准)
*/
//·触摸开始·
//触摸开始的时候触发
function touchstart(event) {
//兼容IE
event = event || window.event;
//取消默认事件
event.preventDefault();
}
//·触摸移动·
//手指在屏幕上滑动的时候触发
function touchmove(event) {
//兼容IE
event = event || window.event;
//取消默认事件
event.preventDefault();
}
//·触摸停止·
//触摸结束的时候触发
function touchend(event) {
//兼容IE
event = event || window.event;
//取消默认事件
event.preventDefault();
}
/**
* 触摸事件注册
*/
//1.W3C标准
//支持:android原生、Chrome、Opera Mobile、UC
this.canvas.addEventListener("touchstart",touchstart,false);
this.canvas.addEventListener("touchmove",touchmove,false);
this.canvas.addEventListener("touchend",touchend,false);
//2.反模式注册
//支持:android原生、Chrome、Opera Mobile、UC
/*
this.canvas.ontouchstart = touchstart;
this.canvas.ontouchmove = touchmove;
this.canvas.ontouchend = touchend;
*/
}
/**
* 获取渲染上下文
*/
D2D_Engine.prototype.getContext = function() {
return this.contextBuffer2D;//返回缓冲区上下文
};
/**
* 获取Canvas
*/
D2D_Engine.prototype.getCanvas = function() {
return this.canvas;
};
/**
* 绘制开始
*/
D2D_Engine.prototype.beginDraw = function() {
//清除画布-?是否需要
//this.context2D.clearRect(0,0,this.canvas.width,this.canvas.height);
};
/**
* 绘制结束
*/
D2D_Engine.prototype.endDraw = function() {
//在canvas中绘制缓冲区内容
this.context2D.drawImage(this.canvasBuffer,0,0);
};
/**
* 颜色清屏
*/
D2D_Engine.prototype.clear = function(color) {
if(color == undefined || color == null) {
//清除所有
this.contextBuffer2D.clearRect(0,0,this.canvasBuffer.width,this.canvasBuffer.height);
} else {
//清除缓冲区颜色
this.contextBuffer2D.fillStyle = color;
this.contextBuffer2D.fillRect(0,0,this.canvasBuffer.width,this.canvasBuffer.height);
}
};
/**
* 取设定帧率
*/
D2D_Engine.prototype.getFps = function() {
return this.fps;
};
/**
* 置设定帧率
*/
D2D_Engine.prototype.setFps = function(fps) {
this.fps = fps;
};
/**
* 取当前帧率-每秒刷新一次
*/
D2D_Engine.prototype.getCurrentFps = function() {
return this.currentFps;
};
/**
* 取宽度
*/
D2D_Engine.prototype.getWidth = function() {
return this.canvas.width;
};
/**
* 取画布宽度
* 函数别名
*/
D2D_Engine.prototype.getCanvasWidth = D2D_Engine.prototype.getWidth;
/**
* 取高度
*/
D2D_Engine.prototype.getHeight = function() {
return this.canvas.height;
};
/**
* 取画布高度
* 函数别名
*/
D2D_Engine.prototype.getCanvasHeight = D2D_Engine.prototype.getHeight;
/**
* 置宽度
*/
D2D_Engine.prototype.setWidth = function(width) {
this.canvas.width = width;
this.canvasBuffer.width = width;//缓冲区-大小相同
};
/**
* 置画布宽度
* 函数别名
*/
D2D_Engine.prototype.setCanvasWidth = D2D_Engine.prototype.setWidth;
/**
* 置高度
*/
D2D_Engine.prototype.setHeight = function(height) {
this.canvas.height = height;
this.canvasBuffer.height = height;//缓冲区-大小相同
};
/**
* 置画布高度
* 函数别名
*/
D2D_Engine.prototype.setCanvasHeight = D2D_Engine.prototype.setHeight;
//=======================================================
// 鼠标事件
//=======================================================
/**
* 取鼠标坐标x
*/
D2D_Engine.prototype.getMousePosX = function() {
return this.canvas.mouseStates.pos.x;
};
/**
* 取鼠标坐标y
*/
D2D_Engine.prototype.getMousePosY = function() {
return this.canvas.mouseStates.pos.y;
};
/**
* 取鼠标坐标
*/
D2D_Engine.prototype.getMousePos = function() {
return this.canvas.mouseStates.pos;
};
/**
* 鼠标是否按下
* 默认参数为左键
* 可传参数为:
* "left","right","middle"
*/
D2D_Engine.prototype.isMouseDown = function(which) {
//左键
if(which == undefined || which == "left") {
return this.canvas.mouseStates.leftButton.down;
}
//右键
else if(which == "right" ) {
return this.canvas.mouseStates.rightButton.down;
}
//中键
else if(which == "middle") {
return this.canvas.mouseStates.middleButton.down;
}
//其他未知
else {
return undefined;
}
};
/**
* 鼠标是否弹起
* 默认参数为左键
* 可传参数为:
* "left","right","middle"
*/
D2D_Engine.prototype.isMouseUp = function(which) {
//左键
if(which == undefined || which == "left") {
return this.canvas.mouseStates.leftButton.up;
}
//右键
else if(which == "right" ) {
return this.canvas.mouseStates.rightButton.up;
}
//中键
else if(which == "middle") {
return this.canvas.mouseStates.middleButton.up;
}
//其他未知
else {
return undefined;
}
};
/**
* 鼠标是否单击
* 默认参数为左键
* 可传参数为:
* "left","right","middle"
*/
D2D_Engine.prototype.isMouseClick = function(which) {
//左键
if(which == undefined || which == "left") {
return this.canvas.mouseStates.leftButton.click;
}
//右键
else if(which == "right" ) {
return this.canvas.mouseStates.rightButton.click;
}
//中键
else if(which == "middle") {
return this.canvas.mouseStates.middleButton.click;
}
//其他未知
else {
return undefined;
}
};
/**
* 鼠标是否双击
* 默认参数为左键
* 可传参数为:
* "left","right","middle"
*/
D2D_Engine.prototype.isMouseDblclick = function(which) {
//左键
if(which == undefined || which == "left") {
return this.canvas.mouseStates.leftButton.dblclick;
}
//右键
else if(which == "right" ) {
return this.canvas.mouseStates.rightButton.dblclick;
}
//中键
else if(which == "middle") {
return this.canvas.mouseStates.middleButton.dblclick;
}
//其他未知
else {
return undefined;
}
};
/**
* 鼠标是否移动
*/
D2D_Engine.prototype.isMouseMove = function() {
return this.canvas.mouseStates.move;
};
/**
* 鼠标是否滚动
*/
D2D_Engine.prototype.isMouseWheel = function() {
return this.canvas.mouseStates.wheel;
};
/**
* 鼠标是否离开画布
*/
D2D_Engine.prototype.isMouseOut = function() {
return this.canvas.mouseStates.out;
};
/**
* 鼠标是否进入画布
*/
D2D_Engine.prototype.isMouseOver = function() {
return this.canvas.mouseStates.over;
};
/**
* 获取鼠标滚动方向
* 1为向上
* -1为向下
* 0为不动
*/
D2D_Engine.prototype.getMouseWheelDelta = function() {
return this.canvas.mouseStates.wheelDelta;
};
/**
* 获取鼠标滚动方向
* 和上一个函数同样功能
*/
D2D_Engine.prototype.getMouseWheel = D2D_Engine.prototype.getMouseWheelDelta;
//=======================================================
// 鼠标样式
//=======================================================
/**
* 设置鼠标样式
* 参数:
* url -- 需被使用的自定义光标的URL-注释:请在此列表的末端始终定义一种普通的光标,以防没有由 URL 定义的可用光标。
* (除IE外不可用)
* default -- 默认光标(通常是一个箭头)
* auto -- 默认。浏览器设置的光标。
* crosshair -- 光标呈现为十字线。
* pointer -- 光标呈现为指示链接的指针(一只手)
* move -- 此光标指示某对象可被移动。
* e-resize -- 此光标指示矩形框的边缘可被向右(东)移动。
* ne-resize -- 此光标指示矩形框的边缘可被向上及向右移动(北/东)。
* nw-resize -- 此光标指示矩形框的边缘可被向上及向左移动(北/西)。
* n-resize -- 此光标指示矩形框的边缘可被向上(北)移动。
* se-resize -- 此光标指示矩形框的边缘可被向下及向右移动(南/东)。
* sw-resize -- 此光标指示矩形框的边缘可被向下及向左移动(南/西)。
* s-resize -- 此光标指示矩形框的边缘可被向下移动(北/西)。
* w-resize -- 此光标指示矩形框的边缘可被向左移动(西)。
* text -- 此光标指示文本。
* wait -- 此光标指示程序正忙(通常是一只表或沙漏)。
* help -- 此光标指示可用的帮助(通常是一个问号或一个气球)。
*/
D2D_Engine.prototype.setCursorStyle = function(style) {
if(style == undefined){
this.canvas.style.cursor = "default";
} else {
this.canvas.style.cursor = style;
}
};
/**
* 设置鼠标样式
* 同上部函数功能相同
*/
D2D_Engine.prototype.setMouseStyle = D2D_Engine.prototype.setCursorStyle;
/**
* 获取鼠标样式
*/
D2D_Engine.prototype.getCursorStyle = function() {
return this.canvas.style.cursor;
};
/**
* 获取鼠标样式
* 同上部函数功能相同
*/
D2D_Engine.prototype.getMouseStyle = D2D_Engine.prototype.getCursorStyle;
//=======================================================
// 触摸事件
//=======================================================
//=======================================================
// 基本绘图
//=======================================================
/**
* 画线
* @param x0 起点
* @param y0
* @param x1 终点
* @param y1
* @param color 颜色
* @param lineWidth 线宽度
*/
D2D_Engine.prototype.drawLine = function(x0,y0,x1,y1,color,lineWidth) {
//保存状态
this.contextBuffer2D.save();
//开始路径
this.contextBuffer2D.beginPath();
//画线
this.contextBuffer2D.moveTo(x0,y0);
this.contextBuffer2D.lineTo(x1,y1);
//如果有边线宽度选项
if (lineWidth != undefined) {
this.contextBuffer2D.lineWidth = lineWidth;
} else {
this.contextBuffer2D.lineWidth = 1;
}
this.contextBuffer2D.strokeStyle = color;
this.contextBuffer2D.stroke();
//恢复状态
this.contextBuffer2D.restore();
};
/**
* 画填充矩形
* @param x 坐标X
* @param y 坐标Y
* @param width 宽度
* @param height 高度
* @param color 颜色
*/
D2D_Engine.prototype.drawFillRect = function(x,y,width,height,color) {
//保存状态
this.contextBuffer2D.save();
this.contextBuffer2D.fillStyle = color;
this.contextBuffer2D.fillRect(x,y,width,height);
//恢复状态
this.contextBuffer2D.restore();
};
/**
* 画线框矩形
* @param x 坐标X
* @param y 坐标Y
* @param width 宽度
* @param height 高度
* @param color 线框颜色
* @param lineWidth 线框宽度
*/
D2D_Engine.prototype.drawStrokeRect = function(x,y,width,height,color,lineWidth) {
//保存状态
this.contextBuffer2D.save();
//如果有边线宽度选项
if (lineWidth != undefined) {
this.contextBuffer2D.lineWidth = lineWidth;
} else {
this.contextBuffer2D.lineWidth = 1;
}
this.contextBuffer2D.strokeStyle = color;
this.contextBuffer2D.strokeRect(x,y,width,height);
//恢复状态
this.contextBuffer2D.restore();
};
/**
* 导出模板
*/
return D2D_Engine;
})();
//=======================================================
// D2D_引擎启动
//=======================================================
/**
* 启动一个D2D_引擎
* @param engine D2D_引擎实例
*/
function startEngine(engine) {
//初始化时间框架
engine.lastTime = new Date().getTime();
//执行函数
var run = function() {
//时间框架
var nowTime = new Date().getTime();
var deltaTime = nowTime - engine.lastTime;
if(deltaTime - 1000/engine.fps >= 0) {
engine.lastTime = nowTime;
//计算实时帧率
engine.frameCounter ++;
engine.timeCounter += deltaTime;
if(engine.timeCounter >= 1000) {
engine.timeCounter -= 1000;
engine.currentFps = engine.frameCounter;
engine.frameCounter = 0;
}
//绘制管线
if(engine.update != undefined) {
engine.update(deltaTime/1000);
}
if(engine.draw != undefined) {
engine.draw(deltaTime/1000);
}
/**
* 清除鼠标状态
* 不清除down事件
*/
//左键
engine.canvas.mouseStates.leftButton.up = false;
engine.canvas.mouseStates.leftButton.click = false;
engine.canvas.mouseStates.leftButton.dblclick = false;
//右键
engine.canvas.mouseStates.rightButton.up = false;
engine.canvas.mouseStates.rightButton.click = false;
engine.canvas.mouseStates.rightButton.dblclick = false;
//中键
engine.canvas.mouseStates.middleButton.up = false;
engine.canvas.mouseStates.middleButton.click = false;
engine.canvas.mouseStates.middleButton.dblclick = false;
//其他状态
engine.canvas.mouseStates.wheel = false;
engine.canvas.mouseStates.move = false;
engine.canvas.mouseStates.out = false;
engine.canvas.mouseStates.over = false;
//滚动方向
engine.canvas.mouseStates.wheelDelta = 0;
/**
* 清除触摸事件
*/
//暂未实现
}
};
//定制计时器,开始循环
window.setInterval(run,1);
}
| apache-2.0 |
openweave/openweave-core | src/lib/profiles/software-update/WeaveImageAnnounceServer.cpp | 2418 | /*
*
* Copyright (c) 2013-2017 Nest Labs, 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.
*/
/**
* @file
* This file implements the Weave Software Update Profile Image
* Announce server class and its delegate interface.
*
* This class encapsulates the logic to listen for Weave image
* announcements and notify a delegate class when it's time to
* send an image query request.
*/
#include "WeaveImageAnnounceServer.h"
namespace nl {
namespace Weave {
namespace Profiles {
namespace SoftwareUpdate {
using namespace ::nl::Weave;
using namespace ::nl::Weave::Profiles;
WeaveImageAnnounceServer::WeaveImageAnnounceServer()
{
mDelegate = NULL;
}
WEAVE_ERROR WeaveImageAnnounceServer::Init(WeaveExchangeManager * exchangeManager, IWeaveImageAnnounceServerDelegate * delegate)
{
mDelegate = delegate;
if (!exchangeManager)
{
return WEAVE_ERROR_INCORRECT_STATE;
}
return exchangeManager->RegisterUnsolicitedMessageHandler(kWeaveProfile_SWU, kMsgType_ImageAnnounce, HandleImageAnnounce, this);
}
void WeaveImageAnnounceServer::HandleImageAnnounce(ExchangeContext * ec, const IPPacketInfo * packetInfo,
const WeaveMessageInfo * msgInfo, uint32_t profileId, uint8_t msgType,
PacketBuffer * imageAnnouncePayload)
{
PacketBuffer::Free(imageAnnouncePayload);
WeaveImageAnnounceServer * server = (WeaveImageAnnounceServer *) ec->AppState;
if (server && server->mDelegate)
{
// Delegate responsible for closing exchange context and connection
server->mDelegate->OnImageAnnounce(ec);
}
else
{
ec->Close();
ec = NULL;
}
}
} // namespace SoftwareUpdate
} // namespace Profiles
} // namespace Weave
} // namespace nl
| apache-2.0 |
thoughtworks/murmurs.air | vendor/jquery/jquery-1.3.2.js | 120625 | /*!
* jQuery JavaScript Library v1.3.2
* http://jquery.com/
*
* Copyright (c) 2009 John Resig
* Dual licensed under the MIT and GPL licenses.
* http://docs.jquery.com/License
*
* Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009)
* Revision: 6246
*/
(function(){
var
// Will speed up references to window, and allows munging its name.
window = this,
// Will speed up references to undefined, and allows munging its name.
undefined,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
jQuery = window.jQuery = window.$ = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context );
},
// A simple way to check for HTML strings or ID strings
// (both of which we optimize for)
quickExpr = /^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,
// Is it a simple selector
isSimple = /^.[^:#\[\.,]*$/;
jQuery.fn = jQuery.prototype = {
init: function( selector, context ) {
// Make sure that a selection was provided
selector = selector || document;
// Handle $(DOMElement)
if ( selector.nodeType ) {
this[0] = selector;
this.length = 1;
this.context = selector;
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
// Are we dealing with HTML string or an ID?
var 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] )
selector = jQuery.clean( [ match[1] ], context );
// HANDLE: $("#id")
else {
var elem = document.getElementById( match[3] );
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem && elem.id != match[3] )
return jQuery().find( selector );
// Otherwise, we inject the element directly into the jQuery object
var ret = jQuery( elem || [] );
ret.context = document;
ret.selector = selector;
return ret;
}
// HANDLE: $(expr, [context])
// (which is just equivalent to: $(content).find(expr)
} else
return jQuery( context ).find( selector );
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) )
return jQuery( document ).ready( selector );
// Make sure that old selector state is passed along
if ( selector.selector && selector.context ) {
this.selector = selector.selector;
this.context = selector.context;
}
return this.setArray(jQuery.isArray( selector ) ?
selector :
jQuery.makeArray(selector));
},
// Start with an empty selector
selector: "",
// The current version of jQuery being used
jquery: "1.3.2",
// The number of elements contained in the matched element set
size: function() {
return this.length;
},
// 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 === undefined ?
// Return a 'clean' array
Array.prototype.slice.call( this ) :
// Return just the object
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 = jQuery( 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;
},
// Force the current matched set of elements to become
// the specified array of elements (destroying the stack in the process)
// You should use pushStack() in order to do this, but maintain the stack
setArray: function( elems ) {
// Resetting the length to 0, then using the native Array push
// is a super-fast way to populate an object with array-like properties
this.length = 0;
Array.prototype.push.apply( this, elems );
return this;
},
// 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 );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem && elem.jquery ? elem[0] : elem
, this );
},
attr: function( name, value, type ) {
var options = name;
// Look for the case where we're accessing a style value
if ( typeof name === "string" )
if ( value === undefined )
return this[0] && jQuery[ type || "attr" ]( this[0], name );
else {
options = {};
options[ name ] = value;
}
// Check to see if we're setting style values
return this.each(function(i){
// Set all the styles
for ( name in options )
jQuery.attr(
type ?
this.style :
this,
name, jQuery.prop( this, options[ name ], type, i, name )
);
});
},
css: function( key, value ) {
// ignore negative width and height values
if ( (key == 'width' || key == 'height') && parseFloat(value) < 0 )
value = undefined;
return this.attr( key, value, "curCSS" );
},
text: function( text ) {
if ( typeof text !== "object" && text != null )
return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
var ret = "";
jQuery.each( text || this, function(){
jQuery.each( this.childNodes, function(){
if ( this.nodeType != 8 )
ret += this.nodeType != 1 ?
this.nodeValue :
jQuery.fn.text( [ this ] );
});
});
return ret;
},
wrapAll: function( html ) {
if ( this[0] ) {
// The elements to wrap the target around
var wrap = jQuery( html, this[0].ownerDocument ).clone();
if ( this[0].parentNode )
wrap.insertBefore( this[0] );
wrap.map(function(){
var elem = this;
while ( elem.firstChild )
elem = elem.firstChild;
return elem;
}).append(this);
}
return this;
},
wrapInner: function( html ) {
return this.each(function(){
jQuery( this ).contents().wrapAll( html );
});
},
wrap: function( html ) {
return this.each(function(){
jQuery( this ).wrapAll( html );
});
},
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() {
return this.domManip(arguments, false, function(elem){
this.parentNode.insertBefore( elem, this );
});
},
after: function() {
return this.domManip(arguments, false, function(elem){
this.parentNode.insertBefore( elem, this.nextSibling );
});
},
end: function() {
return this.prevObject || jQuery( [] );
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: [].push,
sort: [].sort,
splice: [].splice,
find: function( selector ) {
if ( this.length === 1 ) {
var ret = this.pushStack( [], "find", selector );
ret.length = 0;
jQuery.find( selector, this[0], ret );
return ret;
} else {
return this.pushStack( jQuery.unique(jQuery.map(this, function(elem){
return jQuery.find( selector, elem );
})), "find", selector );
}
},
clone: function( events ) {
// Do the clone
var ret = this.map(function(){
if ( !jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this) ) {
// IE copies events bound via attachEvent when
// using cloneNode. Calling detachEvent on the
// clone will also remove the events from the orignal
// In order to get around this, we use innerHTML.
// Unfortunately, this means some modifications to
// attributes in IE that are actually only stored
// as properties will not be copied (such as the
// the name attribute on an input).
var html = this.outerHTML;
if ( !html ) {
var div = this.ownerDocument.createElement("div");
div.appendChild( this.cloneNode(true) );
html = div.innerHTML;
}
return jQuery.clean([html.replace(/ jQuery\d+="(?:\d+|null)"/g, "").replace(/^\s*/, "")])[0];
} else
return this.cloneNode(true);
});
// Copy the events from the original to the clone
if ( events === true ) {
var orig = this.find("*").andSelf(), i = 0;
ret.find("*").andSelf().each(function(){
if ( this.nodeName !== orig[i].nodeName )
return;
var events = jQuery.data( orig[i], "events" );
for ( var type in events ) {
for ( var handler in events[ type ] ) {
jQuery.event.add( this, type, events[ type ][ handler ], events[ type ][ handler ].data );
}
}
i++;
});
}
// Return the cloned set
return ret;
},
filter: function( selector ) {
return this.pushStack(
jQuery.isFunction( selector ) &&
jQuery.grep(this, function(elem, i){
return selector.call( elem, i );
}) ||
jQuery.multiFilter( selector, jQuery.grep(this, function(elem){
return elem.nodeType === 1;
}) ), "filter", selector );
},
closest: function( selector ) {
var pos = jQuery.expr.match.POS.test( selector ) ? jQuery(selector) : null,
closer = 0;
return this.map(function(){
var cur = this;
while ( cur && cur.ownerDocument ) {
if ( pos ? pos.index(cur) > -1 : jQuery(cur).is(selector) ) {
jQuery.data(cur, "closest", closer);
return cur;
}
cur = cur.parentNode;
closer++;
}
});
},
not: function( selector ) {
if ( typeof selector === "string" )
// test special case where just one selector is passed in
if ( isSimple.test( selector ) )
return this.pushStack( jQuery.multiFilter( selector, this, true ), "not", selector );
else
selector = jQuery.multiFilter( selector, this );
var isArrayLike = selector.length && selector[selector.length - 1] !== undefined && !selector.nodeType;
return this.filter(function() {
return isArrayLike ? jQuery.inArray( this, selector ) < 0 : this != selector;
});
},
add: function( selector ) {
return this.pushStack( jQuery.unique( jQuery.merge(
this.get(),
typeof selector === "string" ?
jQuery( selector ) :
jQuery.makeArray( selector )
)));
},
is: function( selector ) {
return !!selector && jQuery.multiFilter( selector, this ).length > 0;
},
hasClass: function( selector ) {
return !!selector && this.is( "." + selector );
},
val: function( value ) {
if ( value === undefined ) {
var elem = this[0];
if ( elem ) {
if( jQuery.nodeName( elem, 'option' ) )
return (elem.attributes.value || {}).specified ? elem.value : elem.text;
// We need to handle select boxes special
if ( jQuery.nodeName( elem, "select" ) ) {
var 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
for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) {
var option = options[ i ];
if ( option.selected ) {
// Get the specifc 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 );
}
}
return values;
}
// Everything else, we just grab the value
return (elem.value || "").replace(/\r/g, "");
}
return undefined;
}
if ( typeof value === "number" )
value += '';
return this.each(function(){
if ( this.nodeType != 1 )
return;
if ( jQuery.isArray(value) && /radio|checkbox/.test( this.type ) )
this.checked = (jQuery.inArray(this.value, value) >= 0 ||
jQuery.inArray(this.name, value) >= 0);
else if ( jQuery.nodeName( this, "select" ) ) {
var values = jQuery.makeArray(value);
jQuery( "option", this ).each(function(){
this.selected = (jQuery.inArray( this.value, values ) >= 0 ||
jQuery.inArray( this.text, values ) >= 0);
});
if ( !values.length )
this.selectedIndex = -1;
} else
this.value = value;
});
},
html: function( value ) {
return value === undefined ?
(this[0] ?
this[0].innerHTML.replace(/ jQuery\d+="(?:\d+|null)"/g, "") :
null) :
this.empty().append( value );
},
replaceWith: function( value ) {
return this.after( value ).remove();
},
eq: function( i ) {
return this.slice( i, +i + 1 );
},
slice: function() {
return this.pushStack( Array.prototype.slice.apply( this, arguments ),
"slice", Array.prototype.slice.call(arguments).join(",") );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function(elem, i){
return callback.call( elem, i, elem );
}));
},
andSelf: function() {
return this.add( this.prevObject );
},
domManip: function( args, table, callback ) {
if ( this[0] ) {
var fragment = (this[0].ownerDocument || this[0]).createDocumentFragment(),
scripts = jQuery.clean( args, (this[0].ownerDocument || this[0]), fragment ),
first = fragment.firstChild;
if ( first )
for ( var i = 0, l = this.length; i < l; i++ )
callback.call( root(this[i], first), this.length > 1 || i > 0 ?
fragment.cloneNode(true) : fragment );
if ( scripts )
jQuery.each( scripts, evalScript );
}
return this;
function root( elem, cur ) {
return table && jQuery.nodeName(elem, "table") && jQuery.nodeName(cur, "tr") ?
(elem.getElementsByTagName("tbody")[0] ||
elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
elem;
}
}
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
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 || "" );
if ( elem.parentNode )
elem.parentNode.removeChild( elem );
}
function now(){
return +new Date;
}
jQuery.extend = jQuery.fn.extend = function() {
// copy reference to target object
var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options;
// 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 ( var name in options ) {
var src = target[ name ], copy = options[ name ];
// Prevent never-ending loop
if ( target === copy )
continue;
// Recurse if we're merging object values
if ( deep && copy && typeof copy === "object" && !copy.nodeType )
target[ name ] = jQuery.extend( deep,
// Never move original objects, clone them
src || ( copy.length != null ? [ ] : { } )
, copy );
// Don't bring in undefined values
else if ( copy !== undefined )
target[ name ] = copy;
}
// Return the modified object
return target;
};
// exclude the following css properties to add px
var exclude = /z-?index|font-?weight|opacity|zoom|line-?height/i,
// cache defaultView
defaultView = document.defaultView || {},
toString = Object.prototype.toString;
jQuery.extend({
noConflict: function( deep ) {
window.$ = _$;
if ( deep )
window.jQuery = _jQuery;
return jQuery;
},
// 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 toString.call(obj) === "[object Function]";
},
isArray: function( obj ) {
return toString.call(obj) === "[object Array]";
},
// check if an element is in a (or is an) XML document
isXMLDoc: function( elem ) {
return elem.nodeType === 9 && elem.documentElement.nodeName !== "HTML" ||
!!elem.ownerDocument && jQuery.isXMLDoc( elem.ownerDocument );
},
// Evalulates a script in a global context
globalEval: function( data ) {
if ( data && /\S/.test(data) ) {
// Inspired by code by Andrea Giammarchi
// http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html
var head = document.getElementsByTagName("head")[0] || document.documentElement,
script = document.createElement("script");
script.type = "text/javascript";
if ( jQuery.support.scriptEval )
script.appendChild( document.createTextNode( data ) );
else
script.text = data;
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709).
head.insertBefore( script, head.firstChild );
head.removeChild( script );
}
},
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;
if ( args ) {
if ( length === undefined ) {
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 ( length === undefined ) {
for ( name in object )
if ( callback.call( object[ name ], name, object[ name ] ) === false )
break;
} else
for ( var value = object[0];
i < length && callback.call( value, i, value ) !== false; value = object[++i] ){}
}
return object;
},
prop: function( elem, value, type, i, name ) {
// Handle executable functions
if ( jQuery.isFunction( value ) )
value = value.call( elem, i );
// Handle passing in a number to a CSS property
return typeof value === "number" && type == "curCSS" && !exclude.test( name ) ?
value + "px" :
value;
},
className: {
// internal only, use addClass("class")
add: function( elem, classNames ) {
jQuery.each((classNames || "").split(/\s+/), function(i, className){
if ( elem.nodeType == 1 && !jQuery.className.has( elem.className, className ) )
elem.className += (elem.className ? " " : "") + className;
});
},
// internal only, use removeClass("class")
remove: function( elem, classNames ) {
if (elem.nodeType == 1)
elem.className = classNames !== undefined ?
jQuery.grep(elem.className.split(/\s+/), function(className){
return !jQuery.className.has( classNames, className );
}).join(" ") :
"";
},
// internal only, use hasClass("class")
has: function( elem, className ) {
return elem && jQuery.inArray( className, (elem.className || elem).toString().split(/\s+/) ) > -1;
}
},
// 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 ( var name in options )
elem.style[ name ] = old[ name ];
},
css: function( elem, name, force, extra ) {
if ( name == "width" || name == "height" ) {
var val, props = { position: "absolute", visibility: "hidden", display:"block" }, which = name == "width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ];
function getWH() {
val = name == "width" ? elem.offsetWidth : elem.offsetHeight;
if ( extra === "border" )
return;
jQuery.each( which, function() {
if ( !extra )
val -= parseFloat(jQuery.curCSS( elem, "padding" + this, true)) || 0;
if ( extra === "margin" )
val += parseFloat(jQuery.curCSS( elem, "margin" + this, true)) || 0;
else
val -= parseFloat(jQuery.curCSS( elem, "border" + this + "Width", true)) || 0;
});
}
if ( elem.offsetWidth !== 0 )
getWH();
else
jQuery.swap( elem, props, getWH );
return Math.max(0, Math.round(val));
}
return jQuery.curCSS( elem, name, force );
},
curCSS: function( elem, name, force ) {
var ret, style = elem.style;
// We need to handle opacity special in IE
if ( name == "opacity" && !jQuery.support.opacity ) {
ret = jQuery.attr( style, "opacity" );
return ret == "" ?
"1" :
ret;
}
// Make sure we're using the right name for getting the float value
if ( name.match( /float/i ) )
name = styleFloat;
if ( !force && style && style[ name ] )
ret = style[ name ];
else if ( defaultView.getComputedStyle ) {
// Only "float" is needed here
if ( name.match( /float/i ) )
name = "float";
name = name.replace( /([A-Z])/g, "-$1" ).toLowerCase();
var computedStyle = defaultView.getComputedStyle( elem, null );
if ( computedStyle )
ret = computedStyle.getPropertyValue( name );
// We should always get a number back from opacity
if ( name == "opacity" && ret == "" )
ret = "1";
} else if ( elem.currentStyle ) {
var camelCase = name.replace(/\-(\w)/g, function(all, letter){
return letter.toUpperCase();
});
ret = elem.currentStyle[ name ] || elem.currentStyle[ camelCase ];
// 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 ( !/^\d+(px)?$/i.test( ret ) && /^\d/.test( ret ) ) {
// Remember the original values
var left = style.left, rsLeft = elem.runtimeStyle.left;
// Put in the new values to get a computed value out
elem.runtimeStyle.left = elem.currentStyle.left;
style.left = ret || 0;
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
elem.runtimeStyle.left = rsLeft;
}
}
return ret;
},
clean: function( elems, context, fragment ) {
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;
// If a single string is passed in and it's a single tag
// just do a createElement and skip the rest
if ( !fragment && elems.length === 1 && typeof elems[0] === "string" ) {
var match = /^<(\w+)\s*\/?>$/.exec(elems[0]);
if ( match )
return [ context.createElement( match[1] ) ];
}
var ret = [], scripts = [], div = context.createElement("div");
jQuery.each(elems, function(i, elem){
if ( typeof elem === "number" )
elem += '';
if ( !elem )
return;
// Convert html string into DOM nodes
if ( typeof elem === "string" ) {
// Fix "XHTML"-style tags in all browsers
elem = elem.replace(/(<(\w+)[^>]*?)\/>/g, function(all, front, tag){
return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i) ?
all :
front + "></" + tag + ">";
});
// Trim whitespace, otherwise indexOf won't work as expected
var tags = elem.replace(/^\s+/, "").substring(0, 10).toLowerCase();
var wrap =
// option or optgroup
!tags.indexOf("<opt") &&
[ 1, "<select multiple='multiple'>", "</select>" ] ||
!tags.indexOf("<leg") &&
[ 1, "<fieldset>", "</fieldset>" ] ||
tags.match(/^<(thead|tbody|tfoot|colg|cap)/) &&
[ 1, "<table>", "</table>" ] ||
!tags.indexOf("<tr") &&
[ 2, "<table><tbody>", "</tbody></table>" ] ||
// <thead> matched above
(!tags.indexOf("<td") || !tags.indexOf("<th")) &&
[ 3, "<table><tbody><tr>", "</tr></tbody></table>" ] ||
!tags.indexOf("<col") &&
[ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ] ||
// IE can't serialize <link> and <script> tags normally
!jQuery.support.htmlSerialize &&
[ 1, "div<div>", "</div>" ] ||
[ 0, "", "" ];
// Go to html and back, then peel off extra wrappers
div.innerHTML = wrap[1] + elem + wrap[2];
// Move to the right depth
while ( wrap[0]-- )
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 = /<tbody/i.test(elem),
tbody = !tags.indexOf("<table") && !hasBody ?
div.firstChild && div.firstChild.childNodes :
// String was a bare <thead> or <tfoot>
wrap[1] == "<table>" && !hasBody ?
div.childNodes :
[];
for ( var 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 && /^\s/.test( elem ) )
div.insertBefore( context.createTextNode( elem.match(/^\s*/)[0] ), div.firstChild );
elem = jQuery.makeArray( div.childNodes );
}
if ( elem.nodeType )
ret.push( elem );
else
ret = jQuery.merge( ret, elem );
});
if ( fragment ) {
for ( var i = 0; ret[i]; i++ ) {
if ( 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 )
ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) );
fragment.appendChild( ret[i] );
}
}
return scripts;
}
return ret;
},
attr: function( elem, name, value ) {
// don't set attributes on text and comment nodes
if (!elem || elem.nodeType == 3 || elem.nodeType == 8)
return undefined;
var notxml = !jQuery.isXMLDoc( elem ),
// Whether we are setting (or getting)
set = value !== undefined;
// Try to normalize/fix the name
name = notxml && jQuery.props[ name ] || name;
// Only do all the following if this is a node (faster for style)
// IE elem.getAttribute passes even for style
if ( elem.tagName ) {
// These attributes require special treatment
var special = /href|src|style/.test( name );
// Safari mis-reports the default selected property of a hidden option
// Accessing the parent's selectedIndex property fixes it
if ( name == "selected" && elem.parentNode )
elem.parentNode.selectedIndex;
// If applicable, access the attribute via the DOM 0 way
if ( name in elem && notxml && !special ) {
if ( set ){
// We can't allow the type property to be changed (since it causes problems in IE)
if ( name == "type" && jQuery.nodeName( elem, "input" ) && elem.parentNode )
throw "type property can't be changed";
elem[ name ] = value;
}
// browsers index elements by id/name on forms, give priority to attributes.
if( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) )
return elem.getAttributeNode( name ).nodeValue;
// 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/
if ( name == "tabIndex" ) {
var attributeNode = elem.getAttributeNode( "tabIndex" );
return attributeNode && attributeNode.specified
? attributeNode.value
: elem.nodeName.match(/(button|input|object|select|textarea)/i)
? 0
: elem.nodeName.match(/^(a|area)$/i) && elem.href
? 0
: undefined;
}
return elem[ name ];
}
if ( !jQuery.support.style && notxml && name == "style" )
return jQuery.attr( elem.style, "cssText", value );
if ( set )
// convert the value to a string (all browsers do this but IE) see #1070
elem.setAttribute( name, "" + value );
var attr = !jQuery.support.hrefNormalized && notxml && special
// Some attributes require a special call on IE
? elem.getAttribute( name, 2 )
: elem.getAttribute( name );
// Non-existent attributes return null, we normalize to undefined
return attr === null ? undefined : attr;
}
// elem is actually elem.style ... set the style
// IE uses filters for opacity
if ( !jQuery.support.opacity && name == "opacity" ) {
if ( set ) {
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
elem.zoom = 1;
// Set the alpha filter to set the opacity
elem.filter = (elem.filter || "").replace( /alpha\([^)]*\)/, "" ) +
(parseInt( value ) + '' == "NaN" ? "" : "alpha(opacity=" + value * 100 + ")");
}
return elem.filter && elem.filter.indexOf("opacity=") >= 0 ?
(parseFloat( elem.filter.match(/opacity=([^)]*)/)[1] ) / 100) + '':
"";
}
name = name.replace(/-([a-z])/ig, function(all, letter){
return letter.toUpperCase();
});
if ( set )
elem[ name ] = value;
return elem[ name ];
},
trim: function( text ) {
return (text || "").replace( /^\s+|\s+$/g, "" );
},
makeArray: function( array ) {
var ret = [];
if( array != null ){
var i = array.length;
// The window, strings (and functions) also have 'length'
if( i == null || typeof array === "string" || jQuery.isFunction(array) || array.setInterval )
ret[0] = array;
else
while( i )
ret[--i] = array[i];
}
return ret;
},
inArray: function( elem, array ) {
for ( var i = 0, length = array.length; i < length; i++ )
// Use === because on IE, window == document
if ( array[ i ] === elem )
return i;
return -1;
},
merge: function( first, second ) {
// We have to loop this way because IE & Opera overwrite the length
// expando of getElementsByTagName
var i = 0, elem, pos = first.length;
// Also, we need to make sure that the correct elements are being returned
// (IE returns comment nodes in a '*' query)
if ( !jQuery.support.getAll ) {
while ( (elem = second[ i++ ]) != null )
if ( elem.nodeType != 8 )
first[ pos++ ] = elem;
} else
while ( (elem = second[ i++ ]) != null )
first[ pos++ ] = elem;
return first;
},
unique: function( array ) {
var ret = [], done = {};
try {
for ( var i = 0, length = array.length; i < length; i++ ) {
var id = jQuery.data( array[ i ] );
if ( !done[ id ] ) {
done[ id ] = true;
ret.push( array[ i ] );
}
}
} catch( e ) {
ret = array;
}
return ret;
},
grep: function( elems, callback, inv ) {
var ret = [];
// Go through the array, only saving the items
// that pass the validator function
for ( var i = 0, length = elems.length; i < length; i++ )
if ( !inv != !callback( elems[ i ], i ) )
ret.push( elems[ i ] );
return ret;
},
map: function( elems, callback ) {
var ret = [];
// Go through the array, translating each of the items to their
// new value (or values).
for ( var i = 0, length = elems.length; i < length; i++ ) {
var value = callback( elems[ i ], i );
if ( value != null )
ret[ ret.length ] = value;
}
return ret.concat.apply( [], ret );
}
});
// Use of jQuery.browser is deprecated.
// It's included for backwards compatibility and plugins,
// although they should work to migrate away.
var userAgent = navigator.userAgent.toLowerCase();
// Figure out what browser is being used
jQuery.browser = {
version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1],
safari: /webkit/.test( userAgent ),
opera: /opera/.test( userAgent ),
msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
};
jQuery.each({
parent: function(elem){return elem.parentNode;},
parents: function(elem){return jQuery.dir(elem,"parentNode");},
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");},
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( selector ) {
var ret = jQuery.map( this, fn );
if ( selector && typeof selector == "string" )
ret = jQuery.multiFilter( selector, ret );
return this.pushStack( jQuery.unique( ret ), name, selector );
};
});
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 );
for ( var i = 0, l = insert.length; i < l; i++ ) {
var elems = (i > 0 ? this.clone(true) : this).get();
jQuery.fn[ original ].apply( jQuery(insert[i]), elems );
ret = ret.concat( elems );
}
return this.pushStack( ret, name, selector );
};
});
jQuery.each({
removeAttr: function( name ) {
jQuery.attr( this, name, "" );
if (this.nodeType == 1)
this.removeAttribute( name );
},
addClass: function( classNames ) {
jQuery.className.add( this, classNames );
},
removeClass: function( classNames ) {
jQuery.className.remove( this, classNames );
},
toggleClass: function( classNames, state ) {
if( typeof state !== "boolean" )
state = !jQuery.className.has( this, classNames );
jQuery.className[ state ? "add" : "remove" ]( this, classNames );
},
remove: function( selector ) {
if ( !selector || jQuery.filter( selector, [ this ] ).length ) {
// Prevent memory leaks
jQuery( "*", this ).add([this]).each(function(){
jQuery.event.remove(this);
jQuery.removeData(this);
});
if (this.parentNode)
this.parentNode.removeChild( this );
}
},
empty: function() {
// Remove element nodes and prevent memory leaks
jQuery(this).children().remove();
// Remove any remaining nodes
while ( this.firstChild )
this.removeChild( this.firstChild );
}
}, function(name, fn){
jQuery.fn[ name ] = function(){
return this.each( fn, arguments );
};
});
// Helper function used by the dimensions and offset modules
function num(elem, prop) {
return elem[0] && parseInt( jQuery.curCSS(elem[0], prop, true), 10 ) || 0;
}
var expando = "jQuery" + now(), uuid = 0, windowData = {};
jQuery.extend({
cache: {},
data: function( elem, name, data ) {
elem = elem == window ?
windowData :
elem;
var id = elem[ expando ];
// Compute a unique ID for the element
if ( !id )
id = elem[ expando ] = ++uuid;
// Only generate the data cache if we're
// trying to access or manipulate it
if ( name && !jQuery.cache[ id ] )
jQuery.cache[ id ] = {};
// Prevent overriding the named cache with undefined values
if ( data !== undefined )
jQuery.cache[ id ][ name ] = data;
// Return the named cache data, or the ID for the element
return name ?
jQuery.cache[ id ][ name ] :
id;
},
removeData: function( elem, name ) {
elem = elem == window ?
windowData :
elem;
var id = elem[ expando ];
// If we want to remove a specific section of the element's data
if ( name ) {
if ( jQuery.cache[ id ] ) {
// Remove the section of cache data
delete jQuery.cache[ id ][ name ];
// If we've removed all the data, remove the element's cache
name = "";
for ( name in jQuery.cache[ id ] )
break;
if ( !name )
jQuery.removeData( elem );
}
// Otherwise, we want to remove all of the element's data
} else {
// Clean up the element expando
try {
delete elem[ expando ];
} catch(e){
// IE has trouble directly removing the expando
// but it's ok with using removeAttribute
if ( elem.removeAttribute )
elem.removeAttribute( expando );
}
// Completely remove the data cache
delete jQuery.cache[ id ];
}
},
queue: function( elem, type, data ) {
if ( elem ){
type = (type || "fx") + "queue";
var q = jQuery.data( elem, type );
if ( !q || jQuery.isArray(data) )
q = jQuery.data( elem, type, jQuery.makeArray(data) );
else if( data )
q.push( data );
}
return q;
},
dequeue: function( elem, type ){
var queue = jQuery.queue( elem, type ),
fn = queue.shift();
if( !type || type === "fx" )
fn = queue[0];
if( fn !== undefined )
fn.call(elem);
}
});
jQuery.fn.extend({
data: function( key, value ){
var parts = key.split(".");
parts[1] = parts[1] ? "." + parts[1] : "";
if ( value === undefined ) {
var data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);
if ( data === undefined && this.length )
data = jQuery.data( this[0], key );
return data === undefined && parts[1] ?
this.data( parts[0] ) :
data;
} else
return this.trigger("setData" + parts[1] + "!", [parts[0], value]).each(function(){
jQuery.data( this, key, value );
});
},
removeData: function( key ){
return this.each(function(){
jQuery.removeData( this, key );
});
},
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.length == 1 )
queue[0].call(this);
});
},
dequeue: function(type){
return this.each(function(){
jQuery.dequeue( this, type );
});
}
});/*!
* Sizzle CSS Selector Engine - v0.9.3
* Copyright 2009, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
* More information: http://sizzlejs.com/
*/
(function(){
var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?/g,
done = 0,
toString = Object.prototype.toString;
var Sizzle = function(selector, context, results, seed) {
results = results || [];
context = context || document;
if ( context.nodeType !== 1 && context.nodeType !== 9 )
return [];
if ( !selector || typeof selector !== "string" ) {
return results;
}
var parts = [], m, set, checkSet, check, mode, extra, prune = true;
// Reset the position of the chunker regexp (start from head)
chunker.lastIndex = 0;
while ( (m = chunker.exec(selector)) !== null ) {
parts.push( m[1] );
if ( m[2] ) {
extra = RegExp.rightContext;
break;
}
}
if ( parts.length > 1 && origPOS.exec( selector ) ) {
if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
set = posProcess( parts[0] + parts[1], context );
} 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 );
}
}
} else {
var ret = seed ?
{ expr: parts.pop(), set: makeArray(seed) } :
Sizzle.find( parts.pop(), parts.length === 1 && context.parentNode ? context.parentNode : context, isXML(context) );
set = Sizzle.filter( ret.expr, ret.set );
if ( parts.length > 0 ) {
checkSet = makeArray(set);
} else {
prune = false;
}
while ( parts.length ) {
var cur = parts.pop(), pop = cur;
if ( !Expr.relative[ cur ] ) {
cur = "";
} else {
pop = parts.pop();
}
if ( pop == null ) {
pop = context;
}
Expr.relative[ cur ]( checkSet, pop, isXML(context) );
}
}
if ( !checkSet ) {
checkSet = set;
}
if ( !checkSet ) {
throw "Syntax error, unrecognized expression: " + (cur || selector);
}
if ( toString.call(checkSet) === "[object Array]" ) {
if ( !prune ) {
results.push.apply( results, checkSet );
} else if ( context.nodeType === 1 ) {
for ( var i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && contains(context, checkSet[i])) ) {
results.push( set[i] );
}
}
} else {
for ( var 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, context, results, seed );
if ( sortOrder ) {
hasDuplicate = false;
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.find = function(expr, context, isXML){
var set, match;
if ( !expr ) {
return [];
}
for ( var i = 0, l = Expr.order.length; i < l; i++ ) {
var type = Expr.order[i], match;
if ( (match = Expr.match[ type ].exec( expr )) ) {
var left = RegExp.leftContext;
if ( left.substr( left.length - 1 ) !== "\\" ) {
match[1] = (match[1] || "").replace(/\\/g, "");
set = Expr.find[ type ]( match, context, isXML );
if ( set != null ) {
expr = expr.replace( Expr.match[ type ], "" );
break;
}
}
}
}
if ( !set ) {
set = context.getElementsByTagName("*");
}
return {set: set, expr: expr};
};
Sizzle.filter = function(expr, set, inplace, not){
var old = expr, result = [], curLoop = set, match, anyFound,
isXMLFilter = set && set[0] && isXML(set[0]);
while ( expr && set.length ) {
for ( var type in Expr.filter ) {
if ( (match = Expr.match[ type ].exec( expr )) != null ) {
var filter = Expr.filter[ type ], found, item;
anyFound = false;
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 ( var i = 0; (item = curLoop[i]) != null; i++ ) {
if ( item ) {
found = filter( item, match, i, curLoop );
var 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 ) {
throw "Syntax error, unrecognized expression: " + expr;
} else {
break;
}
}
old = expr;
}
return curLoop;
};
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|)\s*\]/,
TAG: /^((?:[\w\u00c0-\uFFFF\*_-]|\\.)+)/,
CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,
POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,
PSEUDO: /:((?:[\w\u00c0-\uFFFF_-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/
},
attrMap: {
"class": "className",
"for": "htmlFor"
},
attrHandle: {
href: function(elem){
return elem.getAttribute("href");
}
},
relative: {
"+": function(checkSet, part, isXML){
var isPartStr = typeof part === "string",
isTag = isPartStr && !/\W/.test(part),
isPartStrNotTag = isPartStr && !isTag;
if ( isTag && !isXML ) {
part = part.toUpperCase();
}
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 === part ?
elem || false :
elem === part;
}
}
if ( isPartStrNotTag ) {
Sizzle.filter( part, checkSet, true );
}
},
">": function(checkSet, part, isXML){
var isPartStr = typeof part === "string";
if ( isPartStr && !/\W/.test(part) ) {
part = isXML ? part : part.toUpperCase();
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
var parent = elem.parentNode;
checkSet[i] = parent.nodeName === part ? parent : false;
}
}
} else {
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var 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 doneName = done++, checkFn = dirCheck;
if ( !part.match(/\W/) ) {
var nodeCheck = part = isXML ? part : part.toUpperCase();
checkFn = dirNodeCheck;
}
checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML);
},
"~": function(checkSet, part, isXML){
var doneName = done++, checkFn = dirCheck;
if ( typeof part === "string" && !part.match(/\W/) ) {
var nodeCheck = part = isXML ? part : part.toUpperCase();
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]);
return m ? [m] : [];
}
},
NAME: function(match, context, isXML){
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){
return context.getElementsByTagName(match[1]);
}
},
preFilter: {
CLASS: function(match, curLoop, inplace, result, not, isXML){
match = " " + match[1].replace(/\\/g, "") + " ";
if ( isXML ) {
return match;
}
for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
if ( elem ) {
if ( not ^ (elem.className && (" " + elem.className + " ").indexOf(match) >= 0) ) {
if ( !inplace )
result.push( elem );
} else if ( inplace ) {
curLoop[i] = false;
}
}
}
return false;
},
ID: function(match){
return match[1].replace(/\\/g, "");
},
TAG: function(match, curLoop){
for ( var i = 0; curLoop[i] === false; i++ ){}
return curLoop[i] && isXML(curLoop[i]) ? match[1] : match[1].toUpperCase();
},
CHILD: function(match){
if ( match[1] == "nth" ) {
// 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;
}
// TODO: Move to normal caching system
match[0] = done++;
return match;
},
ATTR: function(match, curLoop, inplace, result, not, isXML){
var name = match[1].replace(/\\/g, "");
if ( !isXML && Expr.attrMap[name] ) {
match[1] = Expr.attrMap[name];
}
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 ( match[3].match(chunker).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
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){
return "text" === elem.type;
},
radio: function(elem){
return "radio" === elem.type;
},
checkbox: function(elem){
return "checkbox" === elem.type;
},
file: function(elem){
return "file" === elem.type;
},
password: function(elem){
return "password" === elem.type;
},
submit: function(elem){
return "submit" === elem.type;
},
image: function(elem){
return "image" === elem.type;
},
reset: function(elem){
return "reset" === elem.type;
},
button: function(elem){
return "button" === elem.type || elem.nodeName.toUpperCase() === "BUTTON";
},
input: function(elem){
return /input|select|textarea|button/i.test(elem.nodeName);
}
},
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 || "").indexOf(match[3]) >= 0;
} else if ( name === "not" ) {
var not = match[3];
for ( var i = 0, l = not.length; i < l; i++ ) {
if ( not[i] === elem ) {
return false;
}
}
return true;
}
},
CHILD: function(elem, match){
var 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':
var first = match[2], last = match[3];
if ( first == 1 && last == 0 ) {
return true;
}
var doneName = match[0],
parent = elem.parentNode;
if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) {
var count = 0;
for ( node = parent.firstChild; node; node = node.nextSibling ) {
if ( node.nodeType === 1 ) {
node.nodeIndex = ++count;
}
}
parent.sizcache = doneName;
}
var 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 === match;
},
CLASS: function(elem, match){
return (" " + (elem.className || elem.getAttribute("class")) + " ")
.indexOf( match ) > -1;
},
ATTR: function(elem, match){
var name = match[1],
result = 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 === "=" ?
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;
for ( var type in Expr.match ) {
Expr.match[ type ] = RegExp( Expr.match[ type ].source + /(?![^\[]*\])(?![^\(]*\))/.source );
}
var makeArray = function(array, results) {
array = Array.prototype.slice.call( array );
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.
try {
Array.prototype.slice.call( document.documentElement.childNodes );
// Provide a fallback method if it does not work
} catch(e){
makeArray = function(array, results) {
var ret = results || [];
if ( toString.call(array) === "[object Array]" ) {
Array.prototype.push.apply( ret, array );
} else {
if ( typeof array.length === "number" ) {
for ( var i = 0, l = array.length; i < l; i++ ) {
ret.push( array[i] );
}
} else {
for ( var i = 0; array[i]; i++ ) {
ret.push( array[i] );
}
}
}
return ret;
};
}
var sortOrder;
if ( document.documentElement.compareDocumentPosition ) {
sortOrder = function( a, b ) {
var ret = a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1;
if ( ret === 0 ) {
hasDuplicate = true;
}
return ret;
};
} else if ( "sourceIndex" in document.documentElement ) {
sortOrder = function( a, b ) {
var ret = a.sourceIndex - b.sourceIndex;
if ( ret === 0 ) {
hasDuplicate = true;
}
return ret;
};
} else if ( document.createRange ) {
sortOrder = function( a, b ) {
var aRange = a.ownerDocument.createRange(), bRange = b.ownerDocument.createRange();
aRange.selectNode(a);
aRange.collapse(true);
bRange.selectNode(b);
bRange.collapse(true);
var ret = aRange.compareBoundaryPoints(Range.START_TO_END, bRange);
if ( ret === 0 ) {
hasDuplicate = true;
}
return ret;
};
}
// 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("form"),
id = "script" + (new Date).getTime();
form.innerHTML = "<input name='" + id + "'/>";
// Inject it into the root element, check its status, and remove it quickly
var root = document.documentElement;
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 );
})();
(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);
};
}
})();
if ( document.querySelectorAll ) (function(){
var oldSizzle = Sizzle, div = document.createElement("div");
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 && context.nodeType === 9 && !isXML(context) ) {
try {
return makeArray( context.querySelectorAll(query), extra );
} catch(e){}
}
return oldSizzle(query, context, extra, seed);
};
Sizzle.find = oldSizzle.find;
Sizzle.filter = oldSizzle.filter;
Sizzle.selectors = oldSizzle.selectors;
Sizzle.matches = oldSizzle.matches;
})();
if ( document.getElementsByClassName && document.documentElement.getElementsByClassName ) (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)
if ( 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]);
}
};
})();
function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
var sibDir = dir == "previousSibling" && !isXML;
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
if ( sibDir && elem.nodeType === 1 ){
elem.sizcache = doneName;
elem.sizset = i;
}
elem = elem[dir];
var match = false;
while ( elem ) {
if ( elem.sizcache === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 && !isXML ){
elem.sizcache = doneName;
elem.sizset = i;
}
if ( elem.nodeName === cur ) {
match = elem;
break;
}
elem = elem[dir];
}
checkSet[i] = match;
}
}
}
function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
var sibDir = dir == "previousSibling" && !isXML;
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
if ( sibDir && elem.nodeType === 1 ) {
elem.sizcache = doneName;
elem.sizset = i;
}
elem = elem[dir];
var match = false;
while ( elem ) {
if ( elem.sizcache === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 ) {
if ( !isXML ) {
elem.sizcache = 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;
}
}
}
var contains = document.compareDocumentPosition ? function(a, b){
return a.compareDocumentPosition(b) & 16;
} : function(a, b){
return a !== b && (a.contains ? a.contains(b) : true);
};
var isXML = function(elem){
return elem.nodeType === 9 && elem.documentElement.nodeName !== "HTML" ||
!!elem.ownerDocument && isXML( elem.ownerDocument );
};
var posProcess = function(selector, context){
var tmpSet = [], later = "", match,
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 );
}
return Sizzle.filter( later, tmpSet );
};
// EXPOSE
jQuery.find = Sizzle;
jQuery.filter = Sizzle.filter;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.filters;
Sizzle.selectors.filters.hidden = function(elem){
return elem.offsetWidth === 0 || elem.offsetHeight === 0;
};
Sizzle.selectors.filters.visible = function(elem){
return elem.offsetWidth > 0 || elem.offsetHeight > 0;
};
Sizzle.selectors.filters.animated = function(elem){
return jQuery.grep(jQuery.timers, function(fn){
return elem === fn.elem;
}).length;
};
jQuery.multiFilter = function( expr, elems, not ) {
if ( not ) {
expr = ":not(" + expr + ")";
}
return Sizzle.matches(expr, elems);
};
jQuery.dir = function( elem, dir ){
var matched = [], cur = elem[dir];
while ( cur && cur != document ) {
if ( cur.nodeType == 1 )
matched.push( cur );
cur = cur[dir];
}
return matched;
};
jQuery.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;
};
jQuery.sibling = function(n, elem){
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType == 1 && n != elem )
r.push( n );
}
return r;
};
return;
window.Sizzle = Sizzle;
})();
/*
* A number of helper functions used for managing events.
* Many of the ideas behind this code originated from
* Dean Edwards' addEvent library.
*/
jQuery.event = {
// Bind an event to an element
// Original by Dean Edwards
add: function(elem, types, handler, data) {
if ( elem.nodeType == 3 || elem.nodeType == 8 )
return;
// For whatever reason, IE has trouble passing the window object
// around, causing it to be cloned in the process
if ( elem.setInterval && elem != window )
elem = window;
// Make sure that the function being executed has a unique ID
if ( !handler.guid )
handler.guid = this.guid++;
// if data is passed, bind to handler
if ( data !== undefined ) {
// Create temporary function pointer to original handler
var fn = handler;
// Create unique handler function, wrapped around original handler
handler = this.proxy( fn );
// Store data in unique handler
handler.data = data;
}
// Init the element's event structure
var events = jQuery.data(elem, "events") || jQuery.data(elem, "events", {}),
handle = jQuery.data(elem, "handle") || jQuery.data(elem, "handle", function(){
// Handle the second event of a trigger and when
// an event is called after a page has unloaded
return typeof jQuery !== "undefined" && !jQuery.event.triggered ?
jQuery.event.handle.apply(arguments.callee.elem, arguments) :
undefined;
});
// Add elem as a property of the handle function
// This is to prevent a memory leak with non-native
// event in IE.
handle.elem = elem;
// Handle multiple events separated by a space
// jQuery(...).bind("mouseover mouseout", fn);
jQuery.each(types.split(/\s+/), function(index, type) {
// Namespaced event handlers
var namespaces = type.split(".");
type = namespaces.shift();
handler.type = namespaces.slice().sort().join(".");
// Get the current list of functions bound to this event
var handlers = events[type];
if ( jQuery.event.specialAll[type] )
jQuery.event.specialAll[type].setup.call(elem, data, namespaces);
// Init the event handler queue
if (!handlers) {
handlers = events[type] = {};
// Check for a special event handler
// Only use addEventListener/attachEvent if the special
// events handler returns false
if ( !jQuery.event.special[type] || jQuery.event.special[type].setup.call(elem, data, namespaces) === false ) {
// Bind the global event handler to the element
if (elem.addEventListener)
elem.addEventListener(type, handle, false);
else if (elem.attachEvent)
elem.attachEvent("on" + type, handle);
}
}
// Add the function to the element's handler list
handlers[handler.guid] = handler;
// Keep track of which events have been used, for global triggering
jQuery.event.global[type] = true;
});
// Nullify elem to prevent memory leaks in IE
elem = null;
},
guid: 1,
global: {},
// Detach an event or set of events from an element
remove: function(elem, types, handler) {
// don't do events on text and comment nodes
if ( elem.nodeType == 3 || elem.nodeType == 8 )
return;
var events = jQuery.data(elem, "events"), ret, index;
if ( events ) {
// Unbind all events for the element
if ( types === undefined || (typeof types === "string" && types.charAt(0) == ".") )
for ( var type in events )
this.remove( elem, type + (types || "") );
else {
// types is actually an event object here
if ( types.type ) {
handler = types.handler;
types = types.type;
}
// Handle multiple events seperated by a space
// jQuery(...).unbind("mouseover mouseout", fn);
jQuery.each(types.split(/\s+/), function(index, type){
// Namespaced event handlers
var namespaces = type.split(".");
type = namespaces.shift();
var namespace = RegExp("(^|\\.)" + namespaces.slice().sort().join(".*\\.") + "(\\.|$)");
if ( events[type] ) {
// remove the given handler for the given type
if ( handler )
delete events[type][handler.guid];
// remove all handlers for the given type
else
for ( var handle in events[type] )
// Handle the removal of namespaced events
if ( namespace.test(events[type][handle].type) )
delete events[type][handle];
if ( jQuery.event.specialAll[type] )
jQuery.event.specialAll[type].teardown.call(elem, namespaces);
// remove generic event handler if no more handlers exist
for ( ret in events[type] ) break;
if ( !ret ) {
if ( !jQuery.event.special[type] || jQuery.event.special[type].teardown.call(elem, namespaces) === false ) {
if (elem.removeEventListener)
elem.removeEventListener(type, jQuery.data(elem, "handle"), false);
else if (elem.detachEvent)
elem.detachEvent("on" + type, jQuery.data(elem, "handle"));
}
ret = null;
delete events[type];
}
}
});
}
// Remove the expando if it's no longer used
for ( ret in events ) break;
if ( !ret ) {
var handle = jQuery.data( elem, "handle" );
if ( handle ) handle.elem = null;
jQuery.removeData( elem, "events" );
jQuery.removeData( elem, "handle" );
}
}
},
// bubbling is internal
trigger: function( event, data, elem, bubbling ) {
// Event object or event type
var type = event.type || event;
if( !bubbling ){
event = typeof event === "object" ?
// jQuery.Event object
event[expando] ? event :
// Object literal
jQuery.extend( jQuery.Event(type), event ) :
// Just the event type (string)
jQuery.Event(type);
if ( type.indexOf("!") >= 0 ) {
event.type = type = type.slice(0, -1);
event.exclusive = true;
}
// Handle a global trigger
if ( !elem ) {
// Don't bubble custom events when global (to avoid too much overhead)
event.stopPropagation();
// Only trigger if we've ever bound an event for it
if ( this.global[type] )
jQuery.each( jQuery.cache, function(){
if ( this.events && this.events[type] )
jQuery.event.trigger( event, data, this.handle.elem );
});
}
// Handle triggering a single element
// don't do events on text and comment nodes
if ( !elem || elem.nodeType == 3 || elem.nodeType == 8 )
return undefined;
// Clean up in case it is reused
event.result = undefined;
event.target = elem;
// Clone the incoming data, if any
data = jQuery.makeArray(data);
data.unshift( event );
}
event.currentTarget = elem;
// Trigger the event, it is assumed that "handle" is a function
var handle = jQuery.data(elem, "handle");
if ( handle )
handle.apply( elem, data );
// Handle triggering native .onfoo handlers (and on links since we don't call .click() for links)
if ( (!elem[type] || (jQuery.nodeName(elem, 'a') && type == "click")) && elem["on"+type] && elem["on"+type].apply( elem, data ) === false )
event.result = false;
// Trigger the native events (except for clicks on links)
if ( !bubbling && elem[type] && !event.isDefaultPrevented() && !(jQuery.nodeName(elem, 'a') && type == "click") ) {
this.triggered = true;
try {
elem[ type ]();
// prevent IE from throwing an error for some hidden elements
} catch (e) {}
}
this.triggered = false;
if ( !event.isPropagationStopped() ) {
var parent = elem.parentNode || elem.ownerDocument;
if ( parent )
jQuery.event.trigger(event, data, parent, true);
}
},
handle: function(event) {
// returned undefined or false
var all, handlers;
event = arguments[0] = jQuery.event.fix( event || window.event );
event.currentTarget = this;
// Namespaced event handlers
var namespaces = event.type.split(".");
event.type = namespaces.shift();
// Cache this now, all = true means, any handler
all = !namespaces.length && !event.exclusive;
var namespace = RegExp("(^|\\.)" + namespaces.slice().sort().join(".*\\.") + "(\\.|$)");
handlers = ( jQuery.data(this, "events") || {} )[event.type];
for ( var j in handlers ) {
var handler = handlers[j];
// Filter the functions by class
if ( all || namespace.test(handler.type) ) {
// Pass in a reference to the handler function itself
// So that we can later remove it
event.handler = handler;
event.data = handler.data;
var ret = handler.apply(this, arguments);
if( ret !== undefined ){
event.result = ret;
if ( ret === false ) {
event.preventDefault();
event.stopPropagation();
}
}
if( event.isImmediatePropagationStopped() )
break;
}
}
},
props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),
fix: function(event) {
if ( event[expando] )
return event;
// store a copy of the original event object
// and "clone" to set read-only properties
var originalEvent = event;
event = jQuery.Event( originalEvent );
for ( var i = this.props.length, prop; i; ){
prop = this.props[ --i ];
event[ prop ] = originalEvent[ prop ];
}
// Fix target property, if necessary
if ( !event.target )
event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either
// check if target is a textnode (safari)
if ( event.target.nodeType == 3 )
event.target = event.target.parentNode;
// Add relatedTarget, if necessary
if ( !event.relatedTarget && event.fromElement )
event.relatedTarget = event.fromElement == event.target ? event.toElement : event.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && event.clientX != null ) {
var doc = document.documentElement, body = document.body;
event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc.clientLeft || 0);
event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc.clientTop || 0);
}
// Add which for key events
if ( !event.which && ((event.charCode || event.charCode === 0) ? event.charCode : event.keyCode) )
event.which = event.charCode || event.keyCode;
// Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
if ( !event.metaKey && event.ctrlKey )
event.metaKey = event.ctrlKey;
// Add which for click: 1 == left; 2 == middle; 3 == right
// Note: button is not normalized, so don't use it
if ( !event.which && event.button )
event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
return event;
},
proxy: function( fn, proxy ){
proxy = proxy || function(){ return fn.apply(this, 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 || this.guid++;
// So proxy can be declared as an argument
return proxy;
},
special: {
ready: {
// Make sure the ready event is setup
setup: bindReady,
teardown: function() {}
}
},
specialAll: {
live: {
setup: function( selector, namespaces ){
jQuery.event.add( this, namespaces[0], liveHandler );
},
teardown: function( namespaces ){
if ( namespaces.length ) {
var remove = 0, name = RegExp("(^|\\.)" + namespaces[0] + "(\\.|$)");
jQuery.each( (jQuery.data(this, "events").live || {}), function(){
if ( name.test(this.type) )
remove++;
});
if ( remove < 1 )
jQuery.event.remove( this, namespaces[0], liveHandler );
}
}
}
}
};
jQuery.Event = function( src ){
// Allow instantiation without the 'new' keyword
if( !this.preventDefault )
return new jQuery.Event(src);
// Event object
if( src && src.type ){
this.originalEvent = src;
this.type = src.type;
// Event type
}else
this.type = src;
// timeStamp is buggy for some events on Firefox(#3843)
// So we won't rely on the native value
this.timeStamp = now();
// Mark it as fixed
this[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)
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
};
// Checks if an event happened on an element within another element
// Used in jQuery.event.special.mouseenter and mouseleave handlers
var withinElement = function(event) {
// Check if mouse(over|out) are still within the same parent element
var parent = event.relatedTarget;
// Traverse up the tree
while ( parent && parent != this )
try { parent = parent.parentNode; }
catch(e) { parent = this; }
if( parent != this ){
// set the correct event type
event.type = event.data;
// handle event if we actually just moused on to a non sub-element
jQuery.event.handle.apply( this, arguments );
}
};
jQuery.each({
mouseover: 'mouseenter',
mouseout: 'mouseleave'
}, function( orig, fix ){
jQuery.event.special[ fix ] = {
setup: function(){
jQuery.event.add( this, orig, withinElement, fix );
},
teardown: function(){
jQuery.event.remove( this, orig, withinElement );
}
};
});
jQuery.fn.extend({
bind: function( type, data, fn ) {
return type == "unload" ? this.one(type, data, fn) : this.each(function(){
jQuery.event.add( this, type, fn || data, fn && data );
});
},
one: function( type, data, fn ) {
var one = jQuery.event.proxy( fn || data, function(event) {
jQuery(this).unbind(event, one);
return (fn || data).apply( this, arguments );
});
return this.each(function(){
jQuery.event.add( this, type, one, fn && data);
});
},
unbind: function( type, fn ) {
return this.each(function(){
jQuery.event.remove( this, type, fn );
});
},
trigger: function( type, data ) {
return this.each(function(){
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
if( this[0] ){
var event = jQuery.Event(type);
event.preventDefault();
event.stopPropagation();
jQuery.event.trigger( event, data, this[0] );
return event.result;
}
},
toggle: function( fn ) {
// Save reference to arguments for access in closure
var args = arguments, i = 1;
// link all the functions, so any of them can unbind this click handler
while( i < args.length )
jQuery.event.proxy( fn, args[i++] );
return this.click( jQuery.event.proxy( fn, function(event) {
// Figure out which function to execute
this.lastToggle = ( this.lastToggle || 0 ) % i;
// Make sure that clicks stop
event.preventDefault();
// and execute the function
return args[ this.lastToggle++ ].apply( this, arguments ) || false;
}));
},
hover: function(fnOver, fnOut) {
return this.mouseenter(fnOver).mouseleave(fnOut);
},
ready: function(fn) {
// Attach the listeners
bindReady();
// If the DOM is already ready
if ( jQuery.isReady )
// Execute the function immediately
fn.call( document, jQuery );
// Otherwise, remember the function for later
else
// Add the function to the wait list
jQuery.readyList.push( fn );
return this;
},
live: function( type, fn ){
var proxy = jQuery.event.proxy( fn );
proxy.guid += this.selector + type;
jQuery(document).bind( liveConvert(type, this.selector), this.selector, proxy );
return this;
},
die: function( type, fn ){
jQuery(document).unbind( liveConvert(type, this.selector), fn ? { guid: fn.guid + this.selector + type } : null );
return this;
}
});
function liveHandler( event ){
var check = RegExp("(^|\\.)" + event.type + "(\\.|$)"),
stop = true,
elems = [];
jQuery.each(jQuery.data(this, "events").live || [], function(i, fn){
if ( check.test(fn.type) ) {
var elem = jQuery(event.target).closest(fn.data)[0];
if ( elem )
elems.push({ elem: elem, fn: fn });
}
});
elems.sort(function(a,b) {
return jQuery.data(a.elem, "closest") - jQuery.data(b.elem, "closest");
});
jQuery.each(elems, function(){
if ( this.fn.call(this.elem, event, this.fn.data) === false )
return (stop = false);
});
return stop;
}
function liveConvert(type, selector){
return ["live", type, selector.replace(/\./g, "`").replace(/ /g, "|")].join(".");
}
jQuery.extend({
isReady: false,
readyList: [],
// Handle when the DOM is ready
ready: function() {
// Make sure that the DOM is not already loaded
if ( !jQuery.isReady ) {
// Remember that the DOM is ready
jQuery.isReady = true;
// If there are functions bound, to execute
if ( jQuery.readyList ) {
// Execute all of them
jQuery.each( jQuery.readyList, function(){
this.call( document, jQuery );
});
// Reset the list of functions
jQuery.readyList = null;
}
// Trigger any bound ready events
jQuery(document).triggerHandler("ready");
}
}
});
var readyBound = false;
function bindReady(){
if ( readyBound ) return;
readyBound = true;
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", function(){
document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
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", function(){
if ( document.readyState === "complete" ) {
document.detachEvent( "onreadystatechange", arguments.callee );
jQuery.ready();
}
});
// If IE and not an iframe
// continually check to see if the document is ready
if ( document.documentElement.doScroll && window == window.top ) (function(){
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( error ) {
setTimeout( arguments.callee, 0 );
return;
}
// and execute any waiting functions
jQuery.ready();
})();
}
// A fallback to window.onload, that will always work
jQuery.event.add( window, "load", jQuery.ready );
}
jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
"mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave," +
"change,select,submit,keydown,keypress,keyup,error").split(","), function(i, name){
// Handle event binding
jQuery.fn[name] = function(fn){
return fn ? this.bind(name, fn) : this.trigger(name);
};
});
// Prevent memory leaks in IE
// And prevent errors on refresh with events like mouseover in other browsers
// Window isn't included so as not to unbind existing unload events
jQuery( window ).bind( 'unload', function(){
for ( var id in jQuery.cache )
// Skip the window
if ( id != 1 && jQuery.cache[ id ].handle )
jQuery.event.remove( jQuery.cache[ id ].handle.elem );
});
(function(){
jQuery.support = {};
var root = document.documentElement,
script = document.createElement("script"),
div = document.createElement("div"),
id = "script" + (new Date).getTime();
div.style.display = "none";
div.innerHTML = ' <link/><table></table><a href="/a" style="color:red;float:left;opacity:.5;">a</a><select><option>text</option></select><object><param/></object>';
var all = div.getElementsByTagName("*"),
a = div.getElementsByTagName("a")[0];
// Can't get basic test support
if ( !all || !all.length || !a ) {
return;
}
jQuery.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 you can get all elements in an <object> element
// IE 7 always returns no results
objectAll: !!div.getElementsByTagName("object")[0]
.getElementsByTagName("*").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 insted)
style: /red/.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)
opacity: a.style.opacity === "0.5",
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
cssFloat: !!a.style.cssFloat,
// Will be defined later
scriptEval: false,
noCloneEvent: true,
boxModel: null
};
script.type = "text/javascript";
try {
script.appendChild( document.createTextNode( "window." + id + "=1;" ) );
} catch(e){}
root.insertBefore( script, root.firstChild );
// Make sure that the execution of code works by injecting a script
// tag with appendChild/createTextNode
// (IE doesn't support this, fails, and uses .text instead)
if ( window[ id ] ) {
jQuery.support.scriptEval = true;
delete window[ id ];
}
root.removeChild( script );
if ( div.attachEvent && div.fireEvent ) {
div.attachEvent("onclick", function(){
// Cloning a node shouldn't copy over any
// bound event handlers (IE does this)
jQuery.support.noCloneEvent = false;
div.detachEvent("onclick", arguments.callee);
});
div.cloneNode(true).fireEvent("onclick");
}
// Figure out if the W3C box model works as expected
// document.body must exist before we can do this
jQuery(function(){
var div = document.createElement("div");
div.style.width = div.style.paddingLeft = "1px";
document.body.appendChild( div );
jQuery.boxModel = jQuery.support.boxModel = div.offsetWidth === 2;
document.body.removeChild( div ).style.display = 'none';
});
})();
var styleFloat = jQuery.support.cssFloat ? "cssFloat" : "styleFloat";
jQuery.props = {
"for": "htmlFor",
"class": "className",
"float": styleFloat,
cssFloat: styleFloat,
styleFloat: styleFloat,
readonly: "readOnly",
maxlength: "maxLength",
cellspacing: "cellSpacing",
rowspan: "rowSpan",
tabindex: "tabIndex"
};
jQuery.fn.extend({
// Keep a copy of the old load
_load: jQuery.fn.load,
load: function( url, params, callback ) {
if ( typeof url !== "string" )
return this._load( url );
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 = null;
// Otherwise, build a param string
} else if( typeof params === "object" ) {
params = jQuery.param( params );
type = "POST";
}
var self = this;
// Request the remote document
jQuery.ajax({
url: url,
type: type,
dataType: "html",
data: params,
complete: function(res, status){
// If successful, inject the HTML into all the matched elements
if ( status == "success" || status == "notmodified" )
// 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(res.responseText.replace(/<script(.|\s)*?\/script>/g, ""))
// Locate the specified elements
.find(selector) :
// If not, just inject the full result
res.responseText );
if( callback )
self.each( callback, [res.responseText, status, res] );
}
});
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 || /select|textarea/i.test(this.nodeName) ||
/text|hidden|password|search/i.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};
}) :
{name: elem.name, value: val};
}).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.bind(o, f);
};
});
var jsc = now();
jQuery.extend({
get: function( url, data, callback, type ) {
// shift arguments if data argument was ommited
if ( jQuery.isFunction( data ) ) {
callback = data;
data = null;
}
return jQuery.ajax({
type: "GET",
url: url,
data: data,
success: callback,
dataType: type
});
},
getScript: function( url, callback ) {
return jQuery.get(url, null, callback, "script");
},
getJSON: function( url, data, callback ) {
return jQuery.get(url, data, callback, "json");
},
post: function( url, data, callback, type ) {
if ( jQuery.isFunction( data ) ) {
callback = data;
data = {};
}
return jQuery.ajax({
type: "POST",
url: url,
data: data,
success: callback,
dataType: type
});
},
ajaxSetup: function( settings ) {
jQuery.extend( jQuery.ajaxSettings, settings );
},
ajaxSettings: {
url: location.href,
global: true,
type: "GET",
contentType: "application/x-www-form-urlencoded",
processData: true,
async: true,
/*
timeout: 0,
data: null,
username: null,
password: null,
*/
// Create the request object; Microsoft failed to properly
// implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
// This function can be overriden by calling jQuery.ajaxSetup
xhr:function(){
return window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
},
accepts: {
xml: "application/xml, text/xml",
html: "text/html",
script: "text/javascript, application/javascript",
json: "application/json, text/javascript",
text: "text/plain",
_default: "*/*"
}
},
// Last-Modified header cache for next request
lastModified: {},
ajax: function( s ) {
// Extend the settings, but re-extend 's' so that it can be
// checked again later (in the test suite, specifically)
s = jQuery.extend(true, s, jQuery.extend(true, {}, jQuery.ajaxSettings, s));
var jsonp, jsre = /=\?(&|$)/g, status, data,
type = s.type.toUpperCase();
// convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" )
s.data = jQuery.param(s.data);
// Handle JSONP Parameter Callbacks
if ( s.dataType == "jsonp" ) {
if ( type == "GET" ) {
if ( !s.url.match(jsre) )
s.url += (s.url.match(/\?/) ? "&" : "?") + (s.jsonp || "callback") + "=?";
} else if ( !s.data || !s.data.match(jsre) )
s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
s.dataType = "json";
}
// Build temporary JSONP function
if ( s.dataType == "json" && (s.data && s.data.match(jsre) || s.url.match(jsre)) ) {
jsonp = "jsonp" + jsc++;
// Replace the =? sequence both in the query string and the data
if ( s.data )
s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
s.url = s.url.replace(jsre, "=" + jsonp + "$1");
// We need to make sure
// that a JSONP style response is executed properly
s.dataType = "script";
// Handle JSONP-style loading
window[ jsonp ] = function(tmp){
data = tmp;
success();
complete();
// Garbage collect
window[ jsonp ] = undefined;
try{ delete window[ jsonp ]; } catch(e){}
if ( head )
head.removeChild( script );
};
}
if ( s.dataType == "script" && s.cache == null )
s.cache = false;
if ( s.cache === false && type == "GET" ) {
var ts = now();
// try replacing _= if it is there
var ret = s.url.replace(/(\?|&)_=.*?(&|$)/, "$1_=" + ts + "$2");
// if nothing was replaced, add timestamp to the end
s.url = ret + ((ret == s.url) ? (s.url.match(/\?/) ? "&" : "?") + "_=" + ts : "");
}
// If data is available, append data to url for get requests
if ( s.data && type == "GET" ) {
s.url += (s.url.match(/\?/) ? "&" : "?") + s.data;
// IE likes to send both get and post data, prevent this
s.data = null;
}
// Watch for a new set of requests
if ( s.global && ! jQuery.active++ )
jQuery.event.trigger( "ajaxStart" );
// Matches an absolute URL, and saves the domain
var parts = /^(\w+:)?\/\/([^\/?#]+)/.exec( s.url );
// If we're requesting a remote document
// and trying to load JSON or Script with a GET
if ( s.dataType == "script" && type == "GET" && parts
&& ( parts[1] && parts[1] != location.protocol || parts[2] != location.host )){
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.src = s.url;
if (s.scriptCharset)
script.charset = s.scriptCharset;
// Handle Script loading
if ( !jsonp ) {
var done = false;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function(){
if ( !done && (!this.readyState ||
this.readyState == "loaded" || this.readyState == "complete") ) {
done = true;
success();
complete();
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
head.removeChild( script );
}
};
}
head.appendChild(script);
// We handle everything using the script element injection
return undefined;
}
var requestDone = false;
// Create the request object
var xhr = s.xhr();
// Open the socket
// Passing null username, generates a login popup on Opera (#2865)
if( s.username )
xhr.open(type, s.url, s.async, s.username, s.password);
else
xhr.open(type, s.url, s.async);
// Need an extra try/catch for cross domain requests in Firefox 3
try {
// Set the correct header, if data is being sent
if ( s.data )
xhr.setRequestHeader("Content-Type", s.contentType);
// Set the If-Modified-Since header, if ifModified mode.
if ( s.ifModified )
xhr.setRequestHeader("If-Modified-Since",
jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
// Set header so the called script knows that it's an XMLHttpRequest
// xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
// Set the Accepts header for the server, depending on the dataType
xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ?
s.accepts[ s.dataType ] + ", */*" :
s.accepts._default );
} catch(e){}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && s.beforeSend(xhr, s) === false ) {
// Handle the global AJAX counter
if ( s.global && ! --jQuery.active )
jQuery.event.trigger( "ajaxStop" );
// close opended socket
xhr.abort();
return false;
}
if ( s.global )
jQuery.event.trigger("ajaxSend", [xhr, s]);
// Wait for a response to come back
var onreadystatechange = function(isTimeout){
// The request was aborted, clear the interval and decrement jQuery.active
if (xhr.readyState == 0) {
if (ival) {
// clear poll interval
clearInterval(ival);
ival = null;
// Handle the global AJAX counter
if ( s.global && ! --jQuery.active )
jQuery.event.trigger( "ajaxStop" );
}
// The transfer is complete and the data is available, or the request timed out
} else if ( !requestDone && xhr && (xhr.readyState == 4 || isTimeout == "timeout") ) {
requestDone = true;
// clear poll interval
if (ival) {
clearInterval(ival);
ival = null;
}
status = isTimeout == "timeout" ? "timeout" :
!jQuery.httpSuccess( xhr ) ? "error" :
s.ifModified && jQuery.httpNotModified( xhr, s.url ) ? "notmodified" :
"success";
if ( status == "success" ) {
// Watch for, and catch, XML document parse errors
try {
// process the data (runs the xml through httpData regardless of callback)
data = jQuery.httpData( xhr, s.dataType, s );
} catch(e) {
status = "parsererror";
}
}
// Make sure that the request was successful or notmodified
if ( status == "success" ) {
// Cache Last-Modified header, if ifModified mode.
var modRes;
try {
modRes = xhr.getResponseHeader("Last-Modified");
} catch(e) {} // swallow exception thrown by FF if header is not available
if ( s.ifModified && modRes )
jQuery.lastModified[s.url] = modRes;
// JSONP handles its own success callback
if ( !jsonp )
success();
} else
jQuery.handleError(s, xhr, status);
// Fire the complete handlers
complete();
if ( isTimeout )
xhr.abort();
// Stop memory leaks
if ( s.async )
xhr = null;
}
};
if ( s.async ) {
// don't attach the handler to the request, just poll it instead
var ival = setInterval(onreadystatechange, 13);
// Timeout checker
if ( s.timeout > 0 )
setTimeout(function(){
// Check to see if the request is still happening
if ( xhr && !requestDone )
onreadystatechange( "timeout" );
}, s.timeout);
}
// Send the data
try {
xhr.send(s.data);
} catch(e) {
jQuery.handleError(s, xhr, null, e);
}
// firefox 1.5 doesn't fire statechange for sync requests
if ( !s.async )
onreadystatechange();
function success(){
// If a local callback was specified, fire it and pass it the data
if ( s.success )
s.success( data, status );
// Fire the global callback
if ( s.global )
jQuery.event.trigger( "ajaxSuccess", [xhr, s] );
}
function complete(){
// Process result
if ( s.complete )
s.complete(xhr, status);
// The request was completed
if ( s.global )
jQuery.event.trigger( "ajaxComplete", [xhr, s] );
// Handle the global AJAX counter
if ( s.global && ! --jQuery.active )
jQuery.event.trigger( "ajaxStop" );
}
// return XMLHttpRequest to allow aborting the request etc.
return xhr;
},
handleError: function( s, xhr, status, e ) {
// If a local callback was specified, fire it
if ( s.error ) s.error( xhr, status, e );
// Fire the global callback
if ( s.global )
jQuery.event.trigger( "ajaxError", [xhr, s, e] );
},
// Counter for holding the number of active queries
active: 0,
// Determines if an XMLHttpRequest was successful or not
httpSuccess: function( xhr ) {
try {
// IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
return !xhr.status && location.protocol == "file:" ||
( xhr.status >= 200 && xhr.status < 300 ) || xhr.status == 304 || xhr.status == 1223;
} catch(e){}
return false;
},
// Determines if an XMLHttpRequest returns NotModified
httpNotModified: function( xhr, url ) {
try {
var xhrRes = xhr.getResponseHeader("Last-Modified");
// Firefox always returns 200. check Last-Modified date
return xhr.status == 304 || xhrRes == jQuery.lastModified[url];
} catch(e){}
return false;
},
httpData: function( xhr, type, s ) {
var ct = xhr.getResponseHeader("content-type"),
xml = type == "xml" || !type && ct && ct.indexOf("xml") >= 0,
data = xml ? xhr.responseXML : xhr.responseText;
if ( xml && data.documentElement.tagName == "parsererror" )
throw "parsererror";
// Allow a pre-filtering function to sanitize the response
// s != null is checked to keep backwards compatibility
if( s && s.dataFilter )
data = s.dataFilter( data, type );
// The filter can actually parse the response
if( typeof data === "string" ){
// If the type is "script", eval it in global context
if ( type == "script" )
jQuery.globalEval( data );
// Get the JavaScript object, if JSON is used.
if ( type == "json" )
data = window["eval"]("(" + data + ")");
}
return data;
},
// Serialize an array of form elements or a set of
// key/values into a query string
param: function( a ) {
var s = [ ];
function add( key, value ){
s[ s.length ] = encodeURIComponent(key) + '=' + encodeURIComponent(value);
};
// If an array was passed in, assume that it is an array
// of form elements
if ( jQuery.isArray(a) || a.jquery )
// Serialize the form elements
jQuery.each( a, function(){
add( this.name, this.value );
});
// Otherwise, assume that it's an object of key/value pairs
else
// Serialize the key/values
for ( var j in a )
// If the value is an array then the key names need to be repeated
if ( jQuery.isArray(a[j]) )
jQuery.each( a[j], function(){
add( j, this );
});
else
add( j, jQuery.isFunction(a[j]) ? a[j]() : a[j] );
// Return the resulting serialization
return s.join("&").replace(/%20/g, "+");
}
});
var elemdisplay = {},
timerId,
fxAttrs = [
// height animations
[ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ],
// width animations
[ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ],
// opacity animations
[ "opacity" ]
];
function genFx( type, num ){
var obj = {};
jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice(0,num)), function(){
obj[ this ] = type;
});
return obj;
}
jQuery.fn.extend({
show: function(speed,callback){
if ( speed ) {
return this.animate( genFx("show", 3), speed, callback);
} else {
for ( var i = 0, l = this.length; i < l; i++ ){
var old = jQuery.data(this[i], "olddisplay");
this[i].style.display = old || "";
if ( jQuery.css(this[i], "display") === "none" ) {
var tagName = this[i].tagName, display;
if ( elemdisplay[ tagName ] ) {
display = elemdisplay[ tagName ];
} else {
var elem = jQuery("<" + tagName + " />").appendTo("body");
display = elem.css("display");
if ( display === "none" )
display = "block";
elem.remove();
elemdisplay[ tagName ] = display;
}
jQuery.data(this[i], "olddisplay", display);
}
}
// Set the display of the elements in a second loop
// to avoid the constant reflow
for ( var i = 0, l = this.length; i < l; i++ ){
this[i].style.display = jQuery.data(this[i], "olddisplay") || "";
}
return this;
}
},
hide: function(speed,callback){
if ( speed ) {
return this.animate( genFx("hide", 3), speed, callback);
} else {
for ( var i = 0, l = this.length; i < l; i++ ){
var old = jQuery.data(this[i], "olddisplay");
if ( !old && old !== "none" )
jQuery.data(this[i], "olddisplay", jQuery.css(this[i], "display"));
}
// Set the display of the elements in a second loop
// to avoid the constant reflow
for ( var i = 0, l = this.length; i < l; i++ ){
this[i].style.display = "none";
}
return this;
}
},
// Save the old toggle function
_toggle: jQuery.fn.toggle,
toggle: function( fn, fn2 ){
var bool = typeof fn === "boolean";
return jQuery.isFunction(fn) && jQuery.isFunction(fn2) ?
this._toggle.apply( this, arguments ) :
fn == null || bool ?
this.each(function(){
var state = bool ? fn : jQuery(this).is(":hidden");
jQuery(this)[ state ? "show" : "hide" ]();
}) :
this.animate(genFx("toggle", 3), fn, fn2);
},
fadeTo: function(speed,to,callback){
return this.animate({opacity: to}, speed, callback);
},
animate: function( prop, speed, easing, callback ) {
var optall = jQuery.speed(speed, easing, callback);
return this[ optall.queue === false ? "each" : "queue" ](function(){
var opt = jQuery.extend({}, optall), p,
hidden = this.nodeType == 1 && jQuery(this).is(":hidden"),
self = this;
for ( p in prop ) {
if ( prop[p] == "hide" && hidden || prop[p] == "show" && !hidden )
return opt.complete.call(this);
if ( ( p == "height" || p == "width" ) && this.style ) {
// Store display property
opt.display = jQuery.css(this, "display");
// Make sure that nothing sneaks out
opt.overflow = this.style.overflow;
}
}
if ( opt.overflow != null )
this.style.overflow = "hidden";
opt.curAnim = jQuery.extend({}, prop);
jQuery.each( prop, function(name, val){
var e = new jQuery.fx( self, opt, name );
if ( /toggle|show|hide/.test(val) )
e[ val == "toggle" ? hidden ? "show" : "hide" : val ]( prop );
else {
var parts = val.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),
start = e.cur(true) || 0;
if ( parts ) {
var end = parseFloat(parts[2]),
unit = parts[3] || "px";
// We need to compute starting value
if ( unit != "px" ) {
self.style[ name ] = (end || 1) + unit;
start = ((end || 1) / e.cur(true)) * start;
self.style[ name ] = 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;
});
},
stop: function(clearQueue, gotoEnd){
var timers = jQuery.timers;
if (clearQueue)
this.queue([]);
this.each(function(){
// go in reverse order so anything added to the queue during the loop is ignored
for ( var i = timers.length - 1; i >= 0; i-- )
if ( timers[i].elem == this ) {
if (gotoEnd)
// force the next step to be the last
timers[i](true);
timers.splice(i, 1);
}
});
// start the next in the queue if the last step wasn't forced
if (!gotoEnd)
this.dequeue();
return this;
}
});
// 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" }
}, function( name, props ){
jQuery.fn[ name ] = function( speed, callback ){
return this.animate( props, speed, callback );
};
});
jQuery.extend({
speed: function(speed, easing, fn) {
var opt = typeof speed === "object" ? 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 :
jQuery.fx.speeds[opt.duration] || jQuery.fx.speeds._default;
// Queueing
opt.old = opt.complete;
opt.complete = function(){
if ( opt.queue !== false )
jQuery(this).dequeue();
if ( jQuery.isFunction( opt.old ) )
opt.old.call( 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;
if ( !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 );
// Set display property to block for height/width animations
if ( ( this.prop == "height" || this.prop == "width" ) && this.elem.style )
this.elem.style.display = "block";
},
// Get the current size
cur: function(force){
if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) )
return this.elem[ this.prop ];
var r = parseFloat(jQuery.css(this.elem, this.prop, force));
return r && r > -10000 ? r : parseFloat(jQuery.curCSS(this.elem, this.prop)) || 0;
},
// Start an animation from one number to another
custom: function(from, to, unit){
this.startTime = now();
this.start = from;
this.end = to;
this.unit = unit || this.unit || "px";
this.now = this.start;
this.pos = this.state = 0;
var self = this;
function t(gotoEnd){
return self.step(gotoEnd);
}
t.elem = this.elem;
if ( t() && jQuery.timers.push(t) && !timerId ) {
timerId = setInterval(function(){
var timers = jQuery.timers;
for ( var i = 0; i < timers.length; i++ )
if ( !timers[i]() )
timers.splice(i--, 1);
if ( !timers.length ) {
clearInterval( timerId );
timerId = undefined;
}
}, 13);
}
},
// Simple 'show' function
show: function(){
// Remember where we started, so that we can go back to it later
this.options.orig[this.prop] = jQuery.attr( this.elem.style, 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
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.attr( this.elem.style, this.prop );
this.options.hide = true;
// Begin the animation
this.custom(this.cur(), 0);
},
// Each step of an animation
step: function(gotoEnd){
var t = now();
if ( gotoEnd || t >= this.options.duration + this.startTime ) {
this.now = this.end;
this.pos = this.state = 1;
this.update();
this.options.curAnim[ this.prop ] = true;
var done = true;
for ( var i in this.options.curAnim )
if ( this.options.curAnim[i] !== true )
done = false;
if ( done ) {
if ( this.options.display != null ) {
// Reset the overflow
this.elem.style.overflow = this.options.overflow;
// Reset the display
this.elem.style.display = this.options.display;
if ( jQuery.css(this.elem, "display") == "none" )
this.elem.style.display = "block";
}
// Hide the element if the "hide" operation was done
if ( this.options.hide )
jQuery(this.elem).hide();
// Reset the properties, if the item has been hidden or shown
if ( this.options.hide || this.options.show )
for ( var p in this.options.curAnim )
jQuery.attr(this.elem.style, p, this.options.orig[p]);
// Execute the complete function
this.options.complete.call( this.elem );
}
return false;
} else {
var n = t - this.startTime;
this.state = n / this.options.duration;
// Perform the easing function, defaults to swing
this.pos = jQuery.easing[this.options.easing || (jQuery.easing.swing ? "swing" : "linear")](this.state, n, 0, 1, this.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, {
speeds:{
slow: 600,
fast: 200,
// Default speed
_default: 400
},
step: {
opacity: function(fx){
jQuery.attr(fx.elem.style, "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;
}
}
});
if ( document.documentElement["getBoundingClientRect"] )
jQuery.fn.offset = function() {
if ( !this[0] ) return { top: 0, left: 0 };
if ( this[0] === this[0].ownerDocument.body ) return jQuery.offset.bodyOffset( this[0] );
var box = this[0].getBoundingClientRect(), doc = this[0].ownerDocument, body = doc.body, docElem = doc.documentElement,
clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0,
top = box.top + (self.pageYOffset || jQuery.boxModel && docElem.scrollTop || body.scrollTop ) - clientTop,
left = box.left + (self.pageXOffset || jQuery.boxModel && docElem.scrollLeft || body.scrollLeft) - clientLeft;
return { top: top, left: left };
};
else
jQuery.fn.offset = function() {
if ( !this[0] ) return { top: 0, left: 0 };
if ( this[0] === this[0].ownerDocument.body ) return jQuery.offset.bodyOffset( this[0] );
jQuery.offset.initialized || jQuery.offset.initialize();
var elem = this[0], offsetParent = elem.offsetParent, prevOffsetParent = elem,
doc = elem.ownerDocument, computedStyle, docElem = doc.documentElement,
body = doc.body, defaultView = doc.defaultView,
prevComputedStyle = defaultView.getComputedStyle(elem, null),
top = elem.offsetTop, left = elem.offsetLeft;
while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) {
computedStyle = defaultView.getComputedStyle(elem, null);
top -= elem.scrollTop, left -= elem.scrollLeft;
if ( elem === offsetParent ) {
top += elem.offsetTop, left += elem.offsetLeft;
if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && /^t(able|d|h)$/i.test(elem.tagName)) )
top += parseInt( computedStyle.borderTopWidth, 10) || 0,
left += parseInt( computedStyle.borderLeftWidth, 10) || 0;
prevOffsetParent = offsetParent, offsetParent = elem.offsetParent;
}
if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" )
top += parseInt( computedStyle.borderTopWidth, 10) || 0,
left += parseInt( computedStyle.borderLeftWidth, 10) || 0;
prevComputedStyle = computedStyle;
}
if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" )
top += body.offsetTop,
left += body.offsetLeft;
if ( prevComputedStyle.position === "fixed" )
top += Math.max(docElem.scrollTop, body.scrollTop),
left += Math.max(docElem.scrollLeft, body.scrollLeft);
return { top: top, left: left };
};
jQuery.offset = {
initialize: function() {
if ( this.initialized ) return;
var body = document.body, container = document.createElement('div'), innerDiv, checkDiv, table, td, rules, prop, bodyMarginTop = body.style.marginTop,
html = '<div style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;"><div></div></div><table style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;" cellpadding="0" cellspacing="0"><tr><td></td></tr></table>';
rules = { position: 'absolute', top: 0, left: 0, margin: 0, border: 0, width: '1px', height: '1px', visibility: 'hidden' };
for ( prop in rules ) container.style[prop] = rules[prop];
container.innerHTML = html;
body.insertBefore(container, body.firstChild);
innerDiv = container.firstChild, checkDiv = innerDiv.firstChild, td = innerDiv.nextSibling.firstChild.firstChild;
this.doesNotAddBorder = (checkDiv.offsetTop !== 5);
this.doesAddBorderForTableAndCells = (td.offsetTop === 5);
innerDiv.style.overflow = 'hidden', innerDiv.style.position = 'relative';
this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5);
body.style.marginTop = '1px';
this.doesNotIncludeMarginInBodyOffset = (body.offsetTop === 0);
body.style.marginTop = bodyMarginTop;
body.removeChild(container);
this.initialized = true;
},
bodyOffset: function(body) {
jQuery.offset.initialized || jQuery.offset.initialize();
var top = body.offsetTop, left = body.offsetLeft;
if ( jQuery.offset.doesNotIncludeMarginInBodyOffset )
top += parseInt( jQuery.curCSS(body, 'marginTop', true), 10 ) || 0,
left += parseInt( jQuery.curCSS(body, 'marginLeft', true), 10 ) || 0;
return { top: top, left: left };
}
};
jQuery.fn.extend({
position: function() {
var left = 0, top = 0, results;
if ( this[0] ) {
// Get *real* offsetParent
var offsetParent = this.offsetParent(),
// Get correct offsets
offset = this.offset(),
parentOffset = /^body|html$/i.test(offsetParent[0].tagName) ? { 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 -= num( this, 'marginTop' );
offset.left -= num( this, 'marginLeft' );
// Add offsetParent borders
parentOffset.top += num( offsetParent, 'borderTopWidth' );
parentOffset.left += num( offsetParent, 'borderLeftWidth' );
// Subtract the two offsets
results = {
top: offset.top - parentOffset.top,
left: offset.left - parentOffset.left
};
}
return results;
},
offsetParent: function() {
var offsetParent = this[0].offsetParent || document.body;
while ( offsetParent && (!/^body|html$/i.test(offsetParent.tagName) && jQuery.css(offsetParent, 'position') == 'static') )
offsetParent = offsetParent.offsetParent;
return jQuery(offsetParent);
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( ['Left', 'Top'], function(i, name) {
var method = 'scroll' + name;
jQuery.fn[ method ] = function(val) {
if (!this[0]) return null;
return val !== undefined ?
// Set the scroll offset
this.each(function() {
this == window || this == document ?
window.scrollTo(
!i ? val : jQuery(window).scrollLeft(),
i ? val : jQuery(window).scrollTop()
) :
this[ method ] = val;
}) :
// Return the scroll offset
this[0] == window || this[0] == document ?
self[ i ? 'pageYOffset' : 'pageXOffset' ] ||
jQuery.boxModel && document.documentElement[ method ] ||
document.body[ method ] :
this[0][ method ];
};
});
// Create innerHeight, innerWidth, outerHeight and outerWidth methods
jQuery.each([ "Height", "Width" ], function(i, name){
var tl = i ? "Left" : "Top", // top or left
br = i ? "Right" : "Bottom", // bottom or right
lower = name.toLowerCase();
// innerHeight and innerWidth
jQuery.fn["inner" + name] = function(){
return this[0] ?
jQuery.css( this[0], lower, false, "padding" ) :
null;
};
// outerHeight and outerWidth
jQuery.fn["outer" + name] = function(margin) {
return this[0] ?
jQuery.css( this[0], lower, false, margin ? "margin" : "border" ) :
null;
};
var type = name.toLowerCase();
jQuery.fn[ type ] = function( size ) {
// Get window width or height
return this[0] == window ?
// Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
document.compatMode == "CSS1Compat" && document.documentElement[ "client" + name ] ||
document.body[ "client" + name ] :
// Get document width or height
this[0] == document ?
// Either scroll[Width/Height] or offset[Width/Height], whichever is greater
Math.max(
document.documentElement["client" + name],
document.body["scroll" + name], document.documentElement["scroll" + name],
document.body["offset" + name], document.documentElement["offset" + name]
) :
// Get or set width or height on the element
size === undefined ?
// Get width or height on the element
(this.length ? jQuery.css( this[0], type ) : null) :
// Set the width or height on the element (default to pixels if value is unitless)
this.css( type, typeof size === "string" ? size : size + "px" );
};
});
})();
| apache-2.0 |
anitaonnuvel/vinavidai | VINA-VIDAI/SOURCE/JAVA/org/ahp/core/managers/IAhpMessageResourceManager.java | 1166 | /*
* Copyright 2012 Anita Onnuvel
*
* 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.ahp.core.managers;
import org.ahp.core.exceptions.AhpExceptionCodes;
/**
*
* @author Anita Onnuvel
*
*/
public interface IAhpMessageResourceManager extends IAhpManagerLifecycle {
public String getMessage( AhpExceptionCodes pExceptionCode, Object[] pMessageArguments, String pResourceName );
public String getMessage( AhpExceptionCodes pExceptionCode, Object[] pMessageArguments );
public String getMessage( AhpExceptionCodes pExceptionCode );
public String getMessage( AhpExceptionCodes pExceptionCode, String pResourceName );
}
| apache-2.0 |
iSergio/gwt-cs | cesiumjs4gwt-main/src/main/java/org/cesiumjs/cs/collections/options/FromIso8601Options.java | 1567 | /*
* Copyright 2018 iserge.
*
* 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.cesiumjs.cs.collections.options;
import jsinterop.annotations.*;
/**
* Options for
* {@link org.cesiumjs.cs.collections.TimeIntervalCollection#fromIso8601}.
*
* @author Serge Silaev aka iSergio
*/
@SuppressWarnings("rawtypes")
@JsType(isNative = true, namespace = JsPackage.GLOBAL, name = "Object")
public class FromIso8601Options extends FromIso8601OptionsAbstract {
/**
* An ISO 8601 interval.
*/
@JsProperty
public String iso8601;
/**
* Options for
* {@link org.cesiumjs.cs.collections.TimeIntervalCollection#fromIso8601}.
*/
@JsConstructor
private FromIso8601Options() {
}
/**
* Options for
* {@link org.cesiumjs.cs.collections.TimeIntervalCollection#fromIso8601}.
*
* @param iso8601 An ISO 8601 interval.
*/
@JsConstructor
public FromIso8601Options(String iso8601) {
}
@JsFunction
public interface DataCallback {
void function();
}
}
| apache-2.0 |
indigits/sparse-plex | library/+spx/+fast/private/mex_sqrt_times.cpp | 1783 | /**
This code is inspired from the example in
https://in.mathworks.com/matlabcentral/answers/6411-matrix-multiplication-optimal-speed-and-memory
*/
#include <mex.h>
#include "argcheck.h"
#include "spx_matarr.hpp"
#include "spx_operator.hpp"
#include "spx_vector.hpp"
const char* func_name = "mex_sqrt_times";
#define S_IN prhs[0]
#define V_IN prhs[1]
#define FLAG_IN prhs[2]
#define A_OUT plhs[0]
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray*prhs[])
{
try {
check_num_input_args(nrhs, 2, 3);
check_num_output_args(nlhs, 0, 1);
check_is_double_vector(S_IN, func_name, "S");
check_is_double_matrix(V_IN, func_name, "V");
spx::Vec S(S_IN);
spx::Matrix V(V_IN);
bool rows = false;
if (nrhs > 2){
check_is_double_scalar(FLAG_IN, func_name, "rows");
rows = mxGetScalar(FLAG_IN) != 0;
}
if (rows){
if (S.length() != V.rows()){
mexErrMsgTxt("The number of eigen values must be same as number of rows of V");
}
} else{
if (S.length() != V.columns()){
mexErrMsgTxt("The number of eigen values must be same as number of columns of V");
}
}
mwSize M = V.rows();
mwSize N = V.columns();
// Perform in place square root of S
S.sqrt();
if (rows){
// Scale the rows of V
for (int i=0; i < M; ++i){
V.scale_row(i, S[i]);
}
} else {
// Scale the columns of V
for (int i=0; i < N; ++i){
V.scale_column(i, S[i]);
}
}
} catch (std::exception& e) {
mexErrMsgTxt(e.what());
return;
}
}
| apache-2.0 |
Groostav/CMPT880-term-project | intruder/benchs/batik/batik-1.7/sources/org/apache/batik/ext/awt/geom/Polygon2D.java | 17390 | /*
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.batik.ext.awt.geom;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.Polygon;
import java.awt.Point;
import java.awt.geom.AffineTransform;
import java.awt.geom.PathIterator;
import java.awt.geom.GeneralPath;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.io.Serializable;
/**
* This class is a Polygon with float coordinates.
*
* @version $Id: DisplacementMapRed.java 478276 2006-11-22 18:33:37Z dvholten $
*/
public class Polygon2D implements Shape, Cloneable, Serializable {
/**
* The total number of points. The value of <code>npoints</code>
* represents the number of valid points in this <code>Polygon</code>.
*
*/
public int npoints;
/**
* The array of <i>x</i> coordinates. The value of {@link #npoints npoints} is equal to the
* number of points in this <code>Polygon2D</code>.
*
*/
public float[] xpoints;
/**
* The array of <i>x</i> coordinates. The value of {@link #npoints npoints} is equal to the
* number of points in this <code>Polygon2D</code>.
*
*/
public float[] ypoints;
/**
* Bounds of the Polygon2D.
* @see #getBounds()
*/
protected Rectangle2D bounds;
private GeneralPath path;
private GeneralPath closedPath;
/**
* Creates an empty Polygon2D.
*/
public Polygon2D() {
xpoints = new float[4];
ypoints = new float[4];
}
/**
* Constructs and initializes a <code>Polygon2D</code> from the specified
* Rectangle2D.
* @param rec the Rectangle2D
* @exception NullPointerException rec is <code>null</code>.
*/
public Polygon2D(Rectangle2D rec) {
if (rec == null) {
throw new IndexOutOfBoundsException("null Rectangle");
}
npoints = 4;
xpoints = new float[4];
ypoints = new float[4];
xpoints[0] = (float)rec.getMinX();
ypoints[0] = (float)rec.getMinY();
xpoints[1] = (float)rec.getMaxX();
ypoints[1] = (float)rec.getMinY();
xpoints[2] = (float)rec.getMaxX();
ypoints[2] = (float)rec.getMaxY();
xpoints[3] = (float)rec.getMinX();
ypoints[3] = (float)rec.getMaxY();
calculatePath();
}
/**
* Constructs and initializes a <code>Polygon2D</code> from the specified
* Polygon.
* @param pol the Polygon
* @exception NullPointerException pol is <code>null</code>.
*/
public Polygon2D(Polygon pol) {
if (pol == null) {
throw new IndexOutOfBoundsException("null Polygon");
}
this.npoints = pol.npoints;
this.xpoints = new float[pol.npoints];
this.ypoints = new float[pol.npoints];
for (int i = 0; i < pol.npoints; i++) {
xpoints[i] = (float)pol.xpoints[i];
ypoints[i] = (float)pol.ypoints[i];
}
calculatePath();
}
/**
* Constructs and initializes a <code>Polygon2D</code> from the specified
* parameters.
* @param xpoints an array of <i>x</i> coordinates
* @param ypoints an array of <i>y</i> coordinates
* @param npoints the total number of points in the <code>Polygon2D</code>
* @exception NegativeArraySizeException if the value of
* <code>npoints</code> is negative.
* @exception IndexOutOfBoundsException if <code>npoints</code> is
* greater than the length of <code>xpoints</code>
* or the length of <code>ypoints</code>.
* @exception NullPointerException if <code>xpoints</code> or
* <code>ypoints</code> is <code>null</code>.
*/
public Polygon2D(float[] xpoints, float[] ypoints, int npoints) {
if (npoints > xpoints.length || npoints > ypoints.length) {
throw new IndexOutOfBoundsException("npoints > xpoints.length || npoints > ypoints.length");
}
this.npoints = npoints;
this.xpoints = new float[npoints];
this.ypoints = new float[npoints];
System.arraycopy(xpoints, 0, this.xpoints, 0, npoints);
System.arraycopy(ypoints, 0, this.ypoints, 0, npoints);
calculatePath();
}
/**
* Constructs and initializes a <code>Polygon2D</code> from the specified
* parameters.
* @param xpoints an array of <i>x</i> coordinates
* @param ypoints an array of <i>y</i> coordinates
* @param npoints the total number of points in the <code>Polygon2D</code>
* @exception NegativeArraySizeException if the value of
* <code>npoints</code> is negative.
* @exception IndexOutOfBoundsException if <code>npoints</code> is
* greater than the length of <code>xpoints</code>
* or the length of <code>ypoints</code>.
* @exception NullPointerException if <code>xpoints</code> or
* <code>ypoints</code> is <code>null</code>.
*/
public Polygon2D(int[] xpoints, int[] ypoints, int npoints) {
if (npoints > xpoints.length || npoints > ypoints.length) {
throw new IndexOutOfBoundsException("npoints > xpoints.length || npoints > ypoints.length");
}
this.npoints = npoints;
this.xpoints = new float[npoints];
this.ypoints = new float[npoints];
for (int i = 0; i < npoints; i++) {
this.xpoints[i] = (float)xpoints[i];
this.ypoints[i] = (float)ypoints[i];
}
calculatePath();
}
/**
* Resets this <code>Polygon</code> object to an empty polygon.
*/
public void reset() {
npoints = 0;
bounds = null;
path = new GeneralPath();
closedPath = null;
}
public Object clone() {
Polygon2D pol = new Polygon2D();
for (int i = 0; i < npoints; i++) {
pol.addPoint(xpoints[i], ypoints[i]);
}
return pol;
}
private void calculatePath() {
path = new GeneralPath();
path.moveTo(xpoints[0], ypoints[0]);
for (int i = 1; i < npoints; i++) {
path.lineTo(xpoints[i], ypoints[i]);
}
bounds = path.getBounds2D();
closedPath = null;
}
private void updatePath(float x, float y) {
closedPath = null;
if (path == null) {
path = new GeneralPath(GeneralPath.WIND_EVEN_ODD);
path.moveTo(x, y);
bounds = new Rectangle2D.Float(x, y, 0, 0);
} else {
path.lineTo(x, y);
float _xmax = (float)bounds.getMaxX();
float _ymax = (float)bounds.getMaxY();
float _xmin = (float)bounds.getMinX();
float _ymin = (float)bounds.getMinY();
if (x < _xmin) _xmin = x;
else if (x > _xmax) _xmax = x;
if (y < _ymin) _ymin = y;
else if (y > _ymax) _ymax = y;
bounds = new Rectangle2D.Float(_xmin, _ymin, _xmax - _xmin, _ymax - _ymin);
}
}
/* get the associated {@link Polyline2D}.
*/
public Polyline2D getPolyline2D() {
Polyline2D pol = new Polyline2D( xpoints, ypoints, npoints );
pol.addPoint( xpoints[0], ypoints[0]);
return pol;
}
public Polygon getPolygon() {
int[] _xpoints = new int[npoints];
int[] _ypoints = new int[npoints];
for (int i = 0; i < npoints; i++) {
_xpoints[i] = (int)xpoints[i]; // todo maybe rounding is better ?
_ypoints[i] = (int)ypoints[i];
}
return new Polygon(_xpoints, _ypoints, npoints);
}
public void addPoint(Point2D p) {
addPoint((float)p.getX(), (float)p.getY());
}
/**
* Appends the specified coordinates to this <code>Polygon2D</code>.
* @param x the specified x coordinate
* @param y the specified y coordinate
*/
public void addPoint(float x, float y) {
if (npoints == xpoints.length) {
float[] tmp;
tmp = new float[npoints * 2];
System.arraycopy(xpoints, 0, tmp, 0, npoints);
xpoints = tmp;
tmp = new float[npoints * 2];
System.arraycopy(ypoints, 0, tmp, 0, npoints);
ypoints = tmp;
}
xpoints[npoints] = x;
ypoints[npoints] = y;
npoints++;
updatePath(x, y);
}
/**
* Determines whether the specified {@link Point} is inside this
* <code>Polygon</code>.
* @param p the specified <code>Point</code> to be tested
* @return <code>true</code> if the <code>Polygon</code> contains the
* <code>Point</code>; <code>false</code> otherwise.
* @see #contains(double, double)
*/
public boolean contains(Point p) {
return contains(p.x, p.y);
}
/**
* Determines whether the specified coordinates are inside this
* <code>Polygon</code>.
* <p>
* @param x the specified x coordinate to be tested
* @param y the specified y coordinate to be tested
* @return <code>true</code> if this <code>Polygon</code> contains
* the specified coordinates, (<i>x</i>, <i>y</i>);
* <code>false</code> otherwise.
*/
public boolean contains(int x, int y) {
return contains((double) x, (double) y);
}
/**
* Returns the high precision bounding box of the {@link Shape}.
* @return a {@link Rectangle2D} that precisely
* bounds the <code>Shape</code>.
*/
public Rectangle2D getBounds2D() {
return bounds;
}
public Rectangle getBounds() {
if (bounds == null) return null;
else return bounds.getBounds();
}
/**
* Determines if the specified coordinates are inside this
* <code>Polygon</code>. For the definition of
* <i>insideness</i>, see the class comments of {@link Shape}.
* @param x the specified x coordinate
* @param y the specified y coordinate
* @return <code>true</code> if the <code>Polygon</code> contains the
* specified coordinates; <code>false</code> otherwise.
*/
public boolean contains(double x, double y) {
if (npoints <= 2 || !bounds.contains(x, y)) {
return false;
}
updateComputingPath();
return closedPath.contains(x, y);
}
private void updateComputingPath() {
if (npoints >= 1) {
if (closedPath == null) {
closedPath = (GeneralPath)path.clone();
closedPath.closePath();
}
}
}
/**
* Tests if a specified {@link Point2D} is inside the boundary of this
* <code>Polygon</code>.
* @param p a specified <code>Point2D</code>
* @return <code>true</code> if this <code>Polygon</code> contains the
* specified <code>Point2D</code>; <code>false</code>
* otherwise.
* @see #contains(double, double)
*/
public boolean contains(Point2D p) {
return contains(p.getX(), p.getY());
}
/**
* Tests if the interior of this <code>Polygon</code> intersects the
* interior of a specified set of rectangular coordinates.
* @param x the x coordinate of the specified rectangular
* shape's top-left corner
* @param y the y coordinate of the specified rectangular
* shape's top-left corner
* @param w the width of the specified rectangular shape
* @param h the height of the specified rectangular shape
* @return <code>true</code> if the interior of this
* <code>Polygon</code> and the interior of the
* specified set of rectangular
* coordinates intersect each other;
* <code>false</code> otherwise.
*/
public boolean intersects(double x, double y, double w, double h) {
if (npoints <= 0 || !bounds.intersects(x, y, w, h)) {
return false;
}
updateComputingPath();
return closedPath.intersects(x, y, w, h);
}
/**
* Tests if the interior of this <code>Polygon</code> intersects the
* interior of a specified <code>Rectangle2D</code>.
* @param r a specified <code>Rectangle2D</code>
* @return <code>true</code> if this <code>Polygon</code> and the
* interior of the specified <code>Rectangle2D</code>
* intersect each other; <code>false</code>
* otherwise.
*/
public boolean intersects(Rectangle2D r) {
return intersects(r.getX(), r.getY(), r.getWidth(), r.getHeight());
}
/**
* Tests if the interior of this <code>Polygon</code> entirely
* contains the specified set of rectangular coordinates.
* @param x the x coordinate of the top-left corner of the
* specified set of rectangular coordinates
* @param y the y coordinate of the top-left corner of the
* specified set of rectangular coordinates
* @param w the width of the set of rectangular coordinates
* @param h the height of the set of rectangular coordinates
* @return <code>true</code> if this <code>Polygon</code> entirely
* contains the specified set of rectangular
* coordinates; <code>false</code> otherwise.
*/
public boolean contains(double x, double y, double w, double h) {
if (npoints <= 0 || !bounds.intersects(x, y, w, h)) {
return false;
}
updateComputingPath();
return closedPath.contains(x, y, w, h);
}
/**
* Tests if the interior of this <code>Polygon</code> entirely
* contains the specified <code>Rectangle2D</code>.
* @param r the specified <code>Rectangle2D</code>
* @return <code>true</code> if this <code>Polygon</code> entirely
* contains the specified <code>Rectangle2D</code>;
* <code>false</code> otherwise.
* @see #contains(double, double, double, double)
*/
public boolean contains(Rectangle2D r) {
return contains(r.getX(), r.getY(), r.getWidth(), r.getHeight());
}
/**
* Returns an iterator object that iterates along the boundary of this
* <code>Polygon</code> and provides access to the geometry
* of the outline of this <code>Polygon</code>. An optional
* {@link AffineTransform} can be specified so that the coordinates
* returned in the iteration are transformed accordingly.
* @param at an optional <code>AffineTransform</code> to be applied to the
* coordinates as they are returned in the iteration, or
* <code>null</code> if untransformed coordinates are desired
* @return a {@link PathIterator} object that provides access to the
* geometry of this <code>Polygon</code>.
*/
public PathIterator getPathIterator(AffineTransform at) {
updateComputingPath();
if (closedPath == null) return null;
else return closedPath.getPathIterator(at);
}
/**
* Returns an iterator object that iterates along the boundary of
* the <code>Polygon2D</code> and provides access to the geometry of the
* outline of the <code>Shape</code>. Only SEG_MOVETO, SEG_LINETO, and
* SEG_CLOSE point types are returned by the iterator.
* Since polygons are already flat, the <code>flatness</code> parameter
* is ignored.
* @param at an optional <code>AffineTransform</code> to be applied to the
* coordinates as they are returned in the iteration, or
* <code>null</code> if untransformed coordinates are desired
* @param flatness the maximum amount that the control points
* for a given curve can vary from colinear before a subdivided
* curve is replaced by a straight line connecting the
* endpoints. Since polygons are already flat the
* <code>flatness</code> parameter is ignored.
* @return a <code>PathIterator</code> object that provides access to the
* <code>Shape</code> object's geometry.
*/
public PathIterator getPathIterator(AffineTransform at, double flatness) {
return getPathIterator(at);
}
}
| apache-2.0 |
googleapis/google-api-php-client-services | src/AdExchangeBuyerII/ClientUser.php | 1897 | <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
namespace Google\Service\AdExchangeBuyerII;
class ClientUser extends \Google\Model
{
/**
* @var string
*/
public $clientAccountId;
/**
* @var string
*/
public $email;
/**
* @var string
*/
public $status;
/**
* @var string
*/
public $userId;
/**
* @param string
*/
public function setClientAccountId($clientAccountId)
{
$this->clientAccountId = $clientAccountId;
}
/**
* @return string
*/
public function getClientAccountId()
{
return $this->clientAccountId;
}
/**
* @param string
*/
public function setEmail($email)
{
$this->email = $email;
}
/**
* @return string
*/
public function getEmail()
{
return $this->email;
}
/**
* @param string
*/
public function setStatus($status)
{
$this->status = $status;
}
/**
* @return string
*/
public function getStatus()
{
return $this->status;
}
/**
* @param string
*/
public function setUserId($userId)
{
$this->userId = $userId;
}
/**
* @return string
*/
public function getUserId()
{
return $this->userId;
}
}
// Adding a class alias for backwards compatibility with the previous class name.
class_alias(ClientUser::class, 'Google_Service_AdExchangeBuyerII_ClientUser');
| apache-2.0 |
code4wt/nutch-learning | src/plugin/scoring-similarity/src/java/org/apache/nutch/scoring/similarity/cosine/package-info.java | 146 | /**
*
*/
/** Implements the cosine similarity metric for scoring relevant documents
*
*/
package org.apache.nutch.scoring.similarity.cosine; | apache-2.0 |
EsupPortail/esup-dematec | src/main/java/fr/univrouen/poste/services/GalaxieMappingService.java | 3727 | /**
* Licensed to ESUP-Portail under one or more contributor license
* agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* ESUP-Portail 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 fr.univrouen.poste.services;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import fr.univrouen.poste.domain.GalaxieEntry;
import fr.univrouen.poste.domain.GalaxieMapping;
@Service
public class GalaxieMappingService {
private final Logger logger = Logger.getLogger(getClass());
public void setAttrFromCell(GalaxieEntry galaxieEntry, String cellName, String cellValue) {
String id_numemploi = GalaxieMapping.getCache_id_numemploi();
String id_numCandidat = GalaxieMapping.getCache_id_numCandidat();
String id_email = GalaxieMapping.getCache_id_email();
String id_civilite = GalaxieMapping.getCache_id_civilite();
String id_nom = GalaxieMapping.getCache_id_nom();
String id_prenom = GalaxieMapping.getCache_id_prenom();
String id_localisation = GalaxieMapping.getCache_id_localisation();
String id_profil = GalaxieMapping.getCache_id_profil();
String id_etat_dossier = GalaxieMapping.getCache_id_etat_dossier();
if (id_numemploi.equals(cellName)) galaxieEntry.setNumEmploi(cellValue.trim());
if (id_numCandidat.equals(cellName)) galaxieEntry.setNumCandidat(cellValue.trim());
if (id_civilite.equals(cellName)) galaxieEntry.setCivilite(cellValue.trim());
if (id_nom.equals(cellName)) galaxieEntry.setNom(cellValue.trim());
if (id_prenom.equals(cellName)) galaxieEntry.setPrenom(cellValue.trim());
if (id_email.equals(cellName)) galaxieEntry.setEmail(cellValue.trim());
if (id_localisation.equals(cellName)) galaxieEntry.setLocalisation(cellValue.trim());
if (id_profil.equals(cellName)) galaxieEntry.setProfil(cellValue.trim());
if (id_etat_dossier.equals(cellName)) galaxieEntry.setEtatDossier(cellValue.trim());
}
public void checkCellsHead(Map<String, Long> cellsPosition) {
String id_numemploi = GalaxieMapping.getCache_id_numemploi();
String id_numCandidat = GalaxieMapping.getCache_id_numCandidat();
String id_email = GalaxieMapping.getCache_id_email();
List<String> columnsNotFound = new ArrayList<String>();
String[] columnNamesRequired = {id_numemploi, id_numCandidat, id_email};
for(String columnName: columnNamesRequired) {
if(!cellsPosition.keySet().contains(columnName)) {
columnsNotFound.add(columnName);
}
}
if(!columnsNotFound.isEmpty()) {
String errorMsg = "La (les) colonne(s) " + StringUtils.join(columnsNotFound, ", ") +
" est (sont) manquante(s) dans le fichier Excel fourni. Les colonnes " + StringUtils.join(columnNamesRequired, ", ") +
" sont obligatoires ; ces libellés étant à configurer pour chaque campagne via l'IHM - menu 'Mapping Galaxie' " +
" , ce en fonction de la structure des fichiers Excel Galaxie.";
logger.error(errorMsg);
throw new RuntimeException(errorMsg);
}
}
}
| apache-2.0 |
kelemetry/beacon | examples/nats/beacon-subscriber.go | 1586 | /*
Copyright 2017 The Kelemetry 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 main
import (
"flag"
"log"
"runtime"
"github.com/nats-io/go-nats"
)
// NOTE: Use tls scheme for TLS, e.g. nats-sub -s tls://demo.nats.io:4443 foo
func usage() {
log.Fatalf("Usage: nats-pod-subsiber [-s server] [-t]\n")
}
func printMsg(m *nats.Msg, i int) {
log.Printf("[#%d] Received on [%s]: '%s'\n", i, m.Subject, string(m.Data))
}
func main() {
var urls = flag.String("s", nats.DefaultURL, "The nats server URLs (separated by comma)")
var showTime = flag.Bool("t", false, "Display timestamps")
log.SetFlags(0)
flag.Usage = usage
flag.Parse()
args := flag.Args()
if len(args) < 1 {
usage()
}
nc, err := nats.Connect(*urls)
if err != nil {
log.Fatalf("Can't connect: %v\n", err)
}
i := 0
subj := "kelemetry/beacon"
nc.Subscribe(subj, func(msg *nats.Msg) {
i += 1
printMsg(msg, i)
})
nc.Flush()
if err := nc.LastError(); err != nil {
log.Fatal(err)
}
log.Printf("Listening on [%s]\n", subj)
if *showTime {
log.SetFlags(log.LstdFlags)
}
runtime.Goexit()
}
| apache-2.0 |
nash-x/hws | neutron/services/firewall/agents/ngfw/ngfw_api.py | 10741 | # Copyright 2013 ngfw Networks 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.
import base64
import commands
import httplib
import urllib
import json
import sys
import time
from oslo.config import cfg
from neutron.openstack.common import jsonutils
from neutron.openstack.common import log as logging
from neutron.services.firewall.agents.ngfw import ngfw_utils
TOTALNUM_KEY_BEGIN = '<summary><totalnumber>'
TOTALNUM_KEY_END = '</totalnumber>'
NGFW_PAGESIZE = 15
OPTS = [
cfg.StrOpt('director', default='localhost',
help=_("ngfw director ip")),
cfg.StrOpt('director_port', default='8448',
help=_("ngfw director port")),
cfg.StrOpt('ngfw_username',
help=_("ngfw director username")),
cfg.StrOpt('ngfw_password', secret=True,
help=_("ngfw director password")),
cfg.StrOpt('director_for_acl', default='localhost',
help=_("ngfw director ip for acl")),
cfg.StrOpt('director_for_fip', default='localhost',
help=_("ngfw director ip for fip")), ]
cfg.CONF.register_opts(OPTS, "ngfw")
class LogClass(object):
def __init__(self):
pass
def debug(self, *str):
pass
def warn(self, *str):
pass
def error(self, *str):
pass
if __name__ == '__main__':
LOG = LogClass()
else:
LOG = logging.getLogger(__name__)
class ngfwAPIException(Exception):
message = _("An unknown exception.")
def __init__(self, **kwargs):
try:
self.err = self.message % kwargs
except Exception:
self.err = self.message
def __str__(self):
return self.err
class AuthenticationFailure(ngfwAPIException):
message = _("Invalid login credential.")
class AuthenticationNoResponse(ngfwAPIException):
message = _("No response from NGFW")
class ngfwRestAPI(object):
def __init__(self):
LOG.debug(_('ngfwRestAPI: started'))
self.user = cfg.CONF.ngfw.ngfw_username
self.passwd = cfg.CONF.ngfw.ngfw_password
self.server = cfg.CONF.ngfw.director
self.port = cfg.CONF.ngfw.director_port
self.director_for_acl = cfg.CONF.ngfw.director_for_acl
self.director_for_fip = cfg.CONF.ngfw.director_for_fip
self.timeout = 5
self.retry = 3
self.retry_delay = 0.1
def fix_header(self, resp_headers, body_len):
headers=ngfw_utils.NGFW_DEFAULT_HEADER.copy()
for head in resp_headers.keys():
if head.lower() == 'token':
headers.update({head:resp_headers[head]})
if head.lower() == 'cookie':
headers.update({head:resp_headers[head]})
if head.lower() == 'sn':
headers.update({'SN':str(int(resp_headers[head])+1)})
headers.update({'Content-Length':str(body_len)})
return headers
def send_request(self, httpClient, method, uri, body, headers):
if httpClient is None:
httpClient = httplib.HTTPConnection(host=self.server, port=self.port, timeout=self.timeout)
try:
httpClient.request(method, uri, body, headers)
response = httpClient.getresponse()
return (httpClient, response)
except Exception:
LOG.error(_('ngfwRestAPI: Could not establish HTTP connection'))
return (httpClient, None)
def auth(self):
headers = ngfw_utils.NGFW_DEFAULT_HEADER.copy()
body='username=%s&password=%s' % (self.user, self.passwd)
(httpClient, resp) = self.send_request(None, 'POST', ngfw_utils.NGFW_URL_AUTH, body, headers)
if resp is None:
LOG.error(_('ngfwRestAPI: auth failed, resp is None'))
httpClient.close()
raise AuthenticationNoResponse()
elif resp.status >=400:
LOG.error(_('ngfwRestAPI: auth failed, resp.status is %d'), resp.status)
resp.read()
httpClient.close()
self.retry = 1
raise AuthenticationFailure()
return (httpClient, resp)
def rest_api_once(self, method, url, body=None, headers=None):
try:
httpClient,response = self.auth()
response.read()
req_headers = dict(response.getheaders())
if headers:
req_headers.update(headers)
if body:
body_data = body
else:
body_data = ''
body_len = len(body_data)
req_headers=self.fix_header(req_headers,body_len)
(httpClient, resp) = self.send_request(httpClient, method, url, body_data, req_headers)
if resp:
resp_status = resp.status
resp_str=resp.read()
else:
resp_status = 500
resp_str="we send request, but no response received from NGFW"
httpClient.close()
return {"status": resp_status,
"body": "%s" % resp_str}
except AuthenticationNoResponse:
return {"status": 500, "body": "Authentication failed, No response from NGFW"}
except AuthenticationFailure:
return {"status": 500, "body": "Authentication failed"}
except Exception:
LOG.error(_('ngfwRestAPI: rest_api_once send has exception'))
return {"status": 500, "body": "unknown exception catched"}
def rest_api_multi(self, method, url, body=None, headers=None):
count = 0
resp = {"status": 500, "body": ""}
while count < self.retry:
count = count + 1
resp = self.rest_api_once(method, url, body, headers)
if resp["status"] >=400:
time.sleep(self.retry_delay)
continue
return resp
return resp
def _rest_api(self, method, url, body=None, headers=None, device_ip=None):
if body is None:
body = ''
if headers is None:
headers = ''
confile = ""
for argument in sys.argv:
if '--config-file' in argument:
confile = confile + "**&&**" + argument
file_path = '/usr/lib64/python2.6/site-packages/neutron/services/firewall/agents/ngfw/ngfw_api.py'
if not device_ip:
cmd = 'python %s %s \'%s\' \'%s\' \'%s\' \'%s\'' % (file_path, method, url, body, headers, confile)
else:
cmd = 'python %s %s \'%s\' \'%s\' \'%s\' \'%s\' \'%s\'' % (file_path, method, url, body, headers, confile, device_ip)
rest, StrOut = commands.getstatusoutput(cmd)
if "psk" in cmd or "psk" in StrOut:
LOG.debug(_("request related to ike peer, status: %s" % rest))
else:
LOG.debug(_('cmd:%s, rest:%s, StrOut:%s' % (cmd, rest, StrOut)))
if rest != 0:
LOG.error(_('run cmd:%s failed, rest is:%s, StrOut is :%s' % (cmd, rest, StrOut)))
return {"status": 500, "body": ""}
try:
StrOutTrans = StrOut.replace("\'", "\"")
StrOutTrans = json.loads(StrOutTrans)
except Exception:
LOG.error(_('ngfwRestAPI: rest_api has exception %s'), StrOut)
return {"status": 500, "body": ""}
if "psk" not in str(StrOutTrans):
LOG.debug(_('StrOutTrans is :%s.' % (StrOutTrans)))
return StrOutTrans
def rest_api(self, method, url, body=None, headers=None, device_ip=None):
if method.lower() == 'get':
#first get totalnum
result = {"status": 500, "body":""}
body_store = ''
if '?' in url:
flag = '&'
else:
flag = '?'
uri = url + flag + 'pageindex=1&pagesize=1'
resp = self._rest_api(method, uri, body, headers, device_ip)
if resp['status'] >= 400:
return resp
total_num_list = ngfw_utils.parse_xml_name(json.dumps(resp), TOTALNUM_KEY_BEGIN, TOTALNUM_KEY_END)
if not total_num_list:
return resp
times = int(total_num_list[0]) / NGFW_PAGESIZE
left = int(total_num_list[0]) % NGFW_PAGESIZE
for i in range(times):
uri = url + flag + 'pageindex=%d&pagesize=%d' % (1+i, NGFW_PAGESIZE)
temp = self._rest_api(method, uri, body, headers, device_ip)
if temp['status'] >= 400:
return temp
body_store = body_store + temp['body']
if left:
uri = url + flag + 'pageindex=%d&pagesize=%d' % (1+times, NGFW_PAGESIZE)
temp = self._rest_api(method, uri, body, headers, device_ip)
if temp['status'] >= 400:
return temp
body_store = body_store + temp['body']
result['status'] = 200
result['body'] = body_store
else:
result = self._rest_api(method, url, body, headers, device_ip)
return result
#self test command:
#1. modify conf option in the file
#2. python ngfw_api.py get /system/information
if __name__ == '__main__':
if len(sys.argv) < 3:
print({"status": 500, "body": ""})
exit(1)
method = sys.argv[1]
url = sys.argv[2]
if len(sys.argv) > 3:
body = sys.argv[3]
else:
body = None
if len(sys.argv) > 4:
headers = sys.argv[4]
else:
headers = None
if len(sys.argv) > 5:
confile = sys.argv[5]
confile_list_temp = confile.split('**&&**')
confile_list = []
for confile_item in confile_list_temp:
if "" != confile_item:
confile_list.append(confile_item)
cfg.CONF(args=confile_list)
else:
confile = None
ngfwcls = ngfwRestAPI()
if len(sys.argv) > 6:
ip_addr = sys.argv[6]
ngfwcls.server = ip_addr
response = ngfwcls.rest_api_multi(method, url, body, headers)
print {"status":response["status"], "body":response["body"]}
exit(0)
| apache-2.0 |
TeamCohen/SEAL | src/com/rcwang/seal/expand/OfflineSeal.java | 16770 | /**************************************************************************
* Developed by Language Technologies Institute, Carnegie Mellon University
* Written by Richard Wang (rcwang#cs,cmu,edu)
*
* and William Cohen (wcohen@cs.cmu.edu)
*
**************************************************************************/
package com.rcwang.seal.expand;
import java.io.File;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collection;
import java.util.TreeSet;
import java.util.HashSet;
import java.util.Set;
import java.net.URL;
import org.apache.log4j.Logger;
import org.w3c.dom.Element;
import com.rcwang.seal.expand.Wrapper.EntityLiteral;
import com.rcwang.seal.fetch.Document;
import com.rcwang.seal.fetch.DocumentSet;
import com.rcwang.seal.fetch.URLBlackLister;
import com.rcwang.seal.fetch.WebFetcher;
import com.rcwang.seal.fetch.WebManager;
import com.rcwang.seal.fetch.Snippet;
import com.rcwang.seal.fetch.OfflineSearcher;
import com.rcwang.seal.rank.Graph;
import com.rcwang.seal.rank.GraphRanker;
import com.rcwang.seal.rank.PageRanker;
import com.rcwang.seal.rank.Ranker;
import com.rcwang.seal.rank.Ranker.Feature;
import com.rcwang.seal.util.GlobalVar;
import com.rcwang.seal.util.Helper;
import com.rcwang.seal.util.PairedTrie;
import com.rcwang.seal.util.XMLUtil;
/** Like Seal, but uses lucene to search an indexed cache **/
public class OfflineSeal extends Pinniped {
/********************** Parameters **************************/
public static boolean readSerializedDocs = true;
public static boolean writeSerializedDocs = false;
/************************************************************/
public static Logger log = Logger.getLogger(OfflineSeal.class);
public static GlobalVar gv = GlobalVar.getGlobalVar();
public static final String SERIAL_DIR = "cache";
public static final String SERIAL_FILENAME_EXT = ".ser";
private Graph graph;
private Ranker ranker;
private DocumentSet lastDocs;
private WrapperFactory wrapperFactory;
private String extractLangID;
private String fetchLangID;
private double logWrapperLength;
private boolean disableWalk;
private int numLastWrappers;
private int numPastWrappers;
private int numPastDocs;
private int numResults;
private int engine;
public static void main(String args[]) {
long startTime = System.currentTimeMillis();
// parse the command line argument
if (args.length == 0) {
log.error("Incorrect arguments in the command line");
log.info("Usage 1: java " + OfflineSeal.class.getName() + " seed_file [hint_file]");
log.info("Usage 2: java " + OfflineSeal.class.getName() + " seed_1 seed_2 ...");
return;
}
File seedFile = new File(args[0]);
String[] seedArr;
String hint = null;
if (seedFile.exists()) {
seedArr = Helper.readFile(seedFile).split("\n");
if (args.length >= 2) {
File hintFile = Helper.toFileOrDie(args[1]);
hint = Helper.readFile(hintFile).replaceAll("[\r\n]+", " ");
}
} else {
for (int i = 0; i < args.length; i++)
args[i] = args[i].replace('_', ' ');
seedArr = args;
}
EntityList seeds = new EntityList(Arrays.asList(seedArr));
OfflineSeal seal = new OfflineSeal();
seal.expand(seeds, seeds, hint);
// seal.saveResults();
// seal.saveWrappers();
seal.save(); // rolled results and wrappers into SetExpander, kmr 5/11/2012
System.out.println(seal.getEntityList().toDetails(100, seal.getFeature()));
Helper.printMemoryUsed();
Helper.printElapsedTime(startTime);
}
public static DocumentSet fetch(EntityList seeds, String hint, String langID,
int numResults, int engine) {
log.info("Retrieving webpages using " + seeds.size() + " queries: {" + seeds + "}");
if (!Helper.empty(hint))
log.info("\tand a hint: " + hint);
OfflineSearcher offlineSearcher = new OfflineSearcher(gv.getIndexDir(),gv.getLocalRoot());
offlineSearcher.setLangID(langID);
offlineSearcher.setNumResults(gv.getNumResults());
offlineSearcher.setUseEngine(engine);
// this ignores relational separators, since it doesn't call
// the Entity.splitRelation method....
// DocumentSet documents = offlineSearcher.fetchDocuments(seeds.getEntityNames(), hint);
ArrayList<String> seedStrings = new ArrayList<String>();
// add queries into the searcher
for (String[] seed : seeds.getEntityNames()) {
for (String s : seed)
seedStrings.add(s);
}
DocumentSet documents = offlineSearcher.fetchDocuments(seedStrings, hint);
int numUrlsFetched = documents.size();
// output the percentage of URLs fetched
log.info("Number of webpages retrieved from cache: " + numUrlsFetched);
return documents;
}
private static File getSerialFile(EntityList seeds, String hint) {
final int prime = 31;
int result = 1;
result = prime * result + ((seeds == null) ? 0 : seeds.hashCode());
result = prime * result + ((hint == null) ? 0 : hint.hashCode());
String filename = Integer.toString(Math.abs(result)) + SERIAL_FILENAME_EXT;
return new File(SERIAL_DIR, filename);
}
public OfflineSeal() {
super();
wrapperFactory = new WrapperFactory();
loadStopwords(gv.getStopwordsList());
// initialize some parameters
setLangID(gv.getLangID());
setFeature(gv.getFeature());
setEngine(gv.getUseEngine());
setNumResults(gv.getNumResults());
setMinContextLength(gv.getMinContextLength());
setMinSeedsBracketed(gv.getMinSeedsBracketed());
URLBlackLister.setListFile(gv.getUrlBlackList());
}
public OfflineSeal(String langID) {
this();
setLangID(langID);
}
public void addStopword(String stopword, boolean isUnigram) {
wrapperFactory.addStopword(stopword, isUnigram);
}
public void addStopwords(Collection<String> stopwords, boolean isUnigram) {
wrapperFactory.addStopwords(stopwords, isUnigram);
}
/**
* reset for a totally new round of expansion/bootstrapping
*/
public void clear() {
super.clear();
ranker.clear();
lastDocs = null;
}
public boolean expand(EntityList seeds) {
return expand(seeds, seeds, null);
}
public boolean expand(EntityList seeds, DocumentSet documents) {
numLastEntities = 0;
numLastWrappers = 0;
this.lastDocs = documents;
if (seeds == null || seeds.isEmpty()) {
log.error("Error: Need at least one wrapper seed!");
return false;
} else if (documents == null || documents.size() == 0) {
log.error("Error: No webpages provided for set expansion!");
return false;
}
// output expansion information
String className = this.getClass().getSimpleName();
log.info(className + " is bracketing " + PairedTrie.toMinTypeStr(getMinSeedsBracketed()) + " of the " + seeds.size() + " wrapper seeds:");
log.info("{" + seeds + "}");
setStartTime();
// associate wrappers with documents
extract(seeds, documents);
// list quality
log.info("Estimated List Quality: " + Helper.formatNumber(getListQuality(), 3));
// load documents into the ranker
rank(seeds, documents);
entityList.assignScore(getFeature(), hasNoisySeeds());
entityList.scoreByLength(); // break any ties
entityList.sortByScore();
setSeeds(seeds); // must be after rank()
setEndTime();
return true;
}
public boolean expand(EntityList wrapperSeeds, EntityList pageSeeds, String hint) {
return expand(wrapperSeeds, readDocuments(pageSeeds, hint));
}
public int getEngine() {
return engine;
}
public String getExtractLangID() {
return extractLangID;
}
public Feature getFeature() {
return getRanker().getRankerID();
}
public String getFetchLangID() {
return fetchLangID;
}
public Graph getGraph() {
return graph;
}
public DocumentSet getLastDocs() {
return lastDocs;
}
public double getListQuality() {
return logWrapperLength / numPastWrappers;
}
public int getMinContextLength() {
return wrapperFactory.getMinContextLength();
}
public int getMinSeedsBracketed() {
return wrapperFactory.getMinSeedsBracketed();
}
public int getNumLastWrappers() {
return numLastWrappers;
}
public int getNumPastDocs() {
return numPastDocs;
}
public int getNumPastWrappers() {
return numPastWrappers;
}
public int getNumResults() {
return numResults;
}
public Ranker getRanker() {
return ranker;
}
public boolean isDisableWalk() {
return disableWalk;
}
public void loadStopwords(File stopwordsFile) {
wrapperFactory.loadStopwords(stopwordsFile);
}
public void setDisableWalk(boolean disableWalk) {
this.disableWalk = disableWalk;
}
public void setEngine(int useEngine) {
this.engine = useEngine;
}
public void setExtractLangID(String extractLangID) {
this.extractLangID = extractLangID;
}
public void setFeature(Feature feature) {
this.ranker = Ranker.toRanker(feature);
}
public void setFetchLangID(String fetchLangID) {
this.fetchLangID = fetchLangID;
}
public void setLangID(String langID) {
extractLangID = langID;
fetchLangID = langID;
}
public void setMinContextLength(int minContextLength) {
wrapperFactory.setMinContextLength(minContextLength);
}
public void setMinSeedsBracketed(int minSeedsBracketed) {
wrapperFactory.setMinSeedsBracketed(minSeedsBracketed);
}
public void setNumResults(int numResults) {
this.numResults = numResults;
}
public Element toXMLElement() {
return toXMLElement(null);
}
/**
* @return expansion results in XML format
*/
public Element toXMLElement(org.w3c.dom.Document document) {
XMLUtil xml = new XMLUtil(document);
// response node is the top node
Element responseNode = xml.createElement("response", null);
xml.createAttrsFor(responseNode, new Object[]{
"elapsedTimeInMS", getElapsedTime()
});
// setting node
Element settingNode = xml.createElement("setting", null);
Element seedsNode = xml.createElementBelow(settingNode, "seeds", null);
for (Entity seed : lastSeeds)
xml.createElementBelow(seedsNode, "seed", seed.getOriginal());
// xml.createElementBelow(settingNode, "hint", hint == null ? "" : hint);
xml.createElementBelow(settingNode, "extract-language", extractLangID);
xml.createElementBelow(settingNode, "fetch-language", fetchLangID);
responseNode.appendChild(settingNode);
// responseNode.appendChild(pastDocs.toXMLElement(xml.getDocument()));
responseNode.appendChild(entityList.toXMLElement(xml.getDocument()));
if (gv.getWrapperSaving()==1) {
// save the wrappers in this xml node
WrapperSaver wrapperSaver = new WrapperSaver();
responseNode.appendChild(wrapperSaver.toXMLElement(xml.getDocument(),lastDocs,entityList,lastSeeds));
}
return responseNode;
}
private void addSeedsToRanker(EntityList seeds, Ranker ranker) {
if (seeds == null || ranker == null) return;
if (pastSeeds.isEmpty()) {
// no seeds have been given before
if (seeds.containsFeature(getFeature())) {
log.info("Using seed weights from input seeds...");
ranker.addSeeds(seeds, getFeature());
} else {
log.info("Seeds are missing " + getFeature() + " weights, using uniform weights...");
ranker.addUniformSeeds(seeds);
}
} else {
// there are some previously expanded seeds
log.info("Using seed weights from previously expanded entities...");
// constructs a union of current seeds and past seeds
EntityList newSeeds = new EntityList();
newSeeds.addAll(seeds);
newSeeds.addAll(pastSeeds);
// the weights of those seeds come from their corresponding entities in last expansion
ranker.addSeeds(entityList.intersect(newSeeds), getFeature());
}
}
private Set<EntityLiteral> extract(EntityList seeds, DocumentSet documents) {
// configure wrapper factory
wrapperFactory.setSeeds(seeds);
wrapperFactory.setLangID(extractLangID);
wrapperFactory.setFeature(getFeature());
int prevPercent = -1;
Set<EntityLiteral> contents = new HashSet<EntityLiteral>();
for (int i = 0; i < documents.size(); i++) {
Document document = documents.get(i);
// progress bar
int percent = (int) ((double)(i+1)/documents.size()*100);
if (percent != prevPercent) {
log.info("Extracting from " + (i+1) + "/" + documents.size() + " (" + percent + "%) documents...\r");
prevPercent = percent;
}
if (document.isEmpty()) continue;
Set<Wrapper> wrappers = wrapperFactory.build(document);
if (wrappers.isEmpty()) continue;
numLastWrappers += wrappers.size();
numPastWrappers += wrappers.size();
document.addWrappers(wrappers);
for (Wrapper wrapper : wrappers) {
logWrapperLength += wrapper.getNumCommonTypes() * Math.log(wrapper.getContextLength());
contents.addAll(wrapper.getContents());
}
}
numPastDocs += documents.size();
numLastEntities = contents.size();
return contents;
}
/**
* assigns scores to each entity and document based on the scoring method
*/
private boolean rank(EntityList seeds, DocumentSet documents) {
if (ranker == null) {
log.error("Error: Feature is not specified!");
return false;
}
// get the graph (added 12/10/2008)
if (ranker instanceof GraphRanker) {
graph = ((GraphRanker) ranker).getGraph();
if (disableWalk) {
graph.load(documents);
return true;
}
}
// PageRank starts from all nodes with uniform weights, so no need seeds
if (!(ranker instanceof PageRanker))
addSeedsToRanker(seeds, ranker);
log.info("Ranking entities by " + getFeature() + " (" + ranker.getDescription() + ")" +
" and " + ranker.getSeedDist().size() + " seeds...");
ranker.load(entityList, documents);
return true;
}
private DocumentSet readDocuments(EntityList seeds, String hint) {
if (Helper.empty(seeds)) return null;
File serialFile = getSerialFile(seeds, hint);
DocumentSet documents = null;
if (readSerializedDocs && serialFile.exists()) {
// documents exist in cache as serialized object
documents = Helper.loadSerialized(serialFile, lastDocs.getClass());
log.info("Successfully loaded " + documents.size() + " webpages!");
} else {
// download documents from the web
documents = fetch(seeds, hint, fetchLangID, numResults, engine);
if (writeSerializedDocs)
Helper.saveSerialized(documents, serialFile, true);
}
return documents;
}
}
| apache-2.0 |
andrewtytula/log-viewer | src/main/java/com/kajj/tools/logviewer/LogViewerRestController.java | 2875 | /*
* Copyright 2014 Andrew Tytula.
*
* 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.kajj.tools.logviewer;
import java.io.IOException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.ResourceAccessException;
/**
* Presentation layer for the log viewer.
*
* @author Andrew Tytula
*/
@RestController
public class LogViewerRestController
{
@Autowired
private LogRepository logRepository;
/**
* Returns the last <code>numberOfLines</code> from the specified log file. The log file must
* be in the containers log directory to be read.
*
* @param fileName the name of the log file.
* @param numberOfLines the number of lines to return in the tail.
* @return The last <code>numberOfLines</code> of the specified log file.
*/
@RequestMapping(value = "/logs/{fileName}/tail", method = RequestMethod.GET,
produces = MediaType.TEXT_PLAIN_VALUE)
public ResponseEntity<String> tailLog(@PathVariable final String fileName,
@RequestParam(value = "lines", defaultValue = "100") final int numberOfLines)
{
try
{
final List<String> logs = logRepository.getTailLog(fileName, numberOfLines);
final StringBuilder tail = new StringBuilder();
int i = 1;
for(final String log : logs)
{
tail.append(i++).append(": ").append(log).append("\n");
}
return new ResponseEntity(tail.toString(), HttpStatus.OK);
}
catch(final IOException ioe)
{
throw new ResourceAccessException("Unable to read log file", ioe);
}
}
@RequestMapping(value = "/logs", method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<String>> getlogFileNames()
{
final List<String> logFileNames = logRepository.getLogFileNames();
return new ResponseEntity(logFileNames, HttpStatus.OK);
}
}
| apache-2.0 |
OpenVidu/openvidu | openvidu-server/src/main/java/io/openvidu/server/config/HttpHandshakeInterceptor.java | 1961 | /*
* (C) Copyright 2017-2020 OpenVidu (https://openvidu.io)
*
* 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 io.openvidu.server.config;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;
public class HttpHandshakeInterceptor implements HandshakeInterceptor {
private static final Logger log = LoggerFactory.getLogger(HttpHandshakeInterceptor.class);
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
Map<String, Object> attributes) throws Exception {
if (request instanceof ServletServerHttpRequest) {
HttpSession session = ((ServletServerHttpRequest) request).getServletRequest().getSession();
session.setMaxInactiveInterval(1800); // HttpSession will expire in 30 minutes
attributes.put("httpSession", session);
log.info("{} HttpSession {}", session.isNew() ? "New" : "Old", session.getId());
}
return true;
}
@Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
Exception ex) {
}
} | apache-2.0 |
rdblue/incubator-nifi | nar-bundles/framework-bundle/framework/core/src/main/java/org/apache/nifi/controller/repository/RingBufferEventRepository.java | 12328 | /*
* 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.nifi.controller.repository;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicReference;
public class RingBufferEventRepository implements FlowFileEventRepository {
private final int numMinutes;
private final ConcurrentMap<String, EventContainer> componentEventMap = new ConcurrentHashMap<>();
public RingBufferEventRepository(final int numMinutes) {
this.numMinutes = numMinutes;
}
@Override
public void close() throws IOException {
}
@Override
public void updateRepository(final FlowFileEvent event) {
final String componentId = event.getComponentIdentifier();
EventContainer eventContainer = componentEventMap.get(componentId);
if (eventContainer == null) {
eventContainer = new SecondPrecisionEventContainer(numMinutes);
final EventContainer oldEventContainer = componentEventMap.putIfAbsent(componentId, eventContainer);
if (oldEventContainer != null) {
eventContainer = oldEventContainer;
}
}
eventContainer.addEvent(event);
}
@Override
public StandardRepositoryStatusReport reportTransferEvents(final long sinceEpochMillis) {
final StandardRepositoryStatusReport report = new StandardRepositoryStatusReport();
for (final Map.Entry<String, EventContainer> entry : componentEventMap.entrySet()) {
final String consumerId = entry.getKey();
final EventContainer container = entry.getValue();
final FlowFileEvent reportEntry = container.generateReport(consumerId, sinceEpochMillis);
report.addReportEntry(reportEntry);
}
return report;
}
@Override
public void purgeTransferEvents(final long cutoffEpochMilliseconds) {
// This is done so that if a processor is removed from the graph, its events
// will be removed rather than being kept in memory
for (final EventContainer container : componentEventMap.values()) {
container.purgeEvents(cutoffEpochMilliseconds);
}
}
private static interface EventContainer {
public void addEvent(FlowFileEvent event);
public void purgeEvents(long cutoffEpochMillis);
public FlowFileEvent generateReport(String consumerId, long sinceEpochMillis);
}
private class EventSum {
private final AtomicReference<EventSumValue> ref = new AtomicReference<>(new EventSumValue());
private void add(final FlowFileEvent event) {
EventSumValue newValue;
EventSumValue value;
do {
value = ref.get();
newValue = new EventSumValue(value,
event.getFlowFilesIn(), event.getFlowFilesOut(), event.getFlowFilesRemoved(),
event.getContentSizeIn(), event.getContentSizeOut(), event.getContentSizeRemoved(),
event.getBytesRead(), event.getBytesWritten(),
event.getFlowFilesReceived(), event.getBytesReceived(),
event.getFlowFilesSent(), event.getBytesSent(),
event.getProcessingNanoseconds(), event.getInvocations(), event.getAggregateLineageMillis());
} while (!ref.compareAndSet(value, newValue));
}
public EventSumValue getValue() {
return ref.get();
}
public void addOrReset(final FlowFileEvent event) {
final long expectedMinute = System.currentTimeMillis() / 60000;
final EventSumValue curValue = ref.get();
if (curValue.getMinuteTimestamp() != expectedMinute) {
ref.compareAndSet(curValue, new EventSumValue());
}
add(event);
}
}
private static class EventSumValue {
private final int flowFilesIn, flowFilesOut, flowFilesRemoved;
private final long contentSizeIn, contentSizeOut, contentSizeRemoved;
private final long bytesRead, bytesWritten;
private final int flowFilesReceived, flowFilesSent;
private final long bytesReceived, bytesSent;
private final long processingNanos;
private final long aggregateLineageMillis;
private final int invocations;
private final long minuteTimestamp;
private final long millisecondTimestamp;
public EventSumValue() {
flowFilesIn = flowFilesOut = flowFilesRemoved = 0;
contentSizeIn = contentSizeOut = contentSizeRemoved = 0;
bytesRead = bytesWritten = 0;
flowFilesReceived = flowFilesSent = 0;
bytesReceived = bytesSent = 0L;
processingNanos = invocations = 0;
aggregateLineageMillis = 0L;
this.millisecondTimestamp = System.currentTimeMillis();
this.minuteTimestamp = millisecondTimestamp / 60000;
}
public EventSumValue(final EventSumValue base, final int flowFilesIn, final int flowFilesOut, final int flowFilesRemoved,
final long contentSizeIn, final long contentSizeOut, final long contentSizeRemoved,
final long bytesRead, final long bytesWritten,
final int flowFilesReceived, final long bytesReceived,
final int flowFilesSent, final long bytesSent,
final long processingNanos, final int invocations, final long aggregateLineageMillis) {
this.flowFilesIn = base.flowFilesIn + flowFilesIn;
this.flowFilesOut = base.flowFilesOut + flowFilesOut;
this.flowFilesRemoved = base.flowFilesRemoved + flowFilesRemoved;
this.contentSizeIn = base.contentSizeIn + contentSizeIn;
this.contentSizeOut = base.contentSizeOut + contentSizeOut;
this.contentSizeRemoved = base.contentSizeRemoved + contentSizeRemoved;
this.bytesRead = base.bytesRead + bytesRead;
this.bytesWritten = base.bytesWritten + bytesWritten;
this.flowFilesReceived = base.flowFilesReceived + flowFilesReceived;
this.bytesReceived = base.bytesReceived + bytesReceived;
this.flowFilesSent = base.flowFilesSent + flowFilesSent;
this.bytesSent = base.bytesSent + bytesSent;
this.processingNanos = base.processingNanos + processingNanos;
this.invocations = base.invocations + invocations;
this.aggregateLineageMillis = base.aggregateLineageMillis + aggregateLineageMillis;
this.millisecondTimestamp = System.currentTimeMillis();
this.minuteTimestamp = millisecondTimestamp / 60000;
}
public long getTimestamp() {
return millisecondTimestamp;
}
public long getMinuteTimestamp() {
return minuteTimestamp;
}
public long getBytesRead() {
return bytesRead;
}
public long getBytesWritten() {
return bytesWritten;
}
public int getFlowFilesIn() {
return flowFilesIn;
}
public int getFlowFilesOut() {
return flowFilesOut;
}
public long getContentSizeIn() {
return contentSizeIn;
}
public long getContentSizeOut() {
return contentSizeOut;
}
public int getFlowFilesRemoved() {
return flowFilesRemoved;
}
public long getContentSizeRemoved() {
return contentSizeRemoved;
}
public long getProcessingNanoseconds() {
return processingNanos;
}
public int getInvocations() {
return invocations;
}
public long getAggregateLineageMillis() {
return aggregateLineageMillis;
}
public int getFlowFilesReceived() {
return flowFilesReceived;
}
public int getFlowFilesSent() {
return flowFilesSent;
}
public long getBytesReceived() {
return bytesReceived;
}
public long getBytesSent() {
return bytesSent;
}
}
private class SecondPrecisionEventContainer implements EventContainer {
private final int numBins;
private final EventSum[] sums;
public SecondPrecisionEventContainer(final int numMinutes) {
numBins = 1 + numMinutes * 60;
sums = new EventSum[numBins];
for (int i = 0; i < numBins; i++) {
sums[i] = new EventSum();
}
}
@Override
public void addEvent(final FlowFileEvent event) {
final int second = (int) (System.currentTimeMillis() / 1000);
final int binIdx = (int) (second % numBins);
final EventSum sum = sums[binIdx];
sum.addOrReset(event);
}
@Override
public void purgeEvents(final long cutoffEpochMilliseconds) {
// no need to do anything
}
@Override
public FlowFileEvent generateReport(final String consumerId, final long sinceEpochMillis) {
int flowFilesIn = 0, flowFilesOut = 0, flowFilesRemoved = 0;
long contentSizeIn = 0L, contentSizeOut = 0L, contentSizeRemoved = 0L;
long bytesRead = 0L, bytesWritten = 0L;
int invocations = 0;
long processingNanos = 0L;
long aggregateLineageMillis = 0L;
int flowFilesReceived = 0, flowFilesSent = 0;
long bytesReceived = 0L, bytesSent = 0L;
final long second = sinceEpochMillis / 1000;
final int startBinIdx = (int) (second % numBins);
for (int i = 0; i < numBins; i++) {
int binIdx = (startBinIdx + i) % numBins;
final EventSum sum = sums[binIdx];
final EventSumValue sumValue = sum.getValue();
if (sumValue.getTimestamp() >= sinceEpochMillis) {
flowFilesIn += sumValue.getFlowFilesIn();
flowFilesOut += sumValue.getFlowFilesOut();
flowFilesRemoved += sumValue.getFlowFilesRemoved();
contentSizeIn += sumValue.getContentSizeIn();
contentSizeOut += sumValue.getContentSizeOut();
contentSizeRemoved += sumValue.getContentSizeRemoved();
bytesRead += sumValue.getBytesRead();
bytesWritten += sumValue.getBytesWritten();
flowFilesReceived += sumValue.getFlowFilesReceived();
bytesReceived += sumValue.getBytesReceived();
flowFilesSent += sumValue.getFlowFilesSent();
bytesSent += sumValue.getBytesSent();
invocations += sumValue.getInvocations();
processingNanos += sumValue.getProcessingNanoseconds();
aggregateLineageMillis += sumValue.getAggregateLineageMillis();
}
}
return new StandardFlowFileEvent(consumerId, flowFilesIn, contentSizeIn,
flowFilesOut, contentSizeOut, flowFilesRemoved, contentSizeRemoved,
bytesRead, bytesWritten, flowFilesReceived, bytesReceived, flowFilesSent, bytesSent,
invocations, aggregateLineageMillis, processingNanos);
}
}
}
| apache-2.0 |
jdcasey/pnc | causeway-client/src/main/java/org/jboss/pnc/causewayclient/remotespi/CallbackMethod.java | 873 | /**
* JBoss, Home of Professional Open Source.
* Copyright 2014-2018 Red Hat, Inc., and individual 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.jboss.pnc.causewayclient.remotespi;
/**
*
* @author Honza Brázdil <jbrazdil@redhat.com>
*/
public enum CallbackMethod {
POST,
PUT;
}
| apache-2.0 |
opensingular/singular-core | form/wicket/src/test/java/org/opensingular/form/wicket/SValidationFeedbackHandlerTest.java | 1584 | /*
*
* * Copyright (C) 2016 Singular Studios (a.k.a Atom Tecnologia) - www.opensingular.com
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package org.opensingular.form.wicket;
import static org.assertj.core.api.Assertions.*;
import java.util.Map;
import org.junit.Test;
import org.opensingular.form.SInstance;
import org.opensingular.form.wicket.feedback.FeedbackFence;
import org.opensingular.form.wicket.helpers.SingularFormDummyPageTester;
public class SValidationFeedbackHandlerTest {
@Test
public void testBasic() {
SingularFormDummyPageTester tester = new SingularFormDummyPageTester();
tester.getDummyPage().setTypeBuilder(tb->tb.addFieldString("string"));
tester.getDummyPage().setAsEditView();
tester.startDummyPage();
Map<String, SInstance> lowerBound = SValidationFeedbackHandler.collectLowerBoundInstances(
new FeedbackFence(tester.getDummyPage().getSingularFormPanel().getParent()));
assertThat(lowerBound.isEmpty()).isFalse();
}
}
| apache-2.0 |
oehme/analysing-gradle-performance | my-app/src/main/java/org/gradle/test/performance/mediummonolithicjavaproject/p148/Production2975.java | 1891 | package org.gradle.test.performance.mediummonolithicjavaproject.p148;
public class Production2975 {
private String property0;
public String getProperty0() {
return property0;
}
public void setProperty0(String value) {
property0 = value;
}
private String property1;
public String getProperty1() {
return property1;
}
public void setProperty1(String value) {
property1 = value;
}
private String property2;
public String getProperty2() {
return property2;
}
public void setProperty2(String value) {
property2 = value;
}
private String property3;
public String getProperty3() {
return property3;
}
public void setProperty3(String value) {
property3 = value;
}
private String property4;
public String getProperty4() {
return property4;
}
public void setProperty4(String value) {
property4 = value;
}
private String property5;
public String getProperty5() {
return property5;
}
public void setProperty5(String value) {
property5 = value;
}
private String property6;
public String getProperty6() {
return property6;
}
public void setProperty6(String value) {
property6 = value;
}
private String property7;
public String getProperty7() {
return property7;
}
public void setProperty7(String value) {
property7 = value;
}
private String property8;
public String getProperty8() {
return property8;
}
public void setProperty8(String value) {
property8 = value;
}
private String property9;
public String getProperty9() {
return property9;
}
public void setProperty9(String value) {
property9 = value;
}
} | apache-2.0 |
brentdavid2008/stripe.net | src/Stripe/Entities/StripeTransferSchedule.cs | 474 | using System.Collections.Generic;
using Newtonsoft.Json;
namespace Stripe
{
public class StripeTransferSchedule
{
[JsonProperty("delay_days")]
public int DelayDays { get; set; }
[JsonProperty("interval")]
public string Interval { get; set; }
[JsonProperty("monthly_anchor")]
public int MonthlyAnchor { get; set; }
[JsonProperty("weekly_anchor")]
public string WeeklyAnchor { get; set; }
}
}
| apache-2.0 |
quocngo2cs/Rhetos.RestGenerator.WebAPI | Rhetos.RestGenerator/Rhetos.RestGenerator/Utilities/RecordsAndTotalCountResult.cs | 286 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Rhetos.WebApiRestGenerator.Utilities
{
public class RecordsAndTotalCountResult<T>
{
public T[] Records { get; set; }
public int TotalCount { get; set; }
}
}
| apache-2.0 |
YihaoLu/pyfolio | pyfolio/timeseries.py | 40495 | #
# Copyright 2015 Quantopian, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import division
from collections import OrderedDict
from functools import partial
import pandas as pd
import numpy as np
import scipy as sp
import scipy.stats as stats
from sklearn import preprocessing
import statsmodels.api as sm
from . import utils
from .utils import APPROX_BDAYS_PER_MONTH, APPROX_BDAYS_PER_YEAR
from .utils import DAILY, WEEKLY, MONTHLY, YEARLY, ANNUALIZATION_FACTORS
from .interesting_periods import PERIODS
def var_cov_var_normal(P, c, mu=0, sigma=1):
"""Variance-covariance calculation of daily Value-at-Risk in a
portfolio.
Parameters
----------
P : float
Portfolio value.
c : float
Confidence level.
mu : float, optional
Mean.
Returns
-------
float
Variance-covariance.
"""
alpha = sp.stats.norm.ppf(1 - c, mu, sigma)
return P - P * (alpha + 1)
def normalize(returns, starting_value=1):
"""
Normalizes a returns timeseries based on the first value.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
starting_value : float, optional
The starting returns (default 1).
Returns
-------
pd.Series
Normalized returns.
"""
return starting_value * (returns / returns.iloc[0])
def cum_returns(returns, starting_value=None):
"""
Compute cumulative returns from simple returns.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
starting_value : float, optional
The starting returns (default 1).
Returns
-------
pandas.Series
Series of cumulative returns.
Notes
-----
For increased numerical accuracy, convert input to log returns
where it is possible to sum instead of multiplying.
"""
# df_price.pct_change() adds a nan in first position, we can use
# that to have cum_returns start at the origin so that
# df_cum.iloc[0] == starting_value
# Note that we can't add that ourselves as we don't know which dt
# to use.
if pd.isnull(returns.iloc[0]):
returns.iloc[0] = 0.
df_cum = np.exp(np.log(1 + returns).cumsum())
if starting_value is None:
return df_cum - 1
else:
return df_cum * starting_value
def aggregate_returns(df_daily_rets, convert_to):
"""
Aggregates returns by week, month, or year.
Parameters
----------
df_daily_rets : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet (returns).
convert_to : str
Can be 'weekly', 'monthly', or 'yearly'.
Returns
-------
pd.Series
Aggregated returns.
"""
def cumulate_returns(x):
return cum_returns(x)[-1]
if convert_to == WEEKLY:
return df_daily_rets.groupby(
[lambda x: x.year,
lambda x: x.month,
lambda x: x.isocalendar()[1]]).apply(cumulate_returns)
elif convert_to == MONTHLY:
return df_daily_rets.groupby(
[lambda x: x.year, lambda x: x.month]).apply(cumulate_returns)
elif convert_to == YEARLY:
return df_daily_rets.groupby(
[lambda x: x.year]).apply(cumulate_returns)
else:
ValueError(
'convert_to must be {}, {} or {}'.format(WEEKLY, MONTHLY, YEARLY)
)
def max_drawdown(returns):
"""
Determines the maximum drawdown of a strategy.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
Returns
-------
float
Maximum drawdown.
Note
-----
See https://en.wikipedia.org/wiki/Drawdown_(economics) for more details.
"""
if returns.size < 1:
return np.nan
df_cum_rets = cum_returns(returns, starting_value=100)
MDD = 0
DD = 0
peak = -99999
for value in df_cum_rets:
if (value > peak):
peak = value
else:
DD = (peak - value) / peak
if (DD > MDD):
MDD = DD
return -1 * MDD
def annual_return(returns, style='compound', period=DAILY):
"""Determines the annual returns of a strategy.
Parameters
----------
returns : pd.Series
Periodic returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
style : str, optional
- If 'compound', then return will be calculated in geometric
terms: (1+mean(all_daily_returns))^252 - 1.
- If 'calendar', then return will be calculated as
((last_value - start_value)/start_value)/num_of_years.
- Otherwise, return is simply mean(all_daily_returns)*252.
period : str, optional
- defines the periodicity of the 'returns' data for purposes of
annualizing. Can be 'monthly', 'weekly', or 'daily'
- defaults to 'daily'.
Returns
-------
float
Annual returns.
"""
if returns.size < 1:
return np.nan
try:
ann_factor = ANNUALIZATION_FACTORS[period]
except KeyError:
raise ValueError(
"period cannot be '{}'. "
"Must be '{}', '{}', or '{}'".format(
period, DAILY, WEEKLY, MONTHLY
)
)
if style == 'calendar':
num_years = len(returns) / ann_factor
df_cum_rets = cum_returns(returns, starting_value=100)
start_value = df_cum_rets[0]
end_value = df_cum_rets[-1]
return ((end_value - start_value) / start_value) / num_years
if style == 'compound':
return pow((1 + returns.mean()), ann_factor) - 1
else:
return returns.mean() * ann_factor
def annual_volatility(returns, period=DAILY):
"""
Determines the annual volatility of a strategy.
Parameters
----------
returns : pd.Series
Periodic returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
period : str, optional
- defines the periodicity of the 'returns' data for purposes of
annualizing volatility. Can be 'monthly' or 'weekly' or 'daily'.
- defaults to 'daily'
Returns
-------
float
Annual volatility.
"""
if returns.size < 2:
return np.nan
try:
ann_factor = ANNUALIZATION_FACTORS[period]
except KeyError:
raise ValueError(
"period cannot be: '{}'."
" Must be '{}', '{}', or '{}'".format(
period, DAILY, WEEKLY, MONTHLY
)
)
return returns.std() * np.sqrt(ann_factor)
def calmar_ratio(returns, returns_style='calendar', period=DAILY):
"""
Determines the Calmar ratio, or drawdown ratio, of a strategy.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
returns_style : str, optional
See annual_returns' style
period : str, optional
- defines the periodicity of the 'returns' data for purposes of
annualizing. Can be 'monthly', 'weekly', or 'daily'
- defaults to 'daily'.
Returns
-------
float
Calmar ratio (drawdown ratio).
Note
-----
See https://en.wikipedia.org/wiki/Calmar_ratio for more details.
"""
temp_max_dd = max_drawdown(returns=returns)
if temp_max_dd < 0:
temp = annual_return(
returns=returns,
style=returns_style,
period=period
) / abs(max_drawdown(returns=returns))
else:
return np.nan
if np.isinf(temp):
return np.nan
return temp
def omega_ratio(returns, annual_return_threshhold=0.0):
"""Determines the Omega ratio of a strategy.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
annual_return_threshold : float, optional
Threshold over which to consider positive vs negative
returns. For the ratio, it will be converted to a daily return
and compared to returns.
Returns
-------
float
Omega ratio.
Note
-----
See https://en.wikipedia.org/wiki/Omega_ratio for more details.
"""
daily_return_thresh = pow(1 + annual_return_threshhold, 1 /
APPROX_BDAYS_PER_YEAR) - 1
returns_less_thresh = returns - daily_return_thresh
numer = sum(returns_less_thresh[returns_less_thresh > 0.0])
denom = -1.0 * sum(returns_less_thresh[returns_less_thresh < 0.0])
if denom > 0.0:
return numer / denom
else:
return np.nan
def sortino_ratio(returns, required_return=0, period=DAILY):
"""
Determines the Sortino ratio of a strategy.
Parameters
----------
returns : pd.Series or pd.DataFrame
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
returns_style : str, optional
See annual_returns' style
required_return: float / series
minimum acceptable return
period : str, optional
- defines the periodicity of the 'returns' data for purposes of
annualizing. Can be 'monthly', 'weekly', or 'daily'
- defaults to 'daily'.
Returns
-------
depends on input type
series ==> float
DataFrame ==> np.array
Annualized Sortino ratio.
"""
try:
ann_factor = ANNUALIZATION_FACTORS[period]
except KeyError:
raise ValueError(
"period cannot be: '{}'."
" Must be '{}', '{}', or '{}'".format(
period, DAILY, WEEKLY, MONTHLY
)
)
mu = np.nanmean(returns - required_return, axis=0)
sortino = mu / downside_risk(returns, required_return)
if len(returns.shape) == 2:
sortino = pd.Series(sortino, index=returns.columns)
return sortino * ann_factor
def downside_risk(returns, required_return=0, period=DAILY):
"""
Determines the downside deviation below a threshold
Parameters
----------
returns : pd.Series or pd.DataFrame
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
required_return: float / series
minimum acceptable return
period : str, optional
- defines the periodicity of the 'returns' data for purposes of
annualizing. Can be 'monthly', 'weekly', or 'daily'
- defaults to 'daily'.
Returns
-------
depends on input type
series ==> float
DataFrame ==> np.array
Annualized downside deviation
"""
try:
ann_factor = ANNUALIZATION_FACTORS[period]
except KeyError:
raise ValueError(
"period cannot be: '{}'."
" Must be '{}', '{}', or '{}'".format(
period, DAILY, WEEKLY, MONTHLY
)
)
downside_diff = returns - required_return
mask = downside_diff > 0
downside_diff[mask] = 0.0
squares = np.square(downside_diff)
mean_squares = np.nanmean(squares, axis=0)
dside_risk = np.sqrt(mean_squares) * np.sqrt(ann_factor)
if len(returns.shape) == 2:
dside_risk = pd.Series(dside_risk, index=returns.columns)
return dside_risk
def sharpe_ratio(returns, returns_style='compound', period=DAILY):
"""
Determines the Sharpe ratio of a strategy.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
returns_style : str, optional
See annual_returns' style
period : str, optional
- defines the periodicity of the 'returns' data for purposes of
annualizing. Can be 'monthly', 'weekly', or 'daily'
- defaults to 'daily'.
Returns
-------
float
Sharpe ratio.
Note
-----
See https://en.wikipedia.org/wiki/Sharpe_ratio for more details.
"""
numer = annual_return(returns, style=returns_style, period=period)
denom = annual_volatility(returns, period=period)
if denom > 0.0:
return numer / denom
else:
return np.nan
def stability_of_timeseries(returns):
"""Determines R-squared of a linear fit to the returns.
Computes an ordinary least squares linear fit, and returns
R-squared.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
Returns
-------
float
R-squared.
"""
if returns.size < 2:
return np.nan
df_cum_rets = cum_returns(returns, starting_value=100)
df_cum_rets_log = np.log10(df_cum_rets.values)
len_returns = df_cum_rets.size
X = list(range(0, len_returns))
X = sm.add_constant(X)
model = sm.OLS(df_cum_rets_log, X).fit()
return model.rsquared
def out_of_sample_vs_in_sample_returns_kde(
bt_ts, oos_ts, transform_style='scale', return_zero_if_exception=True):
"""Determines similarity between two returns timeseries.
Typically a backtest frame (in-sample) and live frame
(out-of-sample).
Parameters
----------
bt_ts : pd.Series
In-sample (backtest) returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet (returns).
oos_ts : pd.Series
Out-of-sample (live trading) returns of the strategy,
noncumulative.
- See full explanation in tears.create_full_tear_sheet (returns).
transform_style : float, optional
'raw', 'scale', 'Normalize_L1', 'Normalize_L2' (default
'scale')
return_zero_if_exception : bool, optional
If there is an exception, return zero instead of NaN.
Returns
-------
float
Similarity between returns.
"""
bt_ts_pct = bt_ts.dropna()
oos_ts_pct = oos_ts.dropna()
bt_ts_r = bt_ts_pct.reshape(len(bt_ts_pct), 1)
oos_ts_r = oos_ts_pct.reshape(len(oos_ts_pct), 1)
if transform_style == 'raw':
bt_scaled = bt_ts_r
oos_scaled = oos_ts_r
if transform_style == 'scale':
bt_scaled = preprocessing.scale(bt_ts_r, axis=0)
oos_scaled = preprocessing.scale(oos_ts_r, axis=0)
if transform_style == 'normalize_L2':
bt_scaled = preprocessing.normalize(bt_ts_r, axis=1)
oos_scaled = preprocessing.normalize(oos_ts_r, axis=1)
if transform_style == 'normalize_L1':
bt_scaled = preprocessing.normalize(bt_ts_r, axis=1, norm='l1')
oos_scaled = preprocessing.normalize(oos_ts_r, axis=1, norm='l1')
X_train = bt_scaled
X_test = oos_scaled
X_train = X_train.reshape(len(X_train))
X_test = X_test.reshape(len(X_test))
x_axis_dim = np.linspace(-4, 4, 100)
kernal_method = 'scott'
try:
scipy_kde_train = stats.gaussian_kde(
X_train,
bw_method=kernal_method)(x_axis_dim)
scipy_kde_test = stats.gaussian_kde(
X_test,
bw_method=kernal_method)(x_axis_dim)
except:
if return_zero_if_exception:
return 0.0
else:
return np.nan
kde_diff = sum(abs(scipy_kde_test - scipy_kde_train)) / \
(sum(scipy_kde_train) + sum(scipy_kde_test))
return kde_diff
def calc_multifactor(returns, factors):
"""Computes multiple ordinary least squares linear fits, and returns
fit parameters.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
factors : pd.Series
Secondary sets to fit.
Returns
-------
pd.DataFrame
Fit parameters.
"""
import statsmodels.api as sm
factors = factors.loc[returns.index]
factors = sm.add_constant(factors)
factors = factors.dropna(axis=0)
results = sm.OLS(returns[factors.index], factors).fit()
return results.params
def rolling_beta(returns, factor_returns,
rolling_window=APPROX_BDAYS_PER_MONTH * 6):
"""Determines the rolling beta of a strategy.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
factor_returns : pd.Series or pd.DataFrame
Daily noncumulative returns of the benchmark.
- This is in the same style as returns.
If DataFrame is passed, computes rolling beta for each column.
rolling_window : int, optional
The size of the rolling window, in days, over which to compute
beta (default 6 months).
Returns
-------
pd.Series
Rolling beta.
Note
-----
See https://en.wikipedia.org/wiki/Beta_(finance) for more details.
"""
if factor_returns.ndim > 1:
# Apply column-wise
return factor_returns.apply(partial(rolling_beta, returns),
rolling_window=rolling_window)
else:
out = pd.Series(index=returns.index)
for beg, end in zip(returns.index[0:-rolling_window],
returns.index[rolling_window:]):
out.loc[end] = calc_alpha_beta(
returns.loc[beg:end],
factor_returns.loc[beg:end])[1]
return out
def rolling_fama_french(returns, factor_returns=None,
rolling_window=APPROX_BDAYS_PER_MONTH * 6):
"""Computes rolling Fama-French single factor betas.
Specifically, returns SMB, HML, and UMD.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
factor_returns : pd.DataFrame, optional
data set containing the Fama-French risk factors. See
utils.load_portfolio_risk_factors.
rolling_window : int, optional
The days window over which to compute the beta.
Default is 6 months.
Returns
-------
pandas.DataFrame
DataFrame containing rolling beta coefficients for SMB, HML
and UMD
"""
if factor_returns is None:
factor_returns = utils.load_portfolio_risk_factors(
start=returns.index[0], end=returns.index[-1])
factor_returns = factor_returns.drop(['Mkt-RF', 'RF'],
axis='columns')
return rolling_beta(returns, factor_returns,
rolling_window=rolling_window)
def calc_alpha_beta(returns, factor_returns):
"""Calculates both alpha and beta.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
factor_returns : pd.Series
Daily noncumulative returns of the factor to which beta is
computed. Usually a benchmark such as the market.
- This is in the same style as returns.
Returns
-------
float
Alpha.
float
Beta.
"""
ret_index = returns.index
beta, alpha = sp.stats.linregress(factor_returns.loc[ret_index].values,
returns.values)[:2]
return alpha * APPROX_BDAYS_PER_YEAR, beta
def perf_stats(
returns,
returns_style='compound',
return_as_dict=False,
period=DAILY):
"""Calculates various performance metrics of a strategy, for use in
plotting.show_perf_stats.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
returns_style : str, optional
See annual_returns' style
return_as_dict : boolean, optional
If True, returns the computed metrics in a dictionary.
period : str, optional
- defines the periodicity of the 'returns' data for purposes of
annualizing. Can be 'monthly', 'weekly', or 'daily'
- defaults to 'daily'.
Returns
-------
dict / pd.DataFrame
Performance metrics.
"""
all_stats = OrderedDict()
all_stats['annual_return'] = annual_return(
returns,
style=returns_style, period=period)
all_stats['annual_volatility'] = annual_volatility(returns, period=period)
all_stats['sharpe_ratio'] = sharpe_ratio(
returns,
returns_style=returns_style, period=period)
all_stats['calmar_ratio'] = calmar_ratio(
returns,
returns_style=returns_style, period=period)
all_stats['stability'] = stability_of_timeseries(returns)
all_stats['max_drawdown'] = max_drawdown(returns)
all_stats['omega_ratio'] = omega_ratio(returns)
all_stats['sortino_ratio'] = sortino_ratio(returns)
all_stats['skewness'] = stats.skew(returns)
all_stats['kurtosis'] = stats.kurtosis(returns)
if return_as_dict:
return all_stats
else:
all_stats_df = pd.DataFrame(
index=list(all_stats.keys()),
data=list(all_stats.values()))
all_stats_df.columns = ['perf_stats']
return all_stats_df
def get_max_drawdown_underwater(underwater):
"""Determines peak, valley, and recovery dates given and 'underwater'
DataFrame.
An underwater DataFrame is a DataFrame that has precomputed
rolling drawdown.
Parameters
----------
underwater : pd.Series
Underwater returns (rolling drawdown) of a strategy.
Returns
-------
peak : datetime
The maximum drawdown's peak.
valley : datetime
The maximum drawdown's valley.
recovery : datetime
The maximum drawdown's recovery.
"""
valley = np.argmax(underwater) # end of the period
# Find first 0
peak = underwater[:valley][underwater[:valley] == 0].index[-1]
# Find last 0
try:
recovery = underwater[valley:][underwater[valley:] == 0].index[0]
except IndexError:
recovery = np.nan # drawdown not recovered
return peak, valley, recovery
def get_max_drawdown(returns):
"""
Finds maximum drawdown.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
Returns
-------
peak : datetime
The maximum drawdown's peak.
valley : datetime
The maximum drawdown's valley.
recovery : datetime
The maximum drawdown's recovery.
Note
-----
See https://en.wikipedia.org/wiki/Drawdown_(economics) for more details.
"""
returns = returns.copy()
df_cum = cum_returns(returns, 1.0)
running_max = np.maximum.accumulate(df_cum)
underwater = (running_max - df_cum) / running_max
return get_max_drawdown_underwater(underwater)
def get_top_drawdowns(returns, top=10):
"""
Finds top drawdowns, sorted by drawdown amount.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
top : int, optional
The amount of top drawdowns to find (default 10).
Returns
-------
drawdowns : list
List of drawdown peaks, valleys, and recoveries. See get_max_drawdown.
"""
returns = returns.copy()
df_cum = cum_returns(returns, 1.0)
running_max = np.maximum.accumulate(df_cum)
underwater = running_max - df_cum
drawdowns = []
for t in range(top):
peak, valley, recovery = get_max_drawdown_underwater(underwater)
# Slice out draw-down period
if not pd.isnull(recovery):
underwater.drop(underwater[peak: recovery].index[1:-1],
inplace=True)
else:
# drawdown has not ended yet
underwater = underwater.loc[:peak]
drawdowns.append((peak, valley, recovery))
if (len(returns) == 0) or (len(underwater) == 0):
break
return drawdowns
def gen_drawdown_table(returns, top=10):
"""
Places top drawdowns in a table.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
top : int, optional
The amount of top drawdowns to find (default 10).
Returns
-------
df_drawdowns : pd.DataFrame
Information about top drawdowns.
"""
df_cum = cum_returns(returns, 1.0)
drawdown_periods = get_top_drawdowns(returns, top=top)
df_drawdowns = pd.DataFrame(index=list(range(top)),
columns=['net drawdown in %',
'peak date',
'valley date',
'recovery date',
'duration'])
for i, (peak, valley, recovery) in enumerate(drawdown_periods):
if pd.isnull(recovery):
df_drawdowns.loc[i, 'duration'] = np.nan
else:
df_drawdowns.loc[i, 'duration'] = len(pd.date_range(peak,
recovery,
freq='B'))
df_drawdowns.loc[i, 'peak date'] = (peak.to_pydatetime()
.strftime('%Y-%m-%d'))
df_drawdowns.loc[i, 'valley date'] = (valley.to_pydatetime()
.strftime('%Y-%m-%d'))
if isinstance(recovery, float):
df_drawdowns.loc[i, 'recovery date'] = recovery
else:
df_drawdowns.loc[i, 'recovery date'] = (recovery.to_pydatetime()
.strftime('%Y-%m-%d'))
df_drawdowns.loc[i, 'net drawdown in %'] = (
(df_cum.loc[peak] - df_cum.loc[valley]) / df_cum.loc[peak]) * 100
df_drawdowns['peak date'] = pd.to_datetime(
df_drawdowns['peak date'],
unit='D')
df_drawdowns['valley date'] = pd.to_datetime(
df_drawdowns['valley date'],
unit='D')
df_drawdowns['recovery date'] = pd.to_datetime(
df_drawdowns['recovery date'],
unit='D')
return df_drawdowns
def rolling_sharpe(returns, rolling_sharpe_window):
"""
Determines the rolling Sharpe ratio of a strategy.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
rolling_sharpe_window : int
Length of rolling window, in days, over which to compute.
Returns
-------
pd.Series
Rolling Sharpe ratio.
Note
-----
See https://en.wikipedia.org/wiki/Sharpe_ratio for more details.
"""
return pd.rolling_mean(returns, rolling_sharpe_window) \
/ pd.rolling_std(returns, rolling_sharpe_window) \
* np.sqrt(APPROX_BDAYS_PER_YEAR)
def cone_rolling(
input_rets,
num_stdev=1.0,
warm_up_days_pct=0.5,
std_scale_factor=APPROX_BDAYS_PER_YEAR,
update_std_oos_rolling=False,
cone_fit_end_date=None,
extend_fit_trend=True,
create_future_cone=True):
"""Computes a rolling cone to place in the cumulative returns
plot. See plotting.plot_rolling_returns.
"""
# if specifying 'cone_fit_end_date' please use a pandas compatible format,
# e.g. '2015-8-4', 'YYYY-MM-DD'
warm_up_days = int(warm_up_days_pct * input_rets.size)
# create initial linear fit from beginning of timeseries thru warm_up_days
# or the specified 'cone_fit_end_date'
if cone_fit_end_date is None:
returns = input_rets[:warm_up_days]
else:
returns = input_rets[input_rets.index < cone_fit_end_date]
perf_ts = cum_returns(returns, 1)
X = list(range(0, perf_ts.size))
X = sm.add_constant(X)
sm.OLS(perf_ts, list(range(0, len(perf_ts))))
line_ols = sm.OLS(perf_ts.values, X).fit()
fit_line_ols_coef = line_ols.params[1]
fit_line_ols_inter = line_ols.params[0]
x_points = list(range(0, perf_ts.size))
x_points = np.array(x_points) * fit_line_ols_coef + fit_line_ols_inter
perf_ts_r = pd.DataFrame(perf_ts)
perf_ts_r.columns = ['perf']
warm_up_std_pct = np.std(perf_ts.pct_change().dropna())
std_pct = warm_up_std_pct * np.sqrt(std_scale_factor)
perf_ts_r['line'] = x_points
perf_ts_r['sd_up'] = perf_ts_r['line'] * (1 + num_stdev * std_pct)
perf_ts_r['sd_down'] = perf_ts_r['line'] * (1 - num_stdev * std_pct)
std_pct = warm_up_std_pct * np.sqrt(std_scale_factor)
last_backtest_day_index = returns.index[-1]
cone_end_rets = input_rets[input_rets.index > last_backtest_day_index]
new_cone_day_scale_factor = int(1)
oos_intercept_shift = perf_ts_r.perf[-1] - perf_ts_r.line[-1]
# make the cone for the out-of-sample/live papertrading period
for i in cone_end_rets.index:
returns = input_rets[:i]
perf_ts = cum_returns(returns, 1)
if extend_fit_trend:
line_ols_coef = fit_line_ols_coef
line_ols_inter = fit_line_ols_inter
else:
X = list(range(0, perf_ts.size))
X = sm.add_constant(X)
sm.OLS(perf_ts, list(range(0, len(perf_ts))))
line_ols = sm.OLS(perf_ts.values, X).fit()
line_ols_coef = line_ols.params[1]
line_ols_inter = line_ols.params[0]
x_points = list(range(0, perf_ts.size))
x_points = np.array(x_points) * line_ols_coef + \
line_ols_inter + oos_intercept_shift
temp_line = x_points
if update_std_oos_rolling:
std_pct = np.sqrt(new_cone_day_scale_factor) * \
np.std(perf_ts.pct_change().dropna())
else:
std_pct = np.sqrt(new_cone_day_scale_factor) * warm_up_std_pct
temp_sd_up = temp_line * (1 + num_stdev * std_pct)
temp_sd_down = temp_line * (1 - num_stdev * std_pct)
new_daily_cone = pd.DataFrame(index=[i],
data={'perf': perf_ts[i],
'line': temp_line[-1],
'sd_up': temp_sd_up[-1],
'sd_down': temp_sd_down[-1]})
perf_ts_r = perf_ts_r.append(new_daily_cone)
new_cone_day_scale_factor += 1
if create_future_cone:
extend_ahead_days = APPROX_BDAYS_PER_YEAR
future_cone_dates = pd.date_range(
cone_end_rets.index[-1], periods=extend_ahead_days, freq='B')
future_cone_intercept_shift = perf_ts_r.perf[-1] - perf_ts_r.line[-1]
future_days_scale_factor = np.linspace(
1,
extend_ahead_days,
extend_ahead_days)
std_pct = np.sqrt(future_days_scale_factor) * warm_up_std_pct
x_points = list(range(perf_ts.size, perf_ts.size + extend_ahead_days))
x_points = np.array(x_points) * line_ols_coef + line_ols_inter + \
oos_intercept_shift + future_cone_intercept_shift
temp_line = x_points
temp_sd_up = temp_line * (1 + num_stdev * std_pct)
temp_sd_down = temp_line * (1 - num_stdev * std_pct)
future_cone = pd.DataFrame(index=list(map(np.datetime64,
future_cone_dates)),
data={'perf': temp_line,
'line': temp_line,
'sd_up': temp_sd_up,
'sd_down': temp_sd_down})
perf_ts_r = perf_ts_r.append(future_cone)
return perf_ts_r
def extract_interesting_date_ranges(returns):
"""Extracts returns based on interesting events. See
gen_date_range_interesting.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
Returns
-------
ranges : OrderedDict
Date ranges, with returns, of all valid events.
"""
returns_dupe = returns.copy()
returns_dupe.index = returns_dupe.index.map(pd.Timestamp)
ranges = OrderedDict()
for name, (start, end) in PERIODS.items():
try:
period = returns_dupe.loc[start:end]
if len(period) == 0:
continue
ranges[name] = period
except:
continue
return ranges
def portfolio_returns(holdings_returns, exclude_non_overlapping=True):
"""Generates an equal-weight portfolio.
Parameters
----------
holdings_returns : list
List containing each individual holding's daily returns of the
strategy, noncumulative.
exclude_non_overlapping : boolean, optional
If True, timeseries returned will include values only for dates
available across all holdings_returns timeseries If False, 0%
returns will be assumed for a holding until it has valid data
Returns
-------
pd.Series
Equal-weight returns timeseries.
"""
port = holdings_returns[0]
for i in range(1, len(holdings_returns)):
port = port + holdings_returns[i]
if exclude_non_overlapping:
port = port.dropna()
else:
port = port.fillna(0)
return port / len(holdings_returns)
def portfolio_returns_metric_weighted(holdings_returns,
exclude_non_overlapping=True,
weight_function=None,
weight_function_window=None,
inverse_weight=False,
portfolio_rebalance_rule='q',
weight_func_transform=None):
"""
Generates an equal-weight portfolio, or portfolio weighted by
weight_function
Parameters
----------
holdings_returns : list
List containing each individual holding's daily returns of the
strategy, noncumulative.
exclude_non_overlapping : boolean, optional
(Only applicable if equal-weight portfolio, e.g. weight_function=None)
If True, timeseries returned will include values only for dates
available across all holdings_returns timeseries If False, 0%
returns will be assumed for a holding until it has valid data
weight_function : function, optional
Function to be applied to holdings_returns timeseries
weight_function_window : int, optional
Rolling window over which weight_function will use as its input values
inverse_weight : boolean, optional
If True, high values returned from weight_function will result in lower
weight for that holding
portfolio_rebalance_rule : string, optional
A pandas.resample valid rule. Specifies how frequently to compute
the weighting criteria
weight_func_transform : function, optional
Function applied to value returned from weight_function
Returns
-------
(pd.Series, pd.DataFrame)
pd.Series : Portfolio returns timeseries.
pd.DataFrame : All the raw data used in the portfolio returns
calculations
"""
if weight_function is None:
if exclude_non_overlapping:
holdings_df = pd.DataFrame(holdings_returns).T.dropna()
else:
holdings_df = pd.DataFrame(holdings_returns).T.fillna(0)
holdings_df['port_ret'] = holdings_df.sum(
axis=1) / len(holdings_returns)
else:
holdings_df_na = pd.DataFrame(holdings_returns).T
holdings_cols = holdings_df_na.columns
holdings_df = holdings_df_na.dropna()
holdings_func = pd.rolling_apply(holdings_df,
window=weight_function_window,
func=weight_function).dropna()
holdings_func_rebal = holdings_func.resample(
rule=portfolio_rebalance_rule,
how='last')
holdings_df = holdings_df.join(
holdings_func_rebal, rsuffix='_f').fillna(method='ffill').dropna()
if weight_func_transform is None:
holdings_func_rebal_t = holdings_func_rebal
holdings_df = holdings_df.join(
holdings_func_rebal_t,
rsuffix='_t').fillna(method='ffill').dropna()
else:
holdings_func_rebal_t = holdings_func_rebal.applymap(
weight_func_transform)
holdings_df = holdings_df.join(
holdings_func_rebal_t,
rsuffix='_t').fillna(method='ffill').dropna()
transform_columns = list(map(lambda x: x + "_t", holdings_cols))
if inverse_weight:
inv_func = 1.0 / holdings_df[transform_columns]
holdings_df_weights = inv_func.div(inv_func.sum(axis=1),
axis='index')
else:
holdings_df_weights = holdings_df[transform_columns] \
.div(holdings_df[transform_columns].sum(axis=1), axis='index')
holdings_df_weights.columns = holdings_cols
holdings_df = holdings_df.join(holdings_df_weights, rsuffix='_w')
holdings_df_weighted_rets = np.multiply(
holdings_df[holdings_cols], holdings_df_weights)
holdings_df_weighted_rets['port_ret'] = holdings_df_weighted_rets.sum(
axis=1)
holdings_df = holdings_df.join(holdings_df_weighted_rets,
rsuffix='_wret')
return holdings_df['port_ret'], holdings_df
def bucket_std(value, bins=[0.12, 0.15, 0.18, 0.21], max_default=0.24):
"""
Simple quantizing function. For use in binning stdevs into a "buckets"
Parameters
----------
value : float
Value corresponding to the the stdev to be bucketed
bins : list, optional
Floats used to describe the buckets which the value can be placed
max_default : float, optional
If value is greater than all the bins, max_default will be returned
Returns
-------
float
bin which the value falls into
"""
annual_vol = value * np.sqrt(252)
for i in bins:
if annual_vol <= i:
return i
return max_default
def min_max_vol_bounds(value, lower_bound=0.12, upper_bound=0.24):
"""
Restrict volatility weighting of the lowest volatility asset versus the
highest volatility asset to a certain limit.
E.g. Never allocate more than 2x to the lowest volatility asset.
round up all the asset volatilities that fall below a certain bound
to a specified "lower bound" and round down all of the asset
volatilites that fall above a certain bound to a specified "upper bound"
Parameters
----------
value : float
Value corresponding to a daily volatility
lower_bound : float, optional
Lower bound for the volatility
upper_bound : float, optional
Upper bound for the volatility
Returns
-------
float
The value input, annualized, or the lower_bound or upper_bound
"""
annual_vol = value * np.sqrt(252)
if annual_vol < lower_bound:
return lower_bound
if annual_vol > upper_bound:
return upper_bound
return annual_vol
| apache-2.0 |
kdart/pycopia3 | core/pycopia/fsm.py | 7789 | #!/usr/bin/python3.4
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
# 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 module implements a Finite State Machine (FSM) with two stacks.
The FSM is fairly simple. It is useful for small parsing tasks.
"""
import re
from pycopia.aid import Enum, Enums
class FSMError(Exception):
pass
_cre = re.compile("test")
SREType = type(_cre)
del _cre
# default state and state Enum constructor
def make_states(*args):
"converts an argument list of strings to a list of Enum. Use as state transitions."
return Enums(list(map(str, args)))
ANY = Enum(-1, "ANY")
class FSM(object):
"""This class is a Finite State Machine (FSM).
You set up a state transition table which is the association of::
(input_symbol, current_state) --> (action, next_state)
When the FSM matches a pair (current_state, input_symbol)
it will call the associated action.
The action is a function reference defined with a signature like this::
def f (input_symbol, fsm):
and pass as parameters the input symbol, and the FSM instance itself.
The action function may produce output and update the stack.
"""
ANY = ANY
def __init__(self, initial_state=0):
self._transitions = {} # Map (input_symbol, state) to (action, next_state).
self._expressions = []
self.default_transition = None
self.RESET = Enum(0, "RESET") # there is always a RESET state
self.initial_state = self.RESET
self._reset()
# FSM stack for user
def push(self, v):
self.stack.append(v)
def pop(self):
return self.stack.pop()
def pushalt(self, v):
self.altstack.append(v)
def popalt(self):
return self.altstack.pop()
def _reset(self):
"""Rest the stacks and resets the current_state to the initial_state. """
self.current_state = self.initial_state
self.stack = [] # primary stack
self.altstack = [] # alternate stack
def reset(self):
"overrideable user reset."
self._reset()
def add_states(self, *args):
for enum in make_states(*args):
if not hasattr(self, str(enum)):
setattr(self, str(enum), enum)
else:
raise FSMError("state or attribute already exists.")
def set_default_transition(self, action, next_state):
'''This sets the default transition.
If the FSM cannot match the pair (input_symbol, current_state)
in the transition table then this is the transition that
will be returned. This is useful for catching errors and undefined states.
The default transition can be removed by calling
`add_default_transition (None, None)`.
If the default is not set and the FSM cannot match
the input_symbol and current_state then it will
raise an exception (see process()).
'''
if action == None and next_state == None:
self.default_transition = None
else:
self.default_transition = (action, next_state)
add_default_transition = set_default_transition # alias
def add_transition(self, input_symbol, state, action, next_state):
'''This adds an association between inputs and outputs.
(input_symbol, current_state) --> (action, next_state)
The action may be set to None.
The input_symbol may be set to None. '''
self._transitions[(input_symbol, state)] = (action, next_state)
def add_expression(self, expression, state, action, next_state, flags=0):
"""Adds a transition that activates if the input symbol matches the
regular expression. The action callable gets a match object instead of
the symbol."""
cre = re.compile(expression, flags)
self._expressions.append( (cre, state, action, next_state) )
self._transitions[(SREType, state)] = (self._check_expression, None)
# self-action to match against expressions
def _check_expression(self, symbol, myself):
for cre, state, action, next_state in self._expressions:
mo = cre.match(symbol)
if state is self.current_state and mo:
if action is not None:
action(mo, self)
self.current_state = next_state
def add_transition_list(self, list_input_symbols, state, action, next_state):
'''This adds lots of the same transitions for different input symbols.
You can pass a list or a string. Don't forget that it is handy to use
string.digits, string.letters, etc. to add transitions that match
those character classes.
'''
for input_symbol in list_input_symbols:
self.add_transition (input_symbol, state, action, next_state)
def get_transition(self, input_symbol, state):
'''This tells what the next state and action would be
given the current state and the input_symbol.
This returns (action, new state).
This does not update the current state
nor does it trigger the output action.
If the transition is not defined and the default state is defined
then that will be used; otherwise, this throws an exception.
'''
try:
return self._transitions[(input_symbol, state)]
except KeyError:
try:
return self._transitions[(ANY, state)]
except KeyError:
try:
return self._transitions[(SREType, state)]
except KeyError:
# no expression matched, so check for default
if self.default_transition is not None:
return self.default_transition
else:
raise FSMError('Transition %r is undefined.' % (input_symbol,))
def process(self, input_symbol):
"""This causes the fsm to change state and call an action:
`(input_symbol, current_state) --> (action, next_state)`.
If the action is None then no action is taken, and
only the current state is changed. """
action, next_state = self.get_transition(input_symbol, self.current_state)
if action is not None:
action(input_symbol, self)
if next_state is not None:
self.current_state = next_state
def step(self, token):
"""This causes the fsm to change state and call an action.
`(token, current_state) --> (action, next_state)` If the action is
None then no action is taken, only the current state is changed.
"""
action, next_state = self.get_transition(token, self.current_state)
if action is not None:
rv = action(token, self)
if rv is None:
if next_state is not None:
self.current_state = next_state
else: # returning a value from a method sets the state, else take the FSM defined default.
self.current_state = rv
elif next_state is not None:
self.current_state = next_state
def process_string(self, s):
for c in s:
self.process(c)
if __name__ == '__main__':
pass
| apache-2.0 |
Mahidharmullapudi/timesheet-upload | src/main/java/com/technumen/constants/EmailServiceConstants.java | 444 | package com.technumen.constants;
public class EmailServiceConstants {
//Email Service Parameters
public static final String mailTemplateTableName = "TIMESHEET_APP_EMAIL_TEMPLATE";
public static final String mailTemplateKeyColumnName = "DSC_EMAIL_TEMPLATE_KEY";
public static final String mailTemplateColumnName = "DSC_EMAIL_TEMPLATE";
public static final String mailTemplateModifiedDateColumnName = "DATE_USER_MODIFIED";
}
| apache-2.0 |
csmith932/uas-schedule-generator | swac-common/src/main/java/gov/faa/ang/swac/common/random/util/RootFinder.java | 6553 | package gov.faa.ang.swac.common.random.util;
/*
* Class: RootFinder
* Description: Provides methods to solve non-linear equations.
* Environment: Java
* Software: SSJ
* Copyright (C) 2001 Pierre L'Ecuyer and Université de Montréal
* Organization: DIRO, Université de Montréal
* @author
* @since
* SSJ is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License (GPL) as published by the
* Free Software Foundation, either version 3 of the License, or
* any later version.
* SSJ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* A copy of the GNU General Public License is available at
<a href="http://www.gnu.org/licenses">GPL licence site</a>.
*/
import gov.faa.ang.swac.common.random.functions.MathFunction;
/**
* This class provides methods to solve non-linear equations.
*
*/
public class RootFinder {
private RootFinder() {}
/**
* Computes a root <SPAN CLASS="MATH"><I>x</I></SPAN> of the function in <TT>f</TT> using the
* Brent-Dekker method. The interval <SPAN CLASS="MATH">[<I>a</I>, <I>b</I>]</SPAN> must contain the root <SPAN CLASS="MATH"><I>x</I></SPAN>.
* The calculations are done with an approximate relative precision
* <TT>tol</TT>. Returns <SPAN CLASS="MATH"><I>x</I></SPAN> such that <SPAN CLASS="MATH"><I>f</I> (<I>x</I>) = 0</SPAN>.
*
* @param a left endpoint of initial interval
*
* @param b right endpoint of initial interval
*
* @param f the function which is evaluated
*
* @param tol accuracy goal
*
* @return the root <SPAN CLASS="MATH"><I>x</I></SPAN>
*
*/
public static double brentDekker (double a, double b,
MathFunction f, double tol) {
final double EPS = 0.5E-15;
final int MAXITER = 120; // Maximum number of iterations
double c, d, e;
double fa, fb, fc;
// Special case I = [b, a]
if (b < a) {
double ctemp = a;
a = b;
b = ctemp;
}
// Initialization
fa = f.evaluate (a);
fb = f.evaluate (b);
c = a;
fc = fa;
d = e = b - a;
tol += EPS + Num.DBL_EPSILON; // in case tol is too small
if (Math.abs (fc) < Math.abs (fb)) {
a = b;
b = c;
c = a;
fa = fb;
fb = fc;
fc = fa;
}
for (int i = 0; i < MAXITER; i++) {
double s, p, q, r;
double tol1 = tol + 4.0 * Num.DBL_EPSILON * Math.abs (b);
double xm = 0.5 * (c - b);
if ((Math.abs (fb) == 0.0) || (Math.abs (xm) <= tol1))
return b;
if ((Math.abs (e) >= tol1) && (Math.abs (fa) > Math.abs (fb))) {
if (a != c) {
// Inverse quadratic interpolation
q = fa / fc;
r = fb / fc;
s = fb / fa;
p = s * (2.0 * xm * q * (q - r) - (b - a) * (r - 1.0));
q = (q - 1.0) * (r - 1.0) * (s - 1.0);
} else {
// Linear interpolation
s = fb / fa;
p = 2.0 * xm * s;
q = 1.0 - s;
}
// Adjust signs
if (p > 0.0)
q = -q;
p = Math.abs (p);
// Is interpolation acceptable ?
if (((2.0 * p) >= (3.0 * xm * q - Math.abs (tol1 * q)))
|| (p >= Math.abs (0.5 * e * q))) {
d = xm;
e = d;
} else {
e = d;
d = p / q;
}
} else {
// Bisection necessary
d = xm;
e = d;
}
a = b;
fa = fb;
if (Math.abs (d) > tol1)
b += d;
else if (xm < 0.0)
b -= tol1;
else
b += tol1;
fb = f.evaluate (b);
if ((fb * (fc / Math.abs (fc))) > 0.0) {
c = a;
fc = fa;
d = e = b - a;
} else {
a = b;
b = c;
c = a;
fa = fb;
fb = fc;
fc = fa;
}
}
return b;
}
/**
* Computes a root <SPAN CLASS="MATH"><I>x</I></SPAN> of the function in <TT>f</TT> using the
* <SPAN CLASS="textit">bisection</SPAN> method. The interval <SPAN CLASS="MATH">[<I>a</I>, <I>b</I>]</SPAN> must contain the root <SPAN CLASS="MATH"><I>x</I></SPAN>.
* The calculations are done with an approximate relative precision
* <TT>tol</TT>. Returns <SPAN CLASS="MATH"><I>x</I></SPAN> such that <SPAN CLASS="MATH"><I>f</I> (<I>x</I>) = 0</SPAN>.
*
* @param a left endpoint of initial interval
*
* @param b right endpoint of initial interval
*
* @param f the function which is evaluated
*
* @param tol accuracy goal
*
* @return the root <SPAN CLASS="MATH"><I>x</I></SPAN>
*
*/
public static double bisection (double a, double b,
MathFunction f, double tol) {
// Case I = [b, a]
if (b < a) {
double ctemp = a;
a = b;
b = ctemp;
}
double xa = a;
double xb = b;
double yb = f.evaluate (b);
double ya = f.evaluate (a);
double x = 0, y = 0;
final int MAXITER = 1200; // Maximum number of iterations
final boolean DEBUG = false;
final double myMIN_NORMAL = 2.25e-308;
if (DEBUG)
System.out.println
("\niter xa xb f(x)");
boolean fini = false;
int i = 0;
while (!fini) {
x = (xa + xb) / 2.0;
y = f.evaluate (x);
if ((Math.abs (y) <= myMIN_NORMAL) ||
(Math.abs (xb - xa) <= tol * Math.abs (x)) ||
(Math.abs (xb - xa) <= 0)) {
return x;
}
if (y * ya < 0.0)
xb = x;
else
xa = x;
++i;
if (DEBUG)
System.out.printf("%3d %18.12g %18.12g %14.4g%n",
i, xa, xb, y);
if (i > MAXITER) {
System.out.println ("***** bisection: SEARCH DOES NOT CONVERGE");
fini = true;
}
}
return x;
}
}
| apache-2.0 |
kvr000/zbynek-java-exp | concurrency-exp/concurrency-primitives-exp/src/main/java/cz/znj/kvr/sw/exp/java/concurrencyexp/primitives/dynamicexecutor/FsDynamicExecutor.java | 1955 | package cz.znj.kvr.sw.exp.java.concurrencyexp.primitives.dynamicexecutor;
import java.io.File;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
/**
* Created by rat on 2015-09-20.
*/
public class FsDynamicExecutor
{
public static void main(String[] args)
{
ExecutorService es = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
AtomicLong counter = new AtomicLong();
for (String file: args) {
es.submit(new FileProcessor(es, counter, new File(file)));
counter.incrementAndGet();
}
synchronized (counter) {
if (counter.get() != 0) {
try {
counter.wait();
}
catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
es.shutdown();
try {
es.awaitTermination(0, TimeUnit.MILLISECONDS);
}
catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
private static class FileProcessor implements Runnable
{
private final ExecutorService es;
private final AtomicLong counter;
private final File file;
public FileProcessor(ExecutorService es, AtomicLong counter, File file)
{
this.es = es;
this.counter = counter;
this.file = file;
}
public void run()
{
File[] children = null;
try {
try {
if (!file.exists())
return;
System.out.println("Producer "+0+": \""+file.getPath()+"\" "+file.length());
if (!file.isDirectory())
return;
children = file.listFiles();
if (children == null)
return;
}
catch (Exception ex) {
}
for (File child : children) {
es.submit(new FileProcessor(es, counter, child));
counter.incrementAndGet();
}
}
finally {
if (counter.decrementAndGet() == 0) {
synchronized (counter) {
counter.notifyAll();
}
}
}
}
}
}
| apache-2.0 |
jjeb/kettle-trunk | ui/src/org/pentaho/di/ui/trans/steps/accessoutput/AccessOutputDialog.java | 20007 | /*******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2012 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.ui.trans.steps.accessoutput;
import java.io.File;
import java.util.Set;
import org.apache.commons.io.FileUtils;
import org.apache.commons.vfs.FileObject;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStepMeta;
import org.pentaho.di.trans.step.StepDialogInterface;
import org.pentaho.di.trans.steps.accessoutput.AccessOutputMeta;
import org.pentaho.di.ui.core.dialog.EnterSelectionDialog;
import org.pentaho.di.ui.core.dialog.ErrorDialog;
import org.pentaho.di.ui.core.widget.TextVar;
import org.pentaho.di.ui.trans.step.BaseStepDialog;
import com.healthmarketscience.jackcess.Database;
public class AccessOutputDialog extends BaseStepDialog implements StepDialogInterface
{
private static Class<?> PKG = AccessOutputMeta.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$
private Label wlFilename;
private Button wbbFilename; // Browse: add file or directory
private TextVar wFilename;
private FormData fdlFilename, fdbFilename, fdFilename;
private Label wlCreateFile;
private Button wCreateFile;
private FormData fdlCreateFile, fdCreateFile;
private Label wlTablename;
private TextVar wTablename;
private Button wbbTablename;
private FormData fdlTablename, fdTablename, fdbTablename;
/*
private Label wlTruncate;
private Button wTruncate;
private FormData fdlTruncate, fdTruncate;
*/
private Label wlCreateTable;
private Button wCreateTable;
private FormData fdlCreateTable, fdCreateTable;
private Label wlCommitSize;
private Text wCommitSize;
private FormData fdlCommitSize, fdCommitSize;
private Label wlAddToResult;
private Button wAddToResult;
private FormData fdlAddToResult, fdAddToResult;
private Label wlDoNotOpenNewFileInit;
private Button wDoNotOpenNewFileInit;
private FormData fdlDoNotOpenNewFileInit, fdDoNotOpenNewFileInit;
private AccessOutputMeta input;
public AccessOutputDialog(Shell parent, Object in, TransMeta transMeta, String sname)
{
super(parent, (BaseStepMeta)in, transMeta, sname);
input=(AccessOutputMeta)in;
}
public String open()
{
Shell parent = getParent();
Display display = parent.getDisplay();
shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN);
props.setLook(shell);
setShellImage(shell, input);
ModifyListener lsMod = new ModifyListener()
{
public void modifyText(ModifyEvent e)
{
input.setChanged();
}
};
SelectionAdapter lsSelMod = new SelectionAdapter()
{
public void widgetSelected(SelectionEvent arg0)
{
input.setChanged();
}
};
backupChanged = input.hasChanged();
int middle = props.getMiddlePct();
int margin = Const.MARGIN;
FormLayout formLayout = new FormLayout ();
formLayout.marginWidth = Const.FORM_MARGIN;
formLayout.marginHeight = Const.FORM_MARGIN;
shell.setLayout(formLayout);
shell.setText(BaseMessages.getString(PKG, "AccessOutputDialog.DialogTitle"));
// Stepname line
wlStepname=new Label(shell, SWT.RIGHT);
wlStepname.setText(BaseMessages.getString(PKG, "System.Label.StepName"));
props.setLook(wlStepname);
fdlStepname=new FormData();
fdlStepname.left = new FormAttachment(0, 0);
fdlStepname.right= new FormAttachment(middle, 0);
fdlStepname.top = new FormAttachment(0, 0);
wlStepname.setLayoutData(fdlStepname);
wStepname=new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wStepname.setText(stepname);
props.setLook(wStepname);
wStepname.addModifyListener(lsMod);
fdStepname=new FormData();
fdStepname.left = new FormAttachment(middle, margin);
fdStepname.top = new FormAttachment(0, 0);
fdStepname.right= new FormAttachment(100, 0);
wStepname.setLayoutData(fdStepname);
// Filename line
wlFilename=new Label(shell, SWT.RIGHT);
wlFilename.setText(BaseMessages.getString(PKG, "AccessOutputDialog.Filename.Label"));
props.setLook(wlFilename);
fdlFilename=new FormData();
fdlFilename.left = new FormAttachment(0, 0);
fdlFilename.top = new FormAttachment(wStepname, margin);
fdlFilename.right= new FormAttachment(middle, 0);
wlFilename.setLayoutData(fdlFilename);
wbbFilename=new Button(shell, SWT.PUSH| SWT.CENTER);
props.setLook(wbbFilename);
wbbFilename.setText(BaseMessages.getString(PKG, "System.Button.Browse"));
wbbFilename.setToolTipText(BaseMessages.getString(PKG, "System.Tooltip.BrowseForFileOrDirAndAdd"));
fdbFilename=new FormData();
fdbFilename.right= new FormAttachment(100, 0);
fdbFilename.top = new FormAttachment(wStepname, margin);
wbbFilename.setLayoutData(fdbFilename);
wFilename=new TextVar(transMeta, shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wFilename.setToolTipText(BaseMessages.getString(PKG, "AccessOutputDialog.Filename.Tooltip"));
props.setLook(wFilename);
wFilename.addModifyListener(lsMod);
fdFilename=new FormData();
fdFilename.left = new FormAttachment(middle, margin);
fdFilename.right= new FormAttachment(wbbFilename, -margin);
fdFilename.top = new FormAttachment(wStepname, margin);
wFilename.setLayoutData(fdFilename);
// Open new File at Init
wlDoNotOpenNewFileInit=new Label(shell, SWT.RIGHT);
wlDoNotOpenNewFileInit.setText(BaseMessages.getString(PKG, "AccessOutputDialog.DoNotOpenNewFileInit.Label"));
props.setLook(wlDoNotOpenNewFileInit);
fdlDoNotOpenNewFileInit=new FormData();
fdlDoNotOpenNewFileInit.left = new FormAttachment(0, 0);
fdlDoNotOpenNewFileInit.top = new FormAttachment(wFilename, margin);
fdlDoNotOpenNewFileInit.right= new FormAttachment(middle, -margin);
wlDoNotOpenNewFileInit.setLayoutData(fdlDoNotOpenNewFileInit);
wDoNotOpenNewFileInit=new Button(shell, SWT.CHECK );
wDoNotOpenNewFileInit.setToolTipText(BaseMessages.getString(PKG, "AccessOutputDialog.DoNotOpenNewFileInit.Tooltip"));
props.setLook(wDoNotOpenNewFileInit);
fdDoNotOpenNewFileInit=new FormData();
fdDoNotOpenNewFileInit.left = new FormAttachment(middle, margin);
fdDoNotOpenNewFileInit.top = new FormAttachment(wFilename, margin);
fdDoNotOpenNewFileInit.right= new FormAttachment(100, 0);
wDoNotOpenNewFileInit.setLayoutData(fdDoNotOpenNewFileInit);
wDoNotOpenNewFileInit.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
input.setChanged();
}
}
);
// Create file?
wlCreateFile=new Label(shell, SWT.RIGHT);
wlCreateFile.setText(BaseMessages.getString(PKG, "AccessOutputDialog.CreateFile.Label"));
wlCreateFile.setToolTipText(BaseMessages.getString(PKG, "AccessOutputDialog.CreateFile.Tooltip"));
props.setLook(wlCreateFile);
fdlCreateFile=new FormData();
fdlCreateFile.left = new FormAttachment(0, 0);
fdlCreateFile.top = new FormAttachment(wDoNotOpenNewFileInit, margin);
fdlCreateFile.right = new FormAttachment(middle, 0);
wlCreateFile.setLayoutData(fdlCreateFile);
wCreateFile=new Button(shell, SWT.CHECK);
wCreateFile.setToolTipText(BaseMessages.getString(PKG, "AccessOutputDialog.CreateFile.Tooltip"));
props.setLook(wCreateFile);
fdCreateFile=new FormData();
fdCreateFile.left = new FormAttachment(middle, margin);
fdCreateFile.top = new FormAttachment(wDoNotOpenNewFileInit, margin);
fdCreateFile.right = new FormAttachment(100, 0);
wCreateFile.setLayoutData(fdCreateFile);
wCreateFile.addSelectionListener(lsSelMod);
// Table line...
wbbTablename=new Button(shell, SWT.PUSH| SWT.CENTER);
props.setLook(wbbTablename);
wbbTablename.setText(BaseMessages.getString(PKG, "System.Button.Browse"));
fdbTablename=new FormData();
fdbTablename.right= new FormAttachment(100, 0);
fdbTablename.top = new FormAttachment(wCreateFile, margin);
wbbTablename.setLayoutData(fdbTablename);
wlTablename=new Label(shell, SWT.RIGHT);
wlTablename.setText(BaseMessages.getString(PKG, "AccessOutputDialog.TargetTable.Label"));
props.setLook(wlTablename);
fdlTablename=new FormData();
fdlTablename.left = new FormAttachment(0, 0);
fdlTablename.top = new FormAttachment(wCreateFile, margin);
fdlTablename.right= new FormAttachment(middle, 0);
wlTablename.setLayoutData(fdlTablename);
wTablename=new TextVar(transMeta, shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wTablename.setToolTipText(BaseMessages.getString(PKG, "AccessOutputDialog.TargetTable.Tooltip"));
props.setLook(wTablename);
fdTablename=new FormData();
fdTablename.left = new FormAttachment(middle, margin);
fdTablename.right= new FormAttachment(wbbTablename, -margin);
fdTablename.top = new FormAttachment(wCreateFile, margin);
wTablename.setLayoutData(fdTablename);
// Create table?
wlCreateTable=new Label(shell, SWT.RIGHT);
wlCreateTable.setText(BaseMessages.getString(PKG, "AccessOutputDialog.CreateTable.Label"));
wlCreateTable.setToolTipText(BaseMessages.getString(PKG, "AccessOutputDialog.CreateTable.Tooltip"));
props.setLook(wlCreateTable);
fdlCreateTable=new FormData();
fdlCreateTable.left = new FormAttachment(0, 0);
fdlCreateTable.top = new FormAttachment(wTablename, margin);
fdlCreateTable.right = new FormAttachment(middle, 0);
wlCreateTable.setLayoutData(fdlCreateTable);
wCreateTable=new Button(shell, SWT.CHECK);
wCreateTable.setToolTipText(BaseMessages.getString(PKG, "AccessOutputDialog.CreateTable.Tooltip"));
props.setLook(wCreateTable);
fdCreateTable=new FormData();
fdCreateTable.left = new FormAttachment(middle, margin);
fdCreateTable.top = new FormAttachment(wTablename, margin);
fdCreateTable.right = new FormAttachment(100, 0);
wCreateTable.setLayoutData(fdCreateTable);
wCreateTable.addSelectionListener(lsSelMod);
// The commit size...
wlCommitSize=new Label(shell, SWT.RIGHT);
wlCommitSize.setText(BaseMessages.getString(PKG, "AccessOutputDialog.CommitSize.Label"));
props.setLook(wlCommitSize);
fdlCommitSize=new FormData();
fdlCommitSize.left = new FormAttachment(0, 0);
fdlCommitSize.top = new FormAttachment(wCreateTable, margin);
fdlCommitSize.right= new FormAttachment(middle, 0);
wlCommitSize.setLayoutData(fdlCommitSize);
wCommitSize=new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wCommitSize.setToolTipText(BaseMessages.getString(PKG, "AccessOutputDialog.CommitSize.Tooltip"));
props.setLook(wCommitSize);
fdCommitSize=new FormData();
fdCommitSize.left = new FormAttachment(middle, margin);
fdCommitSize.right= new FormAttachment(100, 0);
fdCommitSize.top = new FormAttachment(wCreateTable, margin);
wCommitSize.setLayoutData(fdCommitSize);
// Add File to the result files name
wlAddToResult=new Label(shell, SWT.RIGHT);
wlAddToResult.setText(BaseMessages.getString(PKG, "AccessOutputMeta.AddFileToResult.Label"));
props.setLook(wlAddToResult);
fdlAddToResult=new FormData();
fdlAddToResult.left = new FormAttachment(0, 0);
fdlAddToResult.top = new FormAttachment(wCommitSize, 2*margin);
fdlAddToResult.right = new FormAttachment(middle, -margin);
wlAddToResult.setLayoutData(fdlAddToResult);
wAddToResult=new Button(shell, SWT.CHECK);
wAddToResult.setToolTipText(BaseMessages.getString(PKG, "AccessOutputMeta.AddFileToResult.Tooltip"));
props.setLook(wAddToResult);
fdAddToResult=new FormData();
fdAddToResult.left = new FormAttachment(middle, margin);
fdAddToResult.top = new FormAttachment(wCommitSize, 2*margin);
fdAddToResult.right = new FormAttachment(100, 0);
wAddToResult.setLayoutData(fdAddToResult);
SelectionAdapter lsSelR = new SelectionAdapter()
{
public void widgetSelected(SelectionEvent arg0)
{
input.setChanged();
}
};
wAddToResult.addSelectionListener(lsSelR);
// Some buttons
wOK=new Button(shell, SWT.PUSH);
wOK.setText(BaseMessages.getString(PKG, "System.Button.OK"));
wCancel=new Button(shell, SWT.PUSH);
wCancel.setText(BaseMessages.getString(PKG, "System.Button.Cancel"));
setButtonPositions(new Button[] { wOK, wCancel }, margin, wAddToResult);
// Add listeners
lsOK = new Listener() { public void handleEvent(Event e) { ok(); } };
lsCancel = new Listener() { public void handleEvent(Event e) { cancel(); } };
wOK.addListener (SWT.Selection, lsOK );
wCancel.addListener(SWT.Selection, lsCancel);
lsDef=new SelectionAdapter() { public void widgetDefaultSelected(SelectionEvent e) { ok(); } };
wStepname.addSelectionListener( lsDef );
wTablename.addSelectionListener( lsDef );
wbbTablename.addSelectionListener
(
new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
getTableName();
}
}
);
// Listen to the Browse... button
wbbFilename.addSelectionListener
(
new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
FileDialog dialog = new FileDialog(shell, SWT.SAVE);
dialog.setFilterExtensions(new String[] {"*.mdb;*.MDB;*.accdb;*.ACCDB", "*"});
if (!Const.isEmpty(wFilename.getText()))
{
String fname = transMeta.environmentSubstitute(wFilename.getText());
dialog.setFileName( fname );
}
dialog.setFilterNames(new String[] {BaseMessages.getString(PKG, "AccessOutputDialog.FileType.AccessFiles"), BaseMessages.getString(PKG, "System.FileType.AllFiles")});
if (dialog.open()!=null)
{
String str = dialog.getFilterPath()+System.getProperty("file.separator")+dialog.getFileName();
wFilename.setText(str);
}
}
}
);
// Detect X or ALT-F4 or something that kills this window...
shell.addShellListener( new ShellAdapter() { public void shellClosed(ShellEvent e) { cancel(); } } );
// Set the shell size, based upon previous time...
setSize();
getData();
input.setChanged(backupChanged);
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch()) display.sleep();
}
return stepname;
}
/**
* Copy information from the meta-data input to the dialog fields.
*/
public void getData()
{
if (input.getFilename() != null) wFilename.setText(input.getFilename());
if (input.getTablename() != null) wTablename.setText(input.getTablename());
wCreateFile.setSelection( input.isFileCreated() );
wCreateTable.setSelection(input.isFileCreated() );
if (input.getCommitSize()>0) wCommitSize.setText( Integer.toString( input.getCommitSize() ) );
wAddToResult.setSelection(input.isAddToResultFiles());
wDoNotOpenNewFileInit.setSelection(input.isDoNotOpenNewFileInit());
wStepname.selectAll();
}
private void cancel()
{
stepname=null;
input.setChanged(backupChanged);
dispose();
}
private void getInfo(AccessOutputMeta info)
{
info.setFilename( wFilename.getText() );
info.setTablename( wTablename.getText() );
info.setFileCreated( wCreateFile.getSelection() );
info.setTableCreated( wCreateTable.getSelection() );
info.setCommitSize( Const.toInt(wCommitSize.getText(), -1) );
info.setAddToResultFiles( wAddToResult.getSelection() );
input.setDoNotOpenNewFileInit(wDoNotOpenNewFileInit.getSelection() );
}
private void ok()
{
if (Const.isEmpty(wStepname.getText())) return;
stepname = wStepname.getText(); // return value
getInfo(input);
dispose();
}
private void getTableName()
{
AccessOutputMeta meta = new AccessOutputMeta();
getInfo(meta);
Database database = null;
// New class: SelectTableDialog
try
{
String realFilename = transMeta.environmentSubstitute(meta.getFilename());
FileObject fileObject = KettleVFS.getFileObject(realFilename, transMeta);
File file = FileUtils.toFile(fileObject.getURL());
if (!file.exists() || !file.isFile())
{
throw new KettleException(BaseMessages.getString(PKG, "AccessOutputMeta.Exception.FileDoesNotExist", realFilename));
}
database = Database.open(file);
Set<String> set= database.getTableNames();
String[] tablenames = set.toArray(new String[set.size()]);
EnterSelectionDialog dialog = new EnterSelectionDialog(shell, tablenames, BaseMessages.getString(PKG, "AccessOutputDialog.Dialog.SelectATable.Title"), BaseMessages.getString(PKG, "AccessOutputDialog.Dialog.SelectATable.Message"));
String tablename = dialog.open();
if (tablename!=null)
{
wTablename.setText(tablename);
}
}
catch(Throwable e)
{
new ErrorDialog(shell, BaseMessages.getString(PKG, "AccessOutputDialog.UnableToGetListOfTables.Title"), BaseMessages.getString(PKG, "AccessOutputDialog.UnableToGetListOfTables.Message"), e);
}
finally
{
// Don't forget to close the bugger.
try
{
if (database!=null) database.close();
}
catch(Exception e)
{
}
}
}
}
| apache-2.0 |
U-QASAR/u-qasar.platform | src/main/java/eu/uqasar/model/product/Product.java | 3119 | package eu.uqasar.model.product;
/*
* #%L
* U-QASAR
* %%
* Copyright (C) 2012 - 2015 U-QASAR Consortium
* %%
* 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.
* #L%
*/
import de.agilecoders.wicket.core.markup.html.bootstrap.image.IconType;
import eu.uqasar.model.AbstractEntity;
import eu.uqasar.model.Namable;
import eu.uqasar.model.tree.Project;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.apache.commons.lang.StringUtils;
import org.hibernate.search.annotations.Analyze;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Index;
import org.hibernate.search.annotations.Indexed;
import org.hibernate.search.annotations.Store;
import org.hibernate.search.annotations.TermVector;
@NoArgsConstructor
@Setter
@Getter
@Entity
@XmlRootElement
@Table(name = "product")
@Indexed
public class Product extends AbstractEntity implements Namable {
private static final long serialVersionUID = 1724244299796140695L;
public static IconType ICON = new IconType("sitemap");
@NotNull
@Size(min = 2, max = 1024)
@Field(index = Index.YES, analyze = Analyze.YES, store = Store.NO, termVector=TermVector.YES)
private String name;
@Field(index = Index.YES, analyze = Analyze.YES, store = Store.NO, termVector=TermVector.YES)
private String description;
@NotNull
@Field(index = Index.YES, analyze = Analyze.YES, store = Store.NO, termVector=TermVector.YES)
private String version;
@Temporal(javax.persistence.TemporalType.DATE)
@NotNull
private Date releaseDate;
@OneToMany
@JoinColumn(name = "project_id", nullable = true)
private Set<Project> projects = new HashSet<>();
public Product(final String name) {
this.setName(name);
}
/**
*
* @param maxLength
* @return
*/
private String getAbbreviatedName(int maxLength) {
return StringUtils.abbreviate(getName(), maxLength);
}
/**
*
* @return
*/
public String getAbbreviatedName() {
return getAbbreviatedName(48);
}
@Override
public String toString() {
return name;
}
@Override
public String getUniqueName() {
return name;
}
}
| apache-2.0 |
AndreJCL/JCL | JCL_Android/app/src/main/java/javassist/bytecode/StackMap.java | 16032 | /*
* Javassist, a Java-bytecode translator toolkit.
* Copyright (C) 1999- Shigeru Chiba. All Rights Reserved.
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. Alternatively, the contents of this file may be used under
* the terms of the GNU Lesser General Public License Version 2.1 or later,
* or the Apache License Version 2.0.
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*/
package javassist.bytecode;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.Map;
import javassist.CannotCompileException;
/**
* Another <code>stack_map</code> attribute defined in CLDC 1.1 for J2ME.
*
* <p>This is an entry in the attributes table of a Code attribute.
* It was introduced by J2ME CLDC 1.1 (JSR 139) for pre-verification.
*
* <p>According to the CLDC specification, the sizes of some fields are not 16bit
* but 32bit if the code size is more than 64K or the number of the local variables
* is more than 64K. However, for the J2ME CLDC technology, they are always 16bit.
* The implementation of the StackMap class assumes they are 16bit.
*
* @see MethodInfo#doPreverify
* @see StackMapTable
* @since 3.12
*/
public class StackMap extends AttributeInfo {
/**
* The name of this attribute <code>"StackMap"</code>.
*/
public static final String tag = "StackMap";
/**
* Constructs a <code>stack_map</code> attribute.
*/
StackMap(ConstPool cp, byte[] newInfo) {
super(cp, tag, newInfo);
}
StackMap(ConstPool cp, int name_id, DataInputStream in)
throws IOException
{
super(cp, name_id, in);
}
/**
* Returns <code>number_of_entries</code>.
*/
public int numOfEntries() {
return ByteArray.readU16bit(info, 0);
}
/**
* <code>Top_variable_info.tag</code>.
*/
public static final int TOP = 0;
/**
* <code>Integer_variable_info.tag</code>.
*/
public static final int INTEGER = 1;
/**
* <code>Float_variable_info.tag</code>.
*/
public static final int FLOAT = 2;
/**
* <code>Double_variable_info.tag</code>.
*/
public static final int DOUBLE = 3;
/**
* <code>Long_variable_info.tag</code>.
*/
public static final int LONG = 4;
/**
* <code>Null_variable_info.tag</code>.
*/
public static final int NULL = 5;
/**
* <code>UninitializedThis_variable_info.tag</code>.
*/
public static final int THIS = 6;
/**
* <code>Object_variable_info.tag</code>.
*/
public static final int OBJECT = 7;
/**
* <code>Uninitialized_variable_info.tag</code>.
*/
public static final int UNINIT = 8;
/**
* Makes a copy.
*/
public AttributeInfo copy(ConstPool newCp, Map<String, String> classnames) {
Copier copier = new Copier(this, newCp, classnames);
copier.visit();
return copier.getStackMap();
}
/**
* A code walker for a StackMap attribute.
*/
public static class Walker {
byte[] info;
/**
* Constructs a walker.
*/
public Walker(StackMap sm) {
info = sm.get();
}
/**
* Visits each entry of the stack map frames.
*/
public void visit() {
int num = ByteArray.readU16bit(info, 0);
int pos = 2;
for (int i = 0; i < num; i++) {
int offset = ByteArray.readU16bit(info, pos);
int numLoc = ByteArray.readU16bit(info, pos + 2);
pos = locals(pos + 4, offset, numLoc);
int numStack = ByteArray.readU16bit(info, pos);
pos = stack(pos + 2, offset, numStack);
}
}
/**
* Invoked when <code>locals</code> of <code>stack_map_frame</code>
* is visited.
*/
public int locals(int pos, int offset, int num) {
return typeInfoArray(pos, offset, num, true);
}
/**
* Invoked when <code>stack</code> of <code>stack_map_frame</code>
* is visited.
*/
public int stack(int pos, int offset, int num) {
return typeInfoArray(pos, offset, num, false);
}
/**
* Invoked when an array of <code>verification_type_info</code> is
* visited.
*
* @param num the number of elements.
* @param isLocals true if this array is for <code>locals</code>.
* false if it is for <code>stack</code>.
*/
public int typeInfoArray(int pos, int offset, int num, boolean isLocals) {
for (int k = 0; k < num; k++)
pos = typeInfoArray2(k, pos);
return pos;
}
int typeInfoArray2(int k, int pos) {
byte tag = info[pos];
if (tag == OBJECT) {
int clazz = ByteArray.readU16bit(info, pos + 1);
objectVariable(pos, clazz);
pos += 3;
}
else if (tag == UNINIT) {
int offsetOfNew = ByteArray.readU16bit(info, pos + 1);
uninitialized(pos, offsetOfNew);
pos += 3;
}
else {
typeInfo(pos, tag);
pos++;
}
return pos;
}
/**
* Invoked when an element of <code>verification_type_info</code>
* (except <code>Object_variable_info</code> and
* <code>Uninitialized_variable_info</code>) is visited.
*/
public void typeInfo(int pos, byte tag) {}
/**
* Invoked when an element of type <code>Object_variable_info</code>
* is visited.
*/
public void objectVariable(int pos, int clazz) {}
/**
* Invoked when an element of type <code>Uninitialized_variable_info</code>
* is visited.
*/
public void uninitialized(int pos, int offset) {}
}
static class Copier extends Walker {
byte[] dest;
ConstPool srcCp, destCp;
Map<String, String> classnames;
Copier(StackMap map, ConstPool newCp, Map<String, String> classnames) {
super(map);
srcCp = map.getConstPool();
dest = new byte[info.length];
destCp = newCp;
this.classnames = classnames;
}
public void visit() {
int num = ByteArray.readU16bit(info, 0);
ByteArray.write16bit(num, dest, 0);
super.visit();
}
public int locals(int pos, int offset, int num) {
ByteArray.write16bit(offset, dest, pos - 4);
return super.locals(pos, offset, num);
}
public int typeInfoArray(int pos, int offset, int num, boolean isLocals) {
ByteArray.write16bit(num, dest, pos - 2);
return super.typeInfoArray(pos, offset, num, isLocals);
}
public void typeInfo(int pos, byte tag) {
dest[pos] = tag;
}
public void objectVariable(int pos, int clazz) {
dest[pos] = OBJECT;
int newClazz = srcCp.copy(clazz, destCp, classnames);
ByteArray.write16bit(newClazz, dest, pos + 1);
}
public void uninitialized(int pos, int offset) {
dest[pos] = UNINIT;
ByteArray.write16bit(offset, dest, pos + 1);
}
public StackMap getStackMap() {
return new StackMap(destCp, dest);
}
}
/**
* Updates this stack map table when a new local variable is inserted
* for a new parameter.
*
* @param index the index of the added local variable.
* @param tag the type tag of that local variable.
* It is available by <code>StackMapTable.typeTagOf(char)</code>.
* @param classInfo the index of the <code>CONSTANT_Class_info</code> structure
* in a constant pool table. This should be zero unless the tag
* is <code>ITEM_Object</code>.
*
* @see javassist.CtBehavior#addParameter(javassist.CtClass)
* @see StackMapTable#typeTagOf(char)
* @see ConstPool
*/
public void insertLocal(int index, int tag, int classInfo)
throws BadBytecode
{
byte[] data = new InsertLocal(this, index, tag, classInfo).doit();
this.set(data);
}
static class SimpleCopy extends Walker {
Writer writer;
SimpleCopy(StackMap map) {
super(map);
writer = new Writer();
}
byte[] doit() {
visit();
return writer.toByteArray();
}
public void visit() {
int num = ByteArray.readU16bit(info, 0);
writer.write16bit(num);
super.visit();
}
public int locals(int pos, int offset, int num) {
writer.write16bit(offset);
return super.locals(pos, offset, num);
}
public int typeInfoArray(int pos, int offset, int num, boolean isLocals) {
writer.write16bit(num);
return super.typeInfoArray(pos, offset, num, isLocals);
}
public void typeInfo(int pos, byte tag) {
writer.writeVerifyTypeInfo(tag, 0);
}
public void objectVariable(int pos, int clazz) {
writer.writeVerifyTypeInfo(OBJECT, clazz);
}
public void uninitialized(int pos, int offset) {
writer.writeVerifyTypeInfo(UNINIT, offset);
}
}
static class InsertLocal extends SimpleCopy {
private int varIndex;
private int varTag, varData;
InsertLocal(StackMap map, int varIndex, int varTag, int varData) {
super(map);
this.varIndex = varIndex;
this.varTag = varTag;
this.varData = varData;
}
public int typeInfoArray(int pos, int offset, int num, boolean isLocals) {
if (!isLocals || num < varIndex)
return super.typeInfoArray(pos, offset, num, isLocals);
writer.write16bit(num + 1);
for (int k = 0; k < num; k++) {
if (k == varIndex)
writeVarTypeInfo();
pos = typeInfoArray2(k, pos);
}
if (num == varIndex)
writeVarTypeInfo();
return pos;
}
private void writeVarTypeInfo() {
if (varTag == OBJECT)
writer.writeVerifyTypeInfo(OBJECT, varData);
else if (varTag == UNINIT)
writer.writeVerifyTypeInfo(UNINIT, varData);
else
writer.writeVerifyTypeInfo(varTag, 0);
}
}
void shiftPc(int where, int gapSize, boolean exclusive)
throws BadBytecode
{
new Shifter(this, where, gapSize, exclusive).visit();
}
static class Shifter extends Walker {
private int where, gap;
private boolean exclusive;
public Shifter(StackMap smt, int where, int gap, boolean exclusive) {
super(smt);
this.where = where;
this.gap = gap;
this.exclusive = exclusive;
}
public int locals(int pos, int offset, int num) {
if (exclusive ? where <= offset : where < offset)
ByteArray.write16bit(offset + gap, info, pos - 4);
return super.locals(pos, offset, num);
}
}
/**
* Undocumented method. Do not use; internal-use only.
*
* <p>This method is for javassist.convert.TransformNew.
* It is called to update the stack map when
* the NEW opcode (and the following DUP) is removed.
*
* @param where the position of the removed NEW opcode.
*/
public void removeNew(int where) throws CannotCompileException {
byte[] data = new NewRemover(this, where).doit();
this.set(data);
}
static class NewRemover extends SimpleCopy {
int posOfNew;
NewRemover(StackMap map, int where) {
super(map);
posOfNew = where;
}
public int stack(int pos, int offset, int num) {
return stackTypeInfoArray(pos, offset, num);
}
private int stackTypeInfoArray(int pos, int offset, int num) {
int p = pos;
int count = 0;
for (int k = 0; k < num; k++) {
byte tag = info[p];
if (tag == OBJECT)
p += 3;
else if (tag == UNINIT) {
int offsetOfNew = ByteArray.readU16bit(info, p + 1);
if (offsetOfNew == posOfNew)
count++;
p += 3;
}
else
p++;
}
writer.write16bit(num - count);
for (int k = 0; k < num; k++) {
byte tag = info[pos];
if (tag == OBJECT) {
int clazz = ByteArray.readU16bit(info, pos + 1);
objectVariable(pos, clazz);
pos += 3;
}
else if (tag == UNINIT) {
int offsetOfNew = ByteArray.readU16bit(info, pos + 1);
if (offsetOfNew != posOfNew)
uninitialized(pos, offsetOfNew);
pos += 3;
}
else {
typeInfo(pos, tag);
pos++;
}
}
return pos;
}
}
/**
* Prints this stack map.
*/
public void print(java.io.PrintWriter out) {
new Printer(this, out).print();
}
static class Printer extends Walker {
private java.io.PrintWriter writer;
public Printer(StackMap map, java.io.PrintWriter out) {
super(map);
writer = out;
}
public void print() {
int num = ByteArray.readU16bit(info, 0);
writer.println(num + " entries");
visit();
}
public int locals(int pos, int offset, int num) {
writer.println(" * offset " + offset);
return super.locals(pos, offset, num);
}
}
/**
* Internal use only.
*/
public static class Writer {
// see javassist.bytecode.stackmap.MapMaker
private ByteArrayOutputStream output;
/**
* Constructs a writer.
*/
public Writer() {
output = new ByteArrayOutputStream();
}
/**
* Converts the written data into a byte array.
*/
public byte[] toByteArray() {
return output.toByteArray();
}
/**
* Converts to a <code>StackMap</code> attribute.
*/
public StackMap toStackMap(ConstPool cp) {
return new StackMap(cp, output.toByteArray());
}
/**
* Writes a <code>union verification_type_info</code> value.
*
* @param data <code>cpool_index</code> or <code>offset</code>.
*/
public void writeVerifyTypeInfo(int tag, int data) {
output.write(tag);
if (tag == StackMap.OBJECT || tag == StackMap.UNINIT)
write16bit(data);
}
/**
* Writes a 16bit value.
*/
public void write16bit(int value) {
output.write((value >>> 8) & 0xff);
output.write(value & 0xff);
}
}
}
| apache-2.0 |
cljohnso/Rainfall-core | src/main/java/io/rainfall/statistics/StatisticsHolder.java | 1134 | /*
* Copyright 2014 Aurélien Broszniowski
*
* 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 io.rainfall.statistics;
import org.HdrHistogram.Histogram;
import java.util.Set;
/**
* @author Aurelien Broszniowski
*/
public interface StatisticsHolder<E extends Enum<E>> {
Enum<E>[] getResultsReported();
Set<String> getStatisticsKeys();
Statistics<E> getStatistics(String name);
Histogram fetchHistogram(final Enum<E> result);
void reset();
long getCurrentTps(Enum result);
void record(String name, long responseTimeInNs, Enum result);
void increaseAssertionsErrorsCount(String name);
}
| apache-2.0 |
willmorejg/net.ljcomputing.mail | src/main/java/net/ljcomputing/mail/domain/Email.java | 4227 | /**
Copyright 2017, James G. Willmore
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.ljcomputing.mail.domain;
import java.util.LinkedList;
import java.util.List;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
/**
* Email domain.
*
* @author James G. Willmore
*
*/
public class Email {
/** The FROM addresses. */
private final List<InternetAddress> from = new LinkedList<InternetAddress>();
/** The TO addresses. */
private final List<InternetAddress> to = new LinkedList<InternetAddress>();
/** The CC addresses. */
private final List<InternetAddress> cc = new LinkedList<InternetAddress>();
/** The BCC addresses. */
private final List<InternetAddress> bcc = new LinkedList<InternetAddress>();
/** The subject line of the email. */
private String subject;
/**
* Instantiates a new email.
*
* @param message the message
* @throws MessagingException the messaging exception
*/
public Email(final Message message) throws MessagingException {
addFrom(message.getFrom());
addTo(message.getRecipients(RecipientType.TO));
addCc(message.getRecipients(RecipientType.CC));
addBcc(message.getRecipients(RecipientType.BCC));
this.subject = message.getSubject();
}
/**
* Adds the address to list.
*
* @param list the list
* @param addresses the addresses
* @throws AddressException the address exception
*/
private void addAddressToList(final List<InternetAddress> list, final Address ... addresses) throws AddressException {
if (addresses != null) {
for (int a = 0; a < addresses.length; a++) {
list.add((InternetAddress) addresses[a]);
}
}
}
/**
* Adds the FROM addresses.
*
* @param addresses the addresses
* @throws AddressException the address exception
*/
public void addFrom(final Address ... addresses) throws AddressException {
addAddressToList(from, addresses);
}
/**
* Gets the FROM addresses.
*
* @return the from
*/
public List<InternetAddress> getFrom() {
return from;
}
/**
* Adds the TO addresses.
*
* @param addresses the addresses
* @throws AddressException the address exception
*/
public void addTo(final Address ... addresses) throws AddressException {
addAddressToList(to, addresses);
}
/**
* Gets the TO addresses.
*
* @return the to
*/
public List<InternetAddress> getTo() {
return to;
}
/**
* Adds the CC addresses.
*
* @param addresses the addresses
* @throws AddressException the address exception
*/
public void addCc(final Address ... addresses) throws AddressException {
addAddressToList(cc, addresses);
}
/**
* Gets the CC addresses.
*
* @return the cc
*/
public List<InternetAddress> getCc() {
return cc;
}
/**
* Adds the BCC addresses.
*
* @param addresses the addresses
* @throws AddressException the address exception
*/
public void addBcc(final Address ... addresses) throws AddressException {
addAddressToList(bcc, addresses);
}
/**
* Gets the BCC addresses.
*
* @return the bcc
*/
public List<InternetAddress> getBcc() {
return bcc;
}
/**
* Gets subject line of the email.
*
* @return the subject
*/
public String getSubject() {
return subject;
}
@Override
public String toString() {
return "Email [from=" + from + ", to=" + to + ", cc=" + cc + ", bcc=" + bcc + ", subject="
+ subject + "]";
}
}
| apache-2.0 |
breakpoint-au/Hedron | hedron-daogen/src/main/java/au/com/breakpoint/hedron/daogen/AttributeSet.java | 7447 | // __________________________________
// ______| Copyright 2008-2015 |______
// \ | Breakpoint Pty Limited | /
// \ | http://www.breakpoint.com.au | /
// / |__________________________________| \
// /_________/ \_________\
//
// 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 au.com.breakpoint.hedron.daogen;
import java.util.ArrayList;
import java.util.List;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import au.com.breakpoint.hedron.core.context.ThreadContext;
import au.com.breakpoint.hedron.daogen.Util.EnumString;
public class AttributeSet
{
public AttributeSet (final Node node)
{
m_node = node;
}
public boolean getAttributeBoolean (final String name)
{
final String s = getAttributeString (name);
return parseBoolString (s);
}
public boolean getAttributeBoolean (final String name, final boolean defaultValue)
{
final String s = getAttributeString (name, defaultValue ? Util.STRING_YES : Util.STRING_NO);
return parseBoolString (s);
}
public double getAttributeDouble (final String name)
{
final String s = getAttributeString (name);
return Double.parseDouble (s);
}
public double getAttributeDouble (final String name, final double defaultValue)
{
final String s = getAttributeString (name, String.valueOf (defaultValue));
return Double.parseDouble (s);
}
public <T extends Enum<T>> T getAttributeEnum (final Class<T> enumType, final String value)
{
return Enum.valueOf (enumType, value);
}
public <T> T getAttributeEnum (final String name, final EnumString[] enumStrings)
{
final String s = getAttributeString (name); // must exist
// Translate the string to the enum name.
T e = null;
for (int i = 0; e == null && i < enumStrings.length; ++i)
{
final EnumString enumString = enumStrings[i];
if (enumString.m_enumString.equals (s))
{
@SuppressWarnings ("unchecked")
final T t = (T) enumString.m_enumValueEnum;
e = t;
}
}
return e;
}
public int getAttributeEnum (final String name, final EnumString[] enumStrings, final int defaultValue)
{
final String s = getAttributeString (name, null); // can be absent
// attribute match known values
return (s == null ? defaultValue : Util.decodeEnum (s, enumStrings, true));
}
public int getAttributeEnumInt (final String name, final EnumString[] enumStrings)
{
final String s = getAttributeString (name); // must exist
return Util.decodeEnum (s, enumStrings, true); // attribute match known values
}
public int getAttributeInt (final String name)
{
final String s = getAttributeString (name);
return Integer.parseInt (s);
}
public int getAttributeInt (final String name, final int defaultValue)
{
final String s = getAttributeString (name, String.valueOf (defaultValue));
return Integer.parseInt (s);
}
public long getAttributeLong (final String name)
{
final String s = getAttributeString (name);
return Long.parseLong (s);
}
public long getAttributeLong (final String name, final long defaultValue)
{
final String s = getAttributeString (name, String.valueOf (defaultValue));
return Long.parseLong (s);
}
public String getAttributeString (final String name)
{
m_handledAttributeNames.add (name);
final NamedNodeMap attributes = m_node.getAttributes ();
final Node n = attributes.getNamedItem (name);
ThreadContext.assertError (n != null, "Missing mandatory attribute '%s' for XML element '%s'", name,
m_node.getNodeName ());
return n.getNodeValue ();
}
public String getAttributeString (final String name, final String defaultValue)
{
m_handledAttributeNames.add (name);
final NamedNodeMap attributes = m_node.getAttributes ();
final Node n = attributes.getNamedItem (name);
return n == null ? defaultValue : n.getNodeValue ();
}
public void validate ()
{
final NamedNodeMap attributes = m_node.getAttributes ();
// Check that each attribute is allowable.
for (int i = 0; i < attributes.getLength (); ++i)
{
final Node attribute = attributes.item (i);
final String attributeName = attribute.getNodeName ();
final Object lazyString = new Object ()
{
@Override
public String toString ()
{
final Node parentNode = m_node.getParentNode ();
return String.format ("Unknown attribute '%s' for XML element:%n %s%nparent is%n %s",
attributeName, formatNode (m_node), parentNode == null ? "(none)" : formatNode (parentNode));
}
private String formatNode (final Node node)
{
final StringBuilder sb = new StringBuilder ();
final NamedNodeMap as = node.getAttributes ();
// Check that each attribute is allowable.
for (int j = 0; j < as.getLength (); ++j)
{
if (j > 0)
{
sb.append (" ");
}
final Node a = as.item (j);
sb.append (a.getNodeName ());
sb.append ("='");
sb.append (a.getNodeValue ());
sb.append ("'");
}
return String.format ("<%s %s>", node.getNodeName (), sb);
}
};
ThreadContext.assertError (hasMatchingString (m_handledAttributeNames, attributeName), "%s", lazyString);
}
}
public static boolean parseBoolString (final String s)
{
ThreadContext.assertError (s.equals (Util.STRING_YES) || s.equals (Util.STRING_NO),
"Unrecognised boolean value %s should be %s or %s", s, Util.STRING_YES, Util.STRING_NO);
return s.equals (Util.STRING_YES);
}
private static boolean hasMatchingString (final List<String> handledAttributeNames, final String attributeName)
{
boolean has = false;
for (final String s : handledAttributeNames)
{
has = has || s.equals (attributeName);
}
return has;
}
private final List<String> m_handledAttributeNames = new ArrayList<String> ();
private final Node m_node;
}
| apache-2.0 |
smith1302/DM-Assassins | myProfile.php | 8662 | <?php
/*Dance Marathon Assassins
Copyright 2012 Dance Marathon at the University of Florida
This product includes software developed by the Dance Marathon at the University of Florida 2013 Technology Team.
The following developers contributed to this project:
Matthew Gerstman
Dance Marathon at the University of Florida is a year-long effort that culminates in a 26.2-hour event where over 800 students stay awake and on their feet to symbolize the obstacles faced by children with serious illnesses or injuries. The event raises money for Shands Hospital for Children, your local Children’s Miracle Network Hospital, in Gainesville, FL. Our contributions are used where they are needed the most, including, but not limited to, purchasing life-saving medial equipment, funding pediatric research, and purchasing diversionary activities for the kids.
For more information you can visit http://floridadm.org
This software includes the following open source plugins listed below:
Title: HTML5 Image Uploader
Link: http://tutorialzine.com/2011/09/html5-file-upload-jquery-php/
Copyright: None, but we're nice and want to give credit.
Title: Character Count Plugin - jQuery plugin
Link: http://cssglobe.com/post/7161/jquery-plugin-simplest-twitterlike-dynamic-character-count-for-textareas
Copyright: Copyright (c) 2009 Alen Grakalic (http://cssglobe.com)
License: MIT License (http://www.opensource.org/licenses/mit-license.php)
Title: Mobile Detect
Link: http://mobiledetect.net
License: http://www.opensource.org/licenses/mit-license.php
Title: PHPMailer - PHP email class
Link: https://code.google.com/a/apache-extras.org/p/phpmailer/
Copyright: Copyright (c) 2010-2012, Jim Jagielski. All Rights Reserved.
License: LGPL http://www.gnu.org/copyleft/lesser.html
Title: TableSorter 2.0 - Client-side table sorting with ease!
Link: http://tablesorter.com
Copyright: Copyright (c) 2007 Christian Bach
License: http://www.opensource.org/licenses/mit-license.php
Title: twitteroauth
Link: https://github.com/abraham/twitteroauth
Copyright: Copyright (c) 2009 Abraham Williams
License: http://www.opensource.org/licenses/mit-license.php*/
include('checkSession.php');
check();
include('getTeam.php');
?>
<html>
<head>
<link href="styles.css" rel="stylesheet" type="text/css" />
<link href='http://fonts.googleapis.com/css?family=Kameron:700,400' rel='stylesheet' type='text/css'>
<title>My Profile</title>
</head>
<script language="Javascript">//check if password and confirmation are equal
function validate(form) {
var elem = form.elements;
if(elem.new.value != elem.confirm.value) {
alert('Please check your password; the confirmation entry does not match.');
return false;
}
return true;
}
</script>
<body>
<div class="container">
<?php
include("dashboard.php");
printDashboard(1);
$username = $_SESSION['username'];
$_SESSION['workingUser'] = $username;
$usertype = $_SESSION['usertype'];
$table = "users";
//standard dashboard output
include_once("connectToServer.php");
connect();
//get personal info
$result = mysql_query("SELECT * FROM $table where username = '$username'");
$pin = mysql_result($result,0,"pin");
$name = mysql_result($result,0,"name");
$facebook = mysql_result($result,0,"facebook");
$twitter = mysql_result($result,0,"twitter");
$email = mysql_result($result,0,"email");
$team = mysql_result($result,0,"team");
$kills = mysql_result($result,0,"killed");
$img = mysql_result($result,0,"img");
$outputTeam = getTeam($team);
//output personal info
?>
<h1>Your Profile</h1>
<p>Pin Number: <?php echo $pin; ?><br />
Kills: <?php echo $kills; ?> </p>
<img src="editprofile.png" class="editPen" /><p class="item" id="name">Name: <span id="nameSpan"><?php echo $name; ?></span></p><input type="text" id="nameInput" class="profileEdit" category="name" value="<?php echo $name; ?>"/><br /><img src="editprofile.png" class="editPen" /><p class="item" id="facebook">Facebook: http://facebook.com/<span id="facebookSpan"><?php echo $facebook?></span></p><input type="text" id="facebookInput" class="profileEdit" category="facebook" value="<?php echo $facebook; ?>"/><br />
<img src="editprofile.png" class="editPen" /><p class="item" id="twitter">Twitter: http://twitter.com/<span id="twitterSpan"><?php echo $twitter?></span></p><input type="text" id="twitterInput" class="profileEdit" category="twitter" value="<?php echo $twitter; ?>"/><br />
<img src="editprofile.png" class="editPen" /><p class="item" id="email">Email: <span id="emailSpan"><?php echo $email?></span></p><input type="text" id="emailInput" class="profileEdit" category="email" value="<?php echo $email; ?>"/><br />
<img src="editprofile.png" class="editPen" /><p class="item" id="team">Team: <span id="teamSpan"><?php echo $outputTeam;?></span></p>
<select id="teamInput" category="team" class="profileEdit">
<option value=-5>No Team</option>
<option value=1>Art/Layout</option>
<option value=2>Community Events</option>
<option value=3>Dancer Relations</option>
<option value=4>Entertainment</option>
<option value=5>Family Relations</option>
<option value=6>Finance</option>
<option value=7>Hospitality</option>
<option value=8>Marketing</option>
<option value=9>Morale</option>
<option value=10>Operations</option>
<option value=11>Public Relations</option>
<option value=12>Recruitment</option>
<option value=13>Technology</option>
</select><br /><br />
<!--br ><br />To prevent cheating, we have disabled profile editing<br />
If any of the information above is incorrect, please contact your overall.</p><br /-->
<div id="dropbox">
<span class="message"><img class="overall_img" src="<?php if ($img) {echo "uploads/".$img;} else {echo "drophere.png";} ?>" /></i></span>
</div>
<!-- Including The jQuery Library -->
<script src="http://code.jquery.com/jquery-1.6.3.min.js"></script>
<!-- Including the HTML5 Uploader plugin -->
<script src="assets/js/jquery.filedrop.js"></script>
<!-- The main script file -->
<script src="assets/js/script.js"></script>
<?php
if ($img)
{
?><br /><h2>Drag an image on top of the old one to replace it</h2><?php
}
else
{?>
<br /><h2>if you have any issues uploading your image, email your overall and they can do it for you.</h2>
<?php } ?>
<br />
</div>
<script type="text/javascript">
$('.item').live('mouseenter',
function(){
$(this).prev('.editPen').css("display","inline");
$(this).css('margin-left', '0px');
});
$('.item').live('mouseleave',
function(){
$(this).prev('.editPen').css("display","none");
$(this).css('margin-left', '17px');
});
$('.item').click(
function(){
var myId = $(this).attr('id');;
var spanType = $('#'+myId+'Span').is();
var value = $('#'+myId+'Span').text();
$('#'+myId+'Input').css("display", "inline").focus();
$('#'+myId+'Span').css("display", "none");
})
$('.profileEdit').keypress(function (e) {
if (e.which == 13) {
$(this).blur();
}
});
$('#teamInput').val(<?php echo $team; ?>);
$('.profileEdit').blur(function(){
console.log($(this));
var value = $(this).val();
var category = $(this).attr("category");
var text = $("#"+category+ "Input :selected").text();
$(this).css("display", "none");
if ($(this).is(':text'))
$("#"+category+"Span").text(value).css("display", "inline");
else
$("#"+category+"Span").text(text).css("display", "inline");
var data = {
"pin" : <?php echo $pin; ?>,
"column" : category,
"value" : value,
}
$.post('editField.php', data, function(output) { });
})
</script>
<?php
echo($_SESSION['status']);
unset($_SESSION['status']);
?>
</div>
<div class="footer">
<div class="footer_content">
A COPY OF THE OFFICIAL REGISTRATION AND FINANCIAL INFORMATION MAY BE OBTAINED FROM THE DIVISION OF CONSUMER SERVICES BY CALLING TOLL FREE 1-800-435-7352 WITHIN THE STATE. REGISTRATION DOES NOT IMPLY ENDORSEMENT, APPROVAL, OR RECOMMENDATION BY THE STATE. SHANDS TEACHING HOSPITAL AND CLINICS REGISTRATION NUMBER WITH THE STATE OF FLORIDA: SC01801<br />
<div class="footer_spacing">
<a href="http://www.health.ufl.edu/disclaimer.shtml">Disclaimer & Permitted Use</a> |
<a href="http://www.ufl.edu/disability/">Disability Services</a> |
<a href="https://security.health.ufl.edu">Security Policies</a> |
<a href="http://privacy.ufl.edu/privacystatement.html">UF Privacy Policy</a> |
<a href="http://www.shands.org/terms.asp">Shands Privacy Policy</a>
</div>
</div>
</div>
</div>
</body>
</html> | apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-secretsmanager/src/main/java/com/amazonaws/services/secretsmanager/model/DescribeSecretResult.java | 39579 | /*
* Copyright 2014-2019 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.secretsmanager.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/secretsmanager-2017-10-17/DescribeSecret" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeSecretResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* The ARN of the secret.
* </p>
*/
private String aRN;
/**
* <p>
* The user-provided friendly name of the secret.
* </p>
*/
private String name;
/**
* <p>
* The user-provided description of the secret.
* </p>
*/
private String description;
/**
* <p>
* The ARN or alias of the AWS KMS customer master key (CMK) that's used to encrypt the <code>SecretString</code> or
* <code>SecretBinary</code> fields in each version of the secret. If you don't provide a key, then Secrets Manager
* defaults to encrypting the secret fields with the default AWS KMS CMK (the one named
* <code>awssecretsmanager</code>) for this account.
* </p>
*/
private String kmsKeyId;
/**
* <p>
* Specifies whether automatic rotation is enabled for this secret.
* </p>
* <p>
* To enable rotation, use <a>RotateSecret</a> with <code>AutomaticallyRotateAfterDays</code> set to a value greater
* than 0. To disable rotation, use <a>CancelRotateSecret</a>.
* </p>
*/
private Boolean rotationEnabled;
/**
* <p>
* The ARN of a Lambda function that's invoked by Secrets Manager to rotate the secret either automatically per the
* schedule or manually by a call to <code>RotateSecret</code>.
* </p>
*/
private String rotationLambdaARN;
/**
* <p>
* A structure that contains the rotation configuration for this secret.
* </p>
*/
private RotationRulesType rotationRules;
/**
* <p>
* The most recent date and time that the Secrets Manager rotation process was successfully completed. This value is
* null if the secret has never rotated.
* </p>
*/
private java.util.Date lastRotatedDate;
/**
* <p>
* The last date and time that this secret was modified in any way.
* </p>
*/
private java.util.Date lastChangedDate;
/**
* <p>
* The last date that this secret was accessed. This value is truncated to midnight of the date and therefore shows
* only the date, not the time.
* </p>
*/
private java.util.Date lastAccessedDate;
/**
* <p>
* This value exists if the secret is scheduled for deletion. Some time after the specified date and time, Secrets
* Manager deletes the secret and all of its versions.
* </p>
* <p>
* If a secret is scheduled for deletion, then its details, including the encrypted secret information, is not
* accessible. To cancel a scheduled deletion and restore access, use <a>RestoreSecret</a>.
* </p>
*/
private java.util.Date deletedDate;
/**
* <p>
* The list of user-defined tags that are associated with the secret. To add tags to a secret, use
* <a>TagResource</a>. To remove tags, use <a>UntagResource</a>.
* </p>
*/
private java.util.List<Tag> tags;
/**
* <p>
* A list of all of the currently assigned <code>VersionStage</code> staging labels and the <code>VersionId</code>
* that each is attached to. Staging labels are used to keep track of the different versions during the rotation
* process.
* </p>
* <note>
* <p>
* A version that does not have any staging labels attached is considered deprecated and subject to deletion. Such
* versions are not included in this list.
* </p>
* </note>
*/
private java.util.Map<String, java.util.List<String>> versionIdsToStages;
private String owningService;
/**
* <p>
* The ARN of the secret.
* </p>
*
* @param aRN
* The ARN of the secret.
*/
public void setARN(String aRN) {
this.aRN = aRN;
}
/**
* <p>
* The ARN of the secret.
* </p>
*
* @return The ARN of the secret.
*/
public String getARN() {
return this.aRN;
}
/**
* <p>
* The ARN of the secret.
* </p>
*
* @param aRN
* The ARN of the secret.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeSecretResult withARN(String aRN) {
setARN(aRN);
return this;
}
/**
* <p>
* The user-provided friendly name of the secret.
* </p>
*
* @param name
* The user-provided friendly name of the secret.
*/
public void setName(String name) {
this.name = name;
}
/**
* <p>
* The user-provided friendly name of the secret.
* </p>
*
* @return The user-provided friendly name of the secret.
*/
public String getName() {
return this.name;
}
/**
* <p>
* The user-provided friendly name of the secret.
* </p>
*
* @param name
* The user-provided friendly name of the secret.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeSecretResult withName(String name) {
setName(name);
return this;
}
/**
* <p>
* The user-provided description of the secret.
* </p>
*
* @param description
* The user-provided description of the secret.
*/
public void setDescription(String description) {
this.description = description;
}
/**
* <p>
* The user-provided description of the secret.
* </p>
*
* @return The user-provided description of the secret.
*/
public String getDescription() {
return this.description;
}
/**
* <p>
* The user-provided description of the secret.
* </p>
*
* @param description
* The user-provided description of the secret.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeSecretResult withDescription(String description) {
setDescription(description);
return this;
}
/**
* <p>
* The ARN or alias of the AWS KMS customer master key (CMK) that's used to encrypt the <code>SecretString</code> or
* <code>SecretBinary</code> fields in each version of the secret. If you don't provide a key, then Secrets Manager
* defaults to encrypting the secret fields with the default AWS KMS CMK (the one named
* <code>awssecretsmanager</code>) for this account.
* </p>
*
* @param kmsKeyId
* The ARN or alias of the AWS KMS customer master key (CMK) that's used to encrypt the
* <code>SecretString</code> or <code>SecretBinary</code> fields in each version of the secret. If you don't
* provide a key, then Secrets Manager defaults to encrypting the secret fields with the default AWS KMS CMK
* (the one named <code>awssecretsmanager</code>) for this account.
*/
public void setKmsKeyId(String kmsKeyId) {
this.kmsKeyId = kmsKeyId;
}
/**
* <p>
* The ARN or alias of the AWS KMS customer master key (CMK) that's used to encrypt the <code>SecretString</code> or
* <code>SecretBinary</code> fields in each version of the secret. If you don't provide a key, then Secrets Manager
* defaults to encrypting the secret fields with the default AWS KMS CMK (the one named
* <code>awssecretsmanager</code>) for this account.
* </p>
*
* @return The ARN or alias of the AWS KMS customer master key (CMK) that's used to encrypt the
* <code>SecretString</code> or <code>SecretBinary</code> fields in each version of the secret. If you don't
* provide a key, then Secrets Manager defaults to encrypting the secret fields with the default AWS KMS CMK
* (the one named <code>awssecretsmanager</code>) for this account.
*/
public String getKmsKeyId() {
return this.kmsKeyId;
}
/**
* <p>
* The ARN or alias of the AWS KMS customer master key (CMK) that's used to encrypt the <code>SecretString</code> or
* <code>SecretBinary</code> fields in each version of the secret. If you don't provide a key, then Secrets Manager
* defaults to encrypting the secret fields with the default AWS KMS CMK (the one named
* <code>awssecretsmanager</code>) for this account.
* </p>
*
* @param kmsKeyId
* The ARN or alias of the AWS KMS customer master key (CMK) that's used to encrypt the
* <code>SecretString</code> or <code>SecretBinary</code> fields in each version of the secret. If you don't
* provide a key, then Secrets Manager defaults to encrypting the secret fields with the default AWS KMS CMK
* (the one named <code>awssecretsmanager</code>) for this account.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeSecretResult withKmsKeyId(String kmsKeyId) {
setKmsKeyId(kmsKeyId);
return this;
}
/**
* <p>
* Specifies whether automatic rotation is enabled for this secret.
* </p>
* <p>
* To enable rotation, use <a>RotateSecret</a> with <code>AutomaticallyRotateAfterDays</code> set to a value greater
* than 0. To disable rotation, use <a>CancelRotateSecret</a>.
* </p>
*
* @param rotationEnabled
* Specifies whether automatic rotation is enabled for this secret.</p>
* <p>
* To enable rotation, use <a>RotateSecret</a> with <code>AutomaticallyRotateAfterDays</code> set to a value
* greater than 0. To disable rotation, use <a>CancelRotateSecret</a>.
*/
public void setRotationEnabled(Boolean rotationEnabled) {
this.rotationEnabled = rotationEnabled;
}
/**
* <p>
* Specifies whether automatic rotation is enabled for this secret.
* </p>
* <p>
* To enable rotation, use <a>RotateSecret</a> with <code>AutomaticallyRotateAfterDays</code> set to a value greater
* than 0. To disable rotation, use <a>CancelRotateSecret</a>.
* </p>
*
* @return Specifies whether automatic rotation is enabled for this secret.</p>
* <p>
* To enable rotation, use <a>RotateSecret</a> with <code>AutomaticallyRotateAfterDays</code> set to a value
* greater than 0. To disable rotation, use <a>CancelRotateSecret</a>.
*/
public Boolean getRotationEnabled() {
return this.rotationEnabled;
}
/**
* <p>
* Specifies whether automatic rotation is enabled for this secret.
* </p>
* <p>
* To enable rotation, use <a>RotateSecret</a> with <code>AutomaticallyRotateAfterDays</code> set to a value greater
* than 0. To disable rotation, use <a>CancelRotateSecret</a>.
* </p>
*
* @param rotationEnabled
* Specifies whether automatic rotation is enabled for this secret.</p>
* <p>
* To enable rotation, use <a>RotateSecret</a> with <code>AutomaticallyRotateAfterDays</code> set to a value
* greater than 0. To disable rotation, use <a>CancelRotateSecret</a>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeSecretResult withRotationEnabled(Boolean rotationEnabled) {
setRotationEnabled(rotationEnabled);
return this;
}
/**
* <p>
* Specifies whether automatic rotation is enabled for this secret.
* </p>
* <p>
* To enable rotation, use <a>RotateSecret</a> with <code>AutomaticallyRotateAfterDays</code> set to a value greater
* than 0. To disable rotation, use <a>CancelRotateSecret</a>.
* </p>
*
* @return Specifies whether automatic rotation is enabled for this secret.</p>
* <p>
* To enable rotation, use <a>RotateSecret</a> with <code>AutomaticallyRotateAfterDays</code> set to a value
* greater than 0. To disable rotation, use <a>CancelRotateSecret</a>.
*/
public Boolean isRotationEnabled() {
return this.rotationEnabled;
}
/**
* <p>
* The ARN of a Lambda function that's invoked by Secrets Manager to rotate the secret either automatically per the
* schedule or manually by a call to <code>RotateSecret</code>.
* </p>
*
* @param rotationLambdaARN
* The ARN of a Lambda function that's invoked by Secrets Manager to rotate the secret either automatically
* per the schedule or manually by a call to <code>RotateSecret</code>.
*/
public void setRotationLambdaARN(String rotationLambdaARN) {
this.rotationLambdaARN = rotationLambdaARN;
}
/**
* <p>
* The ARN of a Lambda function that's invoked by Secrets Manager to rotate the secret either automatically per the
* schedule or manually by a call to <code>RotateSecret</code>.
* </p>
*
* @return The ARN of a Lambda function that's invoked by Secrets Manager to rotate the secret either automatically
* per the schedule or manually by a call to <code>RotateSecret</code>.
*/
public String getRotationLambdaARN() {
return this.rotationLambdaARN;
}
/**
* <p>
* The ARN of a Lambda function that's invoked by Secrets Manager to rotate the secret either automatically per the
* schedule or manually by a call to <code>RotateSecret</code>.
* </p>
*
* @param rotationLambdaARN
* The ARN of a Lambda function that's invoked by Secrets Manager to rotate the secret either automatically
* per the schedule or manually by a call to <code>RotateSecret</code>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeSecretResult withRotationLambdaARN(String rotationLambdaARN) {
setRotationLambdaARN(rotationLambdaARN);
return this;
}
/**
* <p>
* A structure that contains the rotation configuration for this secret.
* </p>
*
* @param rotationRules
* A structure that contains the rotation configuration for this secret.
*/
public void setRotationRules(RotationRulesType rotationRules) {
this.rotationRules = rotationRules;
}
/**
* <p>
* A structure that contains the rotation configuration for this secret.
* </p>
*
* @return A structure that contains the rotation configuration for this secret.
*/
public RotationRulesType getRotationRules() {
return this.rotationRules;
}
/**
* <p>
* A structure that contains the rotation configuration for this secret.
* </p>
*
* @param rotationRules
* A structure that contains the rotation configuration for this secret.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeSecretResult withRotationRules(RotationRulesType rotationRules) {
setRotationRules(rotationRules);
return this;
}
/**
* <p>
* The most recent date and time that the Secrets Manager rotation process was successfully completed. This value is
* null if the secret has never rotated.
* </p>
*
* @param lastRotatedDate
* The most recent date and time that the Secrets Manager rotation process was successfully completed. This
* value is null if the secret has never rotated.
*/
public void setLastRotatedDate(java.util.Date lastRotatedDate) {
this.lastRotatedDate = lastRotatedDate;
}
/**
* <p>
* The most recent date and time that the Secrets Manager rotation process was successfully completed. This value is
* null if the secret has never rotated.
* </p>
*
* @return The most recent date and time that the Secrets Manager rotation process was successfully completed. This
* value is null if the secret has never rotated.
*/
public java.util.Date getLastRotatedDate() {
return this.lastRotatedDate;
}
/**
* <p>
* The most recent date and time that the Secrets Manager rotation process was successfully completed. This value is
* null if the secret has never rotated.
* </p>
*
* @param lastRotatedDate
* The most recent date and time that the Secrets Manager rotation process was successfully completed. This
* value is null if the secret has never rotated.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeSecretResult withLastRotatedDate(java.util.Date lastRotatedDate) {
setLastRotatedDate(lastRotatedDate);
return this;
}
/**
* <p>
* The last date and time that this secret was modified in any way.
* </p>
*
* @param lastChangedDate
* The last date and time that this secret was modified in any way.
*/
public void setLastChangedDate(java.util.Date lastChangedDate) {
this.lastChangedDate = lastChangedDate;
}
/**
* <p>
* The last date and time that this secret was modified in any way.
* </p>
*
* @return The last date and time that this secret was modified in any way.
*/
public java.util.Date getLastChangedDate() {
return this.lastChangedDate;
}
/**
* <p>
* The last date and time that this secret was modified in any way.
* </p>
*
* @param lastChangedDate
* The last date and time that this secret was modified in any way.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeSecretResult withLastChangedDate(java.util.Date lastChangedDate) {
setLastChangedDate(lastChangedDate);
return this;
}
/**
* <p>
* The last date that this secret was accessed. This value is truncated to midnight of the date and therefore shows
* only the date, not the time.
* </p>
*
* @param lastAccessedDate
* The last date that this secret was accessed. This value is truncated to midnight of the date and therefore
* shows only the date, not the time.
*/
public void setLastAccessedDate(java.util.Date lastAccessedDate) {
this.lastAccessedDate = lastAccessedDate;
}
/**
* <p>
* The last date that this secret was accessed. This value is truncated to midnight of the date and therefore shows
* only the date, not the time.
* </p>
*
* @return The last date that this secret was accessed. This value is truncated to midnight of the date and
* therefore shows only the date, not the time.
*/
public java.util.Date getLastAccessedDate() {
return this.lastAccessedDate;
}
/**
* <p>
* The last date that this secret was accessed. This value is truncated to midnight of the date and therefore shows
* only the date, not the time.
* </p>
*
* @param lastAccessedDate
* The last date that this secret was accessed. This value is truncated to midnight of the date and therefore
* shows only the date, not the time.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeSecretResult withLastAccessedDate(java.util.Date lastAccessedDate) {
setLastAccessedDate(lastAccessedDate);
return this;
}
/**
* <p>
* This value exists if the secret is scheduled for deletion. Some time after the specified date and time, Secrets
* Manager deletes the secret and all of its versions.
* </p>
* <p>
* If a secret is scheduled for deletion, then its details, including the encrypted secret information, is not
* accessible. To cancel a scheduled deletion and restore access, use <a>RestoreSecret</a>.
* </p>
*
* @param deletedDate
* This value exists if the secret is scheduled for deletion. Some time after the specified date and time,
* Secrets Manager deletes the secret and all of its versions.</p>
* <p>
* If a secret is scheduled for deletion, then its details, including the encrypted secret information, is
* not accessible. To cancel a scheduled deletion and restore access, use <a>RestoreSecret</a>.
*/
public void setDeletedDate(java.util.Date deletedDate) {
this.deletedDate = deletedDate;
}
/**
* <p>
* This value exists if the secret is scheduled for deletion. Some time after the specified date and time, Secrets
* Manager deletes the secret and all of its versions.
* </p>
* <p>
* If a secret is scheduled for deletion, then its details, including the encrypted secret information, is not
* accessible. To cancel a scheduled deletion and restore access, use <a>RestoreSecret</a>.
* </p>
*
* @return This value exists if the secret is scheduled for deletion. Some time after the specified date and time,
* Secrets Manager deletes the secret and all of its versions.</p>
* <p>
* If a secret is scheduled for deletion, then its details, including the encrypted secret information, is
* not accessible. To cancel a scheduled deletion and restore access, use <a>RestoreSecret</a>.
*/
public java.util.Date getDeletedDate() {
return this.deletedDate;
}
/**
* <p>
* This value exists if the secret is scheduled for deletion. Some time after the specified date and time, Secrets
* Manager deletes the secret and all of its versions.
* </p>
* <p>
* If a secret is scheduled for deletion, then its details, including the encrypted secret information, is not
* accessible. To cancel a scheduled deletion and restore access, use <a>RestoreSecret</a>.
* </p>
*
* @param deletedDate
* This value exists if the secret is scheduled for deletion. Some time after the specified date and time,
* Secrets Manager deletes the secret and all of its versions.</p>
* <p>
* If a secret is scheduled for deletion, then its details, including the encrypted secret information, is
* not accessible. To cancel a scheduled deletion and restore access, use <a>RestoreSecret</a>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeSecretResult withDeletedDate(java.util.Date deletedDate) {
setDeletedDate(deletedDate);
return this;
}
/**
* <p>
* The list of user-defined tags that are associated with the secret. To add tags to a secret, use
* <a>TagResource</a>. To remove tags, use <a>UntagResource</a>.
* </p>
*
* @return The list of user-defined tags that are associated with the secret. To add tags to a secret, use
* <a>TagResource</a>. To remove tags, use <a>UntagResource</a>.
*/
public java.util.List<Tag> getTags() {
return tags;
}
/**
* <p>
* The list of user-defined tags that are associated with the secret. To add tags to a secret, use
* <a>TagResource</a>. To remove tags, use <a>UntagResource</a>.
* </p>
*
* @param tags
* The list of user-defined tags that are associated with the secret. To add tags to a secret, use
* <a>TagResource</a>. To remove tags, use <a>UntagResource</a>.
*/
public void setTags(java.util.Collection<Tag> tags) {
if (tags == null) {
this.tags = null;
return;
}
this.tags = new java.util.ArrayList<Tag>(tags);
}
/**
* <p>
* The list of user-defined tags that are associated with the secret. To add tags to a secret, use
* <a>TagResource</a>. To remove tags, use <a>UntagResource</a>.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setTags(java.util.Collection)} or {@link #withTags(java.util.Collection)} if you want to override the
* existing values.
* </p>
*
* @param tags
* The list of user-defined tags that are associated with the secret. To add tags to a secret, use
* <a>TagResource</a>. To remove tags, use <a>UntagResource</a>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeSecretResult withTags(Tag... tags) {
if (this.tags == null) {
setTags(new java.util.ArrayList<Tag>(tags.length));
}
for (Tag ele : tags) {
this.tags.add(ele);
}
return this;
}
/**
* <p>
* The list of user-defined tags that are associated with the secret. To add tags to a secret, use
* <a>TagResource</a>. To remove tags, use <a>UntagResource</a>.
* </p>
*
* @param tags
* The list of user-defined tags that are associated with the secret. To add tags to a secret, use
* <a>TagResource</a>. To remove tags, use <a>UntagResource</a>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeSecretResult withTags(java.util.Collection<Tag> tags) {
setTags(tags);
return this;
}
/**
* <p>
* A list of all of the currently assigned <code>VersionStage</code> staging labels and the <code>VersionId</code>
* that each is attached to. Staging labels are used to keep track of the different versions during the rotation
* process.
* </p>
* <note>
* <p>
* A version that does not have any staging labels attached is considered deprecated and subject to deletion. Such
* versions are not included in this list.
* </p>
* </note>
*
* @return A list of all of the currently assigned <code>VersionStage</code> staging labels and the
* <code>VersionId</code> that each is attached to. Staging labels are used to keep track of the different
* versions during the rotation process.</p> <note>
* <p>
* A version that does not have any staging labels attached is considered deprecated and subject to
* deletion. Such versions are not included in this list.
* </p>
*/
public java.util.Map<String, java.util.List<String>> getVersionIdsToStages() {
return versionIdsToStages;
}
/**
* <p>
* A list of all of the currently assigned <code>VersionStage</code> staging labels and the <code>VersionId</code>
* that each is attached to. Staging labels are used to keep track of the different versions during the rotation
* process.
* </p>
* <note>
* <p>
* A version that does not have any staging labels attached is considered deprecated and subject to deletion. Such
* versions are not included in this list.
* </p>
* </note>
*
* @param versionIdsToStages
* A list of all of the currently assigned <code>VersionStage</code> staging labels and the
* <code>VersionId</code> that each is attached to. Staging labels are used to keep track of the different
* versions during the rotation process.</p> <note>
* <p>
* A version that does not have any staging labels attached is considered deprecated and subject to deletion.
* Such versions are not included in this list.
* </p>
*/
public void setVersionIdsToStages(java.util.Map<String, java.util.List<String>> versionIdsToStages) {
this.versionIdsToStages = versionIdsToStages;
}
/**
* <p>
* A list of all of the currently assigned <code>VersionStage</code> staging labels and the <code>VersionId</code>
* that each is attached to. Staging labels are used to keep track of the different versions during the rotation
* process.
* </p>
* <note>
* <p>
* A version that does not have any staging labels attached is considered deprecated and subject to deletion. Such
* versions are not included in this list.
* </p>
* </note>
*
* @param versionIdsToStages
* A list of all of the currently assigned <code>VersionStage</code> staging labels and the
* <code>VersionId</code> that each is attached to. Staging labels are used to keep track of the different
* versions during the rotation process.</p> <note>
* <p>
* A version that does not have any staging labels attached is considered deprecated and subject to deletion.
* Such versions are not included in this list.
* </p>
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeSecretResult withVersionIdsToStages(java.util.Map<String, java.util.List<String>> versionIdsToStages) {
setVersionIdsToStages(versionIdsToStages);
return this;
}
public DescribeSecretResult addVersionIdsToStagesEntry(String key, java.util.List<String> value) {
if (null == this.versionIdsToStages) {
this.versionIdsToStages = new java.util.HashMap<String, java.util.List<String>>();
}
if (this.versionIdsToStages.containsKey(key))
throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided.");
this.versionIdsToStages.put(key, value);
return this;
}
/**
* Removes all the entries added into VersionIdsToStages.
*
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeSecretResult clearVersionIdsToStagesEntries() {
this.versionIdsToStages = null;
return this;
}
/**
* @param owningService
*/
public void setOwningService(String owningService) {
this.owningService = owningService;
}
/**
* @return
*/
public String getOwningService() {
return this.owningService;
}
/**
* @param owningService
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeSecretResult withOwningService(String owningService) {
setOwningService(owningService);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getARN() != null)
sb.append("ARN: ").append(getARN()).append(",");
if (getName() != null)
sb.append("Name: ").append(getName()).append(",");
if (getDescription() != null)
sb.append("Description: ").append(getDescription()).append(",");
if (getKmsKeyId() != null)
sb.append("KmsKeyId: ").append(getKmsKeyId()).append(",");
if (getRotationEnabled() != null)
sb.append("RotationEnabled: ").append(getRotationEnabled()).append(",");
if (getRotationLambdaARN() != null)
sb.append("RotationLambdaARN: ").append(getRotationLambdaARN()).append(",");
if (getRotationRules() != null)
sb.append("RotationRules: ").append(getRotationRules()).append(",");
if (getLastRotatedDate() != null)
sb.append("LastRotatedDate: ").append(getLastRotatedDate()).append(",");
if (getLastChangedDate() != null)
sb.append("LastChangedDate: ").append(getLastChangedDate()).append(",");
if (getLastAccessedDate() != null)
sb.append("LastAccessedDate: ").append(getLastAccessedDate()).append(",");
if (getDeletedDate() != null)
sb.append("DeletedDate: ").append(getDeletedDate()).append(",");
if (getTags() != null)
sb.append("Tags: ").append(getTags()).append(",");
if (getVersionIdsToStages() != null)
sb.append("VersionIdsToStages: ").append(getVersionIdsToStages()).append(",");
if (getOwningService() != null)
sb.append("OwningService: ").append(getOwningService());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof DescribeSecretResult == false)
return false;
DescribeSecretResult other = (DescribeSecretResult) obj;
if (other.getARN() == null ^ this.getARN() == null)
return false;
if (other.getARN() != null && other.getARN().equals(this.getARN()) == false)
return false;
if (other.getName() == null ^ this.getName() == null)
return false;
if (other.getName() != null && other.getName().equals(this.getName()) == false)
return false;
if (other.getDescription() == null ^ this.getDescription() == null)
return false;
if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false)
return false;
if (other.getKmsKeyId() == null ^ this.getKmsKeyId() == null)
return false;
if (other.getKmsKeyId() != null && other.getKmsKeyId().equals(this.getKmsKeyId()) == false)
return false;
if (other.getRotationEnabled() == null ^ this.getRotationEnabled() == null)
return false;
if (other.getRotationEnabled() != null && other.getRotationEnabled().equals(this.getRotationEnabled()) == false)
return false;
if (other.getRotationLambdaARN() == null ^ this.getRotationLambdaARN() == null)
return false;
if (other.getRotationLambdaARN() != null && other.getRotationLambdaARN().equals(this.getRotationLambdaARN()) == false)
return false;
if (other.getRotationRules() == null ^ this.getRotationRules() == null)
return false;
if (other.getRotationRules() != null && other.getRotationRules().equals(this.getRotationRules()) == false)
return false;
if (other.getLastRotatedDate() == null ^ this.getLastRotatedDate() == null)
return false;
if (other.getLastRotatedDate() != null && other.getLastRotatedDate().equals(this.getLastRotatedDate()) == false)
return false;
if (other.getLastChangedDate() == null ^ this.getLastChangedDate() == null)
return false;
if (other.getLastChangedDate() != null && other.getLastChangedDate().equals(this.getLastChangedDate()) == false)
return false;
if (other.getLastAccessedDate() == null ^ this.getLastAccessedDate() == null)
return false;
if (other.getLastAccessedDate() != null && other.getLastAccessedDate().equals(this.getLastAccessedDate()) == false)
return false;
if (other.getDeletedDate() == null ^ this.getDeletedDate() == null)
return false;
if (other.getDeletedDate() != null && other.getDeletedDate().equals(this.getDeletedDate()) == false)
return false;
if (other.getTags() == null ^ this.getTags() == null)
return false;
if (other.getTags() != null && other.getTags().equals(this.getTags()) == false)
return false;
if (other.getVersionIdsToStages() == null ^ this.getVersionIdsToStages() == null)
return false;
if (other.getVersionIdsToStages() != null && other.getVersionIdsToStages().equals(this.getVersionIdsToStages()) == false)
return false;
if (other.getOwningService() == null ^ this.getOwningService() == null)
return false;
if (other.getOwningService() != null && other.getOwningService().equals(this.getOwningService()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getARN() == null) ? 0 : getARN().hashCode());
hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode());
hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode());
hashCode = prime * hashCode + ((getKmsKeyId() == null) ? 0 : getKmsKeyId().hashCode());
hashCode = prime * hashCode + ((getRotationEnabled() == null) ? 0 : getRotationEnabled().hashCode());
hashCode = prime * hashCode + ((getRotationLambdaARN() == null) ? 0 : getRotationLambdaARN().hashCode());
hashCode = prime * hashCode + ((getRotationRules() == null) ? 0 : getRotationRules().hashCode());
hashCode = prime * hashCode + ((getLastRotatedDate() == null) ? 0 : getLastRotatedDate().hashCode());
hashCode = prime * hashCode + ((getLastChangedDate() == null) ? 0 : getLastChangedDate().hashCode());
hashCode = prime * hashCode + ((getLastAccessedDate() == null) ? 0 : getLastAccessedDate().hashCode());
hashCode = prime * hashCode + ((getDeletedDate() == null) ? 0 : getDeletedDate().hashCode());
hashCode = prime * hashCode + ((getTags() == null) ? 0 : getTags().hashCode());
hashCode = prime * hashCode + ((getVersionIdsToStages() == null) ? 0 : getVersionIdsToStages().hashCode());
hashCode = prime * hashCode + ((getOwningService() == null) ? 0 : getOwningService().hashCode());
return hashCode;
}
@Override
public DescribeSecretResult clone() {
try {
return (DescribeSecretResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| apache-2.0 |
fullstackanalytics/pubsub4s | src/main/scala/com/google/api/services/pubsub/PullRequest.scala | 327 | package com.google.api.services.pubsub
final case class PullRequest(maxMessages: Int, returnImmediately: Boolean)
object PullRequest {
implicit def toJava(r: PullRequest): model.PullRequest = {
new model.PullRequest()
.setMaxMessages(r.maxMessages)
.setReturnImmediately(r.returnImmediately)
}
}
| apache-2.0 |
Mashape/kong | spec/02-integration/05-proxy/06-ssl_spec.lua | 15159 | local ssl_fixtures = require "spec.fixtures.ssl"
local helpers = require "spec.helpers"
local cjson = require "cjson"
local function get_cert(server_name)
local _, _, stdout = assert(helpers.execute(
string.format("echo 'GET /' | openssl s_client -connect 0.0.0.0:%d -servername %s",
helpers.get_proxy_port(true), server_name)
))
return stdout
end
for _, strategy in helpers.each_strategy() do
describe("SSL [#" .. strategy .. "]", function()
local proxy_client
local https_client
lazy_setup(function()
local bp = helpers.get_db_utils(strategy, {
"routes",
"services",
"certificates",
"snis",
})
local service = bp.services:insert {
name = "global-cert",
}
bp.routes:insert {
protocols = { "https" },
hosts = { "global.com" },
service = service,
}
local service2 = bp.services:insert {
name = "api-1",
}
bp.routes:insert {
protocols = { "https" },
hosts = { "example.com", "ssl1.com" },
service = service2,
}
local service4 = bp.services:insert {
name = "api-3",
protocol = helpers.mock_upstream_ssl_protocol,
host = helpers.mock_upstream_hostname,
port = helpers.mock_upstream_ssl_port,
}
bp.routes:insert {
protocols = { "https" },
hosts = { "ssl3.com" },
service = service4,
preserve_host = true,
}
local service5 = bp.services:insert {
name = "api-4",
protocol = helpers.mock_upstream_ssl_protocol,
host = helpers.mock_upstream_hostname,
port = helpers.mock_upstream_ssl_port,
}
bp.routes:insert {
protocols = { "https" },
hosts = { "no-sni.com" },
service = service5,
preserve_host = false,
}
local service6 = bp.services:insert {
name = "api-5",
protocol = helpers.mock_upstream_ssl_protocol,
host = "127.0.0.1",
port = helpers.mock_upstream_ssl_port,
}
bp.routes:insert {
protocols = { "https" },
hosts = { "nil-sni.com" },
service = service6,
preserve_host = false,
}
local service7 = bp.services:insert {
name = "service-7",
protocol = helpers.mock_upstream_ssl_protocol,
host = helpers.mock_upstream_hostname,
port = helpers.mock_upstream_ssl_port,
}
bp.routes:insert {
protocols = { "https" },
hosts = { "example.com" },
paths = { "/redirect-301" },
https_redirect_status_code = 301,
service = service7,
preserve_host = false,
}
local service8 = bp.services:insert {
name = "service-8",
protocol = helpers.mock_upstream_ssl_protocol,
host = helpers.mock_upstream_hostname,
port = helpers.mock_upstream_ssl_port,
}
bp.routes:insert {
protocols = { "https" },
hosts = { "example.com" },
paths = { "/redirect-302" },
https_redirect_status_code = 302,
service = service8,
preserve_host = false,
}
local service_mockbin = assert(bp.services:insert {
name = "service-mockbin",
url = "https://mockbin.com/request",
})
assert(bp.routes:insert {
protocols = { "http" },
hosts = { "mockbin.com" },
paths = { "/" },
service = service_mockbin,
})
assert(bp.routes:insert {
protocols = { "http" },
hosts = { "example-clear.com" },
paths = { "/" },
service = service8,
})
local cert = bp.certificates:insert {
cert = ssl_fixtures.cert,
key = ssl_fixtures.key,
}
bp.snis:insert {
name = "example.com",
certificate = cert,
}
bp.snis:insert {
name = "ssl1.com",
certificate = cert,
}
-- wildcard tests
local certificate_alt = bp.certificates:insert {
cert = ssl_fixtures.cert_alt,
key = ssl_fixtures.key_alt,
}
local certificate_alt_alt = bp.certificates:insert {
cert = ssl_fixtures.cert_alt_alt,
key = ssl_fixtures.key_alt_alt,
}
bp.snis:insert {
name = "*.wildcard.com",
certificate = certificate_alt,
}
bp.snis:insert {
name = "wildcard.*",
certificate = certificate_alt,
}
bp.snis:insert {
name = "wildcard.org",
certificate = certificate_alt_alt,
}
bp.snis:insert {
name = "test.wildcard.*",
certificate = certificate_alt_alt,
}
bp.snis:insert {
name = "*.www.wildcard.com",
certificate = certificate_alt_alt,
}
-- /wildcard tests
assert(helpers.start_kong {
database = strategy,
nginx_conf = "spec/fixtures/custom_nginx.template",
trusted_ips = "127.0.0.1",
nginx_http_proxy_ssl_verify = "on",
nginx_http_proxy_ssl_trusted_certificate = "../spec/fixtures/kong_spec.crt",
})
proxy_client = helpers.proxy_client()
https_client = helpers.proxy_ssl_client()
end)
lazy_teardown(function()
helpers.stop_kong()
end)
describe("proxy ssl verify", function()
it("prevents requests to upstream that does not possess a trusted certificate", function()
-- setup: cleanup logs
local test_error_log_path = helpers.test_conf.nginx_err_logs
os.execute(":> " .. test_error_log_path)
local res = assert(proxy_client:send {
method = "GET",
path = "/",
headers = {
Host = "mockbin.com",
},
})
local body = assert.res_status(502, res)
assert.equal("An invalid response was received from the upstream server", body)
local pl_file = require("pl.file")
helpers.wait_until(function()
-- Assertion: there should be [error] resulting from
-- TLS handshake failure
local logs = pl_file.read(test_error_log_path)
local found = false
for line in logs:gmatch("[^\r\n]+") do
if line:find("upstream SSL certificate verify error: " ..
"(20:unable to get local issuer certificate) " ..
"while SSL handshaking to upstream", nil, true)
then
found = true
else
assert.not_match("[error]", line, nil, true)
end
end
if found then
return true
end
end, 2)
end)
it("trusted certificate, request goes through", function()
local res = assert(proxy_client:send {
method = "GET",
path = "/",
headers = {
Host = "example-clear.com",
}
})
assert.res_status(200, res)
end)
end)
describe("global SSL", function()
it("fallbacks on the default proxy SSL certificate when SNI is not provided by client", function()
local res = assert(https_client:send {
method = "GET",
path = "/status/200",
headers = {
Host = "global.com"
}
})
assert.res_status(200, res)
end)
end)
describe("handshake", function()
it("sets the default fallback SSL certificate if no SNI match", function()
local cert = get_cert("test.com")
assert.cn("localhost", cert)
end)
it("sets the configured SSL certificate if SNI match", function()
local cert = get_cert("ssl1.com")
assert.cn("ssl-example.com", cert)
cert = get_cert("example.com")
assert.cn("ssl-example.com", cert)
end)
describe("wildcard sni", function()
it("matches *.wildcard.com (prefix)", function()
local cert = get_cert("test.wildcard.com")
assert.matches("CN%s*=%s*ssl%-alt%.com", cert)
end)
it("matches wildcard.* (suffix)", function()
local cert = get_cert("wildcard.eu")
assert.matches("CN%s*=%s*ssl%-alt%.com", cert)
end)
it("respects matching priorities (exact first)", function()
local cert = get_cert("wildcard.org")
assert.matches("CN%s*=%s*ssl%-alt%-alt%.com", cert)
end)
it("respects matching priorities (prefix second)", function()
local cert = get_cert("test.wildcard.com")
assert.matches("CN%s*=%s*ssl%-alt%.com", cert)
end)
it("respects matching priorities (suffix third)", function()
local cert = get_cert("test.wildcard.org")
assert.matches("CN%s*=%s*ssl%-alt%-alt%.com", cert)
end)
it("matches *.www.wildcard.com", function()
local cert = get_cert("test.www.wildcard.com")
assert.matches("CN%s*=%s*ssl%-alt%-alt%.com", cert)
end)
end)
end)
describe("SSL termination", function()
it("blocks request without HTTPS if protocols = { http }", function()
local res = assert(proxy_client:send {
method = "GET",
path = "/",
headers = {
["Host"] = "example.com",
}
})
local body = assert.res_status(426, res)
local json = cjson.decode(body)
assert.same({ message = "Please use HTTPS protocol" }, json)
assert.contains("Upgrade", res.headers.connection)
assert.equal("TLS/1.2, HTTP/1.1", res.headers.upgrade)
end)
it("returns 301 when route has https_redirect_status_code set to 301", function()
local res = assert(proxy_client:send {
method = "GET",
path = "/redirect-301",
headers = {
["Host"] = "example.com",
}
})
assert.res_status(301, res)
assert.equal("https://example.com/redirect-301", res.headers.location)
end)
it("returns 302 when route has https_redirect_status_code set to 302", function()
local res = assert(proxy_client:send {
method = "GET",
path = "/redirect-302?foo=bar",
headers = {
["Host"] = "example.com",
}
})
assert.res_status(302, res)
assert.equal("https://example.com/redirect-302?foo=bar", res.headers.location)
end)
describe("from not trusted_ip", function()
lazy_setup(function()
assert(helpers.restart_kong {
database = strategy,
nginx_conf = "spec/fixtures/custom_nginx.template",
trusted_ips = nil,
})
proxy_client = helpers.proxy_client()
end)
it("blocks HTTP request with HTTPS in x-forwarded-proto", function()
local res = assert(proxy_client:send {
method = "GET",
path = "/status/200",
headers = {
Host = "ssl1.com",
["x-forwarded-proto"] = "https"
}
})
assert.res_status(426, res)
end)
end)
describe("from trusted_ip", function()
lazy_setup(function()
assert(helpers.restart_kong {
database = strategy,
nginx_conf = "spec/fixtures/custom_nginx.template",
trusted_ips = "127.0.0.1",
})
proxy_client = helpers.proxy_client()
end)
it("allows HTTP requests with x-forwarded-proto", function()
local res = assert(proxy_client:send {
method = "GET",
path = "/status/200",
headers = {
Host = "example.com",
["x-forwarded-proto"] = "https",
}
})
assert.res_status(200, res)
end)
it("blocks HTTP requests with invalid x-forwarded-proto", function()
local res = assert(proxy_client:send {
method = "GET",
path = "/status/200",
headers = {
Host = "example.com",
["x-forwarded-proto"] = "httpsa"
}
})
assert.res_status(426, res)
end)
end)
describe("blocks with https x-forwarded-proto from untrusted client", function()
local client
-- restart kong and use a new client to simulate a connection from an
-- untrusted ip
lazy_setup(function()
assert(helpers.restart_kong {
database = strategy,
nginx_conf = "spec/fixtures/custom_nginx.template",
trusted_ips = "1.2.3.4", -- explicitly trust an IP that is not us
})
client = helpers.proxy_client()
end)
-- despite reloading here with no trusted IPs, this
it("", function()
local res = assert(client:send {
method = "GET",
path = "/status/200",
headers = {
Host = "example.com",
["x-forwarded-proto"] = "https"
}
})
assert.res_status(426, res)
end)
end)
end)
describe("proxy_ssl_name", function()
local https_client_sni
before_each(function()
assert(helpers.restart_kong {
database = strategy,
nginx_conf = "spec/fixtures/custom_nginx.template",
})
https_client_sni = helpers.proxy_ssl_client()
end)
after_each(function()
https_client_sni:close()
end)
describe("properly sets the upstream SNI with preserve_host", function()
it("true", function()
local res = assert(https_client_sni:send {
method = "GET",
path = "/",
headers = {
Host = "ssl3.com"
},
})
local body = assert.res_status(200, res)
local json = cjson.decode(body)
assert.equal("ssl3.com", json.vars.ssl_server_name)
end)
it("false", function()
local res = assert(https_client_sni:send {
method = "GET",
path = "/",
headers = {
Host = "no-sni.com"
},
})
local body = assert.res_status(200, res)
local json = cjson.decode(body)
assert.equal("localhost", json.vars.ssl_server_name)
end)
it("false and IP-based upstream_url", function()
local res = assert(https_client_sni:send {
method = "GET",
path = "/",
headers = {
Host = "nil-sni.com"
}
})
local body = assert.res_status(200, res)
local json = cjson.decode(body)
assert.equal("no SNI", json.vars.ssl_server_name)
end)
end)
end)
end)
end
| apache-2.0 |
StevenLeRoux/warp10-platform | warp10/src/main/java/io/warp10/script/WarpScriptStackFunction.java | 858 | //
// Copyright 2016 Cityzen Data
//
// 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 io.warp10.script;
/**
* Interface implemented by all Einstein functions that can be called
* from the stack.
*/
public interface WarpScriptStackFunction {
public Object apply(WarpScriptStack stack) throws WarpScriptException;
}
| apache-2.0 |
gianluca-nitti/FacadeServer-frontend | src/authentication/ClientIdentity.tsx | 507 | export interface PrivateIdentityCertificate<BigIntegerType> {
modulus: BigIntegerType;
exponent: BigIntegerType;
}
export interface PublicIdentityCertificate<BigIntegerType> {
id: string;
modulus: BigIntegerType;
exponent: BigIntegerType;
signature: BigIntegerType;
}
export interface ClientIdentity<BigIntegerType> {
server: PublicIdentityCertificate<BigIntegerType>;
clientPublic: PublicIdentityCertificate<BigIntegerType>;
clientPrivate: PrivateIdentityCertificate<BigIntegerType>;
}
| apache-2.0 |
puneetcse09/Oracle-Assignements | restdemo/src/books/BookDAO.java | 3994 | package books;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import DBConfig.BaseJDBC;
public class BookDAO {
static Connection con;
ResultSet rs = null;
Statement stmt = null;
String testSql = null;
public Map<String, BookVO> getBookResults()throws Exception{
Map<String, BookVO> rows = new HashMap<String, BookVO>();
String query = "SELECT * FROM book";
try {
con = (Connection) BaseJDBC.getConnPool();
System.out.println("SQl "+query);
stmt = con.createStatement();
rs = stmt.executeQuery(query);
System.out.println("SQl Executed inside getBookResults. . .");
while (rs.next()){
System.out.println("Result Set : "+rs.getString("TITLE"));
BookVO book = new BookVO();
book.setId(Integer.parseInt(rs.getString("ID")));
book.setTitle(rs.getString("TITLE"));
rows.put(rs.getString("ID"), book);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
if (con != null) con.close();
if (stmt != null) stmt.close();
if (rs != null) rs.close();
}
catch (Exception e) {
}
}
return rows;
}
public BookVO getBookResults(int param)throws Exception{
// String query = "SELECT * FROM book where id = :param";
String query = "select * from book, author, category where book.id = :param and book.id = author.id and book.id = category.id";
BookVO book = new BookVO();
try {
con = (Connection) BaseJDBC.getConnPool();
System.out.println("SQl "+query);
PreparedStatement ps = con.prepareStatement(query);
ps.setInt(1, param);
rs = ps.executeQuery();
System.out.println("SQl Executed inside getBookResults with param . . ."+param);
while (rs.next()){
System.out.println("Result Set : "+rs.getString("TITLE"));
book.setId(Integer.parseInt(rs.getString("ID")));
book.setTitle(rs.getString("TITLE"));
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
if (con != null) con.close();
if (stmt != null) stmt.close();
if (rs != null) rs.close();
}
catch (Exception e) {
}
}
return book;
}
public BookVO getDeleteBook(int param)throws Exception{
String query = "delete from book where id = :param";
BookVO book = new BookVO();
try {
con = (Connection) BaseJDBC.getConnPool();
System.out.println("SQl "+query);
PreparedStatement ps = con.prepareStatement(query);
ps.setInt(1, param);
rs = ps.executeQuery();
System.out.println("SQl Executed inside getBookResults with param . . ."+param);
System.out.println("Record is deleted from BOOK table !");
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
if (con != null) con.close();
if (stmt != null) stmt.close();
if (rs != null) rs.close();
}
catch (Exception e) {
}
}
return book;
}
public BookVO updateBook(int bookId, String bookTitle)throws Exception{
// String query = "SELECT * FROM book where id = :param";
String query = "update book set title = :bookTitle where book_id = :bookId";
BookVO book = new BookVO();
try {
con = (Connection) BaseJDBC.getConnPool();
System.out.println("SQl "+query);
PreparedStatement ps = con.prepareStatement(query);
ps.setInt(1, bookId);
ps.setString(2, bookTitle);
rs = ps.executeQuery();
System.out.println("SQl Executed inside getBookResults with param . . ."+bookId);
while (rs.next()){
System.out.println("Result Set : "+rs.getString("TITLE"));
book.setId(Integer.parseInt(rs.getString("ID")));
book.setTitle(rs.getString("TITLE"));
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
if (con != null) con.close();
if (stmt != null) stmt.close();
if (rs != null) rs.close();
}
catch (Exception e) {
}
}
return book;
}
}
| apache-2.0 |
jashwanth9/Expert-recommendation-system | code/wordcharUsefulness.py | 1354 | # gets word/characters usefulness (described in paper: I Want to Answer, Who has a Question?)
import pdb
import math
import operator
import matplotlib.pyplot as plt
def getUscores(tcounts, T):
alpha = 20/float(T)
Lt = {}
for term in tcounts:
Lt[term] = 0
for c in range(T):
prc = 0
den = 0
for c2 in range(T):
den += tcounts[term][c2] + alpha
prc = (tcounts[term][c]+alpha)/float(den)
Lt[term] -= (prc*math.log(prc))
return Lt
wordcount = {}
charcount = {}
best = 0
with open('../train_data/question_info.txt', 'r') as f1:
for line in f1:
sp = line.split()
topic = int(sp[1])
#best = max(topic, best)
try:
words = map(int, sp[2].split('/'))
except:
words = []
try:
chars = map(int, sp[3].split('/'))
except:
chars = []
for word in words:
if word not in wordcount:
wordcount[word] = [0]*20
wordcount[word][topic] += 1
for char in chars:
if char not in charcount:
charcount[char] = [0]*20
charcount[char][topic] += 1
Lc = getUscores(charcount, 20)
sorted_x = sorted(Lc.items(), key=operator.itemgetter(1))
print sorted_x[:20]
print len(sorted_x)
plt.plot([x[1] for x in sorted_x], range(len(sorted_x)))
plt.show()
Lw = getUscores(wordcount, 20)
sorted_x = sorted(Lw.items(), key=operator.itemgetter(1))
plt.plot([x[1] for x in sorted_x], range(len(sorted_x)))
plt.show() | apache-2.0 |
928902646/Gymnast | app/src/main/java/com/gymnast/data/net/UserApi.java | 1203 | package com.gymnast.data.net;
import com.gymnast.data.user.VerifyCode;
import java.util.HashMap;
import okhttp3.RequestBody;
import retrofit2.http.FieldMap;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.PartMap;
import rx.Observable;
/**
* Created by fldyown on 16/6/14.
*/
public interface UserApi {
/**
* 获取验证码
*/
@POST("/v1/sendRegisterCode") @FormUrlEncoded Observable<Result> getVerifyCode(
@FieldMap HashMap<String, String> params);
/**
* 验证手机号
*/
@POST("/v1/account/validate/code") @FormUrlEncoded Observable<Result<VerifyCode>> verifyPhone(
@FieldMap HashMap<String, String> params);
/**
* 注册账号
*/
@Multipart
@POST("/v1/account/register") Observable<Result> register(
@PartMap HashMap<String, RequestBody> params);
/**
* 忘记密码
*/
@POST("/v1/account/retrievepwd") @FormUrlEncoded Observable<Result> retrievePassword(
@FieldMap HashMap<String, String> params);
/**
* 登录
*/
@POST("/v1/account/login") @FormUrlEncoded Observable<Result<UserData>> login(
@FieldMap HashMap<String, String> params);
}
| apache-2.0 |
329277920/Snail | Snail.Pay.Ali.Sdk/Domain/CdpDisplayContent.cs | 1409 | using System;
using System.Xml.Serialization;
namespace Aop.Api.Domain
{
/// <summary>
/// CdpDisplayContent Data Structure.
/// </summary>
[Serializable]
public class CdpDisplayContent : AopObject
{
/// <summary>
/// 点击投放内容跳转地址
/// </summary>
[XmlElement("action_url")]
public string ActionUrl { get; set; }
/// <summary>
/// 投放中的扩展字段
/// </summary>
[XmlElement("ext_info")]
public string ExtInfo { get; set; }
/// <summary>
/// 投放生效结束时间
/// </summary>
[XmlElement("gmt_end")]
public string GmtEnd { get; set; }
/// <summary>
/// 投放生效开始时间
/// </summary>
[XmlElement("gmt_start")]
public string GmtStart { get; set; }
/// <summary>
/// 投放图片地址
/// </summary>
[XmlElement("image_url")]
public string ImageUrl { get; set; }
/// <summary>
/// 投放文本内容
/// </summary>
[XmlElement("text")]
public string Text { get; set; }
/// <summary>
/// 投放类型字段(当前只有红包),红包redPacket、提示tips、全景ar、广告ad
/// </summary>
[XmlElement("type")]
public string Type { get; set; }
}
}
| apache-2.0 |
CruorVolt/mu_bbmap | src/bbmap/current/jgi/MergeBarcodes.java | 16309 | package jgi;
import java.io.File;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import stream.ConcurrentGenericReadInputStream;
import stream.ConcurrentReadInputStream;
import stream.FASTQ;
import stream.FastaReadInputStream;
import stream.ConcurrentReadOutputStream;
import stream.Read;
import dna.Parser;
import dna.Timer;
import fileIO.ByteFile;
import fileIO.ByteFile1;
import fileIO.ByteFile2;
import fileIO.ReadWrite;
import fileIO.FileFormat;
import align2.ListNum;
import align2.ReadStats;
import align2.Shared;
import align2.Tools;
/**
* @author Brian Bushnell
* @date Sep 11, 2012
*
*/
public class MergeBarcodes {
public static void main(String[] args){
Timer t=new Timer();
t.start();
MergeBarcodes mb=new MergeBarcodes(args);
HashMap<String, Read> map=mb.loadBarcodes();
mb.mergeWithMap(t, map);
}
public MergeBarcodes(String[] args){
args=Parser.parseConfig(args);
if(Parser.parseHelp(args)){
printOptions();
System.exit(0);
}
for(String s : args){if(s.startsWith("out=standardout") || s.startsWith("out=stdout")){outstream=System.err;}}
outstream.println("Executing "+getClass().getName()+" "+Arrays.toString(args)+"\n");
boolean setInterleaved=false; //Whether it was explicitly set.
Shared.READ_BUFFER_LENGTH=Tools.min(200, Shared.READ_BUFFER_LENGTH);
Shared.capBuffers(4);
ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
ReadWrite.MAX_ZIP_THREADS=Shared.threads();
ReadWrite.ZIP_THREAD_DIVISOR=2;
Parser parser=new Parser();
for(int i=0; i<args.length; i++){
String arg=args[i];
String[] split=arg.split("=");
String a=split[0].toLowerCase();
String b=split.length>1 ? split[1] : null;
if(b==null || b.equalsIgnoreCase("null")){b=null;}
while(a.startsWith("-")){a=a.substring(1);} //In case people use hyphens
if(parser.parse(arg, a, b)){
//do nothing
}else if(a.equals("null") || a.equals(parser.in2)){
// do nothing
}else if(a.equals("verbose")){
verbose=Tools.parseBoolean(b);
ByteFile1.verbose=verbose;
ByteFile2.verbose=verbose;
stream.FastaReadInputStream.verbose=verbose;
ConcurrentGenericReadInputStream.verbose=verbose;
// align2.FastaReadInputStream2.verbose=verbose;
stream.FastqReadInputStream.verbose=verbose;
ReadWrite.verbose=verbose;
}else if(a.equals("barcode") || a.equals("bar") || a.equals("index")){
inbar=b;
}else if(a.equals("addslash")){
addslash=Tools.parseBoolean(b);
}else if(a.equals("rcompmate") || a.equals("rcm")){
reverseComplimentMate=Tools.parseBoolean(b);
outstream.println("Set RCOMPMATE to "+reverseComplimentMate);
}else if(a.equals("rcomp") || a.equals("rc")){
reverseCompliment=Tools.parseBoolean(b);
outstream.println("Set RCOMP to "+reverseCompliment);
}else if(parser.in1==null && i==0 && !arg.contains("=") && (arg.toLowerCase().startsWith("stdin") || new File(arg).exists())){
parser.in1=arg;
}else{
outstream.println("Unknown parameter "+args[i]);
assert(false) : "Unknown parameter "+args[i];
// throw new RuntimeException("Unknown parameter "+args[i]);
}
}
{//Process parser fields
Parser.processQuality();
maxReads=parser.maxReads;
overwrite=ReadStats.overwrite=parser.overwrite;
append=ReadStats.append=parser.append;
setInterleaved=parser.setInterleaved;
in1=parser.in1;
in2=parser.in2;
qfin1=parser.qfin1;
qfin2=parser.qfin2;
out1=parser.out1;
out2=parser.out2;
qfout1=parser.qfout1;
qfout2=parser.qfout2;
extin=parser.extin;
extout=parser.extout;
}
if(in1!=null && in2==null && in1.indexOf('#')>-1 && !new File(in1).exists()){
in2=in1.replace("#", "2");
in1=in1.replace("#", "1");
}
if(out1!=null && out2==null && out1.indexOf('#')>-1){
out2=out1.replace("#", "2");
out1=out1.replace("#", "1");
}
if(in2!=null){
if(FASTQ.FORCE_INTERLEAVED){outstream.println("Reset INTERLEAVED to false because paired input files were specified.");}
FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
}
assert(FastaReadInputStream.settingsOK());
if(in1==null){
printOptions();
throw new RuntimeException("Error - at least one input file is required.");
}
if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
ByteFile.FORCE_MODE_BF2=true;
}
if(out1==null){
if(out2!=null){
printOptions();
throw new RuntimeException("Error - cannot define out2 without defining out1.");
}
if(!parser.setOut){
System.err.println("No output stream specified. To write to stdout, please specify 'out=stdout.fq' or similar.");
// out1="stdout";
}
}
if(!setInterleaved){
assert(in1!=null && (out1!=null || out2==null)) : "\nin1="+in1+"\nin2="+in2+"\nout1="+out1+"\nout2="+out2+"\n";
if(in2!=null){ //If there are 2 input streams.
FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
}else{ //There is one input stream.
if(out2!=null){
FASTQ.FORCE_INTERLEAVED=true;
FASTQ.TEST_INTERLEAVED=false;
outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
}
}
}
if(out1!=null && out1.equalsIgnoreCase("null")){out1=null;}
if(out2!=null && out2.equalsIgnoreCase("null")){out2=null;}
if(!Tools.testOutputFiles(overwrite, append, false, out1, out2)){
outstream.println((out1==null)+", "+(out2==null)+", "+out1+", "+out2);
throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output files "+out1+", "+out2+"\n");
}
assert(inbar!=null) : "Must specify a barcode file.";
ffbar=FileFormat.testInput(inbar, FileFormat.FASTQ, extin, true, true);
ffout1=FileFormat.testOutput(out1, FileFormat.FASTQ, extout, true, overwrite, append, false);
ffout2=FileFormat.testOutput(out2, FileFormat.FASTQ, extout, true, overwrite, append, false);
ffin1=FileFormat.testInput(in1, FileFormat.FASTQ, extin, true, true);
ffin2=FileFormat.testInput(in2, FileFormat.FASTQ, extin, true, true);
}
public HashMap<String, Read> loadBarcodes(){
return loadBarcodes(outstream, ffbar, maxReads);
}
public static HashMap<String, Read> loadBarcodes(PrintStream outstream, FileFormat ffbar, long maxReads){
Timer t=new Timer();
t.start();
final boolean oldForceInterleaved=FASTQ.FORCE_INTERLEAVED;
final boolean oldTestInterleaved=FASTQ.TEST_INTERLEAVED;
FASTQ.FORCE_INTERLEAVED=false;
FASTQ.TEST_INTERLEAVED=false;
HashMap<String, Read> map=new HashMap<String, Read>(0x10000-1);
final ConcurrentReadInputStream cris;
{
cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffbar, null, null, null);
if(verbose){outstream.println("Started cris for barcodes");}
cris.start(); //4567
}
// final boolean paired=cris.paired();
// if(!ffin1.samOrBam()){outstream.println("Input is being processed as "+(paired ? "paired" : "unpaired"));}
long readsProcessed=0;
long basesProcessed=0;
{
ListNum<Read> ln=cris.nextList();
ArrayList<Read> reads=(ln!=null ? ln.list : null);
// outstream.println("Fetched "+reads);
if(reads!=null && !reads.isEmpty()){
Read r=reads.get(0);
assert((r.mate!=null)==cris.paired());
}
while(reads!=null && reads.size()>0){
for(int idx=0; idx<reads.size(); idx++){
final Read r1=reads.get(idx);
final Read r2=r1.mate;
if(r1.id.indexOf(' ')>=0){r1.id=r1.id.split(" ")[0];}
final int initialLength1=r1.length();
final int initialLength2=(r1.mateLength());
{
readsProcessed++;
basesProcessed+=initialLength1;
}
if(r2!=null){
readsProcessed++;
basesProcessed+=initialLength2;
}
map.put(r1.id, r1);
}
cris.returnList(ln.id, ln.list.isEmpty());
ln=cris.nextList();
reads=(ln!=null ? ln.list : null);
}
if(ln!=null){
cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
}
}
boolean errorState=false;
errorState|=ReadWrite.closeStream(cris);
t.stop();
double rpnano=readsProcessed/(double)(t.elapsed);
double bpnano=basesProcessed/(double)(t.elapsed);
String rpstring=(readsProcessed<100000 ? ""+readsProcessed : readsProcessed<100000000 ? (readsProcessed/1000)+"k" : (readsProcessed/1000000)+"m");
String bpstring=(basesProcessed<100000 ? ""+basesProcessed : basesProcessed<100000000 ? (basesProcessed/1000)+"k" : (basesProcessed/1000000)+"m");
while(rpstring.length()<8){rpstring=" "+rpstring;}
while(bpstring.length()<8){bpstring=" "+bpstring;}
outstream.println("Loaded barcodes.");
outstream.println("Time: \t"+t);
outstream.println("Barcodes Processed: "+rpstring+" \t"+String.format("%.2fk reads/sec", rpnano*1000000));
outstream.println("Bases Processed: "+bpstring+" \t"+String.format("%.2fm bases/sec", bpnano*1000));
outstream.println();
if(errorState){
throw new RuntimeException("MergeBarcodes encountered an error; the output may be corrupt.");
}
FASTQ.FORCE_INTERLEAVED=oldForceInterleaved;
FASTQ.TEST_INTERLEAVED=oldTestInterleaved;
return map;
}
void mergeWithMap(Timer t, HashMap<String, Read> map){
final ConcurrentReadInputStream cris;
{
cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffin1, ffin2, qfin1, qfin2);
if(verbose){outstream.println("Started cris");}
cris.start(); //4567
}
boolean paired=cris.paired();
if(!ffin1.samOrBam()){outstream.println("Input is being processed as "+(paired ? "paired" : "unpaired"));}
final ConcurrentReadOutputStream ros;
if(out1!=null){
final int buff=4;
if(cris.paired() && out2==null && (in1==null || !in1.contains(".sam"))){
outstream.println("Writing interleaved.");
}
assert(!out1.equalsIgnoreCase(in1) && !out1.equalsIgnoreCase(in1)) : "Input file and output file have same name.";
assert(out2==null || (!out2.equalsIgnoreCase(in1) && !out2.equalsIgnoreCase(in2))) : "out1 and out2 have same name.";
ros=ConcurrentReadOutputStream.getStream(ffout1, ffout2, qfout1, qfout2, buff, null, false);
ros.start();
}else{ros=null;}
long readsProcessed=0;
long basesProcessed=0;
long barcodesFound=0;
long barcodesNotFound=0;
final StringBuilder prefix=new StringBuilder();
{
ListNum<Read> ln=cris.nextList();
ArrayList<Read> reads=(ln!=null ? ln.list : null);
// outstream.println("Fetched "+reads);
if(reads!=null && !reads.isEmpty()){
Read r=reads.get(0);
assert((ffin1==null || ffin1.samOrBam()) || (r.mate!=null)==cris.paired());
}
while(reads!=null && reads.size()>0){
for(int idx=0; idx<reads.size(); idx++){
final Read r1=reads.get(idx);
final Read r2=r1.mate;
final int initialLength1=r1.length();
final int initialLength2=(r1.mateLength());
{
readsProcessed++;
basesProcessed+=initialLength1;
if(reverseCompliment){r1.reverseComplement();}
}
if(r2!=null){
readsProcessed++;
basesProcessed+=initialLength2;
if(reverseCompliment || reverseComplimentMate){r2.reverseComplement();}
}
String key=r1.id;
if(key.indexOf(' ')>=0){key=key.split(" ")[0];}
Read bar=map.remove(key);
if(bar!=null){
for(byte b : bar.bases){prefix.append((char)b);}
prefix.append('_');
for(byte b : bar.quality){prefix.append((char)(b+33));}
prefix.append('_');
r1.id=prefix+r1.id;
barcodesFound++;
if(r2!=null){
r2.id=prefix+r2.id;
barcodesFound++;
}
prefix.setLength(0);
}else{
barcodesNotFound++;
if(r2!=null){barcodesNotFound++;}
}
}
final ArrayList<Read> listOut=reads;
if(ros!=null){ros.add(listOut, ln.id);}
cris.returnList(ln.id, ln.list.isEmpty());
ln=cris.nextList();
reads=(ln!=null ? ln.list : null);
}
if(ln!=null){
cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
}
}
errorState|=ReadStats.writeAll();
errorState|=ReadWrite.closeStreams(cris, ros);
t.stop();
double rpnano=readsProcessed/(double)(t.elapsed);
double bpnano=basesProcessed/(double)(t.elapsed);
String rpstring=(readsProcessed<100000 ? ""+readsProcessed : readsProcessed<100000000 ? (readsProcessed/1000)+"k" : (readsProcessed/1000000)+"m");
String bpstring=(basesProcessed<100000 ? ""+basesProcessed : basesProcessed<100000000 ? (basesProcessed/1000)+"k" : (basesProcessed/1000000)+"m");
while(rpstring.length()<8){rpstring=" "+rpstring;}
while(bpstring.length()<8){bpstring=" "+bpstring;}
{
outstream.println("Barcodes Found: \t"+barcodesFound+" reads ("+String.format("%.2f",barcodesFound*100.0/readsProcessed)+"%)");
outstream.println("Barcodes Not Found: \t"+barcodesNotFound+" reads ("+String.format("%.2f",barcodesNotFound*100.0/readsProcessed)+"%)");
}
outstream.println("Time: \t"+t);
outstream.println("Reads Processed: "+rpstring+" \t"+String.format("%.2fk reads/sec", rpnano*1000000));
outstream.println("Bases Processed: "+bpstring+" \t"+String.format("%.2fm bases/sec", bpnano*1000));
if(errorState){
throw new RuntimeException("ReformatReads terminated in an error state; the output may be corrupt.");
}
}
/*--------------------------------------------------------------*/
private void printOptions(){
assert(false) : "printOptions: TODO";
// outstream.println("Syntax:\n");
// outstream.println("java -ea -Xmx512m -cp <path> jgi.ReformatReads in=<infile> in2=<infile2> out=<outfile> out2=<outfile2>");
// outstream.println("\nin2 and out2 are optional. \nIf input is paired and there is only one output file, it will be written interleaved.\n");
// outstream.println("Other parameters and their defaults:\n");
// outstream.println("overwrite=false \tOverwrites files that already exist");
// outstream.println("ziplevel=4 \tSet compression level, 1 (low) to 9 (max)");
// outstream.println("interleaved=false\tDetermines whether input file is considered interleaved");
// outstream.println("fastawrap=70 \tLength of lines in fasta output");
// outstream.println("qin=auto \tASCII offset for input quality. May be set to 33 (Sanger), 64 (Illumina), or auto");
// outstream.println("qout=auto \tASCII offset for output quality. May be set to 33 (Sanger), 64 (Illumina), or auto (meaning same as input)");
// outstream.println("outsingle=<file> \t(outs) Write singleton reads here, when conditionally discarding reads from pairs.");
}
/*--------------------------------------------------------------*/
private String inbar=null;
private String in1=null;
private String in2=null;
private String qfin1=null;
private String qfin2=null;
private String out1=null;
private String out2=null;
private String qfout1=null;
private String qfout2=null;
private String extin=null;
private String extout=null;
/*--------------------------------------------------------------*/
private boolean reverseComplimentMate=false;
private boolean reverseCompliment=false;
/** Add /1 and /2 to paired reads */
private boolean addslash=false;
private long maxReads=-1;
/*--------------------------------------------------------------*/
private final FileFormat ffbar;
private final FileFormat ffin1;
private final FileFormat ffin2;
private final FileFormat ffout1;
private final FileFormat ffout2;
/*--------------------------------------------------------------*/
private PrintStream outstream=System.err;
public static boolean verbose=false;
public boolean errorState=false;
private boolean overwrite=false;
private boolean append=false;
}
| apache-2.0 |
fabric8io/kubernetes-client | kubernetes-client/src/main/java/io/fabric8/kubernetes/client/utils/KubernetesResourceUtil.java | 14284 | /**
* Copyright (C) 2015 Red Hat, 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.
*/
package io.fabric8.kubernetes.client.utils;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.fabric8.kubernetes.api.builder.VisitableBuilder;
import io.fabric8.kubernetes.api.model.EnvVar;
import io.fabric8.kubernetes.api.model.EnvVarBuilder;
import io.fabric8.kubernetes.api.model.Event;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.api.model.KubernetesList;
import io.fabric8.kubernetes.api.model.KubernetesResourceList;
import io.fabric8.kubernetes.api.model.ObjectMeta;
import io.fabric8.kubernetes.api.model.OwnerReference;
import io.fabric8.kubernetes.api.model.Secret;
import io.fabric8.kubernetes.api.model.SecretBuilder;
import io.fabric8.kubernetes.client.CustomResourceList;
import io.fabric8.kubernetes.client.internal.readiness.Readiness;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
public class KubernetesResourceUtil {
private KubernetesResourceUtil() {}
public static final Pattern KUBERNETES_DNS1123_LABEL_REGEX = Pattern.compile("[a-z0-9]([-a-z0-9]{0,61}[a-z0-9])?");
private static final Pattern INVALID_LABEL_CHARS_PATTERN = Pattern.compile("[^-A-Za-z0-9]+");
/**
* Returns the resource version for the entity or null if it does not have one
*
* @param entity entity provided
* @return returns resource version of provided entity
*/
public static String getResourceVersion(HasMetadata entity) {
if (entity != null) {
ObjectMeta metadata = entity.getMetadata();
if (metadata != null) {
String resourceVersion = metadata.getResourceVersion();
if (!Utils.isNullOrEmpty(resourceVersion)) {
return resourceVersion;
}
}
}
return null;
}
/**
* Set resource version of a kubernetes resource
*
* @param entity entity provided
* @param resourceVersion updated resource version
*/
public static void setResourceVersion(HasMetadata entity, String resourceVersion) {
if (entity != null) {
ObjectMeta metadata = entity.getMetadata();
if (metadata != null) {
metadata.setResourceVersion(resourceVersion);
}
}
}
/**
* Returns the kind of the entity
*
* @param entity provided entity
* @return returns kind of entity provided
*/
public static String getKind(HasMetadata entity) {
if (entity != null) {
// TODO use reflection to find the kind?
if (entity instanceof KubernetesList) {
return "List";
} else {
return entity.getClass().getSimpleName();
}
} else {
return null;
}
}
/**
* Returns Qualified name for the specified Kubernetes Resource
*
* @param entity Kubernetes resource
* @return returns qualified name
*/
public static String getQualifiedName(HasMetadata entity) {
if (entity != null) {
return "" + getNamespace(entity) + "/" + getName(entity);
} else {
return null;
}
}
/**
* Returns name of the resource from it's Metadata
*
* @param entity Kubernetes resource
* @return returns name of resource
*/
public static String getName(HasMetadata entity) {
if (entity != null) {
return getName(entity.getMetadata());
} else {
return null;
}
}
/**
* Returns true if this entity has a valid non blank resourceVersion in its metadata
*
* @param entity entity provided
* @return returns a boolean value indicating whether it has a valid non blank resourceVersion
*/
public static boolean hasResourceVersion(HasMetadata entity) {
return getResourceVersion(entity) != null;
}
/**
* Returns name of the resource from it's Metadata
*
* @param entity MetaData of kubernetes resource
* @return returns name of resource
*/
public static String getName(ObjectMeta entity) {
if (entity != null) {
return Utils.coalesce(entity.getName(),
getAdditionalPropertyText(entity.getAdditionalProperties(), "id"),
entity.getUid());
} else {
return null;
}
}
/**
* Used to get additional properties from Object's metadata
*
* @param additionalProperties additional properties
* @param name name of resource
* @return returns additional property text
*/
protected static String getAdditionalPropertyText(Map<String, Object> additionalProperties, String name) {
if (additionalProperties != null) {
Object value = additionalProperties.get(name);
if (value != null) {
return value.toString();
}
}
return null;
}
/**
* Null safe get operation for getting namespace from Kubernetes Resource's MetaData
*
* @param entity Kubernetes Resource
* @return returns namespace as plain string
*/
public static String getNamespace(ObjectMeta entity) {
if (entity != null) {
return entity.getNamespace();
} else {
return null;
}
}
/**
* Getting namespace from Kubernetes Resource
*
* @param entity Kubernetes Resource
* @return returns namespace as plain string
*/
public static String getNamespace(HasMetadata entity) {
if (entity != null) {
return getNamespace(entity.getMetadata());
} else {
return null;
}
}
/**
* Null safe get for fetching annotations from MetaData of Kubernetes Resource
*
* @param entity Kubernetes resource
* @return returns a hashmap containing annotations
*/
public static Map<String, String> getOrCreateAnnotations(HasMetadata entity) {
ObjectMeta metadata = getOrCreateMetadata(entity);
Map<String, String> answer = metadata.getAnnotations();
if (answer == null) {
// use linked so the annotations can be in the FIFO order
answer = new LinkedHashMap<>();
metadata.setAnnotations(answer);
}
return answer;
}
/**
* Returns an identifier from the given string that can be used as resource name.
*
* @param name which needs to be sanitized
* @return sanitized name
*/
public static String sanitizeName(String name) {
if(name != null) {
name = INVALID_LABEL_CHARS_PATTERN.matcher(name).replaceAll("-");
if (!Character.isLetterOrDigit(name.charAt(0))) {
name = "a" + name;
}
if (name.length() > 63) {
name = name.substring(0, 63);
}
name = name.toLowerCase();
final int lastChar = name.length() - 1;
if (!Character.isLetterOrDigit(name.charAt(lastChar))) {
name = name.substring(0, lastChar - 1) + "a";
}
return name;
}
return null;
}
/**
* Null safe get method for getting Labels of a Kubernetes Resource
*
* @param entity Kubernetes Resource
* @return returns a hashmap containing labels
*/
public static Map<String, String> getOrCreateLabels(HasMetadata entity) {
ObjectMeta metadata = getOrCreateMetadata(entity);
Map<String, String> answer = metadata.getLabels();
if (answer == null) {
// use linked so the annotations can be in the FIFO order
answer = new LinkedHashMap<>();
metadata.setLabels(answer);
}
return answer;
}
/**
* Returns the labels of the given metadata object or an empty map if the metadata or labels are null
*
* @param metadata ObjectMeta for resource's metadata
* @return returns labels as a hashmap
*/
@SuppressWarnings("unchecked")
public static Map<String, String> getLabels(ObjectMeta metadata) {
if (metadata != null) {
Map<String, String> labels = metadata.getLabels();
if (labels != null) {
return labels;
}
}
return Collections.emptyMap();
}
/**
* Null safe operation for getting Metadata of a Kubernetes resource
*
* @param entity Kubernetes Resource
* @return returns ObjectMeta as metadata
*/
public static ObjectMeta getOrCreateMetadata(HasMetadata entity) {
ObjectMeta metadata = entity.getMetadata();
if (metadata == null) {
metadata = new ObjectMeta();
entity.setMetadata(metadata);
}
return metadata;
}
/**
* Validates name of Kubernetes Resource name, label or annotation based on Kubernetes regex
*
* @param name Name of resource/label/annotation
* @return returns a boolean value indicating whether it's valid or not
*/
public static boolean isValidName(String name) {
return Utils.isNotNullOrEmpty(name) && KUBERNETES_DNS1123_LABEL_REGEX.matcher(name).matches();
}
/**
* Validates labels/annotations of Kubernetes resources
*
* @param map Label/Annotation of resource
* @return returns a boolean value indicating whether it's valid or not
*/
public static boolean isValidLabelOrAnnotation(Map<String, String> map) {
for(Map.Entry<String, String> entry : map.entrySet()) {
if(!(isValidName(entry.getKey()) && isValidName(entry.getValue()))) {
return false;
}
}
return true;
}
/**
* Checks whether the resource has some controller(parent) or not.
*
* @param resource resource
* @return boolean value indicating whether it's a child or not.
*/
public static boolean hasController(HasMetadata resource) {
return getControllerUid(resource) != null;
}
public static OwnerReference getControllerUid(HasMetadata resource) {
if (resource.getMetadata() != null) {
List<OwnerReference> ownerReferenceList = resource.getMetadata().getOwnerReferences();
for (OwnerReference ownerReference : ownerReferenceList) {
if (Boolean.TRUE.equals(ownerReference.getController())) {
return ownerReference;
}
}
}
return null;
}
public static void sortEventListBasedOnTimestamp(List<Event> eventList) {
if (eventList != null) {
// Sort to get latest events in beginning, putting events without lastTimestamp first
eventList.sort(Comparator.comparing(Event::getLastTimestamp, Comparator.nullsFirst(Comparator.comparing(Instant::parse).reversed())));
}
}
public static List<EnvVar> convertMapToEnvVarList(Map<String, String> envVarMap) {
List<EnvVar> envVars = new ArrayList<>();
for (Map.Entry<String, String> entry : envVarMap.entrySet()) {
if (entry.getKey() != null && entry.getValue() != null) {
envVars.add(new EnvVarBuilder()
.withName(entry.getKey())
.withValue(entry.getValue())
.build());
}
}
return envVars;
}
/**
* Check whether a Kubernetes resource is Ready or not. Applicable only to
* Deployment, ReplicaSet, Pod, ReplicationController, Endpoints, Node and
* StatefulSet
* @param item item which needs to be checked
* @return boolean value indicating it's status
*/
public static boolean isResourceReady(HasMetadata item) {
return Readiness.getInstance().isReady(item);
}
/**
* Calculates age of a kubernetes resource
* @param kubernetesResource
* @return a positive duration indicating age of the kubernetes resource
*/
public static Duration getAge(HasMetadata kubernetesResource) {
Instant instant = Instant.parse(kubernetesResource.getMetadata().getCreationTimestamp());
return Duration.between(instant, Instant.now()).abs();
}
public static <T extends HasMetadata> Class<? extends KubernetesResourceList> inferListType(Class<T> type) {
return (Class<? extends KubernetesResourceList>) loadRelated(type, "List", CustomResourceList.class);
}
public static <T extends HasMetadata, V extends VisitableBuilder<T, V>> Class<V> inferBuilderType(Class<T> type) {
return (Class<V>) loadRelated(type, "Builder", null);
}
private static Class<?> loadRelated(Class<?> type, String suffix, Class<?> defaultClass) {
try {
return Thread.currentThread().getContextClassLoader().loadClass(type.getName() + suffix);
} catch (ClassNotFoundException | ClassCastException e) {
try {
return type.getClassLoader().loadClass(type.getName() + suffix);
} catch (ClassNotFoundException | ClassCastException ex) {
return defaultClass;
}
}
}
/**
* Create Secret by using username and password.
* @param dockerServer User to store key value pair for auths map
* @param username username that needs to be used during secret creation
* @param password password that needs to be used during secret creation
* @return an object of Secret
*/
public static Secret createDockerRegistrySecret(String dockerServer, String username, String password) throws JsonProcessingException {
Map<String, Object> dockerConfigMap = new HashMap<>();
Map<String, Object> auths = new HashMap<>();
Map<String, Object> credentials = new HashMap<>();
credentials.put("username", username);
credentials.put("password", password);
String usernameAndPasswordAuth = username + ":" + password;
credentials.put("auth", Base64.getEncoder().encodeToString(usernameAndPasswordAuth.getBytes(StandardCharsets.UTF_8)));
auths.put(dockerServer, credentials);
dockerConfigMap.put("auths", auths);
String dockerConfigAsStr = Serialization.jsonMapper().writeValueAsString(dockerConfigMap);
return new SecretBuilder()
.withNewMetadata().withName("harbor-secret").endMetadata()
.withType("kubernetes.io/dockerconfigjson")
.addToData(".dockerconfigjson", Base64.getEncoder().encodeToString(dockerConfigAsStr.getBytes(StandardCharsets.UTF_8)))
.build();
}
}
| apache-2.0 |
notbrain/play-bootstrap | test/views/html/layout/base.scala | 4272 | /*
* Copyright 2013 Marconi Lanna
*
* 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 test.views.html.layout
class base extends org.scalatest.FunSuite {
test("Title: no parameters") {
val result = views.html.layout.base()(null)
assert(result.contentType === "text/html")
assert(result.body.contains("<title>Site Name</title>"))
}
test("Title: null parameter") {
val result = views.html.layout.base(null)(null)
assert(result.contentType === "text/html")
assert(result.body.contains("<title>Site Name</title>"))
}
test("Title: empty string") {
val result = views.html.layout.base("")(null)
assert(result.contentType === "text/html")
assert(result.body.contains("<title>Site Name</title>"))
}
test("Title: simple string") {
val result = views.html.layout.base("Test")(null)
assert(result.contentType === "text/html")
assert(result.body.contains("<title>Test - Site Name</title>"))
}
test("Title: Unicode string") {
val result = views.html.layout.base("àêíõüç ÀÊÍÕÜÇ π Я 中文 漢字 한글 ☃")(null)
assert(result.contentType === "text/html")
assert(result.body.contains("<title>àêíõüç ÀÊÍÕÜÇ π Я 中文 漢字 한글 ☃ - Site Name</title>"))
}
test("Title: HTML encoding") {
val result = views.html.layout.base("\"Test\"</title>")(null)
assert(result.contentType === "text/html")
assert(result.body.contains("<title>"Test"</title> - Site Name</title>"))
}
test("Site name: null parameter") {
val result = views.html.layout.base(siteName = null)(null)
assert(result.contentType === "text/html")
assert(result.body.contains("<title></title>"))
}
test("Site name: empty string") {
val result = views.html.layout.base(siteName = "")(null)
assert(result.contentType === "text/html")
assert(result.body.contains("<title></title>"))
}
test("Site name: simple string") {
val result = views.html.layout.base(siteName = "Test")(null)
assert(result.contentType === "text/html")
assert(result.body.contains("<title>Test</title>"))
}
test("Site name and title: simple string") {
val result = views.html.layout.base("My page", "MySite.com")(null)
assert(result.contentType === "text/html")
assert(result.body.contains("<title>My page - MySite.com</title>"))
}
test("Description: null parameter") {
val result = views.html.layout.base(description = null)(null)
assert(result.contentType === "text/html")
assert(!result.body.contains("<meta name=\"description\""))
}
test("Description: empty string") {
val result = views.html.layout.base(description = "")(null)
assert(result.contentType === "text/html")
assert(!result.body.contains("<meta name=\"description\""))
}
test("Description: simple string") {
val result = views.html.layout.base(description = "Test")(null)
assert(result.contentType === "text/html")
assert(result.body.contains("<meta name=\"description\" content=\"Test\">"))
}
test("Body: no id, no class") {
val result = views.html.layout.base()(null)
assert(result.contentType === "text/html")
assert(result.body.contains("<body>"))
}
test("Body: id only") {
val result = views.html.layout.base(id = "testId")(null)
assert(result.contentType === "text/html")
assert(result.body.contains("<body id=\"testId\">"))
}
test("Body: class only") {
val result = views.html.layout.base(_class = "testClass")(null)
assert(result.contentType === "text/html")
assert(result.body.contains("<body class=\"testClass\">"))
}
test("Body: id and class") {
val result = views.html.layout.base(id = "testId", _class = "testClass")(null)
assert(result.contentType === "text/html")
assert(result.body.contains("<body id=\"testId\" class=\"testClass\">"))
}
}
| apache-2.0 |
agustinsantos/DOOP.ec | DDS-RTPS/DDS/omg/dds/core/policy/DestinationOrderQosPolicy.cs | 1607 | /* Copyright 2010, Object Management Group, Inc.
* Copyright 2010, PrismTech, Inc.
* Copyright 2010, Real-Time Innovations, 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.
*/
using org.omg.dds.core.policy.modifiable;
namespace org.omg.dds.core.policy
{
public interface DestinationOrderQosPolicy : QosPolicy<DestinationOrderQosPolicy, ModifiableDestinationOrderQosPolicy>
{
// -----------------------------------------------------------------------
// Methods
// -----------------------------------------------------------------------
/// <summary>
///
/// </summary>
/// <returns>The kind</returns>
DestinationOrderQosPolicyKind GetKind();
}
// -----------------------------------------------------------------------
// Types
// -----------------------------------------------------------------------
public enum DestinationOrderQosPolicyKind
{
BY_RECEPTION_TIMESTAMP,
BY_SOURCE_TIMESTAMP
}
} | apache-2.0 |
OLR-xray/XRay-NEW | XRay/xr_3da/xrGame/relation_registry_actions.cpp | 11179 | #include "stdafx.h"
#include "relation_registry.h"
#include "alife_registry_wrappers.h"
#include "actor.h"
#include "ai/stalker/ai_stalker.h"
#include "seniority_hierarchy_holder.h"
#include "team_hierarchy_holder.h"
#include "squad_hierarchy_holder.h"
#include "group_hierarchy_holder.h"
#include "memory_manager.h"
#include "enemy_manager.h"
struct SAttackGoodwillStorage
{
CHARACTER_GOODWILL friend_attack_goodwill;
CHARACTER_GOODWILL neutral_attack_goodwill;
CHARACTER_GOODWILL enemy_attack_goodwill;
CHARACTER_GOODWILL friend_attack_reputation;
CHARACTER_GOODWILL neutral_attack_reputation;
CHARACTER_GOODWILL enemy_attack_reputation;
void load(LPCSTR prefix)
{
string128 s;
friend_attack_goodwill = pSettings->r_s32(ACTIONS_POINTS_SECT, strconcat(s,prefix,"friend_attack_goodwill"));
neutral_attack_goodwill = pSettings->r_s32(ACTIONS_POINTS_SECT, strconcat(s,prefix,"neutral_attack_goodwill"));
enemy_attack_goodwill = pSettings->r_s32(ACTIONS_POINTS_SECT, strconcat(s,prefix,"enemy_attack_goodwill"));
friend_attack_reputation = pSettings->r_s32(ACTIONS_POINTS_SECT, strconcat(s,prefix,"friend_attack_reputation"));
neutral_attack_reputation = pSettings->r_s32(ACTIONS_POINTS_SECT, strconcat(s,prefix,"neutral_attack_reputation"));
enemy_attack_reputation = pSettings->r_s32(ACTIONS_POINTS_SECT, strconcat(s,prefix,"enemy_attack_reputation"));
}
};
SAttackGoodwillStorage gw_danger,gw_free;
void load_attack_goodwill()
{
gw_danger.load("danger_");
gw_free.load("free_");
}
void RELATION_REGISTRY::Action (CEntityAlive* from, CEntityAlive* to, ERelationAction action)
{
static CHARACTER_GOODWILL friend_kill_goodwill = pSettings->r_s32(ACTIONS_POINTS_SECT, "friend_kill_goodwill");
static CHARACTER_GOODWILL neutral_kill_goodwill = pSettings->r_s32(ACTIONS_POINTS_SECT, "neutral_kill_goodwill");
static CHARACTER_GOODWILL enemy_kill_goodwill = pSettings->r_s32(ACTIONS_POINTS_SECT, "enemy_kill_goodwill");
static CHARACTER_GOODWILL community_member_kill_goodwill = pSettings->r_s32(ACTIONS_POINTS_SECT, "community_member_kill_goodwill");
static CHARACTER_REPUTATION_VALUE friend_kill_reputation = pSettings->r_s32(ACTIONS_POINTS_SECT, "friend_kill_reputation");
static CHARACTER_REPUTATION_VALUE neutral_kill_reputation = pSettings->r_s32(ACTIONS_POINTS_SECT, "neutral_kill_reputation");
static CHARACTER_REPUTATION_VALUE enemy_kill_reputation = pSettings->r_s32(ACTIONS_POINTS_SECT, "enemy_kill_reputation");
//(ñ) ìèí. âðåìÿ ÷åðåç êîòîðîå ñíîâà áóäåò çàðåãåñòðèðîâàíî ñîîáùåíèå îá àòàêå íà ïåðñîíàæà
static u32 min_attack_delta_time = u32(1000.f * pSettings->r_float(ACTIONS_POINTS_SECT, "min_attack_delta_time"));
static CHARACTER_GOODWILL friend_fight_help_goodwill = pSettings->r_s32(ACTIONS_POINTS_SECT, "friend_fight_help_goodwill");
static CHARACTER_GOODWILL neutral_fight_help_goodwill = pSettings->r_s32(ACTIONS_POINTS_SECT, "neutral_fight_help_goodwill");
static CHARACTER_GOODWILL enemy_fight_help_goodwill = pSettings->r_s32(ACTIONS_POINTS_SECT, "enemy_fight_help_goodwill");
static CHARACTER_REPUTATION_VALUE friend_fight_help_reputation = pSettings->r_s32(ACTIONS_POINTS_SECT, "friend_fight_help_reputation");
static CHARACTER_REPUTATION_VALUE neutral_fight_help_reputation = pSettings->r_s32(ACTIONS_POINTS_SECT, "neutral_fight_help_reputation");
static CHARACTER_REPUTATION_VALUE enemy_fight_help_reputation = pSettings->r_s32(ACTIONS_POINTS_SECT, "enemy_fight_help_reputation");
CActor* actor = smart_cast<CActor*> (from);
CInventoryOwner* inv_owner_from = smart_cast<CInventoryOwner*> (from);
CAI_Stalker* stalker_from = smart_cast<CAI_Stalker*> (from);
CAI_Stalker* stalker = smart_cast<CAI_Stalker*> (to);
//âû÷èñëåíèå èçìåíåíèÿ ðåïóòàöèè è ðåéòèíãà ïîêà âåäåòñÿ
//òîëüêî äëÿ àêòåðà
if(!inv_owner_from || from->cast_base_monster()) return;
ALife::ERelationType relation = ALife::eRelationTypeDummy;
if(stalker)
{
stalker->m_actor_relation_flags.set(action, TRUE);
relation = GetRelationType(smart_cast<CInventoryOwner*>(stalker), inv_owner_from);
}
switch(action)
{
case ATTACK:
{
if(actor)
{
//ó÷èòûâàòü ATTACK è FIGHT_HELP, òîëüêî åñëè ïðîøëî âðåìÿ
//min_attack_delta_time
FIGHT_DATA* fight_data_from = FindFight (from->ID(), true);
if(Device.dwTimeGlobal - fight_data_from->attack_time < min_attack_delta_time)
break;
fight_data_from->attack_time = Device.dwTimeGlobal;
//åñëè ìû àòàêîâàëè ïåðñîíàæà èëè ìîíñòðà, êîòîðûé
//êîãî-òî àòàêîâàë, òî ìû ïîìîãëè òîìó, êòî çàùèùàëñÿ
FIGHT_DATA* fight_data = FindFight (to->ID(),true);
if(fight_data)
{
CAI_Stalker* defending_stalker = smart_cast<CAI_Stalker*>(Level().Objects.net_Find(fight_data->defender));
if(defending_stalker)
{
CAI_Stalker* attacking_stalker = smart_cast<CAI_Stalker*>(Level().Objects.net_Find(fight_data->attacker));
Action(actor, defending_stalker, attacking_stalker?FIGHT_HELP_HUMAN:FIGHT_HELP_MONSTER);
}
}
}
if(stalker)
{
bool bDangerScheme = false;
const CEntityAlive* stalker_enemy = stalker->memory().enemy().selected();
if(actor && stalker_enemy)
{
const CInventoryOwner* const_inv_owner_from = inv_owner_from;
if(stalker_enemy->human_being())
{
const CInventoryOwner* const_inv_owner_stalker_enemy = smart_cast<const CInventoryOwner*>(stalker_enemy);
ALife::ERelationType relation_to_actor = GetRelationType(const_inv_owner_stalker_enemy, const_inv_owner_from);
if(relation_to_actor == ALife::eRelationTypeEnemy)
bDangerScheme = true;
}
}
SAttackGoodwillStorage* st = bDangerScheme?&gw_danger:&gw_free;
CHARACTER_GOODWILL delta_goodwill = 0;
CHARACTER_REPUTATION_VALUE delta_reputation = 0;
switch (relation)
{
case ALife::eRelationTypeEnemy:
{
delta_goodwill = st->enemy_attack_goodwill;
delta_reputation = st->enemy_attack_reputation;
}break;
case ALife::eRelationTypeNeutral:
{
delta_goodwill = st->neutral_attack_goodwill;
delta_reputation = st->neutral_attack_reputation;
}break;
case ALife::eRelationTypeFriend:
{
delta_goodwill = st->friend_attack_goodwill;
delta_reputation = st->friend_attack_reputation;
}break;
};
//ñòàëêåð ïðè íàïàäåíèè íà ÷ëåíîâ ñâîåé æå ãðóïïèðîâêè îòíîøåíèÿ íå ìåíÿþò
//(ñ÷èòàåòñÿ, ÷òî òàêîå íàïàäåíèå âñåãäà ñëó÷àéíî)
// change relation only for pairs actor->stalker, do not use pairs stalker->stalker
bool stalker_attack_team_mate = stalker && stalker_from;
if (delta_goodwill && !stalker_attack_team_mate) {
//èçìåíèòü îòíîøåíèå êî âñåì ÷ëåíàì àòàêîâàíîé ãðóïïû (åñëè òàêàÿ åñòü)
//êàê ê òîìó êîãî àòàêîâàëè
CGroupHierarchyHolder& group = Level().seniority_holder().team(stalker->g_Team()).squad(stalker->g_Squad()).group(stalker->g_Group());
for(std::size_t i = 0; i < group.members().size(); i++)
ChangeGoodwill(group.members()[i]->ID(), from->ID(), delta_goodwill);
ChangeCommunityGoodwill(stalker->Community(), from->ID(),
(CHARACTER_GOODWILL)(CHARACTER_COMMUNITY::sympathy(stalker->Community())*(float)delta_goodwill));
}
if(delta_reputation)
inv_owner_from->ChangeReputation(delta_reputation);
}
}
break;
case KILL:
{
if(stalker)
{
FIGHT_DATA* fight_data_from = FindFight (from->ID(), true);
//ìû ïîìíèì òî, êàêîå îòíîøåíèå îáîðîíÿþùåãîñÿ ê àòàêóþùåìó
//áûëî ïåðåä íà÷àëîì äðàêè
ALife::ERelationType relation_before_attack = ALife::eRelationTypeDummy;
if(fight_data_from)
relation_before_attack = fight_data_from->defender_to_attacker;
else
relation_before_attack = relation;
CHARACTER_GOODWILL delta_goodwill = 0;
CHARACTER_REPUTATION_VALUE delta_reputation = 0;
switch (relation_before_attack)
{
case ALife::eRelationTypeEnemy:
{
delta_goodwill = enemy_kill_goodwill;
delta_reputation = enemy_kill_reputation;
}break;
case ALife::eRelationTypeNeutral:
{
delta_goodwill = neutral_kill_goodwill;
delta_reputation = neutral_kill_reputation;
}break;
case ALife::eRelationTypeFriend:
{
delta_goodwill = friend_kill_goodwill;
delta_reputation = friend_kill_reputation;
}break;
};
CHARACTER_GOODWILL community_goodwill =
(CHARACTER_GOODWILL)(CHARACTER_COMMUNITY::sympathy(stalker->Community())*
(float)(delta_goodwill+community_member_kill_goodwill));
//ñòàëêåð ïðè íàïàäåíèè íà ÷ëåíîâ ñâîåé æå ãðóïïèðîâêè îòíîøåíèÿ íå ìåíÿþò
//(ñ÷èòàåòñÿ, ÷òî òàêîå íàïàäåíèå âñåãäà ñëó÷àéíî)
bool stalker_kills_team_mate = stalker_from && (stalker_from->Community() == stalker->Community());
if(delta_goodwill && !stalker_kills_team_mate)
{
//èçìåíèòü îòíîøåíèå êî âñåì ÷ëåíàì ãðóïïû (åñëè òàêàÿ åñòü)
//óáèòîãî, êðîìå íåãî ñàìîãî
CGroupHierarchyHolder& group = Level().seniority_holder().team(stalker->g_Team()).squad(stalker->g_Squad()).group(stalker->g_Group());
for(std::size_t i = 0; i < group.members().size(); i++)
if(stalker->ID() != group.members()[i]->ID())
ChangeGoodwill(group.members()[i]->ID(), from->ID(), delta_goodwill);
if (community_goodwill)
ChangeCommunityGoodwill(stalker->Community(), from->ID(), community_goodwill);
}
if(delta_reputation)
inv_owner_from->ChangeReputation(delta_reputation);
CHARACTER_RANK_VALUE delta_rank = 0;
delta_rank = CHARACTER_RANK::rank_kill_points(CHARACTER_RANK::ValueToIndex(stalker->Rank()));
if(delta_rank)
inv_owner_from->ChangeRank(delta_rank);
}
}
break;
case FIGHT_HELP_HUMAN:
case FIGHT_HELP_MONSTER:
{
if(stalker && stalker->g_Alive())
{
CHARACTER_GOODWILL delta_goodwill = 0;
CHARACTER_REPUTATION_VALUE delta_reputation = 0;
switch (relation)
{
case ALife::eRelationTypeEnemy:
{
delta_goodwill = enemy_fight_help_goodwill;
delta_reputation = enemy_fight_help_reputation;
}break;
case ALife::eRelationTypeNeutral:
{
delta_goodwill = neutral_fight_help_goodwill;
delta_reputation = neutral_fight_help_reputation;
}break;
case ALife::eRelationTypeFriend:
{
delta_goodwill = friend_fight_help_goodwill;
delta_reputation = friend_fight_help_reputation;
}break;
};
if(delta_goodwill)
{
//èçìåíèòü îòíîøåíèå êî âñåì ÷ëåíàì àòàêîâàíîé ãðóïïû (åñëè òàêàÿ åñòü)
//êàê ê òîìó êîãî àòàêîâàëè
CGroupHierarchyHolder& group = Level().seniority_holder().team(stalker->g_Team()).squad(stalker->g_Squad()).group(stalker->g_Group());
for(std::size_t i = 0; i < group.members().size(); i++)
ChangeGoodwill(group.members()[i]->ID(), from->ID(), delta_goodwill);
ChangeCommunityGoodwill(stalker->Community(), from->ID(),
(CHARACTER_GOODWILL)(CHARACTER_COMMUNITY::sympathy(stalker->Community())*(float)delta_goodwill));
}
if(delta_reputation)
inv_owner_from->ChangeReputation(delta_reputation);
}
}
break;
}
} | apache-2.0 |
Muni10/flyway | flyway-core/src/main/java/org/flywaydb/core/internal/dbsupport/derby/DerbyTable.java | 1863 | /*
* Copyright 2010-2017 Boxfuse 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.
*/
package org.flywaydb.core.internal.dbsupport.derby;
import org.flywaydb.core.internal.dbsupport.DbSupport;
import org.flywaydb.core.internal.dbsupport.JdbcTemplate;
import org.flywaydb.core.internal.dbsupport.Schema;
import org.flywaydb.core.internal.dbsupport.Table;
import java.sql.SQLException;
/**
* Derby-specific table.
*/
public class DerbyTable extends Table {
/**
* Creates a new Derby table.
*
* @param jdbcTemplate The Jdbc Template for communicating with the DB.
* @param dbSupport The database-specific support.
* @param schema The schema this table lives in.
* @param name The name of the table.
*/
public DerbyTable(JdbcTemplate jdbcTemplate, DbSupport dbSupport, Schema schema, String name) {
super(jdbcTemplate, dbSupport, schema, name);
}
@Override
protected void doDrop() throws SQLException {
jdbcTemplate.execute("DROP TABLE " + dbSupport.quote(schema.getName(), name));
}
@Override
protected boolean doExists() throws SQLException {
return exists(null, schema, name);
}
@Override
protected void doLock() throws SQLException {
jdbcTemplate.execute("LOCK TABLE " + this + " IN EXCLUSIVE MODE");
}
} | apache-2.0 |
dagnir/aws-sdk-java | aws-java-sdk-ses/src/main/java/com/amazonaws/services/simpleemail/waiters/IdentityExists.java | 2845 | /*
* Copyright 2012-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.
*/
package com.amazonaws.services.simpleemail.waiters;
import com.amazonaws.annotation.SdkInternalApi;
import com.amazonaws.waiters.WaiterAcceptor;
import com.amazonaws.waiters.WaiterState;
import com.amazonaws.waiters.AcceptorPathMatcher;
import com.amazonaws.services.simpleemail.model.*;
import com.fasterxml.jackson.databind.JsonNode;
import com.amazonaws.jmespath.*;
import java.io.IOException;
import javax.annotation.Generated;
@SdkInternalApi
@Generated("com.amazonaws:aws-java-sdk-code-generator")
class IdentityExists {
static class IsSuccessMatcher extends WaiterAcceptor<GetIdentityVerificationAttributesResult> {
private static final JsonNode expectedResult;
static {
try {
expectedResult = ObjectMapperSingleton.getObjectMapper().readTree("\"Success\"");
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
private static final JmesPathExpression ast = new JmesPathValueProjection(new JmesPathField("VerificationAttributes"), new JmesPathField(
"VerificationStatus"));
/**
* Takes the result and determines whether the state of the resource matches the expected state. To determine
* the current state of the resource, JmesPath expression is evaluated and compared against the expected result.
*
* @param result
* Corresponding result of the operation
* @return True if current state of the resource matches the expected state, False otherwise
*/
@Override
public boolean matches(GetIdentityVerificationAttributesResult result) {
JsonNode queryNode = ObjectMapperSingleton.getObjectMapper().valueToTree(result);
JsonNode finalResult = ast.accept(new JmesPathEvaluationVisitor(), queryNode);
return AcceptorPathMatcher.pathAll(expectedResult, finalResult);
}
/**
* Represents the current waiter state in the case where resource state matches the expected state
*
* @return Corresponding state of the waiter
*/
@Override
public WaiterState getState() {
return WaiterState.SUCCESS;
}
}
}
| apache-2.0 |
DEVSENSE/PTVS | Python/Tests/Core.UI/PythonTestDefinitions.cs | 1170 | // Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// 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
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System.ComponentModel.Composition;
using TestUtilities.SharedProject;
namespace PythonToolsUITests {
public sealed class PythonTestDefintions {
[Export]
[ProjectExtension(".pyproj")]
[ProjectTypeGuid("888888a0-9f3d-457c-b088-3a5042f75d52")]
[CodeExtension(".py")]
[SampleCode("print('hi')")]
internal static ProjectTypeDefinition ProjectTypeDefinition = new ProjectTypeDefinition();
}
}
| apache-2.0 |
nurmuhammad/rvc | src/main/java/rvc/ann/After.java | 398 | package rvc.ann;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* @author nurmuhammad
*/
@Retention(RUNTIME)
@Target(METHOD)
public @interface After {
String value() default Constants.NULL_VALUE;
boolean absolutePath() default false;
} | apache-2.0 |
LorenzReinhart/ONOSnew | core/api/src/main/java/org/onosproject/net/intent/TopologyChangeDelegate.java | 1390 | /*
* Copyright 2014-present Open Networking Laboratory
*
* 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.onosproject.net.intent;
/**
* Auxiliary delegate for integration of intent manager and flow trackerService.
*/
public interface TopologyChangeDelegate {
/**
* Notifies that topology has changed in such a way that the specified
* intents should be recompiled. If the {@code compileAllFailed} parameter
* is true, then all intents in {@link org.onosproject.net.intent.IntentState#FAILED}
* state should be compiled as well.
*
* @param intentIds intents that should be recompiled
* @param compileAllFailed true implies full compile of all failed intents
* is required; false for selective recompile only
*/
void triggerCompile(Iterable<Key> intentIds, boolean compileAllFailed);
}
| apache-2.0 |
buerkle/mc-boom | src/main/java/com/thebuerkle/mcboom/packet/BlockChangePacket.java | 1174 | package com.thebuerkle.mcboom.packet;
import com.google.common.base.Objects;
import com.thebuerkle.mcboom.Buffers;
import com.thebuerkle.mcboom.DataType;
import org.jboss.netty.buffer.ChannelBuffer;
public class BlockChangePacket extends Packet {
public static final int ID = BLOCK_CHANGE;
public static final DataType[] ENCODING = new DataType[] {
DataType.mc_int,
DataType.mc_byte,
DataType.mc_int,
DataType.mc_short,
DataType.mc_byte
};
public final int x;
public final int y;
public final int z;
public final short type;
public final int metadata;
public BlockChangePacket(ChannelBuffer in) {
super(ID);
this.x = Buffers.mc_int(in);
this.y = Buffers.mc_byte(in);
this.z = Buffers.mc_int(in);
this.type = Buffers.mc_short(in);
this.metadata = Buffers.mc_byte(in);
}
@Override()
public String toString() {
return Objects.toStringHelper(this)
.add("x", x)
.add("y", y)
.add("z", z)
.add("type", type)
.add("metadata", metadata)
.toString();
}
}
| apache-2.0 |