repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
Netflix/msl
|
core/src/main/java/com/netflix/msl/msg/MessageContext.java
|
13988
|
/**
* Copyright (c) 2012-2018 Netflix, 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.netflix.msl.msg;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import com.netflix.msl.MslConstants.ResponseCode;
import com.netflix.msl.MslCryptoException;
import com.netflix.msl.MslEncodingException;
import com.netflix.msl.MslException;
import com.netflix.msl.MslKeyExchangeException;
import com.netflix.msl.MslMessageException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.keyx.KeyRequestData;
import com.netflix.msl.tokens.MslUser;
import com.netflix.msl.userauth.UserAuthenticationData;
/**
* <p>The message context provides the information that should be used to
* construct a single message. Each message should have its own context.</p>
*
* <p>All context methods may be called multiple times except for
* {@code #write(OutputStream)} which is guaranteed to be called only once.
* (The written data will be cached in memory in case the message needs to be
* resent.)</p>
*
* @author Wesley Miaw <wmiaw@netflix.com>
*/
public interface MessageContext {
/** Re-authentication reason codes. */
public static enum ReauthCode {
/** The user authentication data did not identify a user. */
USERDATA_REAUTH(ResponseCode.USERDATA_REAUTH),
/** The single-sign-on token was rejected as bad, invalid, or expired. */
SSOTOKEN_REJECTED(ResponseCode.SSOTOKEN_REJECTED),
;
/**
* @return the re-authentication code corresponding to the response
* code.
* @throws IllegalArgumentException if the response code does not map
* onto a re-authentication code.
*/
public static ReauthCode valueOf(final ResponseCode code) {
for (final ReauthCode value : ReauthCode.values()) {
if (value.code == code)
return value;
}
throw new IllegalArgumentException("Unknown reauthentication code value " + code + ".");
}
/**
* Create a new re-authentication code mapped from the specified
* response code.
*
* @param code the response code for the re-authentication code.
*/
private ReauthCode(final ResponseCode code) {
this.code = code;
}
/**
* @return the integer value of the response code.
*/
public int intValue() {
return code.intValue();
}
/** The response code value. */
private final ResponseCode code;
}
/**
* <p>Called when receiving a message to process service tokens.</p>
*
* <p>This method should return a map of crypto contexts by service token
* name for all known service tokens. If the service token name is not
* found then the crypto context mapped onto the empty string will be
* used if found.</p>
*
* @return the service token crypto contexts.
*/
public Map<String,ICryptoContext> getCryptoContexts();
/**
* <p>Called to identify the expected remote entity identity. If the remote
* entity identity is not known this method must return {@code null}.</p>
*
* <p>Trusted network servers may always return {@code null}.</p>
*
* @return the remote entity identity or {@code null} if the identity is
* not known.
*/
public String getRemoteEntityIdentity();
/**
* <p>Called to determine if the message application data must be
* encrypted.</p>
*
* @return true if the application data must be encrypted.
*/
public boolean isEncrypted();
/**
* <p>Called to determine if the message application data must be integrity
* protected.</p>
*
* @return true if the application data must be integrity protected.
*/
public boolean isIntegrityProtected();
/**
* <p>Called to determine if a message should be marked as non-replayable.</p>
*
* <p>Trusted network servers must always return {@code false}.</p>
*
* @return true if the application data should not be carried in a
* replayable message.
*/
public boolean isNonReplayable();
/**
* <p>Called to determine if a message is requesting a master token, user
* ID token, or service tokens.</p>
*
* <p>Trusted network servers must always return {@code false}.</p>
*
* @return true if the message must have a master token and user ID token
* (if associated with a user) or must be carried in a renewable
* message to acquire said tokens.
*/
public boolean isRequestingTokens();
/**
* <p>Called to identify the local user the message should be sent with. If
* a user ID token exists for this user it will be used.</p>
*
* <p>Trusted network servers must always return {@code null}.</p>
*
* <p>Any non-null value returned by this method must match the local user
* associated with the user authentication data returned by
* {@link #getUserAuthData(ReauthCode, boolean, boolean)}.</p>
*
* <p>This method may return a non-null value when
* {@link #getUserAuthData(ReauthCode, boolean, boolean)} will return null
* if the message should be associated with a user but there is no user
* authentication data. For example during new user creation.</p>
*
* <p>This method must return {@code null} if the message should not be
* associated with a user and
* {@link #getUserAuthData(ReauthCode, boolean, boolean)} will also return
* {@code null}.</p>
*
* @return the local user identity or null.
*/
public String getUserId();
/**
* <p>Called if the user ID is not {@code null} to attach user
* authentication data to messages.</p>
*
* <p>Trusted network servers must always return {@code null}.</p>
*
* <p>This method should return user authentication data if the message
* should be associated with a user that has not already received a user ID
* token. This may involve prompting the user for credentials. If the
* message should not be associated with a user, a user ID token already
* exists for the user, or if user credentials are unavailable then this
* method should return {@code null}.</p>
*
* <p>The one exception is if the application wishes to re-authenticate the
* user against the current user ID token in which case this method should
* return user authentication data. The {@code renewable} parameter may be
* used to limit this operation to renewable messages.</p>
*
* <p>This method may be called if user re-authentication is required for
* the transaction to complete. If the application knows that user
* authentication is required for the request being sent and is unable to
* provide user authentication data then it should attempt to cancel the
* request and return {@code null}.</p>
*
* <p>If the {@code reauthCode} parameter is non-{@code null} then new user
* authentication data should be returned for this and all subsequent calls.
* The application may wish to return {@code null} if it knows that the
* request being sent can no longer succeed because the existing user ID
* token or service tokens are no longer valid. This will abort the
* request. Note that a {@code reauthCode} argument may be provided even if
* no user authentication data was included in the message.</p>
*
* <p>If the {@code required} parameter is true then user authentication
* should be returned for this call, even if a user ID token already exists
* for the user. {@code null} should still be returned when {@code required}
* is true if the message should be associated with a user but there is no
* user authentication data. For example during new user creation.</p>
*
* <p>This method will be called multiple times.</p>
*
* @param reauthCode non-{@code null} if new user authentication data is
* required. The reason the old user authentication data was
* rejected is identified by the code.
* @param renewable true if the message being sent is renewable.
* @param required true if user authentication data must be returned.
* @return the user authentication data or null.
*/
public UserAuthenticationData getUserAuthData(final ReauthCode reauthCode, final boolean renewable, final boolean required);
/**
* <p>Called if a message does not contain a user ID token for the remote
* user.</p>
*
* <p>Trusted network clients must always return {@code null}.</p>
*
* <p>If a non-null value is returned by this method and a master token
* exists for the remote entity then a new user ID token will be created
* for the remote user and sent in the message. This is not the user
* identified by {@link #getUserId()} or authenticated by
* {@link #getUserAuthData(ReauthCode, boolean, boolean)} as those methods
* are used for the local user.</p>
*
* @return the user to attach to the message or null.
*/
public MslUser getUser();
/**
* <p>Called if a request is eligible for key exchange (i.e. the request
* is renewable and contains entity authentication data or a renewable
* master token).</p>
*
* <p>Trusted network servers must always return the empty set.</p>
*
* <p>This method must return key request data for all supported key
* exchange schemes. Failure to provide any key request data may result in
* message delivery failures.</p>
*
* <p>This method may also be called if entity re-authentication is required
* for the transaction to complete.</p>
*
* @return the key request data. May be the empty set.
* @throws MslKeyExchangeException if there is an error generating the key
* request data.
*/
public Set<KeyRequestData> getKeyRequestData() throws MslKeyExchangeException;
/**
* <p>Called prior to message sending to allow the processor to modify the
* message being built.</p>
*
* <p>The boolean {@code handshake} will be true if the function is being
* called for a handshake message that must be sent before the application
* data can be sent. The builder for handshake messages may lack a master
* token, user ID token, and other bound service tokens.</p>
*
* <p>The processor must not attempt to access or retain a reference to the
* builder after this function completes.</p>
*
* <p>This method will be called multiple times. The set of service tokens
* managed by the provided message service token builder may be different
* for each call. The processor should treat each call to this method
* independently from each other.</p>
*
* @param builder message service token builder.
* @param handshake true if the provided builder is for a handshake message.
* @throws MslMessageException if the builder throws an exception or the
* desired service tokens cannot be attached.
* @throws MslCryptoException if there is an error encrypting or signing
* the service token data.
* @throws MslEncodingException if there is an error encoding the service
* token JSON data.
* @throws MslException if there is an error compressing the data.
* @see com.netflix.msl.MslError#RESPONSE_REQUIRES_MASTERTOKEN
* @see com.netflix.msl.MslError#RESPONSE_REQUIRES_USERIDTOKEN
*/
public void updateServiceTokens(final MessageServiceTokenBuilder builder, final boolean handshake) throws MslMessageException, MslCryptoException, MslEncodingException, MslException;
/**
* <p>Called when the message is ready to be sent. The processor should
* use the provided {@code MessageOutputStream} to write its application
* data. This method will only be called once.</p>
*
* <p>The processor must not attempt to access or retain a reference to the
* message output stream after this function completes. It is okay for this
* method to be long-running as the data will be streamed.</p>
*
* <p>If application data must be sent before the remote entity can reply
* then this method must call {@link MessageOutputStream#flush()} before
* returning. If all of the application data must be sent before the remote
* entity can reply then this method must call
* {@link MessageOutputStream#close()} before returning. Closing the
* message output stream will prevent further use of the output stream
* returned by {@link MslControl}.</p>
*
* @param output message output stream.
* @throws IOException if the output stream throws an I/O exception.
*/
public void write(final MessageOutputStream output) throws IOException;
/**
* Returns a message debug context applicable to the message being sent or
* received.
*
* @return the message debug context or {@code null} if there is none.
*/
public MessageDebugContext getDebugContext();
}
|
apache-2.0
|
waans11/incubator-asterixdb-hyracks
|
algebricks/algebricks-core/src/main/java/org/apache/hyracks/algebricks/core/algebra/operators/logical/AbstractLogicalOperator.java
|
7076
|
/*
* 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.hyracks.algebricks.core.algebra.operators.logical;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.mutable.Mutable;
import org.apache.hyracks.algebricks.common.exceptions.AlgebricksException;
import org.apache.hyracks.algebricks.core.algebra.base.IHyracksJobBuilder;
import org.apache.hyracks.algebricks.core.algebra.base.ILogicalOperator;
import org.apache.hyracks.algebricks.core.algebra.base.IOptimizationContext;
import org.apache.hyracks.algebricks.core.algebra.base.IPhysicalOperator;
import org.apache.hyracks.algebricks.core.algebra.base.LogicalOperatorTag;
import org.apache.hyracks.algebricks.core.algebra.base.LogicalVariable;
import org.apache.hyracks.algebricks.core.algebra.expressions.IVariableTypeEnvironment;
import org.apache.hyracks.algebricks.core.algebra.properties.IPhysicalPropertiesVector;
import org.apache.hyracks.algebricks.core.algebra.properties.PhysicalRequirements;
import org.apache.hyracks.algebricks.core.algebra.properties.TypePropagationPolicy;
import org.apache.hyracks.algebricks.core.algebra.typing.ITypeEnvPointer;
import org.apache.hyracks.algebricks.core.algebra.typing.ITypingContext;
import org.apache.hyracks.algebricks.core.algebra.typing.OpRefTypeEnvPointer;
import org.apache.hyracks.algebricks.core.algebra.typing.PropagatingTypeEnvironment;
import org.apache.hyracks.algebricks.core.jobgen.impl.JobGenContext;
public abstract class AbstractLogicalOperator implements ILogicalOperator {
/*********************************************************************
* UNPARTITIONED, the input data is not partitioned
* PARTITIONED, the input data is partitioned, the operator is executed on
* each partition and may receive input from other partitions (e.g. if it is
* a join or an aggregate)
* LOCAL, the input data is partitioned, the operator is executed on each
* partition and only processes data from that partition
*/
public static enum ExecutionMode {
UNPARTITIONED,
PARTITIONED,
LOCAL
}
private AbstractLogicalOperator.ExecutionMode mode = AbstractLogicalOperator.ExecutionMode.UNPARTITIONED;
protected IPhysicalOperator physicalOperator;
private final Map<String, Object> annotations = new HashMap<String, Object>();
private boolean bJobGenEnabled = true;
final protected List<Mutable<ILogicalOperator>> inputs;
// protected List<LogicalOperatorReference> outputs;
protected List<LogicalVariable> schema;
public AbstractLogicalOperator() {
inputs = new ArrayList<Mutable<ILogicalOperator>>();
}
@Override
public abstract LogicalOperatorTag getOperatorTag();
@Override
public ExecutionMode getExecutionMode() {
return mode;
}
public void setExecutionMode(ExecutionMode mode) {
this.mode = mode;
}
@Override
public List<LogicalVariable> getSchema() {
return schema;
}
public void setPhysicalOperator(IPhysicalOperator physicalOp) {
this.physicalOperator = physicalOp;
}
public IPhysicalOperator getPhysicalOperator() {
return physicalOperator;
}
/**
* @return for each child, one vector of required physical properties
*/
@Override
public final PhysicalRequirements getRequiredPhysicalPropertiesForChildren(
IPhysicalPropertiesVector requiredProperties) {
return physicalOperator.getRequiredPropertiesForChildren(this, requiredProperties);
}
/**
* @return the physical properties that this operator delivers, based on
* what its children deliver
*/
@Override
public final IPhysicalPropertiesVector getDeliveredPhysicalProperties() {
return physicalOperator.getDeliveredProperties();
}
@Override
public final void computeDeliveredPhysicalProperties(IOptimizationContext context) throws AlgebricksException {
physicalOperator.computeDeliveredProperties(this, context);
}
@Override
public final List<Mutable<ILogicalOperator>> getInputs() {
return inputs;
}
// @Override
// public final List<LogicalOperatorReference> getOutputs() {
// return outputs;
// }
@Override
public final boolean hasInputs() {
return !inputs.isEmpty();
}
public boolean hasNestedPlans() {
return false;
}
@Override
public Map<String, Object> getAnnotations() {
return annotations;
}
@Override
public void removeAnnotation(String annotationName) {
annotations.remove(annotationName);
}
@Override
public final void contributeRuntimeOperator(IHyracksJobBuilder builder, JobGenContext context,
IOperatorSchema propagatedSchema, IOperatorSchema[] inputSchemas, IOperatorSchema outerPlanSchema)
throws AlgebricksException {
if (bJobGenEnabled) {
if (physicalOperator == null) {
throw new AlgebricksException("Physical operator not set for operator: " + this);
}
physicalOperator.contributeRuntimeOperator(builder, context, this, propagatedSchema, inputSchemas,
outerPlanSchema);
}
}
public void disableJobGen() {
bJobGenEnabled = false;
}
public boolean isJobGenEnabled() {
return bJobGenEnabled;
}
@Override
public IVariableTypeEnvironment computeInputTypeEnvironment(ITypingContext ctx) throws AlgebricksException {
return createPropagatingAllInputsTypeEnvironment(ctx);
}
protected PropagatingTypeEnvironment createPropagatingAllInputsTypeEnvironment(ITypingContext ctx) {
int n = inputs.size();
ITypeEnvPointer[] envPointers = new ITypeEnvPointer[n];
for (int i = 0; i < n; i++) {
envPointers[i] = new OpRefTypeEnvPointer(inputs.get(i), ctx);
}
return new PropagatingTypeEnvironment(ctx.getExpressionTypeComputer(), ctx.getNullableTypeComputer(),
ctx.getMetadataProvider(), TypePropagationPolicy.ALL, envPointers);
}
@Override
public boolean requiresVariableReferenceExpressions() {
return true;
}
}
|
apache-2.0
|
PrinceChou/IotSdk
|
src/com/iotsdk/config/SdkConfig.java
|
1490
|
package com.iotsdk.config;
import java.text.SimpleDateFormat;
import android.os.Environment;
public class SdkConfig {
public static String TAG="sdk config";
public static String IOSDK_SD_DB_DEFAULT_PATH="";
public final static String SHAREDPR_ENAME = "kinder_sdk_config";
public final static String ROOT = Environment.getExternalStorageDirectory()
.getPath() + "/nuagesys/";
public final static String THUMB_PATH = ROOT + "thumb/";
public final static String PHOTO_TAKE_PATH = ROOT + "photo/";
public final static String ADUIO_TAKE_PATH = ROOT + "aduio/";
public final static String DATABASE_PATH = ROOT + "database/";
public final static String APP_PATH = ROOT + "app/";
public final static String PDF_PATH = ROOT + "pdf/";
public final static SimpleDateFormat DEFAULT_DATA_FORMAT = new SimpleDateFormat(
"yyyyMMddHHmmss");
public final static String SKEY_LAST_READ_NOTICE = "last_read_notice_time:user%1$s";
public static final String NUAGE_PIC_JPG_SUFFIX = ".jpg";
/**
* 图片的压缩质量
*/
public static final int PHOTO_QUALITY = 80;
/**
* 缩略图的压缩质量
*/
public static final int PHOTO_THUMBNAIL_QUALITY = 60;
/**
* 缩略图默认大小
*/
public static final int MEDIA_THUMBNAIL_DEFAULT_WIDTH = 256;
public static final int MEDIA_THUMBNAIL_DEFAULT_HEIGHT = 256;
/**
* 相机拍照图默认大小
*/
public static final int MEDIA_DEFAULT_WIDTH = 640;
public static final int MEDIA_DEFAULT_HEIGHT = 960;
}
|
apache-2.0
|
stankovski/azure-sdk-for-net
|
sdk/network/Azure.ResourceManager.Network/src/Generated/ExpressRoutePortsOperations.cs
|
19959
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager.Network.Models;
namespace Azure.ResourceManager.Network
{
/// <summary> The ExpressRoutePorts service client. </summary>
public partial class ExpressRoutePortsOperations
{
private readonly ClientDiagnostics _clientDiagnostics;
private readonly HttpPipeline _pipeline;
internal ExpressRoutePortsRestOperations RestClient { get; }
/// <summary> Initializes a new instance of ExpressRoutePortsOperations for mocking. </summary>
protected ExpressRoutePortsOperations()
{
}
/// <summary> Initializes a new instance of ExpressRoutePortsOperations. </summary>
/// <param name="clientDiagnostics"> The handler for diagnostic messaging in the client. </param>
/// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="endpoint"> server parameter. </param>
internal ExpressRoutePortsOperations(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string subscriptionId, Uri endpoint = null)
{
RestClient = new ExpressRoutePortsRestOperations(clientDiagnostics, pipeline, subscriptionId, endpoint);
_clientDiagnostics = clientDiagnostics;
_pipeline = pipeline;
}
/// <summary> Retrieves the requested ExpressRoutePort resource. </summary>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="expressRoutePortName"> The name of ExpressRoutePort. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<Response<ExpressRoutePort>> GetAsync(string resourceGroupName, string expressRoutePortName, CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("ExpressRoutePortsOperations.Get");
scope.Start();
try
{
return await RestClient.GetAsync(resourceGroupName, expressRoutePortName, cancellationToken).ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Retrieves the requested ExpressRoutePort resource. </summary>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="expressRoutePortName"> The name of ExpressRoutePort. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response<ExpressRoutePort> Get(string resourceGroupName, string expressRoutePortName, CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("ExpressRoutePortsOperations.Get");
scope.Start();
try
{
return RestClient.Get(resourceGroupName, expressRoutePortName, cancellationToken);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Update ExpressRoutePort tags. </summary>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="expressRoutePortName"> The name of the ExpressRoutePort resource. </param>
/// <param name="parameters"> Parameters supplied to update ExpressRoutePort resource tags. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<Response<ExpressRoutePort>> UpdateTagsAsync(string resourceGroupName, string expressRoutePortName, TagsObject parameters, CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("ExpressRoutePortsOperations.UpdateTags");
scope.Start();
try
{
return await RestClient.UpdateTagsAsync(resourceGroupName, expressRoutePortName, parameters, cancellationToken).ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Update ExpressRoutePort tags. </summary>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="expressRoutePortName"> The name of the ExpressRoutePort resource. </param>
/// <param name="parameters"> Parameters supplied to update ExpressRoutePort resource tags. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response<ExpressRoutePort> UpdateTags(string resourceGroupName, string expressRoutePortName, TagsObject parameters, CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("ExpressRoutePortsOperations.UpdateTags");
scope.Start();
try
{
return RestClient.UpdateTags(resourceGroupName, expressRoutePortName, parameters, cancellationToken);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> List all the ExpressRoutePort resources in the specified resource group. </summary>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual AsyncPageable<ExpressRoutePort> ListByResourceGroupAsync(string resourceGroupName, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
async Task<Page<ExpressRoutePort>> FirstPageFunc(int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("ExpressRoutePortsOperations.ListByResourceGroup");
scope.Start();
try
{
var response = await RestClient.ListByResourceGroupAsync(resourceGroupName, cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
async Task<Page<ExpressRoutePort>> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("ExpressRoutePortsOperations.ListByResourceGroup");
scope.Start();
try
{
var response = await RestClient.ListByResourceGroupNextPageAsync(nextLink, resourceGroupName, cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary> List all the ExpressRoutePort resources in the specified resource group. </summary>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Pageable<ExpressRoutePort> ListByResourceGroup(string resourceGroupName, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
Page<ExpressRoutePort> FirstPageFunc(int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("ExpressRoutePortsOperations.ListByResourceGroup");
scope.Start();
try
{
var response = RestClient.ListByResourceGroup(resourceGroupName, cancellationToken);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
Page<ExpressRoutePort> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("ExpressRoutePortsOperations.ListByResourceGroup");
scope.Start();
try
{
var response = RestClient.ListByResourceGroupNextPage(nextLink, resourceGroupName, cancellationToken);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary> List all the ExpressRoutePort resources in the specified subscription. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual AsyncPageable<ExpressRoutePort> ListAsync(CancellationToken cancellationToken = default)
{
async Task<Page<ExpressRoutePort>> FirstPageFunc(int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("ExpressRoutePortsOperations.List");
scope.Start();
try
{
var response = await RestClient.ListAsync(cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
async Task<Page<ExpressRoutePort>> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("ExpressRoutePortsOperations.List");
scope.Start();
try
{
var response = await RestClient.ListNextPageAsync(nextLink, cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary> List all the ExpressRoutePort resources in the specified subscription. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Pageable<ExpressRoutePort> List(CancellationToken cancellationToken = default)
{
Page<ExpressRoutePort> FirstPageFunc(int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("ExpressRoutePortsOperations.List");
scope.Start();
try
{
var response = RestClient.List(cancellationToken);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
Page<ExpressRoutePort> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("ExpressRoutePortsOperations.List");
scope.Start();
try
{
var response = RestClient.ListNextPage(nextLink, cancellationToken);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary> Deletes the specified ExpressRoutePort resource. </summary>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="expressRoutePortName"> The name of the ExpressRoutePort resource. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<ExpressRoutePortsDeleteOperation> StartDeleteAsync(string resourceGroupName, string expressRoutePortName, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (expressRoutePortName == null)
{
throw new ArgumentNullException(nameof(expressRoutePortName));
}
using var scope = _clientDiagnostics.CreateScope("ExpressRoutePortsOperations.StartDelete");
scope.Start();
try
{
var originalResponse = await RestClient.DeleteAsync(resourceGroupName, expressRoutePortName, cancellationToken).ConfigureAwait(false);
return new ExpressRoutePortsDeleteOperation(_clientDiagnostics, _pipeline, RestClient.CreateDeleteRequest(resourceGroupName, expressRoutePortName).Request, originalResponse);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Deletes the specified ExpressRoutePort resource. </summary>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="expressRoutePortName"> The name of the ExpressRoutePort resource. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual ExpressRoutePortsDeleteOperation StartDelete(string resourceGroupName, string expressRoutePortName, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (expressRoutePortName == null)
{
throw new ArgumentNullException(nameof(expressRoutePortName));
}
using var scope = _clientDiagnostics.CreateScope("ExpressRoutePortsOperations.StartDelete");
scope.Start();
try
{
var originalResponse = RestClient.Delete(resourceGroupName, expressRoutePortName, cancellationToken);
return new ExpressRoutePortsDeleteOperation(_clientDiagnostics, _pipeline, RestClient.CreateDeleteRequest(resourceGroupName, expressRoutePortName).Request, originalResponse);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Creates or updates the specified ExpressRoutePort resource. </summary>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="expressRoutePortName"> The name of the ExpressRoutePort resource. </param>
/// <param name="parameters"> Parameters supplied to the create ExpressRoutePort operation. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<ExpressRoutePortsCreateOrUpdateOperation> StartCreateOrUpdateAsync(string resourceGroupName, string expressRoutePortName, ExpressRoutePort parameters, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (expressRoutePortName == null)
{
throw new ArgumentNullException(nameof(expressRoutePortName));
}
if (parameters == null)
{
throw new ArgumentNullException(nameof(parameters));
}
using var scope = _clientDiagnostics.CreateScope("ExpressRoutePortsOperations.StartCreateOrUpdate");
scope.Start();
try
{
var originalResponse = await RestClient.CreateOrUpdateAsync(resourceGroupName, expressRoutePortName, parameters, cancellationToken).ConfigureAwait(false);
return new ExpressRoutePortsCreateOrUpdateOperation(_clientDiagnostics, _pipeline, RestClient.CreateCreateOrUpdateRequest(resourceGroupName, expressRoutePortName, parameters).Request, originalResponse);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Creates or updates the specified ExpressRoutePort resource. </summary>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="expressRoutePortName"> The name of the ExpressRoutePort resource. </param>
/// <param name="parameters"> Parameters supplied to the create ExpressRoutePort operation. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual ExpressRoutePortsCreateOrUpdateOperation StartCreateOrUpdate(string resourceGroupName, string expressRoutePortName, ExpressRoutePort parameters, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (expressRoutePortName == null)
{
throw new ArgumentNullException(nameof(expressRoutePortName));
}
if (parameters == null)
{
throw new ArgumentNullException(nameof(parameters));
}
using var scope = _clientDiagnostics.CreateScope("ExpressRoutePortsOperations.StartCreateOrUpdate");
scope.Start();
try
{
var originalResponse = RestClient.CreateOrUpdate(resourceGroupName, expressRoutePortName, parameters, cancellationToken);
return new ExpressRoutePortsCreateOrUpdateOperation(_clientDiagnostics, _pipeline, RestClient.CreateCreateOrUpdateRequest(resourceGroupName, expressRoutePortName, parameters).Request, originalResponse);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
}
}
|
apache-2.0
|
frankdede/CMPUT466Project
|
feature.py
|
65
|
import nltk
from bigram import bigram
from unigram import unigram
|
apache-2.0
|
srinivasiyerb/Scholst
|
target/Scholastic/static/js/ext/src/ext-core/examples/jsonp/jsonp.js
|
2434
|
/*!
* Ext JS Library 3.3.1
* Copyright(c) 2006-2010 Sencha Inc.
* licensing@sencha.com
* http://www.sencha.com/license
*/
Ext.ns('Ext.ux');
Ext.ux.JSONP = (function(){
var _queue = [],
_current = null,
_nextRequest = function() {
_current = null;
if(_queue.length) {
_current = _queue.shift();
_current.script.src = _current.url + '?' + _current.params;
document.getElementsByTagName('head')[0].appendChild(_current.script);
}
};
return {
request: function(url, o) {
if(!url) {
return;
}
var me = this;
o.params = o.params || {};
if(o.callbackKey) {
o.params[o.callbackKey] = 'Ext.ux.JSONP.callback';
}
var params = Ext.urlEncode(o.params);
var script = document.createElement('script');
script.type = 'text/javascript';
if(o.isRawJSON) {
if(Ext.isIE) {
Ext.fly(script).on('readystatechange', function() {
if(script.readyState == 'complete') {
var data = script.innerHTML;
if(data.length) {
me.callback(Ext.decode(data));
}
}
});
}
else {
Ext.fly(script).on('load', function() {
var data = script.innerHTML;
if(data.length) {
me.callback(Ext.decode(data));
}
});
}
}
_queue.push({
url: url,
script: script,
callback: o.callback || function(){},
scope: o.scope || window,
params: params || null
});
if(!_current) {
_nextRequest();
}
},
callback: function(json) {
_current.callback.apply(_current.scope, [json]);
Ext.fly(_current.script).removeAllListeners();
document.getElementsByTagName('head')[0].removeChild(_current.script);
_nextRequest();
}
}
})();
|
apache-2.0
|
BlockHorizons/BlockPets
|
src/BlockHorizons/BlockPets/pets/creatures/SquidPet.php
|
321
|
<?php
declare(strict_types = 1);
namespace BlockHorizons\BlockPets\pets\creatures;
use BlockHorizons\BlockPets\pets\SwimmingPet;
class SquidPet extends SwimmingPet {
const NETWORK_NAME = "SQUID_PET";
const NETWORK_ORIG_ID = self::SQUID;
public $width = 0.8;
public $height = 0.8;
public $name = "Squid Pet";
}
|
apache-2.0
|
crysehillmes/PersistentSearchView
|
persistentsearchview/src/main/java/io/codetail/animation/SupportAnimator.java
|
6514
|
package io.codetail.animation;
import android.view.animation.Interpolator;
import java.lang.ref.WeakReference;
public abstract class SupportAnimator {
WeakReference<RevealAnimator> mTarget;
public SupportAnimator(RevealAnimator target) {
mTarget = new WeakReference<>(target);
}
/**
* @return true if using native android animation framework, otherwise is
* nineoldandroids
*/
public abstract boolean isNativeAnimator();
/**
* @return depends from {@link android.os.Build.VERSION} if sdk version
* {@link android.os.Build.VERSION_CODES#LOLLIPOP} and greater will return
* {@link android.animation.Animator}
*/
public abstract Object get();
/**
* Starts this animation. If the animation has a nonzero startDelay, the animation will start
* running after that delay elapses. A non-delayed animation will have its initial
* value(s) set immediately, followed by calls to
* {@link android.animation.Animator.AnimatorListener#onAnimationStart(android.animation.Animator)}
* for any listeners of this animator.
*
* <p>The animation started by calling this method will be run on the thread that called
* this method. This thread should have a Looper on it (a runtime exception will be thrown if
* this is not the case). Also, if the animation will animate
* properties of objects in the view hierarchy, then the calling thread should be the UI
* thread for that view hierarchy.</p>
*
*/
public abstract void start();
/**
* Sets the duration of the animation.
*
* @param duration The length of the animation, in milliseconds.
*/
public abstract void setDuration(int duration);
/**
* The time interpolator used in calculating the elapsed fraction of the
* animation. The interpolator determines whether the animation runs with
* linear or non-linear motion, such as acceleration and deceleration. The
* default value is {@link android.view.animation.AccelerateDecelerateInterpolator}.
*
* @param value the interpolator to be used by this animation
*/
public abstract void setInterpolator(Interpolator value);
/**
* Adds a listener to the set of listeners that are sent events through the life of an
* animation, such as start, repeat, and end.
*
* @param listener the listener to be added to the current set of listeners for this animation.
*/
public abstract void addListener(AnimatorListener listener);
/**
* Returns whether this Animator is currently running (having been started and gone past any
* initial startDelay period and not yet ended).
*
* @return Whether the Animator is running.
*/
public abstract boolean isRunning();
/**
* Cancels the animation. Unlike {@link #end()}, <code>cancel()</code> causes the animation to
* stop in its tracks, sending an
* {@link AnimatorListener#onAnimationCancel()} to
* its listeners, followed by an
* {@link AnimatorListener#onAnimationEnd()} message.
*
* <p>This method must be called on the thread that is running the animation.</p>
*/
public abstract void cancel();
/**
* Ends the animation. This causes the animation to assign the end value of the property being
* animated, then calling the
* {@link AnimatorListener#onAnimationEnd()} method on
* its listeners.
*
* <p>This method must be called on the thread that is running the animation.</p>
*/
public void end() {
}
/**
* This method tells the object to use appropriate information to extract
* starting values for the animation. For example, a AnimatorSet object will pass
* this call to its child objects to tell them to set up the values. A
* ObjectAnimator object will use the information it has about its target object
* and PropertyValuesHolder objects to get the start values for its properties.
* A ValueAnimator object will ignore the request since it does not have enough
* information (such as a target object) to gather these values.
*/
public void setupStartValues() {
}
/**
* This method tells the object to use appropriate information to extract
* ending values for the animation. For example, a AnimatorSet object will pass
* this call to its child objects to tell them to set up the values. A
* ObjectAnimator object will use the information it has about its target object
* and PropertyValuesHolder objects to get the start values for its properties.
* A ValueAnimator object will ignore the request since it does not have enough
* information (such as a target object) to gather these values.
*/
public void setupEndValues() {
}
/**
* Experimental feature
*/
public SupportAnimator reverse() {
if(isRunning()){
return null;
}
RevealAnimator target = mTarget.get();
if(target != null){
return target.startReverseAnimation();
}
return null;
}
/**
* <p>An animation listener receives notifications from an animation.
* Notifications indicate animation related events, such as the end or the
* repetition of the animation.</p>
*/
public interface AnimatorListener {
/**
* <p>Notifies the start of the animation.</p>
*/
void onAnimationStart();
/**
* <p>Notifies the end of the animation. This callback is not invoked
* for animations with repeat count set to INFINITE.</p>
*/
void onAnimationEnd();
/**
* <p>Notifies the cancellation of the animation. This callback is not invoked
* for animations with repeat count set to INFINITE.</p>
*/
void onAnimationCancel();
/**
* <p>Notifies the repetition of the animation.</p>
*/
void onAnimationRepeat();
}
/**
* <p>Provides default implementation for AnimatorListener.</p>
*/
public static abstract class SimpleAnimatorListener implements AnimatorListener {
@Override
public void onAnimationStart() {
}
@Override
public void onAnimationEnd() {
}
@Override
public void onAnimationCancel() {
}
@Override
public void onAnimationRepeat() {
}
}
}
|
apache-2.0
|
davidbz/trafficserver
|
iocore/net/quic/QUICIntUtil.cc
|
2958
|
/** @file
*
* A brief file description
*
* @section license License
*
* 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.
*/
#include "QUICIntUtil.h"
#include "tscore/ink_endian.h"
#include <memory>
#include <cstring>
size_t
QUICVariableInt::size(const uint8_t *src)
{
return 1 << (src[0] >> 6);
}
size_t
QUICVariableInt::size(uint64_t src)
{
uint8_t flag = 0;
if (src > 4611686018427387903) {
// max usable bits is 62
return 0;
} else if (src > 1073741823) {
flag = 0x03;
} else if (src > 16383) {
flag = 0x02;
} else if (src > 63) {
flag = 0x01;
} else {
flag = 0x00;
}
return 1 << flag;
}
int
QUICVariableInt::encode(uint8_t *dst, size_t dst_len, size_t &len, uint64_t src)
{
uint8_t flag = 0;
if (src > 4611686018427387903) {
// max usable bits is 62
return 1;
} else if (src > 1073741823) {
flag = 0x03;
} else if (src > 16383) {
flag = 0x02;
} else if (src > 63) {
flag = 0x01;
} else {
flag = 0x00;
}
len = 1 << flag;
if (len > dst_len) {
return 1;
}
size_t dummy = 0;
QUICIntUtil::write_uint_as_nbytes(src, len, dst, &dummy);
dst[0] |= (flag << 6);
return 0;
}
int
QUICVariableInt::decode(uint64_t &dst, size_t &len, const uint8_t *src, size_t src_len)
{
if (src_len < 1) {
return -1;
}
len = 1 << (src[0] >> 6);
if (src_len < len) {
return 1;
}
uint8_t buf[8] = {0};
memcpy(buf, src, len);
buf[0] &= 0x3f;
dst = QUICIntUtil::read_nbytes_as_uint(buf, len);
return 0;
}
uint64_t
QUICIntUtil::read_QUICVariableInt(const uint8_t *buf)
{
uint64_t dst = 0;
size_t len = 0;
QUICVariableInt::decode(dst, len, buf, 8);
return dst;
}
void
QUICIntUtil::write_QUICVariableInt(uint64_t data, uint8_t *buf, size_t *len)
{
QUICVariableInt::encode(buf, 8, *len, data);
}
uint64_t
QUICIntUtil::read_nbytes_as_uint(const uint8_t *buf, uint8_t n)
{
uint64_t value = 0;
memcpy(&value, buf, n);
return be64toh(value << (64 - n * 8));
}
void
QUICIntUtil::write_uint_as_nbytes(uint64_t value, uint8_t n, uint8_t *buf, size_t *len)
{
value = htobe64(value) >> (64 - n * 8);
memcpy(buf, reinterpret_cast<uint8_t *>(&value), n);
*len = n;
}
|
apache-2.0
|
weitenghuang/dirigent-cli
|
cmd/version.go
|
310
|
package cmd
import (
"fmt"
"github.com/spf13/cobra"
)
var versionCmd = &cobra.Command{
Use: "version",
Short: "Print the version number of dirigent",
Long: `Print dirigent's current version number`,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("dirigent is on version v0.0.1")
},
}
|
apache-2.0
|
dads-software-brotherhood/sekc
|
node_modules/generator-jhipster/generators/client/templates/angular/src/main/webapp/app/shared/_shared.module.ts
|
2259
|
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { DatePipe } from '@angular/common';
import { CookieService } from 'angular2-cookie/services/cookies.service';
import {
<%=angular2AppName%>SharedLibsModule,
<%=angular2AppName%>SharedCommonModule,
CSRFService,
AuthService,
<%_ if (!skipServer) { _%>
AuthServerProvider,
<%_ } _%>
AccountService,
<%_ if (!skipUserManagement) { _%>
UserService,
<%_ } _%>
StateStorageService,
LoginService,
LoginModalService,
Principal,
<%_ if (websocket === 'spring-websocket') { _%>
<%=jhiPrefixCapitalized%>TrackerService,
<%_ } _%>
HasAnyAuthorityDirective,
<%_ if (enableSocialSignIn) { _%>
<%=jhiPrefixCapitalized%>SocialComponent,
SocialService,
<%_ } _%>
<%=jhiPrefixCapitalized%>LoginModalComponent
} from './';
@NgModule({
imports: [
<%=angular2AppName%>SharedLibsModule,
<%=angular2AppName%>SharedCommonModule
],
declarations: [
<%_ if (enableSocialSignIn) { _%>
<%=jhiPrefixCapitalized%>SocialComponent,
<%_ } _%>
<%=jhiPrefixCapitalized%>LoginModalComponent,
HasAnyAuthorityDirective
],
providers: [
CookieService,
LoginService,
LoginModalService,
AccountService,
StateStorageService,
Principal,
CSRFService,
<%_ if (websocket === 'spring-websocket') { _%>
<%=jhiPrefixCapitalized%>TrackerService,
<%_ } _%>
<%_ if (!skipServer) { _%>
AuthServerProvider,
<%_ } _%>
<%_ if (enableSocialSignIn) { _%>
SocialService,
<%_ } _%>
AuthService,
<%_ if (!skipUserManagement) { _%>
UserService,
<%_ } _%>
DatePipe
],
entryComponents: [<%=jhiPrefixCapitalized%>LoginModalComponent],
exports: [
<%=angular2AppName%>SharedCommonModule,
<%_ if (enableSocialSignIn) { _%>
<%=jhiPrefixCapitalized%>SocialComponent,
<%_ } _%>
<%=jhiPrefixCapitalized%>LoginModalComponent,
HasAnyAuthorityDirective,
DatePipe
],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class <%=angular2AppName%>SharedModule {}
|
apache-2.0
|
stdlib-js/stdlib
|
lib/node_modules/@stdlib/stats/base/dnanmeanwd/src/addon.cpp
|
3615
|
/**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib 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.
*/
#include "stdlib/stats/base/dnanmeanwd.h"
#include <node_api.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
/**
* Add-on namespace.
*/
namespace stdlib_stats_base_dnanmeanwd {
/**
* Computes the arithmetic mean of a double-precision floating-point strided array, using Welford's algorithm and ignoring `NaN` values.
*
* ## Notes
*
* - When called from JavaScript, the function expects three arguments:
*
* - `N`: number of indexed elements
* - `X`: input array
* - `stride`: stride length
*/
napi_value node_dnanmeanwd( napi_env env, napi_callback_info info ) {
napi_status status;
size_t argc = 3;
napi_value argv[ 3 ];
status = napi_get_cb_info( env, info, &argc, argv, nullptr, nullptr );
assert( status == napi_ok );
if ( argc < 3 ) {
napi_throw_error( env, nullptr, "invalid invocation. Must provide 3 arguments." );
return nullptr;
}
napi_valuetype vtype0;
status = napi_typeof( env, argv[ 0 ], &vtype0 );
assert( status == napi_ok );
if ( vtype0 != napi_number ) {
napi_throw_type_error( env, nullptr, "invalid argument. First argument must be a number." );
return nullptr;
}
bool res;
status = napi_is_typedarray( env, argv[ 1 ], &res );
assert( status == napi_ok );
if ( res == false ) {
napi_throw_type_error( env, nullptr, "invalid argument. Second argument must be a Float64Array." );
return nullptr;
}
napi_valuetype vtype2;
status = napi_typeof( env, argv[ 2 ], &vtype2 );
assert( status == napi_ok );
if ( vtype2 != napi_number ) {
napi_throw_type_error( env, nullptr, "invalid argument. Third argument must be a number." );
return nullptr;
}
int64_t N;
status = napi_get_value_int64( env, argv[ 0 ], &N );
assert( status == napi_ok );
int64_t stride;
status = napi_get_value_int64( env, argv[ 2 ], &stride );
assert( status == napi_ok );
napi_typedarray_type vtype1;
size_t xlen;
void *X;
status = napi_get_typedarray_info( env, argv[ 1 ], &vtype1, &xlen, &X, nullptr, nullptr );
assert( status == napi_ok );
if ( vtype1 != napi_float64_array ) {
napi_throw_type_error( env, nullptr, "invalid argument. Second argument must be a Float64Array." );
return nullptr;
}
if ( (N-1)*llabs(stride) >= (int64_t)xlen ) {
napi_throw_range_error( env, nullptr, "invalid argument. Second argument has insufficient elements based on the associated stride and the number of indexed elements." );
return nullptr;
}
napi_value v;
status = napi_create_double( env, stdlib_strided_dnanmeanwd( N, (double *)X, stride ), &v );
assert( status == napi_ok );
return v;
}
napi_value Init( napi_env env, napi_value exports ) {
napi_status status;
napi_value fcn;
status = napi_create_function( env, "exports", NAPI_AUTO_LENGTH, node_dnanmeanwd, NULL, &fcn );
assert( status == napi_ok );
return fcn;
}
NAPI_MODULE( NODE_GYP_MODULE_NAME, Init )
} // end namespace stdlib_stats_base_dnanmeanwd
|
apache-2.0
|
saulbein/web3j
|
core/src/main/java/org/web3j/abi/datatypes/generated/Ufixed152x40.java
|
594
|
package org.web3j.abi.datatypes.generated;
import java.math.BigInteger;
import org.web3j.abi.datatypes.Ufixed;
/**
* <p>Auto generated code.<br>
* <strong>Do not modifiy!</strong><br>
* Please use {@link org.web3j.codegen.AbiTypesGenerator} to update.</p>
*/
public class Ufixed152x40 extends Ufixed {
public static final Ufixed152x40 DEFAULT = new Ufixed152x40(BigInteger.ZERO);
public Ufixed152x40(BigInteger value) {
super(152, 40, value);
}
public Ufixed152x40(int mBitSize, int nBitSize, BigInteger m, BigInteger n) {
super(152, 40, m, n);
}
}
|
apache-2.0
|
cedral/aws-sdk-cpp
|
aws-cpp-sdk-codecommit/source/model/DeleteFileEntry.cpp
|
1462
|
/*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/codecommit/model/DeleteFileEntry.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace CodeCommit
{
namespace Model
{
DeleteFileEntry::DeleteFileEntry() :
m_filePathHasBeenSet(false)
{
}
DeleteFileEntry::DeleteFileEntry(JsonView jsonValue) :
m_filePathHasBeenSet(false)
{
*this = jsonValue;
}
DeleteFileEntry& DeleteFileEntry::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("filePath"))
{
m_filePath = jsonValue.GetString("filePath");
m_filePathHasBeenSet = true;
}
return *this;
}
JsonValue DeleteFileEntry::Jsonize() const
{
JsonValue payload;
if(m_filePathHasBeenSet)
{
payload.WithString("filePath", m_filePath);
}
return payload;
}
} // namespace Model
} // namespace CodeCommit
} // namespace Aws
|
apache-2.0
|
o-evin/glacier-console
|
source/main/api/hasher/tree_hash.js
|
4860
|
import fs from 'fs';
import crypto from 'crypto';
import {Size} from '../../../contracts/const';
const PART_SIZE = Size.MEGABYTE_IN_BYTES;
class Node {
constructor({tree, parent, depth = 0, index = 0}) {
this.tree = tree;
this.index = index;
this.depth = depth;
this.parent = parent;
this.checksum = null;
if(depth < tree.depth) {
this.children = new Array(2);
this.children[0] = new Node({
tree,
parent: this,
depth: depth + 1,
index: index * 2,
});
this.children[1] = new Node({
tree,
parent: this,
depth: depth + 1,
index: index * 2 + 1,
});
}
}
set(partIndex, checksum) {
this.children[partIndex].checksum = checksum;
const [leftChild, rightChild] = this.children;
if(leftChild.checksum && rightChild.checksum) {
let digest = leftChild.checksum;
if(rightChild.checksum.length > 0) {
const buffer = Buffer.concat(this.children.map(
item => item.checksum
));
digest = crypto.createHash('sha256')
.update(buffer)
.digest();
}
if(this.parent) {
this.parent.set(this.index % 2, digest);
} else {
this.tree.checksum = digest;
}
this.children = null;
}
}
}
class DigestTree {
constructor(length) {
this.length = length;
this.pairsNumber = Math.ceil(length / 2);
this.depth = Math.ceil(Math.log2(this.pairsNumber)) + 1;
this.root = new Node({tree: this});
const treeLength = Math.pow(2, this.depth);
Array.apply(null, {length: treeLength - length}).map(
(value, index) => this.update(length + index, Buffer.alloc(0))
);
this.checksum = null;
}
update(index, checksum, depth = this.depth) {
const pairIndex = Math.floor(index / 2);
const pairDepth = depth - 1;
const node = this.traverse(this.root, pairIndex, pairDepth);
const partIndex = index % 2;
node.set(partIndex, checksum);
}
traverse(node, index, depth) {
if(depth === 0) return node;
const range = Math.pow(2, depth);
const rightChild = ((index + 1) / range) > 0.5;
const nextIndex = rightChild ? index - (range / 2) : index;
return this.traverse(node.children[+rightChild], nextIndex, --depth);
}
}
export default class TreeHash {
static read(fd, index, tree) {
return new Promise((resolve, reject)=> {
let buffer = Buffer.alloc(PART_SIZE);
const pos = index * PART_SIZE;
fs.read(fd, buffer, 0, PART_SIZE, pos,
(error, bytesRead, buffer) => {
if(error) return reject(error);
const hasher = crypto.createHash('sha256');
const checksum = hasher.update(
buffer.slice(0, bytesRead)
).digest();
buffer = null;
tree.update(index, checksum);
resolve();
});
});
}
static from(source, pos, length) {
if(Array.isArray(source)) {
return TreeHash.fromArray(source);
}
if(source instanceof Buffer) {
return TreeHash.fromBuffer(source);
}
return TreeHash.fromFile(source, pos, length);
}
static fromArray(data) {
const tree = new DigestTree(data.length);
data.forEach((value, index) =>
tree.update(index, Buffer.from(value, 'hex'))
);
return tree.checksum && tree.checksum.toString('hex');
}
static fromBuffer(data) {
const partsCount = Math.ceil(data.length / PART_SIZE);
const tree = new DigestTree(partsCount);
Array.apply(null, {length: partsCount}).map(
(value, index) => {
const pos = index * PART_SIZE;
const bytesCount = Math.min(PART_SIZE, data.length - pos);
const hasher = crypto.createHash('sha256');
const checksum = hasher.update(
data.slice(pos, pos + bytesCount)
).digest();
tree.update(index, checksum);
});
return tree.checksum && tree.checksum.toString('hex');
}
static fromFile(filePath, pos, length) {
if(length) {
var partsCount = Math.ceil(length / PART_SIZE);
} else {
const stats = fs.statSync(filePath);
partsCount = Math.ceil(stats.size / PART_SIZE);
}
const tree = new DigestTree(partsCount);
const fd = fs.openSync(filePath, 'r');
Array.apply(null, {length: partsCount}).map(
(value, index) => {
let buffer = Buffer.alloc(PART_SIZE);
const pos = index * PART_SIZE;
const bytesRead = fs.readSync(fd, buffer, 0, PART_SIZE, pos);
const hasher = crypto.createHash('sha256');
const checksum = hasher.update(
buffer.slice(0, bytesRead)
).digest();
buffer = null;
tree.update(index, checksum);
});
fs.closeSync(fd);
return tree.checksum && tree.checksum.toString('hex');
}
}
|
apache-2.0
|
janstk/boxJae
|
bb-library/Box/App.php
|
8224
|
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
use Box\InjectionAwareInterface;
class Box_App {
protected $mappings = array(), $before_filters = Array(), $after_filters = Array();
protected $shared = array();
protected $options;
protected $di = NULL;
protected $ext = 'phtml';
protected $mod = 'index';
protected $url = '/';
public $uri = NULL;
public function __construct($options=array())
{
$this->options = new ArrayObject($options);
}
public function setDi($di)
{
$this->di = $di;
}
public function setUrl($url)
{
$this->url = $url;
}
protected function registerModule()
{
//bind module urls and process
//determine module and bind urls
$requestUri = $this->url;
if(empty($requestUri)) {
$requestUri = '/';
}
if($requestUri == '/') {
$mod = 'index';
} else {
$requestUri = trim($requestUri, '/');
if(strpos($requestUri, '/') === false) {
$mod = $requestUri;
} else {
list($mod) = explode('/',$requestUri);
}
}
$mod = filter_var($mod, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$this->mod = $mod;
$this->uri = $requestUri;
}
protected function init(){}
public function show404(Exception $e) {
error_log($e->getMessage());
header("HTTP/1.0 404 Not Found");
return $this->render('404', array('exception'=>$e));
}
/**
* @param string $url
* @param string $methodName
* @param string $class
*/
public function get($url, $methodName, $conditions = array(), $class = null) {
$this->event('get', $url, $methodName, $conditions, $class);
}
/**
* @param string $url
* @param string $methodName
* @param string $class
*/
public function post($url, $methodName, $conditions = array(), $class = null) {
$this->event('post', $url, $methodName, $conditions, $class);
}
public function put($url, $methodName, $conditions = array(), $class = null) {
$this->event('put', $url, $methodName, $conditions, $class);
}
public function delete($url, $methodName, $conditions = array(), $class = null) {
$this->event('delete', $url, $methodName, $conditions, $class);
}
public function before($methodName, $filterName) {
$this->push_filter($this->before_filters, $methodName, $filterName);
}
public function after($methodName, $filterName) {
$this->push_filter($this->after_filters, $methodName, $filterName);
}
protected function push_filter(&$arr_filter, $methodName, $filterName) {
if (!is_array($methodName)) {
$methodName = explode('|', $methodName);
}
for ($i = 0; $i < count($methodName); $i++) {
$method = $methodName[$i];
if (!isset($arr_filter[$method])) {
$arr_filter[$method] = array();
}
array_push($arr_filter[$method], $filterName);
}
}
protected function run_filter($arr_filter, $methodName) {
if(isset($arr_filter[$methodName])) {
for ($i=0; $i < count($arr_filter[$methodName]); $i++) {
$return = call_user_func(array($this, $arr_filter[$methodName][$i]));
if(!is_null($return)) {
return $return;
}
}
}
}
public function run()
{
$this->registerModule();
$this->init();
return $this->processRequest();
}
/**
* @param string $path
*/
public function redirect($path)
{
$location = $this->di['url']->link($path);
header("Location: $location");
exit;
}
/**
* @param string $fileName
*/
public function render($fileName, $variableArray = array())
{
print 'Rendering '.$fileName;
}
public function sendFile($filename, $contentType, $path) {
header("Content-type: $contentType");
header("Content-Disposition: attachment; filename=$filename");
return readfile($path);
}
public function sendDownload($filename, $path) {
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$filename".";");
header("Content-Transfer-Encoding: binary");
return readfile($path);
}
protected function executeShared($classname, $methodName, $params)
{
$class = new $classname();
if($class instanceof InjectionAwareInterface) {
$class->setDi($this->di);
}
$reflection = new ReflectionMethod(get_class($class), $methodName);
$args = array();
$args[] = $this; // first param always app instance
foreach($reflection->getParameters() as $param) {
if(isset($params[$param->name])) {
$args[$param->name] = $params[$param->name];
}
else if($param->isDefaultValueAvailable()) {
$args[$param->name] = $param->getDefaultValue();
}
}
return $reflection->invokeArgs($class, $args);
}
protected function execute($methodName, $params, $classname = null) {
$return = $this->run_filter($this->before_filters, $methodName);
if (!is_null($return)) {
return $return;
}
$reflection = new ReflectionMethod(get_class($this), $methodName);
$args = array();
foreach($reflection->getParameters() as $param) {
if(isset($params[$param->name])) {
$args[$param->name] = $params[$param->name];
}
else if($param->isDefaultValueAvailable()) {
$args[$param->name] = $param->getDefaultValue();
}
}
$response = $reflection->invokeArgs($this, $args);
$return = $this->run_filter($this->after_filters, $methodName);
if (!is_null($return)) {
return $return;
}
return $response;
}
/**
* @param string $httpMethod
*/
protected function event($httpMethod, $url, $methodName, $conditions=array(), $classname = null) {
if (method_exists($this, $methodName)) {
array_push($this->mappings, array($httpMethod, $url, $methodName, $conditions));
}
if (null !== $classname) {
array_push($this->shared, array($httpMethod, $url, $methodName, $conditions, $classname));
}
}
protected function processRequest()
{
for($i = 0; $i < count($this->shared); $i++) {
$mapping = $this->shared[$i];
$url = new Box_UrlHelper($mapping[0], $mapping[1], $mapping[3], $this->url);
if($url->match) {
return $this->executeShared($mapping[4], $mapping[2], $url->params);
}
}
// this class mappings
for($i = 0; $i < count($this->mappings); $i++) {
$mapping = $this->mappings[$i];
$url = new Box_UrlHelper($mapping[0], $mapping[1], $mapping[3], $this->url);
if($url->match) {
return $this->execute($mapping[2], $url->params);
}
}
$e = new \Box_Exception('Page :url not found', array(':url'=>$this->url), 404);
return $this->show404($e);
}
/**
* @deprecated
*/
public function getApiAdmin()
{
return $this->di['api_admin'];
}
/**
* @deprecated
*/
public function getApiClient()
{
return $this->di['api_client'];
}
/**
* @deprecated
*/
public function getApiGuest()
{
return $this->di['api_guest'];
}
}
|
apache-2.0
|
wangfakang/geo
|
s2/cellid_test.go
|
16300
|
/*
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package s2
import (
"sort"
"testing"
"github.com/golang/geo/r2"
"github.com/golang/geo/s1"
)
func TestCellIDFromFace(t *testing.T) {
for face := 0; face < 6; face++ {
fpl := CellIDFromFacePosLevel(face, 0, 0)
f := CellIDFromFace(face)
if fpl != f {
t.Errorf("CellIDFromFacePosLevel(%d, 0, 0) != CellIDFromFace(%d), got %v wanted %v", face, face, f, fpl)
}
}
}
func TestParentChildRelationships(t *testing.T) {
ci := CellIDFromFacePosLevel(3, 0x12345678, maxLevel-4)
if !ci.IsValid() {
t.Errorf("CellID %v should be valid", ci)
}
if f := ci.Face(); f != 3 {
t.Errorf("ci.Face() is %v, want 3", f)
}
if p := ci.Pos(); p != 0x12345700 {
t.Errorf("ci.Pos() is 0x%X, want 0x12345700", p)
}
if l := ci.Level(); l != 26 { // 26 is maxLevel - 4
t.Errorf("ci.Level() is %v, want 26", l)
}
if ci.IsLeaf() {
t.Errorf("CellID %v should not be a leaf", ci)
}
if kid2 := ci.ChildBeginAtLevel(ci.Level() + 2).Pos(); kid2 != 0x12345610 {
t.Errorf("child two levels down is 0x%X, want 0x12345610", kid2)
}
if kid0 := ci.ChildBegin().Pos(); kid0 != 0x12345640 {
t.Errorf("first child is 0x%X, want 0x12345640", kid0)
}
if kid0 := ci.Children()[0].Pos(); kid0 != 0x12345640 {
t.Errorf("first child is 0x%X, want 0x12345640", kid0)
}
if parent := ci.immediateParent().Pos(); parent != 0x12345400 {
t.Errorf("ci.immediateParent().Pos() = 0x%X, want 0x12345400", parent)
}
if parent := ci.Parent(ci.Level() - 2).Pos(); parent != 0x12345000 {
t.Errorf("ci.Parent(l-2).Pos() = 0x%X, want 0x12345000", parent)
}
if uint64(ci.ChildBegin()) >= uint64(ci) {
t.Errorf("ci.ChildBegin() is 0x%X, want < 0x%X", ci.ChildBegin(), ci)
}
if uint64(ci.ChildEnd()) <= uint64(ci) {
t.Errorf("ci.ChildEnd() is 0x%X, want > 0x%X", ci.ChildEnd(), ci)
}
if ci.ChildEnd() != ci.ChildBegin().Next().Next().Next().Next() {
t.Errorf("ci.ChildEnd() is 0x%X, want 0x%X", ci.ChildEnd(), ci.ChildBegin().Next().Next().Next().Next())
}
if ci.RangeMin() != ci.ChildBeginAtLevel(maxLevel) {
t.Errorf("ci.RangeMin() is 0x%X, want 0x%X", ci.RangeMin(), ci.ChildBeginAtLevel(maxLevel))
}
if ci.RangeMax().Next() != ci.ChildEndAtLevel(maxLevel) {
t.Errorf("ci.RangeMax().Next() is 0x%X, want 0x%X", ci.RangeMax().Next(), ci.ChildEndAtLevel(maxLevel))
}
}
func TestContainment(t *testing.T) {
a := CellID(0x80855c0000000000) // Pittsburg
b := CellID(0x80855d0000000000) // child of a
c := CellID(0x80855dc000000000) // child of b
d := CellID(0x8085630000000000) // part of Pittsburg disjoint from a
tests := []struct {
x, y CellID
xContainsY, yContainsX, xIntersectsY bool
}{
{a, a, true, true, true},
{a, b, true, false, true},
{a, c, true, false, true},
{a, d, false, false, false},
{b, b, true, true, true},
{b, c, true, false, true},
{b, d, false, false, false},
{c, c, true, true, true},
{c, d, false, false, false},
{d, d, true, true, true},
}
should := func(b bool) string {
if b {
return "should"
}
return "should not"
}
for _, test := range tests {
if test.x.Contains(test.y) != test.xContainsY {
t.Errorf("%v %s contain %v", test.x, should(test.xContainsY), test.y)
}
if test.x.Intersects(test.y) != test.xIntersectsY {
t.Errorf("%v %s intersect %v", test.x, should(test.xIntersectsY), test.y)
}
if test.y.Contains(test.x) != test.yContainsX {
t.Errorf("%v %s contain %v", test.y, should(test.yContainsX), test.x)
}
}
// TODO(dsymonds): Test Contains, Intersects better, such as with adjacent cells.
}
func TestCellIDString(t *testing.T) {
ci := CellID(0xbb04000000000000)
if s, exp := ci.String(), "5/31200"; s != exp {
t.Errorf("ci.String() = %q, want %q", s, exp)
}
}
func TestLatLng(t *testing.T) {
// You can generate these with the s2cellid2latlngtestcase C++ program in this directory.
tests := []struct {
id CellID
lat, lng float64
}{
{0x47a1cbd595522b39, 49.703498679, 11.770681595},
{0x46525318b63be0f9, 55.685376759, 12.588490937},
{0x52b30b71698e729d, 45.486546517, -93.449700022},
{0x46ed8886cfadda85, 58.299984854, 23.049300056},
{0x3663f18a24cbe857, 34.364439040, 108.330699969},
{0x10a06c0a948cf5d, -30.694551352, -30.048758753},
{0x2b2bfd076787c5df, -25.285264027, 133.823116966},
{0xb09dff882a7809e1, -75.000000031, 0.000000133},
{0x94daa3d000000001, -24.694439215, -47.537363213},
{0x87a1000000000001, 38.899730392, -99.901813021},
{0x4fc76d5000000001, 81.647200334, -55.631712940},
{0x3b00955555555555, 10.050986518, 78.293170610},
{0x1dcc469991555555, -34.055420593, 18.551140038},
{0xb112966aaaaaaaab, -69.219262171, 49.670072392},
}
for _, test := range tests {
l1 := LatLngFromDegrees(test.lat, test.lng)
l2 := test.id.LatLng()
if l1.Distance(l2) > 1e-9*s1.Degree { // ~0.1mm on earth.
t.Errorf("LatLng() for CellID %x (%s) : got %s, want %s", uint64(test.id), test.id, l2, l1)
}
c1 := test.id
c2 := CellIDFromLatLng(l1)
if c1 != c2 {
t.Errorf("CellIDFromLatLng(%s) = %x (%s), want %s", l1, uint64(c2), c2, c1)
}
}
}
func TestEdgeNeighbors(t *testing.T) {
// Check the edge neighbors of face 1.
faces := []int{5, 3, 2, 0}
for i, nbr := range cellIDFromFaceIJ(1, 0, 0).Parent(0).EdgeNeighbors() {
if !nbr.isFace() {
t.Errorf("CellID(%d) is not a face", nbr)
}
if got, want := nbr.Face(), faces[i]; got != want {
t.Errorf("CellID(%d).Face() = %d, want %d", nbr, got, want)
}
}
// Check the edge neighbors of the corner cells at all levels. This case is
// trickier because it requires projecting onto adjacent faces.
const maxIJ = maxSize - 1
for level := 1; level <= maxLevel; level++ {
id := cellIDFromFaceIJ(1, 0, 0).Parent(level)
// These neighbors were determined manually using the face and axis
// relationships.
levelSizeIJ := sizeIJ(level)
want := []CellID{
cellIDFromFaceIJ(5, maxIJ, maxIJ).Parent(level),
cellIDFromFaceIJ(1, levelSizeIJ, 0).Parent(level),
cellIDFromFaceIJ(1, 0, levelSizeIJ).Parent(level),
cellIDFromFaceIJ(0, maxIJ, 0).Parent(level),
}
for i, nbr := range id.EdgeNeighbors() {
if nbr != want[i] {
t.Errorf("CellID(%d).EdgeNeighbors()[%d] = %v, want %v", id, i, nbr, want[i])
}
}
}
}
type byCellID []CellID
func (v byCellID) Len() int { return len(v) }
func (v byCellID) Swap(i, j int) { v[i], v[j] = v[j], v[i] }
func (v byCellID) Less(i, j int) bool { return uint64(v[i]) < uint64(v[j]) }
func TestVertexNeighbors(t *testing.T) {
// Check the vertex neighbors of the center of face 2 at level 5.
id := cellIDFromPoint(PointFromCoords(0, 0, 1))
neighbors := id.VertexNeighbors(5)
sort.Sort(byCellID(neighbors))
for n, nbr := range neighbors {
i, j := 1<<29, 1<<29
if n < 2 {
i--
}
if n == 0 || n == 3 {
j--
}
want := cellIDFromFaceIJ(2, i, j).Parent(5)
if nbr != want {
t.Errorf("CellID(%s).VertexNeighbors()[%d] = %v, want %v", id, n, nbr, want)
}
}
// Check the vertex neighbors of the corner of faces 0, 4, and 5.
id = CellIDFromFacePosLevel(0, 0, maxLevel)
neighbors = id.VertexNeighbors(0)
sort.Sort(byCellID(neighbors))
if len(neighbors) != 3 {
t.Errorf("len(CellID(%d).VertexNeighbors()) = %d, wanted %d", id, len(neighbors), 3)
}
if neighbors[0] != CellIDFromFace(0) {
t.Errorf("CellID(%d).VertexNeighbors()[0] = %d, wanted %d", id, neighbors[0], CellIDFromFace(0))
}
if neighbors[1] != CellIDFromFace(4) {
t.Errorf("CellID(%d).VertexNeighbors()[1] = %d, wanted %d", id, neighbors[1], CellIDFromFace(4))
}
}
func TestCellIDTokensNominal(t *testing.T) {
tests := []struct {
token string
id CellID
}{
{"1", 0x1000000000000000},
{"3", 0x3000000000000000},
{"14", 0x1400000000000000},
{"41", 0x4100000000000000},
{"094", 0x0940000000000000},
{"537", 0x5370000000000000},
{"3fec", 0x3fec000000000000},
{"72f3", 0x72f3000000000000},
{"52b8c", 0x52b8c00000000000},
{"990ed", 0x990ed00000000000},
{"4476dc", 0x4476dc0000000000},
{"2a724f", 0x2a724f0000000000},
{"7d4afc4", 0x7d4afc4000000000},
{"b675785", 0xb675785000000000},
{"40cd6124", 0x40cd612400000000},
{"3ba32f81", 0x3ba32f8100000000},
{"08f569b5c", 0x08f569b5c0000000},
{"385327157", 0x3853271570000000},
{"166c4d1954", 0x166c4d1954000000},
{"96f48d8c39", 0x96f48d8c39000000},
{"0bca3c7f74c", 0x0bca3c7f74c00000},
{"1ae3619d12f", 0x1ae3619d12f00000},
{"07a77802a3fc", 0x07a77802a3fc0000},
{"4e7887ec1801", 0x4e7887ec18010000},
{"4adad7ae74124", 0x4adad7ae74124000},
{"90aba04afe0c5", 0x90aba04afe0c5000},
{"8ffc3f02af305c", 0x8ffc3f02af305c00},
{"6fa47550938183", 0x6fa4755093818300},
{"aa80a565df5e7fc", 0xaa80a565df5e7fc0},
{"01614b5e968e121", 0x01614b5e968e1210},
{"aa05238e7bd3ee7c", 0xaa05238e7bd3ee7c},
{"48a23db9c2963e5b", 0x48a23db9c2963e5b},
}
for _, test := range tests {
ci := CellIDFromToken(test.token)
if ci != test.id {
t.Errorf("CellIDFromToken(%q) = %x, want %x", test.token, uint64(ci), uint64(test.id))
}
token := ci.ToToken()
if token != test.token {
t.Errorf("ci.ToToken = %q, want %q", token, test.token)
}
}
}
func TestCellIDFromTokensErrorCases(t *testing.T) {
noneToken := CellID(0).ToToken()
if noneToken != "X" {
t.Errorf("CellID(0).Token() = %q, want X", noneToken)
}
noneID := CellIDFromToken(noneToken)
if noneID != CellID(0) {
t.Errorf("CellIDFromToken(%q) = %x, want 0", noneToken, uint64(noneID))
}
tests := []string{
"876b e99",
"876bee99\n",
"876[ee99",
" 876bee99",
}
for _, test := range tests {
ci := CellIDFromToken(test)
if uint64(ci) != 0 {
t.Errorf("CellIDFromToken(%q) = %x, want 0", test, uint64(ci))
}
}
}
func TestIJLevelToBoundUV(t *testing.T) {
maxIJ := 1<<maxLevel - 1
tests := []struct {
i int
j int
level int
want r2.Rect
}{
// The i/j space is [0, 2^30 - 1) which maps to [-1, 1] for the
// x/y axes of the face surface. Results are scaled by the size of a cell
// at the given level. At level 0, everything is one cell of the full size
// of the space. At maxLevel, the bounding rect is almost floating point
// noise.
// What should be out of bounds values, but passes the C++ code as well.
{
-1, -1, 0,
r2.RectFromPoints(r2.Point{-5, -5}, r2.Point{-1, -1}),
},
{
-1 * maxIJ, -1 * maxIJ, 0,
r2.RectFromPoints(r2.Point{-5, -5}, r2.Point{-1, -1}),
},
{
-1, -1, maxLevel,
r2.RectFromPoints(r2.Point{-1.0000000024835267, -1.0000000024835267},
r2.Point{-1, -1}),
},
{
0, 0, maxLevel + 1,
r2.RectFromPoints(r2.Point{-1, -1}, r2.Point{-1, -1}),
},
// Minimum i,j at different levels
{
0, 0, 0,
r2.RectFromPoints(r2.Point{-1, -1}, r2.Point{1, 1}),
},
{
0, 0, maxLevel / 2,
r2.RectFromPoints(r2.Point{-1, -1},
r2.Point{-0.999918621033430099, -0.999918621033430099}),
},
{
0, 0, maxLevel,
r2.RectFromPoints(r2.Point{-1, -1},
r2.Point{-0.999999997516473060, -0.999999997516473060}),
},
// Just a hair off the outer bounds at different levels.
{
1, 1, 0,
r2.RectFromPoints(r2.Point{-1, -1}, r2.Point{1, 1}),
},
{
1, 1, maxLevel / 2,
r2.RectFromPoints(r2.Point{-1, -1},
r2.Point{-0.999918621033430099, -0.999918621033430099}),
},
{
1, 1, maxLevel,
r2.RectFromPoints(r2.Point{-0.9999999975164731, -0.9999999975164731},
r2.Point{-0.9999999950329462, -0.9999999950329462}),
},
// Center point of the i,j space at different levels.
{
maxIJ / 2, maxIJ / 2, 0,
r2.RectFromPoints(r2.Point{-1, -1}, r2.Point{1, 1})},
{
maxIJ / 2, maxIJ / 2, maxLevel / 2,
r2.RectFromPoints(r2.Point{-0.000040691345930099, -0.000040691345930099},
r2.Point{0, 0})},
{
maxIJ / 2, maxIJ / 2, maxLevel,
r2.RectFromPoints(r2.Point{-0.000000001241763433, -0.000000001241763433},
r2.Point{0, 0})},
// Maximum i, j at different levels.
{
maxIJ, maxIJ, 0,
r2.RectFromPoints(r2.Point{-1, -1}, r2.Point{1, 1}),
},
{
maxIJ, maxIJ, maxLevel / 2,
r2.RectFromPoints(r2.Point{0.999918621033430099, 0.999918621033430099},
r2.Point{1, 1}),
},
{
maxIJ, maxIJ, maxLevel,
r2.RectFromPoints(r2.Point{0.999999997516473060, 0.999999997516473060},
r2.Point{1, 1}),
},
}
for _, test := range tests {
uv := ijLevelToBoundUV(test.i, test.j, test.level)
if !float64Eq(uv.X.Lo, test.want.X.Lo) ||
!float64Eq(uv.X.Hi, test.want.X.Hi) ||
!float64Eq(uv.Y.Lo, test.want.Y.Lo) ||
!float64Eq(uv.Y.Hi, test.want.Y.Hi) {
t.Errorf("ijLevelToBoundUV(%d, %d, %d), got %v, want %v",
test.i, test.j, test.level, uv, test.want)
}
}
}
func TestCommonAncestorLevel(t *testing.T) {
tests := []struct {
ci CellID
other CellID
want int
wantOk bool
}{
// Identical cell IDs.
{
CellIDFromFace(0),
CellIDFromFace(0),
0,
true,
},
{
CellIDFromFace(0).ChildBeginAtLevel(30),
CellIDFromFace(0).ChildBeginAtLevel(30),
30,
true,
},
// One cell is a descendant of the other.
{
CellIDFromFace(0).ChildBeginAtLevel(30),
CellIDFromFace(0),
0,
true,
},
{
CellIDFromFace(5),
CellIDFromFace(5).ChildEndAtLevel(30).Prev(),
0,
true,
},
// No common ancestors.
{
CellIDFromFace(0),
CellIDFromFace(5),
0,
false,
},
{
CellIDFromFace(2).ChildBeginAtLevel(30),
CellIDFromFace(3).ChildBeginAtLevel(20),
0,
false,
},
// Common ancestor distinct from both.
{
CellIDFromFace(5).ChildBeginAtLevel(9).Next().ChildBeginAtLevel(15),
CellIDFromFace(5).ChildBeginAtLevel(9).ChildBeginAtLevel(20),
8,
true,
},
{
CellIDFromFace(0).ChildBeginAtLevel(2).ChildBeginAtLevel(30),
CellIDFromFace(0).ChildBeginAtLevel(2).Next().ChildBeginAtLevel(5),
1,
true,
},
}
for _, test := range tests {
if got, ok := test.ci.CommonAncestorLevel(test.other); ok != test.wantOk || got != test.want {
t.Errorf("CellID(%v).VertexNeighbors(%v) = %d, %t; want %d, %t", test.ci, test.other, got, ok, test.want, test.wantOk)
}
}
}
func TestFindMSBSetNonZero64(t *testing.T) {
testOne := uint64(0x8000000000000000)
testAll := uint64(0xFFFFFFFFFFFFFFFF)
testSome := uint64(0xFEDCBA9876543210)
for i := 63; i >= 0; i-- {
if got := findMSBSetNonZero64(testOne); got != i {
t.Errorf("findMSBSetNonZero64(%x) = %d, want = %d", testOne, got, i)
}
if got := findMSBSetNonZero64(testAll); got != i {
t.Errorf("findMSBSetNonZero64(%x) = %d, want = %d", testAll, got, i)
}
if got := findMSBSetNonZero64(testSome); got != i {
t.Errorf("findMSBSetNonZero64(%x) = %d, want = %d", testSome, got, i)
}
testOne >>= 1
testAll >>= 1
testSome >>= 1
}
}
func TestAdvance(t *testing.T) {
tests := []struct {
ci CellID
steps int64
want CellID
}{
{
CellIDFromFace(0).ChildBeginAtLevel(0),
7,
CellIDFromFace(5).ChildEndAtLevel(0),
},
{
CellIDFromFace(0).ChildBeginAtLevel(0),
12,
CellIDFromFace(5).ChildEndAtLevel(0),
},
{
CellIDFromFace(5).ChildEndAtLevel(0),
-7,
CellIDFromFace(0).ChildBeginAtLevel(0),
},
{
CellIDFromFace(5).ChildEndAtLevel(0),
-12000000,
CellIDFromFace(0).ChildBeginAtLevel(0),
},
{
CellIDFromFace(0).ChildBeginAtLevel(5),
500,
CellIDFromFace(5).ChildEndAtLevel(5).Advance(500 - (6 << (2 * 5))),
},
{
CellIDFromFacePosLevel(3, 0x12345678, maxLevel-4).ChildBeginAtLevel(maxLevel),
256,
CellIDFromFacePosLevel(3, 0x12345678, maxLevel-4).Next().ChildBeginAtLevel(maxLevel),
},
{
CellIDFromFacePosLevel(1, 0, maxLevel),
4 << (2 * maxLevel),
CellIDFromFacePosLevel(5, 0, maxLevel),
},
}
for _, test := range tests {
if got := test.ci.Advance(test.steps); got != test.want {
t.Errorf("CellID(%v).Advance(%d) = %v; want = %v", test.ci, test.steps, got, test.want)
}
}
}
|
apache-2.0
|
puppetlabs/puppetlabs-stdlib
|
spec/functions/shell_join_spec.rb
|
1473
|
# frozen_string_literal: true
require 'spec_helper'
describe 'shell_join' do
it { is_expected.not_to eq(nil) }
describe 'signature validation' do
it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) }
it { is_expected.to run.with_params(['foo'], ['bar']).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) }
it { is_expected.to run.with_params('foo').and_raise_error(Puppet::ParseError, %r{is not an Array}i) }
end
describe 'shell argument joining' do
it { is_expected.to run.with_params(['foo']).and_return('foo') }
it { is_expected.to run.with_params(['foo', 'bar']).and_return('foo bar') }
it { is_expected.to run.with_params(['foo', 'bar baz']).and_return('foo bar\ baz') }
it {
is_expected.to run.with_params(['~`!@#$', '%^&*()_-=', '[]\{}|;\':"', ',./<>?'])
.and_return('\~\`\!@\#\$ \%\^\&\*\(\)_-\= \[\]\\\\\{\}\|\;\\\':\" ,./\<\>\?')
}
context 'with UTF8 and double byte characters' do
it { is_expected.to run.with_params(['μťƒ', '8', 'ŧĕχť']).and_return('\\μ\\ť\\ƒ 8 \\ŧ\\ĕ\\χ\\ť') }
it { is_expected.to run.with_params(['スペー', 'スを含むテ', ' キスト']).and_return('\\ス\\ペ\\ー \\ス\\を\\含\\む\\テ \\ \\キ\\ス\\ト') }
end
end
describe 'stringification' do
it { is_expected.to run.with_params([10, false, 'foo']).and_return('10 false foo') }
end
end
|
apache-2.0
|
baade-org/eel
|
eel-tools/src/main/java/org/baade/eel/tools/generator/msg/IMessageGen.java
|
286
|
package org.baade.eel.tools.generator.msg;
import org.baade.eel.tools.generator.IGenerator;
/**
* 消息的生成
* @author <a href="http://eel.baade.org">Baade Eel Project</a>
* 2017/4/1.
*/
public interface IMessageGen extends IGenerator{
public boolean check();
}
|
apache-2.0
|
ilangostl/postgresql-async
|
mysql-async/src/main/scala/com/github/mauricio/async/db/mysql/codec/MySQLConnectionHandler.scala
|
10773
|
/*
* Copyright 2013 Maurício Linhares
*
* Maurício Linhares 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.github.mauricio.async.db.mysql.codec
import com.github.mauricio.async.db.Configuration
import com.github.mauricio.async.db.general.MutableResultSet
import com.github.mauricio.async.db.mysql.binary.BinaryRowDecoder
import com.github.mauricio.async.db.mysql.message.client._
import com.github.mauricio.async.db.mysql.message.server._
import com.github.mauricio.async.db.mysql.util.CharsetMapper
import com.github.mauricio.async.db.util.ChannelFutureTransformer.toFuture
import com.github.mauricio.async.db.util._
import io.netty.bootstrap.Bootstrap
import io.netty.buffer.ByteBufAllocator
import io.netty.channel._
import io.netty.channel.socket.nio.NioSocketChannel
import io.netty.handler.codec.CodecException
import java.net.InetSocketAddress
import scala.Some
import scala.annotation.switch
import scala.collection.mutable.{ArrayBuffer, HashMap}
import scala.concurrent._
import com.github.mauricio.async.db.exceptions.DatabaseException
class MySQLConnectionHandler(
configuration: Configuration,
charsetMapper: CharsetMapper,
handlerDelegate: MySQLHandlerDelegate,
group : EventLoopGroup,
executionContext : ExecutionContext,
connectionId : String
)
extends SimpleChannelInboundHandler[Object] {
private implicit val internalPool = executionContext
private final val log = Log.getByName(s"[connection-handler]${connectionId}")
private final val bootstrap = new Bootstrap().group(this.group)
private final val connectionPromise = Promise[MySQLConnectionHandler]
private final val decoder = new MySQLFrameDecoder(configuration.charset, connectionId)
private final val encoder = new MySQLOneToOneEncoder(configuration.charset, charsetMapper)
private final val currentParameters = new ArrayBuffer[ColumnDefinitionMessage]()
private final val currentColumns = new ArrayBuffer[ColumnDefinitionMessage]()
private final val parsedStatements = new HashMap[String,PreparedStatementHolder]()
private final val binaryRowDecoder = new BinaryRowDecoder()
private var currentPreparedStatementHolder : PreparedStatementHolder = null
private var currentPreparedStatement : PreparedStatementMessage = null
private var currentQuery : MutableResultSet[ColumnDefinitionMessage] = null
private var currentContext: ChannelHandlerContext = null
def connect: Future[MySQLConnectionHandler] = {
this.bootstrap.channel(classOf[NioSocketChannel])
this.bootstrap.handler(new ChannelInitializer[io.netty.channel.Channel]() {
override def initChannel(channel: io.netty.channel.Channel): Unit = {
channel.pipeline.addLast(
decoder,
encoder,
MySQLConnectionHandler.this)
}
})
this.bootstrap.option[java.lang.Boolean](ChannelOption.SO_KEEPALIVE, true)
this.bootstrap.option[ByteBufAllocator](ChannelOption.ALLOCATOR, LittleEndianByteBufAllocator.INSTANCE)
this.bootstrap.connect(new InetSocketAddress(configuration.host, configuration.port)).onFailure {
case exception => this.connectionPromise.tryFailure(exception)
}
this.connectionPromise.future
}
override def channelRead0(ctx: ChannelHandlerContext, message: Object) {
message match {
case m: ServerMessage => {
(m.kind: @switch) match {
case ServerMessage.ServerProtocolVersion => {
handlerDelegate.onHandshake(m.asInstanceOf[HandshakeMessage])
}
case ServerMessage.Ok => {
this.clearQueryState
handlerDelegate.onOk(m.asInstanceOf[OkMessage])
}
case ServerMessage.Error => {
this.clearQueryState
handlerDelegate.onError(m.asInstanceOf[ErrorMessage])
}
case ServerMessage.EOF => {
this.handleEOF(m)
}
case ServerMessage.ColumnDefinition => {
val message = m.asInstanceOf[ColumnDefinitionMessage]
if ( currentPreparedStatementHolder != null && this.currentPreparedStatementHolder.needsAny ) {
this.currentPreparedStatementHolder.add(message)
}
this.currentColumns += message
}
case ServerMessage.ColumnDefinitionFinished => {
this.onColumnDefinitionFinished()
}
case ServerMessage.PreparedStatementPrepareResponse => {
this.onPreparedStatementPrepareResponse(m.asInstanceOf[PreparedStatementPrepareResponse])
}
case ServerMessage.Row => {
val message = m.asInstanceOf[ResultSetRowMessage]
val items = new Array[Any](message.size)
var x = 0
while ( x < message.size ) {
items(x) = if ( message(x) == null ) {
null
} else {
val columnDescription = this.currentQuery.columnTypes(x)
columnDescription.textDecoder.decode(columnDescription, message(x), configuration.charset)
}
x += 1
}
this.currentQuery.addRow(items)
}
case ServerMessage.BinaryRow => {
val message = m.asInstanceOf[BinaryRowMessage]
this.currentQuery.addRow( this.binaryRowDecoder.decode(message.buffer, this.currentColumns ))
}
case ServerMessage.ParamProcessingFinished => {
}
case ServerMessage.ParamAndColumnProcessingFinished => {
this.onColumnDefinitionFinished()
}
}
}
}
}
override def channelActive(ctx: ChannelHandlerContext): Unit = {
log.debug("Channel became active")
handlerDelegate.connected(ctx)
}
override def channelInactive(ctx: ChannelHandlerContext) {
log.debug("Channel became inactive")
}
override def exceptionCaught(ctx: ChannelHandlerContext, cause: Throwable) {
// unwrap CodecException if needed
cause match {
case t: CodecException => handleException(t.getCause)
case _ => handleException(cause)
}
}
private def handleException(cause: Throwable) {
if (!this.connectionPromise.isCompleted) {
this.connectionPromise.failure(cause)
}
handlerDelegate.exceptionCaught(cause)
}
override def handlerAdded(ctx: ChannelHandlerContext) {
this.currentContext = ctx
}
def write( message : QueryMessage ) : ChannelFuture = {
this.decoder.queryProcessStarted()
writeAndHandleError(message)
}
def write( message : PreparedStatementMessage ) {
this.currentColumns.clear()
this.currentParameters.clear()
this.currentPreparedStatement = message
this.parsedStatements.get(message.statement) match {
case Some( item ) => {
this.executePreparedStatement(item.statementId, item.columns.size, message.values, item.parameters)
}
case None => {
decoder.preparedStatementPrepareStarted()
writeAndHandleError( new PreparedStatementPrepareMessage(message.statement) )
}
}
}
def write( message : HandshakeResponseMessage ) : ChannelFuture = {
writeAndHandleError(message)
}
def write( message : AuthenticationSwitchResponse ) : ChannelFuture = writeAndHandleError(message)
def write( message : QuitMessage ) : ChannelFuture = {
writeAndHandleError(message)
}
def disconnect: ChannelFuture = this.currentContext.close()
def clearQueryState {
this.currentColumns.clear()
this.currentParameters.clear()
this.currentQuery = null
}
def isConnected : Boolean = {
if ( this.currentContext != null && this.currentContext.channel() != null ) {
this.currentContext.channel.isActive
} else {
false
}
}
private def executePreparedStatement( statementId : Array[Byte], columnsCount : Int, values : Seq[Any], parameters : Seq[ColumnDefinitionMessage] ) {
decoder.preparedStatementExecuteStarted(columnsCount, parameters.size)
this.currentColumns.clear()
this.currentParameters.clear()
writeAndHandleError(new PreparedStatementExecuteMessage( statementId, values, parameters ))
}
private def onPreparedStatementPrepareResponse( message : PreparedStatementPrepareResponse ) {
this.currentPreparedStatementHolder = new PreparedStatementHolder( this.currentPreparedStatement.statement, message)
}
def onColumnDefinitionFinished() {
val columns = if ( this.currentPreparedStatementHolder != null ) {
this.currentPreparedStatementHolder.columns
} else {
this.currentColumns
}
this.currentQuery = new MutableResultSet[ColumnDefinitionMessage](columns)
if ( this.currentPreparedStatementHolder != null ) {
this.parsedStatements.put( this.currentPreparedStatementHolder.statement, this.currentPreparedStatementHolder )
this.executePreparedStatement(
this.currentPreparedStatementHolder.statementId,
this.currentPreparedStatementHolder.columns.size,
this.currentPreparedStatement.values,
this.currentPreparedStatementHolder.parameters
)
this.currentPreparedStatementHolder = null
this.currentPreparedStatement = null
}
}
private def writeAndHandleError( message : Any ) : ChannelFuture = {
if ( this.currentContext.channel().isActive ) {
val future = this.currentContext.writeAndFlush(message)
future.onFailure {
case e : Throwable => handleException(e)
}
future
} else {
throw new DatabaseException("This channel is not active and can't take messages")
}
}
private def handleEOF( m : ServerMessage ) {
m match {
case eof : EOFMessage => {
val resultSet = this.currentQuery
this.clearQueryState
if ( resultSet != null ) {
handlerDelegate.onResultSet( resultSet, eof )
} else {
handlerDelegate.onEOF(eof)
}
}
case authenticationSwitch : AuthenticationSwitchRequest => {
handlerDelegate.switchAuthentication(authenticationSwitch)
}
}
}
}
|
apache-2.0
|
orientechnologies/orientdb
|
core/src/test/java/com/orientechnologies/orient/core/storage/impl/local/paginated/wal/po/cellbtree/multivalue/v2/entrypoint/CellBTreeMultiValueV2EntryPointSetPagesSizePOTest.java
|
5271
|
package com.orientechnologies.orient.core.storage.impl.local.paginated.wal.po.cellbtree.multivalue.v2.entrypoint;
import com.orientechnologies.common.directmemory.OByteBufferPool;
import com.orientechnologies.common.directmemory.ODirectMemoryAllocator.Intention;
import com.orientechnologies.common.directmemory.OPointer;
import com.orientechnologies.orient.core.storage.cache.OCacheEntry;
import com.orientechnologies.orient.core.storage.cache.OCacheEntryImpl;
import com.orientechnologies.orient.core.storage.cache.OCachePointer;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.po.PageOperationRecord;
import com.orientechnologies.orient.core.storage.index.sbtree.multivalue.v2.CellBTreeMultiValueV2EntryPoint;
import java.nio.ByteBuffer;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
public class CellBTreeMultiValueV2EntryPointSetPagesSizePOTest {
@Test
public void testRedo() {
final int pageSize = 64 * 1024;
final OByteBufferPool byteBufferPool = new OByteBufferPool(pageSize);
try {
final OPointer pointer = byteBufferPool.acquireDirect(false, Intention.TEST);
final OCachePointer cachePointer = new OCachePointer(pointer, byteBufferPool, 0, 0);
final OCacheEntry entry = new OCacheEntryImpl(0, 0, cachePointer, false);
CellBTreeMultiValueV2EntryPoint bucket = new CellBTreeMultiValueV2EntryPoint(entry);
bucket.init();
bucket.setPagesSize(42);
entry.clearPageOperations();
final OPointer restoredPointer = byteBufferPool.acquireDirect(false, Intention.TEST);
final OCachePointer restoredCachePointer =
new OCachePointer(restoredPointer, byteBufferPool, 0, 0);
final OCacheEntry restoredCacheEntry = new OCacheEntryImpl(0, 0, restoredCachePointer, false);
final ByteBuffer originalBuffer = cachePointer.getBufferDuplicate();
final ByteBuffer restoredBuffer = restoredCachePointer.getBufferDuplicate();
Assert.assertNotNull(originalBuffer);
Assert.assertNotNull(restoredBuffer);
restoredBuffer.put(originalBuffer);
bucket.setPagesSize(24);
final List<PageOperationRecord> operations = entry.getPageOperations();
Assert.assertEquals(1, operations.size());
Assert.assertTrue(operations.get(0) instanceof CellBTreeMultiValueV2EntryPointSetPagesSizePO);
final CellBTreeMultiValueV2EntryPointSetPagesSizePO pageOperation =
(CellBTreeMultiValueV2EntryPointSetPagesSizePO) operations.get(0);
CellBTreeMultiValueV2EntryPoint restoredBucket =
new CellBTreeMultiValueV2EntryPoint(restoredCacheEntry);
Assert.assertEquals(42, restoredBucket.getPagesSize());
pageOperation.redo(restoredCacheEntry);
Assert.assertEquals(24, restoredBucket.getPagesSize());
byteBufferPool.release(pointer);
byteBufferPool.release(restoredPointer);
} finally {
byteBufferPool.clear();
}
}
@Test
public void testUndo() {
final int pageSize = 64 * 1024;
final OByteBufferPool byteBufferPool = new OByteBufferPool(pageSize);
try {
final OPointer pointer = byteBufferPool.acquireDirect(false, Intention.TEST);
final OCachePointer cachePointer = new OCachePointer(pointer, byteBufferPool, 0, 0);
final OCacheEntry entry = new OCacheEntryImpl(0, 0, cachePointer, false);
CellBTreeMultiValueV2EntryPoint bucket = new CellBTreeMultiValueV2EntryPoint(entry);
bucket.init();
bucket.setPagesSize(42);
entry.clearPageOperations();
bucket.setPagesSize(24);
final List<PageOperationRecord> operations = entry.getPageOperations();
Assert.assertTrue(operations.get(0) instanceof CellBTreeMultiValueV2EntryPointSetPagesSizePO);
final CellBTreeMultiValueV2EntryPointSetPagesSizePO pageOperation =
(CellBTreeMultiValueV2EntryPointSetPagesSizePO) operations.get(0);
final CellBTreeMultiValueV2EntryPoint restoredBucket =
new CellBTreeMultiValueV2EntryPoint(entry);
Assert.assertEquals(24, restoredBucket.getPagesSize());
pageOperation.undo(entry);
Assert.assertEquals(42, restoredBucket.getPagesSize());
byteBufferPool.release(pointer);
} finally {
byteBufferPool.clear();
}
}
@Test
public void testSerialization() {
CellBTreeMultiValueV2EntryPointSetPagesSizePO operation =
new CellBTreeMultiValueV2EntryPointSetPagesSizePO(12, 21);
operation.setFileId(42);
operation.setPageIndex(24);
operation.setOperationUnitId(1);
final int serializedSize = operation.serializedSize();
final byte[] stream = new byte[serializedSize + 1];
int pos = operation.toStream(stream, 1);
Assert.assertEquals(serializedSize + 1, pos);
CellBTreeMultiValueV2EntryPointSetPagesSizePO restoredOperation =
new CellBTreeMultiValueV2EntryPointSetPagesSizePO();
restoredOperation.fromStream(stream, 1);
Assert.assertEquals(42, restoredOperation.getFileId());
Assert.assertEquals(24, restoredOperation.getPageIndex());
Assert.assertEquals(1, restoredOperation.getOperationUnitId());
Assert.assertEquals(12, restoredOperation.getPagesSize());
Assert.assertEquals(21, restoredOperation.getPrevPagesSize());
}
}
|
apache-2.0
|
weld/core
|
weld-lite-extension-translator/src/main/java/org/jboss/weld/lite/extension/translator/TypeImpl.java
|
3471
|
package org.jboss.weld.lite.extension.translator;
import jakarta.enterprise.inject.spi.BeanManager;
import jakarta.enterprise.lang.model.types.Type;
import org.jboss.weld.lite.extension.translator.logging.LiteExtensionTranslatorLogger;
import org.jboss.weld.lite.extension.translator.util.AnnotationOverrides;
import org.jboss.weld.lite.extension.translator.util.reflection.AnnotatedTypes;
import java.util.Arrays;
import java.util.Objects;
abstract class TypeImpl<ReflectionType extends java.lang.reflect.AnnotatedType> extends AnnotationTargetImpl<ReflectionType> implements Type {
TypeImpl(ReflectionType reflectionType, AnnotationOverrides overrides, BeanManager bm) {
super(reflectionType, overrides, bm);
}
static Type fromReflectionType(java.lang.reflect.AnnotatedType reflectionType, BeanManager bm) {
return fromReflectionType(reflectionType, null, bm);
}
static Type fromReflectionType(java.lang.reflect.AnnotatedType reflectionType, AnnotationOverrides overrides, BeanManager bm) {
if (reflectionType instanceof java.lang.reflect.AnnotatedParameterizedType) {
return new ParameterizedTypeImpl((java.lang.reflect.AnnotatedParameterizedType) reflectionType, overrides, bm);
} else if (reflectionType instanceof java.lang.reflect.AnnotatedTypeVariable) {
return new TypeVariableImpl((java.lang.reflect.AnnotatedTypeVariable) reflectionType, overrides, bm);
} else if (reflectionType instanceof java.lang.reflect.AnnotatedArrayType) {
return new ArrayTypeImpl((java.lang.reflect.AnnotatedArrayType) reflectionType, overrides, bm);
} else if (reflectionType instanceof java.lang.reflect.AnnotatedWildcardType) {
return new WildcardTypeImpl((java.lang.reflect.AnnotatedWildcardType) reflectionType, overrides, bm);
} else {
// plain java.lang.reflect.AnnotatedType
if (reflectionType.getType() instanceof Class) {
Class<?> clazz = (Class<?>) reflectionType.getType();
if (clazz.isPrimitive()) {
if (clazz == void.class) {
return new VoidTypeImpl(bm);
} else {
return new PrimitiveTypeImpl(reflectionType, overrides, bm);
}
}
if (clazz.isArray()) {
return new ArrayTypeImpl((java.lang.reflect.AnnotatedArrayType) AnnotatedTypes.from(clazz), overrides, bm);
}
return new ClassTypeImpl(reflectionType, overrides, bm);
} else {
throw LiteExtensionTranslatorLogger.LOG.unknownReflectionType(reflectionType);
}
}
}
@Override
public String toString() {
return reflection.getType().toString();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof TypeImpl)) {
return false;
}
TypeImpl<?> type = (TypeImpl<?>) o;
return Objects.equals(reflection.getType(), type.reflection.getType())
&& Objects.deepEquals(reflection.getAnnotations(), type.reflection.getAnnotations());
}
@Override
public int hashCode() {
int result = Objects.hash(reflection.getType());
result = 31 * result + Arrays.hashCode(reflection.getAnnotations());
return result;
}
}
|
apache-2.0
|
jentfoo/aws-sdk-java
|
aws-java-sdk-mediastore/src/main/java/com/amazonaws/services/mediastore/AWSMediaStoreAsyncClient.java
|
25987
|
/*
* 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.mediastore;
import javax.annotation.Generated;
import com.amazonaws.services.mediastore.model.*;
import com.amazonaws.client.AwsAsyncClientParams;
import com.amazonaws.annotation.ThreadSafe;
import java.util.concurrent.ExecutorService;
/**
* Client for accessing MediaStore asynchronously. Each asynchronous method will return a Java Future object
* representing the asynchronous operation; overloads which accept an {@code AsyncHandler} can be used to receive
* notification when an asynchronous operation completes.
* <p>
* <p>
* An AWS Elemental MediaStore container is a namespace that holds folders and objects. You use a container endpoint to
* create, read, and delete objects.
* </p>
*/
@ThreadSafe
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AWSMediaStoreAsyncClient extends AWSMediaStoreClient implements AWSMediaStoreAsync {
private static final int DEFAULT_THREAD_POOL_SIZE = 50;
private final java.util.concurrent.ExecutorService executorService;
public static AWSMediaStoreAsyncClientBuilder asyncBuilder() {
return AWSMediaStoreAsyncClientBuilder.standard();
}
/**
* Constructs a new asynchronous client to invoke service methods on MediaStore using the specified parameters.
*
* @param asyncClientParams
* Object providing client parameters.
*/
AWSMediaStoreAsyncClient(AwsAsyncClientParams asyncClientParams) {
super(asyncClientParams);
this.executorService = asyncClientParams.getExecutor();
}
/**
* Returns the executor service used by this client to execute async requests.
*
* @return The executor service used by this client to execute async requests.
*/
public ExecutorService getExecutorService() {
return executorService;
}
@Override
public java.util.concurrent.Future<CreateContainerResult> createContainerAsync(CreateContainerRequest request) {
return createContainerAsync(request, null);
}
@Override
public java.util.concurrent.Future<CreateContainerResult> createContainerAsync(final CreateContainerRequest request,
final com.amazonaws.handlers.AsyncHandler<CreateContainerRequest, CreateContainerResult> asyncHandler) {
final CreateContainerRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<CreateContainerResult>() {
@Override
public CreateContainerResult call() throws Exception {
CreateContainerResult result = null;
try {
result = executeCreateContainer(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<DeleteContainerResult> deleteContainerAsync(DeleteContainerRequest request) {
return deleteContainerAsync(request, null);
}
@Override
public java.util.concurrent.Future<DeleteContainerResult> deleteContainerAsync(final DeleteContainerRequest request,
final com.amazonaws.handlers.AsyncHandler<DeleteContainerRequest, DeleteContainerResult> asyncHandler) {
final DeleteContainerRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<DeleteContainerResult>() {
@Override
public DeleteContainerResult call() throws Exception {
DeleteContainerResult result = null;
try {
result = executeDeleteContainer(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<DeleteContainerPolicyResult> deleteContainerPolicyAsync(DeleteContainerPolicyRequest request) {
return deleteContainerPolicyAsync(request, null);
}
@Override
public java.util.concurrent.Future<DeleteContainerPolicyResult> deleteContainerPolicyAsync(final DeleteContainerPolicyRequest request,
final com.amazonaws.handlers.AsyncHandler<DeleteContainerPolicyRequest, DeleteContainerPolicyResult> asyncHandler) {
final DeleteContainerPolicyRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<DeleteContainerPolicyResult>() {
@Override
public DeleteContainerPolicyResult call() throws Exception {
DeleteContainerPolicyResult result = null;
try {
result = executeDeleteContainerPolicy(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<DeleteCorsPolicyResult> deleteCorsPolicyAsync(DeleteCorsPolicyRequest request) {
return deleteCorsPolicyAsync(request, null);
}
@Override
public java.util.concurrent.Future<DeleteCorsPolicyResult> deleteCorsPolicyAsync(final DeleteCorsPolicyRequest request,
final com.amazonaws.handlers.AsyncHandler<DeleteCorsPolicyRequest, DeleteCorsPolicyResult> asyncHandler) {
final DeleteCorsPolicyRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<DeleteCorsPolicyResult>() {
@Override
public DeleteCorsPolicyResult call() throws Exception {
DeleteCorsPolicyResult result = null;
try {
result = executeDeleteCorsPolicy(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<DeleteLifecyclePolicyResult> deleteLifecyclePolicyAsync(DeleteLifecyclePolicyRequest request) {
return deleteLifecyclePolicyAsync(request, null);
}
@Override
public java.util.concurrent.Future<DeleteLifecyclePolicyResult> deleteLifecyclePolicyAsync(final DeleteLifecyclePolicyRequest request,
final com.amazonaws.handlers.AsyncHandler<DeleteLifecyclePolicyRequest, DeleteLifecyclePolicyResult> asyncHandler) {
final DeleteLifecyclePolicyRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<DeleteLifecyclePolicyResult>() {
@Override
public DeleteLifecyclePolicyResult call() throws Exception {
DeleteLifecyclePolicyResult result = null;
try {
result = executeDeleteLifecyclePolicy(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<DescribeContainerResult> describeContainerAsync(DescribeContainerRequest request) {
return describeContainerAsync(request, null);
}
@Override
public java.util.concurrent.Future<DescribeContainerResult> describeContainerAsync(final DescribeContainerRequest request,
final com.amazonaws.handlers.AsyncHandler<DescribeContainerRequest, DescribeContainerResult> asyncHandler) {
final DescribeContainerRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<DescribeContainerResult>() {
@Override
public DescribeContainerResult call() throws Exception {
DescribeContainerResult result = null;
try {
result = executeDescribeContainer(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<GetContainerPolicyResult> getContainerPolicyAsync(GetContainerPolicyRequest request) {
return getContainerPolicyAsync(request, null);
}
@Override
public java.util.concurrent.Future<GetContainerPolicyResult> getContainerPolicyAsync(final GetContainerPolicyRequest request,
final com.amazonaws.handlers.AsyncHandler<GetContainerPolicyRequest, GetContainerPolicyResult> asyncHandler) {
final GetContainerPolicyRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<GetContainerPolicyResult>() {
@Override
public GetContainerPolicyResult call() throws Exception {
GetContainerPolicyResult result = null;
try {
result = executeGetContainerPolicy(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<GetCorsPolicyResult> getCorsPolicyAsync(GetCorsPolicyRequest request) {
return getCorsPolicyAsync(request, null);
}
@Override
public java.util.concurrent.Future<GetCorsPolicyResult> getCorsPolicyAsync(final GetCorsPolicyRequest request,
final com.amazonaws.handlers.AsyncHandler<GetCorsPolicyRequest, GetCorsPolicyResult> asyncHandler) {
final GetCorsPolicyRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<GetCorsPolicyResult>() {
@Override
public GetCorsPolicyResult call() throws Exception {
GetCorsPolicyResult result = null;
try {
result = executeGetCorsPolicy(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<GetLifecyclePolicyResult> getLifecyclePolicyAsync(GetLifecyclePolicyRequest request) {
return getLifecyclePolicyAsync(request, null);
}
@Override
public java.util.concurrent.Future<GetLifecyclePolicyResult> getLifecyclePolicyAsync(final GetLifecyclePolicyRequest request,
final com.amazonaws.handlers.AsyncHandler<GetLifecyclePolicyRequest, GetLifecyclePolicyResult> asyncHandler) {
final GetLifecyclePolicyRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<GetLifecyclePolicyResult>() {
@Override
public GetLifecyclePolicyResult call() throws Exception {
GetLifecyclePolicyResult result = null;
try {
result = executeGetLifecyclePolicy(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<ListContainersResult> listContainersAsync(ListContainersRequest request) {
return listContainersAsync(request, null);
}
@Override
public java.util.concurrent.Future<ListContainersResult> listContainersAsync(final ListContainersRequest request,
final com.amazonaws.handlers.AsyncHandler<ListContainersRequest, ListContainersResult> asyncHandler) {
final ListContainersRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<ListContainersResult>() {
@Override
public ListContainersResult call() throws Exception {
ListContainersResult result = null;
try {
result = executeListContainers(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<ListTagsForResourceResult> listTagsForResourceAsync(ListTagsForResourceRequest request) {
return listTagsForResourceAsync(request, null);
}
@Override
public java.util.concurrent.Future<ListTagsForResourceResult> listTagsForResourceAsync(final ListTagsForResourceRequest request,
final com.amazonaws.handlers.AsyncHandler<ListTagsForResourceRequest, ListTagsForResourceResult> asyncHandler) {
final ListTagsForResourceRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<ListTagsForResourceResult>() {
@Override
public ListTagsForResourceResult call() throws Exception {
ListTagsForResourceResult result = null;
try {
result = executeListTagsForResource(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<PutContainerPolicyResult> putContainerPolicyAsync(PutContainerPolicyRequest request) {
return putContainerPolicyAsync(request, null);
}
@Override
public java.util.concurrent.Future<PutContainerPolicyResult> putContainerPolicyAsync(final PutContainerPolicyRequest request,
final com.amazonaws.handlers.AsyncHandler<PutContainerPolicyRequest, PutContainerPolicyResult> asyncHandler) {
final PutContainerPolicyRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<PutContainerPolicyResult>() {
@Override
public PutContainerPolicyResult call() throws Exception {
PutContainerPolicyResult result = null;
try {
result = executePutContainerPolicy(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<PutCorsPolicyResult> putCorsPolicyAsync(PutCorsPolicyRequest request) {
return putCorsPolicyAsync(request, null);
}
@Override
public java.util.concurrent.Future<PutCorsPolicyResult> putCorsPolicyAsync(final PutCorsPolicyRequest request,
final com.amazonaws.handlers.AsyncHandler<PutCorsPolicyRequest, PutCorsPolicyResult> asyncHandler) {
final PutCorsPolicyRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<PutCorsPolicyResult>() {
@Override
public PutCorsPolicyResult call() throws Exception {
PutCorsPolicyResult result = null;
try {
result = executePutCorsPolicy(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<PutLifecyclePolicyResult> putLifecyclePolicyAsync(PutLifecyclePolicyRequest request) {
return putLifecyclePolicyAsync(request, null);
}
@Override
public java.util.concurrent.Future<PutLifecyclePolicyResult> putLifecyclePolicyAsync(final PutLifecyclePolicyRequest request,
final com.amazonaws.handlers.AsyncHandler<PutLifecyclePolicyRequest, PutLifecyclePolicyResult> asyncHandler) {
final PutLifecyclePolicyRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<PutLifecyclePolicyResult>() {
@Override
public PutLifecyclePolicyResult call() throws Exception {
PutLifecyclePolicyResult result = null;
try {
result = executePutLifecyclePolicy(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<StartAccessLoggingResult> startAccessLoggingAsync(StartAccessLoggingRequest request) {
return startAccessLoggingAsync(request, null);
}
@Override
public java.util.concurrent.Future<StartAccessLoggingResult> startAccessLoggingAsync(final StartAccessLoggingRequest request,
final com.amazonaws.handlers.AsyncHandler<StartAccessLoggingRequest, StartAccessLoggingResult> asyncHandler) {
final StartAccessLoggingRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<StartAccessLoggingResult>() {
@Override
public StartAccessLoggingResult call() throws Exception {
StartAccessLoggingResult result = null;
try {
result = executeStartAccessLogging(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<StopAccessLoggingResult> stopAccessLoggingAsync(StopAccessLoggingRequest request) {
return stopAccessLoggingAsync(request, null);
}
@Override
public java.util.concurrent.Future<StopAccessLoggingResult> stopAccessLoggingAsync(final StopAccessLoggingRequest request,
final com.amazonaws.handlers.AsyncHandler<StopAccessLoggingRequest, StopAccessLoggingResult> asyncHandler) {
final StopAccessLoggingRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<StopAccessLoggingResult>() {
@Override
public StopAccessLoggingResult call() throws Exception {
StopAccessLoggingResult result = null;
try {
result = executeStopAccessLogging(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<TagResourceResult> tagResourceAsync(TagResourceRequest request) {
return tagResourceAsync(request, null);
}
@Override
public java.util.concurrent.Future<TagResourceResult> tagResourceAsync(final TagResourceRequest request,
final com.amazonaws.handlers.AsyncHandler<TagResourceRequest, TagResourceResult> asyncHandler) {
final TagResourceRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<TagResourceResult>() {
@Override
public TagResourceResult call() throws Exception {
TagResourceResult result = null;
try {
result = executeTagResource(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<UntagResourceResult> untagResourceAsync(UntagResourceRequest request) {
return untagResourceAsync(request, null);
}
@Override
public java.util.concurrent.Future<UntagResourceResult> untagResourceAsync(final UntagResourceRequest request,
final com.amazonaws.handlers.AsyncHandler<UntagResourceRequest, UntagResourceResult> asyncHandler) {
final UntagResourceRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<UntagResourceResult>() {
@Override
public UntagResourceResult call() throws Exception {
UntagResourceResult result = null;
try {
result = executeUntagResource(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
/**
* Shuts down the client, releasing all managed resources. This includes forcibly terminating all pending
* asynchronous service calls. Clients who wish to give pending asynchronous service calls time to complete should
* call {@code getExecutorService().shutdown()} followed by {@code getExecutorService().awaitTermination()} prior to
* calling this method.
*/
@Override
public void shutdown() {
super.shutdown();
executorService.shutdownNow();
}
}
|
apache-2.0
|
google/depan
|
DepanEdgeUI/prod/src/com/google/devtools/depan/relations/persistence/RelationSetConverters.java
|
5648
|
/*
* Copyright 2015 The Depan Project Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.depan.relations.persistence;
import com.google.devtools.depan.persistence.AbstractTypeConverter;
import com.google.devtools.depan.persistence.AbstractCollectionConverter;
import com.google.devtools.depan.graph.api.Relation;
import com.google.devtools.depan.graph.api.RelationSet;
import com.google.devtools.depan.model.RelationSets;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.mapper.Mapper;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
/**
* {@code XStream} converters to handle {@link RelationSet}s.
* In order to facilitate selection, etc., make sure that all built-in
* relation sets use the same instance.
*
* @author <a href="mailto:leeca@pnambic.com">Lee Carver</a>
*/
public class RelationSetConverters {
private static final String RELATION_SET_ALL_TAG = "relation-set-all";
private static final String RELATION_SET_EMPTY_TAG = "relation-set-empty";
private static final String RELATION_SET_ARRAY_TAG = "relation-set-array";
private static final String RELATION_SET_SIMPLE_TAG = "relation-set-simple";
private static final String RELATION_SET_SINGLE_TAG = "relation-set-single";
private RelationSetConverters() {
// Prevent instantiations.
}
protected static void configXStream(
XStream xstream, String typeTag, AbstractTypeConverter converter) {
xstream.aliasType(typeTag, converter.getType());
xstream.registerConverter(converter);
}
public static void configXStream(XStream xstream) {
Mapper mapper = xstream.getMapper();
new ForValue(RelationSets.ALL).registerWithTag(
xstream, RELATION_SET_ALL_TAG);
new ForValue(RelationSets.EMPTY).registerWithTag(
xstream, RELATION_SET_EMPTY_TAG);
new ForArray(mapper).registerWithTag(
xstream, RELATION_SET_ARRAY_TAG);
new ForSimple(mapper).registerWithTag(
xstream, RELATION_SET_SIMPLE_TAG);
new ForSingle(mapper).registerWithTag(
xstream, RELATION_SET_SINGLE_TAG);
}
private static class ForValue extends AbstractTypeConverter {
private final RelationSet value;
public ForValue(RelationSet value) {
this.value = value;
}
@Override
public Class<?> getType() {
return value.getClass();
}
@Override
public void marshal(Object source, HierarchicalStreamWriter writer,
MarshallingContext context) {
}
@Override
public Object unmarshal(HierarchicalStreamReader reader,
UnmarshallingContext context) {
return value;
}
}
private static class ForSingle extends AbstractCollectionConverter<Relation> {
public ForSingle(Mapper mapper) {
super(ForSingle.class, Relation.class, mapper);
}
@Override
public void marshal(Object source, HierarchicalStreamWriter writer,
MarshallingContext context) {
RelationSets.Single relationSet = (RelationSets.Single) source;
marshalObject(relationSet.getRelation(), writer, context);
}
@Override
public Object unmarshal(HierarchicalStreamReader reader,
UnmarshallingContext context) {
try {
Relation relation = unmarshalChild(reader, context);
return RelationSets.createSingle(relation);
} catch (RuntimeException err) {
err.printStackTrace();
throw err;
}
}
}
private static class ForArray extends AbstractCollectionConverter<Relation> {
public ForArray(Mapper mapper) {
super(RelationSets.Array.class, Relation.class, mapper);
}
@Override
public void marshal(Object source, HierarchicalStreamWriter writer,
MarshallingContext context) {
RelationSets.Array relationSet = (RelationSets.Array) source;
marshalCollection(
Arrays.asList(relationSet.getRelations()), writer, context);
}
@Override
public Object unmarshal(HierarchicalStreamReader reader,
UnmarshallingContext context) {
List<Relation> result = unmarshalList(reader, context);
return new RelationSets.Array((Relation[]) result.toArray());
}
}
private static class ForSimple extends AbstractCollectionConverter<Relation> {
public ForSimple(Mapper mapper) {
super(RelationSets.Simple.class, Relation.class, mapper);
}
@Override
public void marshal(Object source, HierarchicalStreamWriter writer,
MarshallingContext context) {
RelationSets.Simple relationSet = (RelationSets.Simple) source;
marshalCollection(relationSet.getRelations(), writer, context);
}
@Override
public Object unmarshal(HierarchicalStreamReader reader,
UnmarshallingContext context) {
Set<Relation> result = unmarshalSet(reader, context);
return new RelationSets.Simple(result);
}
}
}
|
apache-2.0
|
bazelbuild/rules_docker
|
testdata/py_image_complex_library.py
|
938
|
# Copyright 2017 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from testdata import py_image_library_using_six
from testdata.test import py_image_library_using_addict
def fn(what_comes_in):
return "\n".join([
py_image_library_using_six.fn(what_comes_in + "through py_image_complex_library: "),
py_image_library_using_addict.fn(what_comes_in + "through py_image_complex_library: "),
])
|
apache-2.0
|
opencb/biodata
|
biodata-models/src/main/java/org/opencb/biodata/models/core/RegulatoryPfm.java
|
3252
|
package org.opencb.biodata.models.core;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
import java.util.Map;
public class RegulatoryPfm {
@JsonProperty("stable_id")
private String id;
private String name;
@JsonProperty("associated_transcription_factor_complexes")
private List<String> transcriptionFactors;
private float threshold;
private String source;
private String unit;
@JsonProperty("max_position_sum")
private int maxPositionSum;
private int length;
private Map<String, Map<String, Integer>> elements;
@JsonProperty("elements_string")
private String elementsString;
public RegulatoryPfm() {
}
public RegulatoryPfm(String id, String name, List<String> transcriptionFactors, float threshold, String source, String unit,
int maxPositionSum, int length, Map<String, Map<String, Integer>> elements, String elementsString) {
this.id = id;
this.name = name;
this.transcriptionFactors = transcriptionFactors;
this.threshold = threshold;
this.source = source;
this.unit = unit;
this.maxPositionSum = maxPositionSum;
this.length = length;
this.elements = elements;
this.elementsString = elementsString;
}
public String getId() {
return id;
}
public RegulatoryPfm setId(String id) {
this.id = id;
return this;
}
public String getName() {
return name;
}
public RegulatoryPfm setName(String name) {
this.name = name;
return this;
}
public List<String> getTranscriptionFactors() {
return transcriptionFactors;
}
public RegulatoryPfm setTranscriptionFactors(List<String> transcriptionFactors) {
this.transcriptionFactors = transcriptionFactors;
return this;
}
public float getThreshold() {
return threshold;
}
public RegulatoryPfm setThreshold(float threshold) {
this.threshold = threshold;
return this;
}
public String getSource() {
return source;
}
public RegulatoryPfm setSource(String source) {
this.source = source;
return this;
}
public String getUnit() {
return unit;
}
public RegulatoryPfm setUnit(String unit) {
this.unit = unit;
return this;
}
public int getMaxPositionSum() {
return maxPositionSum;
}
public RegulatoryPfm setMaxPositionSum(int maxPositionSum) {
this.maxPositionSum = maxPositionSum;
return this;
}
public int getLength() {
return length;
}
public RegulatoryPfm setLength(int length) {
this.length = length;
return this;
}
public Map<String, Map<String, Integer>> getElements() {
return elements;
}
public RegulatoryPfm setElements(Map<String, Map<String, Integer>> elements) {
this.elements = elements;
return this;
}
public String getElementsString() {
return elementsString;
}
public RegulatoryPfm setElementsString(String elementsString) {
this.elementsString = elementsString;
return this;
}
}
|
apache-2.0
|
crow-misia/ermaster.old
|
org.insightech.er/src/org/insightech/er/editor/controller/editpart/element/AbstractModelEditPart.java
|
1923
|
package org.insightech.er.editor.controller.editpart.element;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.editparts.AbstractGraphicalEditPart;
import org.insightech.er.Activator;
import org.insightech.er.editor.model.AbstractModel;
import org.insightech.er.editor.model.ERDiagram;
import org.insightech.er.editor.model.diagram_contents.element.node.category.Category;
public abstract class AbstractModelEditPart extends AbstractGraphicalEditPart
implements PropertyChangeListener {
private static final Logger logger = Logger.getLogger(AbstractModelEditPart.class
.getName());
private static final boolean DEBUG = false;
@Override
public void activate() {
super.activate();
AbstractModel model = (AbstractModel) this.getModel();
model.addPropertyChangeListener(this);
}
@Override
public void deactivate() {
AbstractModel model = (AbstractModel) this.getModel();
model.removePropertyChangeListener(this);
super.deactivate();
}
protected final ERDiagram getDiagram() {
return (ERDiagram) this.getRoot().getContents().getModel();
}
protected final Category getCurrentCategory() {
return this.getDiagram().getCurrentCategory();
}
protected final void execute(final Command command) {
this.getViewer().getEditDomain().getCommandStack().execute(command);
}
public final void propertyChange(PropertyChangeEvent event) {
try {
if (DEBUG) {
logger.log(Level.INFO, this.getClass().getName() + ":"
+ event.getPropertyName() + ":" + event.toString());
}
this.doPropertyChange(event);
} catch (Exception e) {
Activator.showExceptionDialog(e);
}
}
protected void doPropertyChange(PropertyChangeEvent event) {
}
}
|
apache-2.0
|
doctang/TestPlatform
|
MTBF/src/com/ztemt/test/mtbf/Cer_MTBF_04.java
|
727
|
package com.ztemt.test.mtbf;
import com.android.uiautomator.core.UiObjectNotFoundException;
/**
* 发送彩信
* 循环次数:10
* @author 0016001973
*
*/
public class Cer_MTBF_04 extends Cer_MTBF_Mms implements UiAutomatorTestable {
@Override
public void test() throws UiObjectNotFoundException {
loop(10);
}
@Override
protected void execute() throws UiObjectNotFoundException {
super.execute();
// 清空会话
clearMessage();
// 新建信息
newMessage();
// 发送信息
sendMessage();
// 退出信息
getUiDevice().pressBack();
getUiDevice().pressBack();
}
}
|
apache-2.0
|
jessemull/MicroFlex
|
src/main/java/com/github/jessemull/microflex/integerflex/stat/GeometricMeanInteger.java
|
7501
|
/**
* 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 --------------------------------- */
package com.github.jessemull.microflex.integerflex.stat;
/* ----------------------------- Dependencies ------------------------------- */
import java.util.List;
/**
* This class calculates the geometric mean of integer plate stacks, plates,
* wells and well sets as the nth root of the product of n numbers.
*
* <br><br>
*
* From wikipedia: a weight function is a mathematical device used when performing
* a sum, integral, or average to give some elements more "weight" or influence on
* the result than other elements in the same set. In statistics a weighted function
* is often used to correct bias. The weighted statistic class implements a weighted
* function by accepting an array of values as weights. The values in each well of
* the stack, plate, set or well are multiplied by the values within the double
* array prior to the statistical calculation.
*
* <br><br>
*
* Weighted statistical operations can be performed on stacks, plates, sets and
* wells using standard or aggregated functions. Standard functions calculate the
* desired statistic for each well in the stack, plate or set. Aggregated functions
* aggregate the values from all the wells in the stack, plate or set and perform
* the weighted statistical operation on the aggregated values. Both standard and
* aggregated functions can be performed on a subset of data within the stack,
* plate, set or well.
*
* <br><br>
*
* The methods within the MicroFlex library are meant to be flexible and the
* descriptive statistic object supports operations using a single stack, plate,
* set or well as well as collections and arrays of stacks, plates, sets or wells.
*
* <table cellspacing="10px" style="text-align:left; margin: 20px;">
* <th><div style="border-bottom: 1px solid black; padding-bottom: 5px; padding-top: 18px;">Operation<div></th>
* <th><div style="border-bottom: 1px solid black; padding-bottom: 5px;">Beginning<br>Index<div></th>
* <th><div style="border-bottom: 1px solid black; padding-bottom: 5px;">Length of<br>Subset<div></th>
* <th><div style="border-bottom: 1px solid black; padding-bottom: 5px; padding-top: 18px;">Input/Output</div></th>
* <tr>
* <td valign="top">
* <table>
* <tr>
* <td>Standard</td>
* </tr>
* </table>
* </td>
* <td valign="top">
* <table>
* <tr>
* <td>+/-</td>
* </tr>
* </table>
* </td>
* <td valign="top">
* <table>
* <tr>
* <td>+/-</td>
* </tr>
* </table>
* </td>
* <td valign="top">
* <table>
* <tr>
* <td style="padding-bottom: 7px;">Accepts a single well, set, plate or stack and an array of weights as input</td>
* </tr>
* <tr>
* <td>Multiplies the values in each well of a well, set, plate or stack by the values
* <br> in the weights array then calculates the statistic using the weighted values</td>
* </tr>
* </table>
* </td>
* </tr>
* <tr>
* <td valign="top">
* <table>
* <tr>
* <td>Aggregated</td>
* </tr>
* </table>
* </td>
* <td valign="top">
* <table>
* <tr>
* <td>+/-</td>
* </tr>
* </table>
* </td>
* <td valign="top">
* <table>
* <tr>
* <td>+/-</td>
* </tr>
* </table>
* </td>
* <td valign="top">
* <table>
* <tr>
* <td style="padding-bottom: 7px;">Accepts a single well/set/plate/stack or a collection/array of wells/sets/plates/stacks
* <br>and an array of weights as input</td>
* </tr>
* <tr>
* <td>Multiplies the values in each well of a well, set, plate or stack by the values in the
* <br>weights array, aggregates the data from all the wells in the well/set/plate/stack then
* <br>calculates the statistic using the aggregated weighted values</td>
* </tr>
* </table>
* </td>
* </tr>
* </table>
*
* @author Jesse L. Mull
* @update Updated Oct 18, 2016
* @address http://www.jessemull.com
* @email hello@jessemull.com
*/
public class GeometricMeanInteger extends DescriptiveStatisticIntegerWeights{
/**
* Calculates the geometric mean.
* @param List<Double> the list
* @return the result
*/
public double calculate(List<Double> list) {
if(list.size() == 0) {
return 0;
}
double result = 1.0;
for(double db : list) {
result *= db;
}
return Math.pow(result, 1.0 / list.size());
}
/**
* Calculates the weighted geometric mean.
* @param List<Double> the list
* @param double[] weights for the data set
* @return the result
*/
public double calculate(List<Double> list, double[] weights) {
if(list.size() == 0) {
return 0;
}
double result = 1.0;
for(int i = 0; i < list.size(); i++) {
double weighted = list.get(i) * weights[i];
result *= weighted;
}
return Math.pow(result, 1.0 / list.size());
}
/**
* Calculates the geometric mean of the values between the beginning and
* ending indices.
* @param List<Double> the list
* @param int beginning index of subset
* @param int length of subset
* @return the result
*/
public double calculate(List<Double> list, int begin, int length) {
return calculate(list.subList(begin, begin + length));
}
/**
* Calculates the weighted geometric mean of the values between the beginning and
* ending indices.
* @param List<Double> the list
* @param double[] weights of the data set
* @param int beginning index of subset
* @param int length of subset
* @return the result
*/
public double calculate(List<Double> list, double[] weights, int begin, int length) {
return calculate(list.subList(begin, begin + length), weights);
}
}
|
apache-2.0
|
jeske/SimpleScene
|
SimpleScene/Objects/SSObjectHUDQuad.cs
|
1805
|
// Copyright(C) David W. Jeske, 2013
// Released to the public domain.
using System;
using OpenTK;
using OpenTK.Graphics.OpenGL;
namespace SimpleScene
{
public class SSObjectHUDQuad : SSObject
{
int GLu_textureID;
public override void Render(SSRenderConfig renderConfig) {
base.Render (renderConfig);
// mode setup
SSShaderProgram.DeactivateAll(); // disable GLSL
GL.ActiveTexture(TextureUnit.Texture0);
GL.Enable(EnableCap.Texture2D);
GL.BindTexture(TextureTarget.Texture2D, 0); // reset first
GL.BindTexture(TextureTarget.Texture2D, GLu_textureID); // now bind the shadowmap texture id
// GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (float)TextureMagFilter.Nearest);
// GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (float)TextureMinFilter.Nearest);
// draw quad...
GL.Begin(PrimitiveType.Triangles);
float w=500;
float h=500;
// upper-left
GL.TexCoord2(0.0, 0.0); GL.Vertex3(0.0, 0.0, 0.0);
GL.TexCoord2(0.0, 1.0); GL.Vertex3(0.0, h, 0.0);
GL.TexCoord2(1.0, 0.0); GL.Vertex3(w, 0.0, 0.0);
// lower-right
GL.TexCoord2(0.0, 1.0); GL.Vertex3(0.0, h, 0.0);
GL.TexCoord2(1.0, 1.0); GL.Vertex3(w, h, 0.0);
GL.TexCoord2(1.0, 0.0); GL.Vertex3(w, 0.0, 0.0);
GL.End();
}
public SSObjectHUDQuad (int GLu_textureID) : base() {
this.GLu_textureID = GLu_textureID;
this.Pos = new Vector3(0,0,0);
this.renderState.alphaBlendingOn = false;
this.renderState.lighted = false;
this.renderState.depthTest = false;
this.renderState.depthWrite = false;
}
}
}
|
apache-2.0
|
tcalmant/ipopo
|
tests/ipopo/test_field_callbacks.py
|
6656
|
#!/usr/bin/env python
# -- Content-Encoding: UTF-8 --
"""
Tests the iPOPO @Bind/Update/UnbindField decorators.
:author: Thomas Calmant
"""
# Standard library
try:
import unittest2 as unittest
except ImportError:
import unittest
# Pelix
from pelix.framework import FrameworkFactory
# Tests
from tests.ipopo import install_bundle, install_ipopo
# ------------------------------------------------------------------------------
__version_info__ = (1, 0, 1)
__version__ = ".".join(str(x) for x in __version_info__)
# ------------------------------------------------------------------------------
class FieldCallbackTest(unittest.TestCase):
"""
Tests the component life cycle
"""
def setUp(self):
"""
Called before each test. Initiates a framework.
"""
self.framework = FrameworkFactory.get_framework()
self.framework.start()
self.ipopo = install_ipopo(self.framework)
self.module = install_bundle(self.framework,
"tests.ipopo.ipopo_fields_bundle")
def tearDown(self):
"""
Called after each test
"""
self.framework.stop()
FrameworkFactory.delete_framework()
def testLifeCycleFieldCallback(self):
"""
Tests the order of field notifications
"""
# Consumer
compo = self.ipopo.instantiate(self.module.FACTORY_C, "consumer")
self.assertEqual(compo.states, [], "States should be empty")
# Service A
svc_a = self.ipopo.instantiate(self.module.FACTORY_A, "svcA")
self.assertEqual(compo.states,
[self.module.BIND_A, self.module.BIND_FIELD_A],
"Service A bound incorrectly")
del compo.states[:]
# Service B
svc_b = self.ipopo.instantiate(self.module.FACTORY_B, "svcB")
self.assertEqual(compo.states,
[self.module.BIND_B, self.module.BIND_FIELD_B],
"Service B bound incorrectly")
del compo.states[:]
# Update A
self.assertNotEqual(svc_a._prop, 42,
"Value already at requested value")
compo.change_a(42)
self.assertEqual(svc_a._prop, 42, "Value not changed")
self.assertEqual(compo.states,
[self.module.UPDATE_FIELD_A, self.module.UPDATE_A],
"Service A updated incorrectly")
del compo.states[:]
# Update B
self.assertNotEqual(svc_b._prop, -123,
"Value already at requested value")
compo.change_b(-123)
self.assertEqual(svc_b._prop, -123, "Value not changed")
self.assertEqual(compo.states,
[self.module.UPDATE_FIELD_B, self.module.UPDATE_B],
"Service B updated incorrectly")
del compo.states[:]
# Kill service A
self.ipopo.kill("svcA")
self.assertEqual(compo.states,
[self.module.UNBIND_FIELD_A, self.module.UNBIND_A],
"Service A unbound incorrectly")
del compo.states[:]
# Kill service B
self.ipopo.kill("svcB")
self.assertEqual(compo.states,
[self.module.UNBIND_FIELD_B, self.module.UNBIND_B],
"Service B unbound incorrectly")
del compo.states[:]
# Kill consumer
self.ipopo.kill("consumer")
def testLifeCycleFieldCallbackIfValid(self):
"""
Tests the order of field notifications with the "if_valid" flag
"""
# Consumer
compo = self.ipopo.instantiate(self.module.FACTORY_D, "consumer")
self.assertEqual(compo.states, [], "States should be empty")
# -- Component is invalid
# Start Service B
svc_b = self.ipopo.instantiate(self.module.FACTORY_B, "svcB")
self.assertEqual(compo.states, [], "Service B bound: called")
del compo.states[:]
# Update B
self.assertNotEqual(svc_b._prop, -123,
"Value already at requested value")
compo.change_b(-123)
self.assertEqual(svc_b._prop, -123, "Value not changed")
self.assertEqual(compo.states, [], "Service B updated: called")
del compo.states[:]
# Kill service B
self.ipopo.kill("svcB")
self.assertEqual(compo.states, [], "Service B unbound: called")
del compo.states[:]
# Start Service A
self.ipopo.instantiate(self.module.FACTORY_A, "svcA")
del compo.states[:]
# -- Component is valid
# Start Service B
svc_b = self.ipopo.instantiate(self.module.FACTORY_B, "svcB")
self.assertEqual(compo.states, [self.module.BIND_FIELD_B],
"Service B bound: not called")
del compo.states[:]
# Update B
self.assertNotEqual(svc_b._prop, -123,
"Value already at requested value")
compo.change_b(-123)
self.assertEqual(svc_b._prop, -123, "Value not changed")
self.assertEqual(compo.states, [self.module.UPDATE_FIELD_B],
"Service B updated: not called")
del compo.states[:]
# Kill service B
self.ipopo.kill("svcB")
self.assertEqual(compo.states, [self.module.UNBIND_FIELD_B],
"Service B unbound: not called")
del compo.states[:]
# Restart Service B
svc_b = self.ipopo.instantiate(self.module.FACTORY_B, "svcB")
self.assertEqual(compo.states, [self.module.BIND_FIELD_B],
"Service B bound: not called")
del compo.states[:]
# Kill service A
self.ipopo.kill("svcA")
del compo.states[:]
# -- Component is invalid (again)
# Update B
self.assertNotEqual(svc_b._prop, -123,
"Value already at requested value")
compo.change_b(-123)
self.assertEqual(svc_b._prop, -123, "Value not changed")
self.assertEqual(compo.states, [], "Service B updated: called")
del compo.states[:]
# Kill service B
self.ipopo.kill("svcB")
self.assertEqual(compo.states, [], "Service B unbound: called")
del compo.states[:]
# Kill consumer
self.ipopo.kill("consumer")
# ------------------------------------------------------------------------------
if __name__ == "__main__":
# Set logging level
import logging
logging.basicConfig(level=logging.DEBUG)
unittest.main()
|
apache-2.0
|
FangWW/meinv
|
app/src/main/java/com/meinv/bean/BaseEntity.java
|
1206
|
/*
* Copyright (c) 2015 [1076559197@qq.com | tchen0707@gmail.com]
*
* Licensed under the Apache License, Version 2.0 (the "License”);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.meinv.bean;
/**
* Author: Tau.Chen
* Email: 1076559197@qq.com | tauchen1990@gmail.com
* Date: 2015/3/19.
* Description:
*/
public class BaseEntity {
private String id;
private String name;
public BaseEntity(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
apache-2.0
|
itzg/titan-browser
|
src/main/java/me/itzg/titanbrowser/model/ConfigurationUpdate.java
|
260
|
package me.itzg.titanbrowser.model;
public class ConfigurationUpdate {
String seedHost;
Authentication authentication;
public static class Authentication {
boolean authenticate;
String authUser;
String authPass;
}
}
|
apache-2.0
|
jboismar/SKM
|
ha_setup.php
|
2097
|
<?php include('MyFunctions.inc.php');
if (isset($_GET["id"])) $id_host = $_GET["id"]; else $id_host = "";
if (isset($_GET["host_name"])) $host_name = $_GET["host_name"]; else $host_name = "";
if (isset($_GET["id_hostgroup"])) $id_hostgroup = $_GET["id_hostgroup"]; else $id_hostgroup = "";
if (isset($_POST["account"])) $id_account = $_POST["account"]; else $id_account = "";
// We get the list of accounts
$result = mysql_query( "SELECT * FROM `accounts`" );
if (isset($_POST["step"])) $step = $_POST["step"]; else $step = "";
if($step != '1')
{
?>
<html>
<HEAD>
<TITLE>Hosts - Accounts Association</TITLE>
<LINK REL=STYLESHEET HREF="skm.css" TYPE="text/css">
</HEAD>
<BODY>
<?php start_main_frame(); ?>
<?php start_left_pane(); ?>
<?php display_menu(); ?>
<?php end_left_pane(); ?>
<?php start_right_pane(); ?>
<center>
<form name="setup_ha" action="ha_setup.php" method="post">
<fieldset><legend>Adding Account(s) to host <?php echo("$host_name");?></legend>
<table border='0' align='center' class="modif_contact">
<tr>
<td class="Type"><?php display_availables_accounts(); ?></td>
</td>
</tr>
</table>
</fieldset>
<center>
<input name="step" type="hidden" value="1">
<input name="id_hostgroup" type="hidden" value="<?php echo $id_hostgroup?>">
<input name="id" type="hidden" value="<?php echo $id_host?>">
<input name="submit" type="submit" value="add">
</center>
</form>
</center>
<? end_right_pane(); ?>
<? end_main_frame(); ?>
</body>
</html>
<?php
}
else
{
$error_list = "";
if( empty( $error_list ) )
{
$id_host = $_POST['id'];
$id_hostgroup = $_POST['id_hostgroup'];
mysql_query( "INSERT INTO `hosts-accounts` (`id_host`, `id_account`, `expand`) VALUES('$id_host','$id_account','Y')" ) or die(mysql_error()."<br>Couldn't execute query");
header("Location:host-view.php?id_hostgroup=$id_hostgroup&id=$id_host");
echo ("account Added, redirecting...");
exit ();
}
else
{
// Error occurred let's notify it
echo( $error_list );
}
}
?>
|
apache-2.0
|
leilihh/nova
|
nova/db/sqlalchemy/migrate_repo/versions/235_add_npar_resource_table.py
|
3397
|
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from sqlalchemy import Column
from sqlalchemy import DateTime
from sqlalchemy import Integer
from sqlalchemy import MetaData
from sqlalchemy import String
from sqlalchemy import Table
from nova.openstack.common.gettextutils import _
from nova.openstack.common import log as logging
from nova.openstack.common import timeutils
LOG = logging.getLogger(__name__)
def upgrade(migrate_engine):
meta = MetaData()
meta.bind = migrate_engine
nPar_resource = Table('nPar_resource', meta,
Column('id', Integer, primary_key=True, nullable=False),
Column('created_at', DateTime, default=timeutils.utcnow),
Column('updated_at', DateTime, onupdate=timeutils.utcnow),
Column('deleted_at', DateTime),
Column('ip_addr', String(length=255), nullable=False),
Column('vcpus', Integer, nullable=True),
Column('vcpus_used', Integer, nullable=True),
Column('memory', Integer, nullable=True),
Column('memory_used', Integer, nullable=True),
Column('disk', Integer, nullable=True),
Column('disk_used', Integer, nullable=True),
Column('deleted', String(length=36), nullable=False),
mysql_engine='InnoDB',
mysql_charset='utf8'
)
shadow_nPar_resource = Table('shadow_nPar_resource', meta,
Column('id', Integer, primary_key=True, nullable=False),
Column('created_at', DateTime),
Column('updated_at', DateTime),
Column('deleted_at', DateTime),
Column('ip_addr', String(length=255), nullable=False),
Column('vcpus', Integer, nullable=True),
Column('vcpus_used', Integer, nullable=True),
Column('memory', Integer, nullable=True),
Column('memory_used', Integer, nullable=True),
Column('disk', Integer, nullable=True),
Column('disk_used', Integer, nullable=True),
Column('deleted', String(length=36), nullable=False),
mysql_engine='InnoDB',
mysql_charset='utf8'
)
try:
# Drop the compute_node_stats table and add a 'stats' column to
# compute_nodes directly. The data itself is transient and doesn't
# need to be copied over.
table_names = ('nPar_resource', 'shadow_nPar_resource')
for table_name in table_names:
table = Table(table_name, meta, autoload=True)
table.create()
except Exception:
LOG.info(repr(nPar_resource))
LOG.exception(_('Exception while creating table.'))
raise
def downgrade(migrate_engine):
meta = MetaData()
meta.bind = migrate_engine
table_name = ('nPar_resource')
table = Table(table_name, meta, autoload=True)
table.drop()
table_name = ('shadow_nPar_resource')
table = Table(table_name, meta, autoload=True)
table.drop()
|
apache-2.0
|
bartnorsk/gep
|
src/com/bartnorsk/basic/tests/SubstractionOfTwoNucleotideTest.java
|
1410
|
package com.bartnorsk.basic.tests;
import static org.junit.Assert.*;
import org.junit.Test;
import com.bartnorsk.basic.SubstractionOfTwoNucleotide;
import com.bartnorsk.basic.TypeDoubleNucleotide;
import com.bartnorsk.basic.TypeIntegerNucleotide;
/**
* @author Bart JV
*
*/
public class SubstractionOfTwoNucleotideTest {
SubstractionOfTwoNucleotide nucleotide;
@Test
public void constructorShouldSetArityTwo() {
TypeIntegerNucleotide subNuc = new TypeIntegerNucleotide(1);
nucleotide = new SubstractionOfTwoNucleotide(subNuc, subNuc);
assertEquals(2, nucleotide.getArity());
}
@Test
public void subtractionReturnsNegativeOne() {
TypeDoubleNucleotide leftMember = new TypeDoubleNucleotide(1.0);
TypeDoubleNucleotide rightMember = new TypeDoubleNucleotide(2.0);
nucleotide = new SubstractionOfTwoNucleotide(leftMember, rightMember);
assertEquals(-1.0, nucleotide.execute());
}
@Test
public void valueDoesntChange() {
TypeIntegerNucleotide subNuc = new TypeIntegerNucleotide(1);
nucleotide = new SubstractionOfTwoNucleotide(subNuc, subNuc);
nucleotide.setValue("+");
assertEquals("-", nucleotide.getValue());
}
@Test
public void constructorSetsValueToAddSymbol() {
TypeIntegerNucleotide subNuc = new TypeIntegerNucleotide(1);
nucleotide = new SubstractionOfTwoNucleotide(subNuc, subNuc);
assertEquals("-", nucleotide.getValue());
}
}
|
apache-2.0
|
multi-os-engine/moe-core
|
moe.apple/moe.platform.ios/src/main/java/apple/avfoundation/AVVideoComposition.java
|
17155
|
/*
Copyright 2014-2016 Intel Corporation
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 apple.avfoundation;
import apple.NSObject;
import apple.avfoundation.protocol.AVVideoCompositing;
import apple.avfoundation.protocol.AVVideoCompositionValidationHandling;
import apple.coregraphics.struct.CGSize;
import apple.coremedia.struct.CMTime;
import apple.coremedia.struct.CMTimeRange;
import apple.foundation.NSArray;
import apple.foundation.NSMethodSignature;
import apple.foundation.NSNumber;
import apple.foundation.NSSet;
import apple.foundation.protocol.NSCopying;
import apple.foundation.protocol.NSMutableCopying;
import org.moe.natj.c.ann.FunctionPtr;
import org.moe.natj.general.NatJ;
import org.moe.natj.general.Pointer;
import org.moe.natj.general.ann.ByValue;
import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.Library;
import org.moe.natj.general.ann.Mapped;
import org.moe.natj.general.ann.MappedReturn;
import org.moe.natj.general.ann.NInt;
import org.moe.natj.general.ann.NUInt;
import org.moe.natj.general.ann.Owned;
import org.moe.natj.general.ann.Runtime;
import org.moe.natj.general.ptr.VoidPtr;
import org.moe.natj.objc.Class;
import org.moe.natj.objc.ObjCRuntime;
import org.moe.natj.objc.SEL;
import org.moe.natj.objc.ann.ObjCBlock;
import org.moe.natj.objc.ann.ObjCClassBinding;
import org.moe.natj.objc.ann.Selector;
import org.moe.natj.objc.map.ObjCObjectMapper;
@Generated
@Library("AVFoundation")
@Runtime(ObjCRuntime.class)
@ObjCClassBinding
public class AVVideoComposition extends NSObject implements NSCopying, NSMutableCopying {
static {
NatJ.register();
}
@Generated
protected AVVideoComposition(Pointer peer) {
super(peer);
}
@Generated
@Selector("accessInstanceVariablesDirectly")
public static native boolean accessInstanceVariablesDirectly();
@Generated
@Owned
@Selector("alloc")
public static native AVVideoComposition alloc();
@Owned
@Generated
@Selector("allocWithZone:")
public static native AVVideoComposition allocWithZone(VoidPtr zone);
@Generated
@Selector("automaticallyNotifiesObserversForKey:")
public static native boolean automaticallyNotifiesObserversForKey(String key);
@Generated
@Selector("cancelPreviousPerformRequestsWithTarget:")
public static native void cancelPreviousPerformRequestsWithTarget(@Mapped(ObjCObjectMapper.class) Object aTarget);
@Generated
@Selector("cancelPreviousPerformRequestsWithTarget:selector:object:")
public static native void cancelPreviousPerformRequestsWithTargetSelectorObject(
@Mapped(ObjCObjectMapper.class) Object aTarget, SEL aSelector,
@Mapped(ObjCObjectMapper.class) Object anArgument);
@Generated
@Selector("classFallbacksForKeyedArchiver")
public static native NSArray<String> classFallbacksForKeyedArchiver();
@Generated
@Selector("classForKeyedUnarchiver")
public static native Class classForKeyedUnarchiver();
@Generated
@Selector("debugDescription")
public static native String debugDescription_static();
@Generated
@Selector("description")
public static native String description_static();
@Generated
@Selector("hash")
@NUInt
public static native long hash_static();
@Generated
@Selector("instanceMethodForSelector:")
@FunctionPtr(name = "call_instanceMethodForSelector_ret")
public static native NSObject.Function_instanceMethodForSelector_ret instanceMethodForSelector(SEL aSelector);
@Generated
@Selector("instanceMethodSignatureForSelector:")
public static native NSMethodSignature instanceMethodSignatureForSelector(SEL aSelector);
@Generated
@Selector("instancesRespondToSelector:")
public static native boolean instancesRespondToSelector(SEL aSelector);
@Generated
@Selector("isSubclassOfClass:")
public static native boolean isSubclassOfClass(Class aClass);
@Generated
@Selector("keyPathsForValuesAffectingValueForKey:")
public static native NSSet<String> keyPathsForValuesAffectingValueForKey(String key);
@Generated
@Owned
@Selector("new")
public static native AVVideoComposition new_objc();
@Generated
@Selector("resolveClassMethod:")
public static native boolean resolveClassMethod(SEL sel);
@Generated
@Selector("resolveInstanceMethod:")
public static native boolean resolveInstanceMethod(SEL sel);
@Generated
@Selector("setVersion:")
public static native void setVersion_static(@NInt long aVersion);
@Generated
@Selector("superclass")
public static native Class superclass_static();
@Generated
@Selector("version")
@NInt
public static native long version_static();
/**
* videoCompositionWithAsset:options:applyingCIFiltersWithHandler:
* <p>
* Returns a new instance of AVVideoComposition with values and instructions that will apply the specified handler block to video frames represented as instances of CIImage.
* <p>
* The returned AVVideoComposition will cause the specified handler block to be called to filter each frame of the asset's first enabled video track. The handler block should use the properties of the provided AVAsynchronousCIImageFilteringRequest and respond using finishWithImage:context: with a "filtered" new CIImage (or the provided source image for no affect). In the event of an error, respond to the request using finishWithError:. The error can be observed via AVPlayerItemFailedToPlayToEndTimeNotification, see AVPlayerItemFailedToPlayToEndTimeErrorKey in notification payload.
* <p>
* NOTE: The returned AVVideoComposition's properties are private and support only CIFilter-based operations. Mutations are not supported, either in the values of properties of the AVVideoComposition itself or in its private instructions. If rotations or other transformations are desired, they must be accomplished via the application of CIFilters during the execution of your specified handler.
* <p>
* The video composition will also have the following values for its properties:
* <p>
* - The original timing of the asset's first enabled video track will be used.
* - A renderSize that encompasses the asset's first enabled video track respecting the track's preferredTransform.
* - A renderScale of 1.0.
* <p>
* The default CIContext has the following properties:
* <p>
* - iOS: Device RGB color space
* - OS X: sRGB color space
* <p>
* Example usage:
* <p>
* playerItem.videoComposition = [AVVideoComposition videoCompositionWithAsset:srcAsset applyingCIFiltersWithHandler:
* ^(AVAsynchronousCIImageFilteringRequest *request)
* {
* NSError *err = nil;
* CIImage *filtered = myRenderer(request, &err);
* if (filtered)
* [request finishWithImage:filtered context:nil];
* else
* [request finishWithError:err];
* }];
*
* @param asset An instance of AVAsset. For best performance, ensure that the duration and tracks properties of the asset are already loaded before invoking this method.
* @return An instance of AVVideoComposition.
*/
@Generated
@Selector("videoCompositionWithAsset:applyingCIFiltersWithHandler:")
public static native AVVideoComposition videoCompositionWithAssetApplyingCIFiltersWithHandler(AVAsset asset,
@ObjCBlock(name = "call_videoCompositionWithAssetApplyingCIFiltersWithHandler") Block_videoCompositionWithAssetApplyingCIFiltersWithHandler applier);
/**
* videoCompositionWithPropertiesOfAsset:
* <p>
* Returns a new instance of AVVideoComposition with values and instructions suitable for presenting the video tracks of the specified asset according to its temporal and geometric properties and those of its tracks.
* <p>
* The returned AVVideoComposition will have instructions that respect the spatial properties and timeRanges of the specified asset's video tracks.
* It will also have the following values for its properties:
* <p>
* - If the asset has exactly one video track, the original timing of the source video track will be used. If the asset has more than one video track, and the nominal frame rate of any of video tracks is known, the reciprocal of the greatest known nominalFrameRate will be used as the value of frameDuration. Otherwise, a default framerate of 30fps is used.
* - If the specified asset is an instance of AVComposition, the renderSize will be set to the naturalSize of the AVComposition; otherwise the renderSize will be set to a value that encompasses all of the asset's video tracks.
* - A renderScale of 1.0.
* - A nil animationTool.
* <p>
* If the specified asset has no video tracks, this method will return an AVVideoComposition instance with an empty collection of instructions.
*
* @param asset An instance of AVAsset. Ensure that the duration and tracks properties of the asset are already loaded before invoking this method.
* @return An instance of AVVideoComposition.
*/
@Generated
@Selector("videoCompositionWithPropertiesOfAsset:")
public static native AVVideoComposition videoCompositionWithPropertiesOfAsset(AVAsset asset);
/**
* indicates a special video composition tool for use of Core Animation; may be nil
*/
@Generated
@Selector("animationTool")
public native AVVideoCompositionCoreAnimationTool animationTool();
/**
* [@property] colorPrimaries
* <p>
* Rendering will use these primaries and frames will be tagged as such. If the value of this property is nil then the source's primaries will be propagated and used.
* <p>
* Default is nil. Valid values are those suitable for AVVideoColorPrimariesKey. Generally set as a triple along with colorYCbCrMatrix and colorTransferFunction.
*/
@Generated
@Selector("colorPrimaries")
public native String colorPrimaries();
/**
* [@property] colorTransferFunction
* <p>
* Rendering will use this transfer function and frames will be tagged as such. If the value of this property is nil then the source's transfer function will be propagated and used.
* <p>
* Default is nil. Valid values are those suitable for AVVideoTransferFunctionKey. Generally set as a triple along with colorYCbCrMatrix and colorYCbCrMatrix.
*/
@Generated
@Selector("colorTransferFunction")
public native String colorTransferFunction();
/**
* [@property] colorYCbCrMatrix
* <p>
* Rendering will use this matrix and frames will be tagged as such. If the value of this property is nil then the source's matrix will be propagated and used.
* <p>
* Default is nil. Valid values are those suitable for AVVideoYCbCrMatrixKey. Generally set as a triple along with colorPrimaries and colorTransferFunction.
*/
@Generated
@Selector("colorYCbCrMatrix")
public native String colorYCbCrMatrix();
@Generated
@Owned
@Selector("copyWithZone:")
@MappedReturn(ObjCObjectMapper.class)
public native Object copyWithZone(VoidPtr zone);
/**
* indicates a custom compositor class to use. The class must implement the AVVideoCompositing protocol.
* If nil, the default, internal video compositor is used
*/
@Generated
@Selector("customVideoCompositorClass")
@MappedReturn(ObjCObjectMapper.class)
public native AVVideoCompositing customVideoCompositorClass();
/**
* indicates the interval which the video composition, when enabled, should render composed video frames
*/
@Generated
@Selector("frameDuration")
@ByValue
public native CMTime frameDuration();
@Generated
@Selector("init")
public native AVVideoComposition init();
/**
* Indicates instructions for video composition via an NSArray of instances of classes implementing the AVVideoCompositionInstruction protocol.
* For the first instruction in the array, timeRange.start must be less than or equal to the earliest time for which playback or other processing will be attempted
* (note that this will typically be kCMTimeZero). For subsequent instructions, timeRange.start must be equal to the prior instruction's end time. The end time of
* the last instruction must be greater than or equal to the latest time for which playback or other processing will be attempted (note that this will often be
* the duration of the asset with which the instance of AVVideoComposition is associated).
*/
@Generated
@Selector("instructions")
public native NSArray<?> instructions();
/**
* isValidForAsset:timeRange:validationDelegate:
* <p>
* Indicates whether the timeRanges of the receiver's instructions conform to the requirements described for them immediately above (in connection with the instructions property) and also whether all of the layer instructions have a value for trackID that corresponds either to a track of the specified asset or to the receiver's animationTool.
* <p>
* In the course of validation, the receiver will invoke its validationDelegate with reference to any trouble spots in the video composition.
* An exception will be raised if the delegate modifies the receiver's array of instructions or the array of layerInstructions of any AVVideoCompositionInstruction contained therein during validation.
*
* @param asset Pass a reference to an AVAsset if you wish to validate the timeRanges of the instructions against the duration of the asset and the trackIDs of the layer instructions against the asset's tracks. Pass nil to skip that validation. Clients should ensure that the keys @"tracks" and @"duration" are already loaded on the AVAsset before validation is attempted.
* @param timeRange A CMTimeRange. Only those instuctions with timeRanges that overlap with the specified timeRange will be validated. To validate all instructions that may be used for playback or other processing, regardless of timeRange, pass CMTimeRangeMake(kCMTimeZero, kCMTimePositiveInfinity).
* @param validationDelegate Indicates an object implementing the AVVideoCompositionValidationHandling protocol to receive information about troublesome portions of a video composition during processing of -isValidForAsset:. May be nil.
*/
@Generated
@Selector("isValidForAsset:timeRange:validationDelegate:")
public native boolean isValidForAssetTimeRangeValidationDelegate(AVAsset asset, @ByValue CMTimeRange timeRange,
@Mapped(ObjCObjectMapper.class) AVVideoCompositionValidationHandling validationDelegate);
@Owned
@Generated
@Selector("mutableCopyWithZone:")
@MappedReturn(ObjCObjectMapper.class)
public native Object mutableCopyWithZone(VoidPtr zone);
/**
* indicates the scale at which the video composition should render. May only be other than 1.0 for a video composition set on an AVPlayerItem
*/
@Generated
@Selector("renderScale")
public native float renderScale();
/**
* indicates the size at which the video composition, when enabled, should render
*/
@Generated
@Selector("renderSize")
@ByValue
public native CGSize renderSize();
@Runtime(ObjCRuntime.class)
@Generated
public interface Block_videoCompositionWithAssetApplyingCIFiltersWithHandler {
@Generated
void call_videoCompositionWithAssetApplyingCIFiltersWithHandler(AVAsynchronousCIImageFilteringRequest request);
}
/**
* If sourceTrackIDForFrameTiming is not kCMPersistentTrackID_Invalid, frame timing for the video composition is derived from the source asset's track with the corresponding ID. This may be used to preserve a source asset's variable frame timing. If an empty edit is encountered in the source asset’s track, the compositor composes frames as needed up to the frequency specified in frameDuration property.
*/
@Generated
@Selector("sourceTrackIDForFrameTiming")
public native int sourceTrackIDForFrameTiming();
/**
* List of all track IDs for tracks from which sample data should be presented to the compositor at any point in the overall composition. The sample data will be delivered to the custom compositor via AVAsynchronousVideoCompositionRequest.
*/
@Generated
@Selector("sourceSampleDataTrackIDs")
public native NSArray<? extends NSNumber> sourceSampleDataTrackIDs();
}
|
apache-2.0
|
xehoth/OnlineJudgeCodes
|
codechef/CC DISTNUM2-Easy Queries-区间树.cpp
|
5936
|
/**
* Copyright (c) 2016-2018, xehoth
* 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.
*
* 「CC DISTNUM2」Easy Queries 29-04-2018
* 区间树
* @author xehoth
*/
#include <bits/stdc++.h>
struct InputOutputStream {
enum { SIZE = 1024 * 1024 };
char ibuf[SIZE], *s, *t, obuf[SIZE], *oh;
InputOutputStream() : s(), t(), oh(obuf) {}
~InputOutputStream() { fwrite(obuf, 1, oh - obuf, stdout); }
inline char read() {
if (s == t) t = (s = ibuf) + fread(ibuf, 1, SIZE, stdin);
return s == t ? -1 : *s++;
}
template <typename T>
inline InputOutputStream &operator>>(T &x) {
static char c;
static bool iosig;
for (c = read(), iosig = false; !isdigit(c); c = read()) {
if (c == -1) return *this;
iosig |= c == '-';
}
for (x = 0; isdigit(c); c = read()) x = x * 10 + (c ^ '0');
if (iosig) x = -x;
return *this;
}
inline void print(char c) {
if (oh == obuf + SIZE) {
fwrite(obuf, 1, SIZE, stdout);
oh = obuf;
}
*oh++ = c;
}
template <typename T>
inline void print(T x) {
static int buf[21], cnt;
if (x != 0) {
if (x < 0) {
print('-');
x = -x;
}
for (cnt = 0; x; x /= 10) buf[++cnt] = x % 10 | 48;
while (cnt) print((char)buf[cnt--]);
} else {
print('0');
}
}
template <typename T>
inline InputOutputStream &operator<<(const T &x) {
print(x);
return *this;
}
} io;
const int POOL_SIZE = 1024 * 1024 * 400;
char pool[POOL_SIZE];
void *operator new(size_t size) {
static char *s = pool;
char *t = s;
s += size;
return t;
}
void operator delete(void *) {}
void operator delete(void *, size_t) {}
struct RangeTree2D {
using Node = RangeTree2D;
int l, r;
std::vector<int> d;
Node *lc, *rc;
RangeTree2D(const std::vector<std::pair<int, int> > &a, int l, int r) {
this->l = a[l].first;
this->r = a[r].first;
if (l == r) {
d.push_back(a[l].second);
lc = rc = nullptr;
return;
}
int mid = (l + r) >> 1;
lc = new Node(a, l, mid);
rc = new Node(a, mid + 1, r);
d.resize(r - l + 1);
std::merge(lc->d.begin(), lc->d.end(), rc->d.begin(), rc->d.end(),
d.begin());
}
int query(int l, int r) {
l = std::lower_bound(d.begin(), d.end(), l) - d.begin();
r = std::upper_bound(d.begin(), d.end(), r) - d.begin();
return r - l;
}
int query(int lX, int rX, int lY, int rY) {
if (lX <= l && rX >= r) return query(lY, rY);
if (r < lX || l > rX) return 0;
return lc->query(lX, rX, lY, rY) + rc->query(lX, rX, lY, rY);
}
};
struct RangeTree3D {
using Node = RangeTree3D;
int l, r;
std::vector<std::pair<int, int> > d;
RangeTree2D *tree;
Node *lc, *rc;
RangeTree3D(const std::vector<std::pair<int, std::pair<int, int> > > &a,
int l, int r) {
this->l = a[l].first;
this->r = a[r].first;
if (l == r) {
d.emplace_back(a[l].second);
} else {
int mid = (l + r) >> 1;
lc = new Node(a, l, mid);
rc = new Node(a, mid + 1, r);
d.resize(r - l + 1);
std::merge(lc->d.begin(), lc->d.end(), rc->d.begin(), rc->d.end(),
d.begin());
}
tree = new RangeTree2D(d, 0, d.size() - 1);
}
int query(int lX, int rX, int lY, int rY, int lZ, int rZ) {
if (lX <= l && rX >= r) return tree->query(lY, rY, lZ, rZ);
if (r < lX || l > rX) return 0;
return lc->query(lX, rX, lY, rY, lZ, rZ) +
rc->query(lX, rX, lY, rY, lZ, rZ);
}
int query(int l, int r, int k) {
if (this->l == this->r) return this->l;
int cnt = lc->tree->query(0, l - 1, l, r);
return k <= cnt ? lc->query(l, r, k) : rc->query(l, r, k - cnt);
}
};
const int MAXN = 100000 + 9;
int a[MAXN], num[MAXN], pre[MAXN];
int main() {
int n, q;
io >> n >> q;
std::vector<std::pair<int, int> > b(n);
for (int i = 1; i <= n; i++) {
io >> a[i];
b[i - 1] = {a[i], i};
}
std::sort(b.begin(), b.end());
for (int i = 0, idx; i < n; i++) {
idx = b[i].second;
if (i == 0 || b[i].first != b[i - 1].first) {
num[i + 1] = a[idx];
a[idx] = i + 1;
} else {
a[idx] = a[b[i - 1].second];
}
}
num[0] = -1;
std::vector<std::pair<int, std::pair<int, int> > > pts(n);
for (int i = 1; i <= n; i++) {
pts[i - 1] = {a[i], {pre[a[i]], i}};
pre[a[i]] = i;
}
std::sort(pts.begin(), pts.end());
RangeTree3D *tree = new RangeTree3D(pts, 0, n - 1);
int ans = 0, inf = pts[n - 1].first;
for (int a, b, c, d, k, l, r, idx; q--;) {
io >> a >> b >> c >> d >> k;
l = (a * std::max(ans, 0) + b) % n + 1;
r = (c * std::max(ans, 0) + d) % n + 1;
if (l > r) std::swap(l, r);
idx = tree->query(l, r, k);
if (idx == inf && tree->query(0, idx, 0, l - 1, l, r) != k) {
idx = 0;
}
ans = num[idx];
io << ans << '\n';
}
return 0;
}
|
apache-2.0
|
aspnet/AspNetCore
|
src/Servers/Kestrel/Core/src/Internal/Infrastructure/HeartbeatManager.cs
|
1265
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Threading;
namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure
{
internal class HeartbeatManager : IHeartbeatHandler, ISystemClock
{
private readonly ConnectionManager _connectionManager;
private readonly Action<KestrelConnection> _walkCallback;
private DateTimeOffset _now;
private long _nowTicks;
public HeartbeatManager(ConnectionManager connectionManager)
{
_connectionManager = connectionManager;
_walkCallback = WalkCallback;
}
public DateTimeOffset UtcNow => new DateTimeOffset(UtcNowTicks, TimeSpan.Zero);
public long UtcNowTicks => Volatile.Read(ref _nowTicks);
public DateTimeOffset UtcNowUnsynchronized => _now;
public void OnHeartbeat(DateTimeOffset now)
{
_now = now;
Volatile.Write(ref _nowTicks, now.Ticks);
_connectionManager.Walk(_walkCallback);
}
private void WalkCallback(KestrelConnection connection)
{
connection.TickHeartbeat();
}
}
}
|
apache-2.0
|
puppetlabs/puppetlabs-cloudpassage
|
cloudpassage/lib/puppet/parser/functions/cp2resource.rb
|
1713
|
require 'rubygems'
require 'httparty'
require 'pp'
class Cloudpassage
include HTTParty
attr_accessor :server_id, :api_key, :base_url
def initialize ( server_id, api_key, base_url)
@uri = "#{base_url}/#{server_id}/issues"
@api_key = api_key
end
def auth_headers
self.class.headers 'x-cpauth-access' => @api_key
end
def default_format
self.class.format json
end
def get_issues
report = self.class.get @uri, self.auth_headers
issue = Hash.new
report['sca']['findings'].each do |findings|
findings['details'].each do |check|
if check['type'] && check['target'] && check.delete('status') == 'bad'
title = "#{check.delete('type')}:#{check["config_key"]}:#{check['target']}"
issue[title] = Hash.new
issue[title]['message'] = "This will eventually be converted into a resource for remediation:\n"
check.each_pair do |key, value|
issue[title]['message'] = issue[title]['message'] + "#{key} => #{value}\n"
end
end
end
end
return issue
end
end
def hash2resource(title, hash)
resource = Puppet::Parser::Resource.new('notify', 'title', :scope => self, :source => @main)
hash.each do |param, value|
resource.set_parameter(param, value) unless %w{type title}.include?(param)
end
resource
end
def create(hash)
issue.each_pair do |title, hash|
resource = hash2resource(title, hash)
self.compiler.add_resource(self, resource)
end
end
module Puppet::Parser::Functions
newfunction(:cp2resource) do |args|
issues = Cloudpassage.new(args[0], args[1], args[2]).get_issues
issues.each do |issue|
pp issue
#create(issue)
end
end
end
|
apache-2.0
|
laocaixw/coolweather
|
src/com/laocaixw/coolweather/model/Province.java
|
534
|
package com.laocaixw.coolweather.model;
public class Province {
private int id;
private String provinceName;
private String provinceCode;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getProvinceName() {
return provinceName;
}
public void setProvinceName(String provinceName) {
this.provinceName = provinceName;
}
public String getProvinceCode() {
return provinceCode;
}
public void setProvinceCode(String provinceCode) {
this.provinceCode = provinceCode;
}
}
|
apache-2.0
|
nuclio/nuclio
|
pkg/processor/trigger/mqtt/iotcore/factory.go
|
2152
|
/*
Copyright 2017 The Nuclio 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 iotcoremqtt
import (
"github.com/nuclio/nuclio/pkg/functionconfig"
"github.com/nuclio/nuclio/pkg/processor/runtime"
"github.com/nuclio/nuclio/pkg/processor/trigger"
"github.com/nuclio/nuclio/pkg/processor/worker"
"github.com/nuclio/errors"
"github.com/nuclio/logger"
)
type factory struct {
trigger.Factory
}
func (f *factory) Create(parentLogger logger.Logger,
id string,
triggerConfiguration *functionconfig.Trigger,
runtimeConfiguration *runtime.Configuration,
namedWorkerAllocators *worker.AllocatorSyncMap) (trigger.Trigger, error) {
// create logger parent
triggerLogger := parentLogger.GetChild(triggerConfiguration.Kind)
configuration, err := NewConfiguration(id, triggerConfiguration, runtimeConfiguration)
if err != nil {
return nil, errors.Wrap(err, "Failed to create configuration")
}
// get or create worker allocator
workerAllocator, err := f.GetWorkerAllocator(triggerConfiguration.WorkerAllocatorName,
namedWorkerAllocators,
func() (worker.Allocator, error) {
return worker.WorkerFactorySingleton.CreateFixedPoolWorkerAllocator(triggerLogger,
configuration.MaxWorkers,
runtimeConfiguration)
})
if err != nil {
return nil, errors.Wrap(err, "Failed to create worker allocator")
}
// finally, create the trigger
triggerInstance, err := newTrigger(triggerLogger,
workerAllocator,
configuration,
)
if err != nil {
return nil, errors.Wrap(err, "Failed to create trigger")
}
return triggerInstance, nil
}
// register factory
func init() {
trigger.RegistrySingleton.Register("iotCoreMqtt", &factory{})
}
|
apache-2.0
|
deepmind/deepmind-research
|
rl_unplugged/atari_example.py
|
1668
|
# Lint as: python3
# Copyright 2020 DeepMind Technologies Limited.
#
# 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.
r"""Atari dataset example.
Instructions:
> mkdir -p /tmp/dataset/Asterix
> gsutil cp gs://rl_unplugged/atari/Asterix/run_1-00000-of-00100 \
/tmp/dataset/Asterix/run_1-00000-of-00001
> python atari_example.py --path=/tmp/dataset --game=Asterix
"""
from absl import app
from absl import flags
from acme import specs
import tree
from rl_unplugged import atari
flags.DEFINE_string('path', '/tmp/dataset', 'Path to dataset.')
flags.DEFINE_string('game', 'Asterix', 'Game.')
FLAGS = flags.FLAGS
def main(_):
ds = atari.dataset(FLAGS.path, FLAGS.game, 1,
num_shards=1,
shuffle_buffer_size=1)
for sample in ds.take(1):
print('Data spec')
print(tree.map_structure(lambda x: (x.dtype, x.shape), sample.data))
env = atari.environment(FLAGS.game)
print('Environment spec')
print(specs.make_environment_spec(env))
print('Environment observation')
timestep = env.reset()
print(tree.map_structure(lambda x: (x.dtype, x.shape), timestep.observation))
if __name__ == '__main__':
app.run(main)
|
apache-2.0
|
rmeindl/jenetics.net
|
src/core/Jenetics/CompositeAlterer.cs
|
3115
|
// Java Genetic Algorithm Library.
// Copyright (c) 2017 Franz Wilhelmstötter
//
// 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.
//
// Author:
// Franz Wilhelmstötter (franz.wilhelmstoetter@gmx.at)
using System;
using System.Collections.Generic;
using System.Linq;
using Jenetics.Internal.Util;
using Jenetics.Util;
namespace Jenetics
{
public class CompositeAlterer<TGene, TAllele> : AltererBase<TGene, TAllele>
where TGene : IGene<TGene>
where TAllele : IComparable<TAllele>, IConvertible
{
public CompositeAlterer(ISeq<IAlterer<TGene, TAllele>> alterers) : base(1.0)
{
Alterers = Normalize(alterers);
}
public IImmutableSeq<IAlterer<TGene, TAllele>> Alterers { get; }
private static IImmutableSeq<IAlterer<TGene, TAllele>> Normalize(ISeq<IAlterer<TGene, TAllele>> alterers)
{
IEnumerable<IAlterer<TGene, TAllele>> Mapper(IAlterer<TGene, TAllele> a)
{
return a is CompositeAlterer<TGene, TAllele> alterer
? alterer.Alterers
: Enumerable.Repeat(a, 1);
}
return alterers.SelectMany(Mapper).ToList().ToImmutableSeq();
}
public override int Alter(Population<TGene, TAllele> population, long generation)
{
return Alterers.Select(a => a.Alter(population, generation)).Sum();
}
public override bool Equals(object obj)
{
return obj is CompositeAlterer<TGene, TAllele> alterer &&
Equality.Eq(alterer.Alterers, Alterers);
}
public override int GetHashCode()
{
return Hash.Of(GetType()).And(Alterers).Value;
}
public override string ToString()
{
return $"{GetType().Name}:\n{string.Join("\n", Alterers.Select(a => " - " + a))}";
}
}
public static class CompositeAlterer
{
public static CompositeAlterer<TGene, TAllele> Of<TGene, TAllele>(params IAlterer<TGene, TAllele>[] alterers)
where TGene : IGene<TGene>
where TAllele : IComparable<TAllele>, IConvertible
{
return new CompositeAlterer<TGene, TAllele>(ImmutableSeq.Of(alterers));
}
public static CompositeAlterer<TGene, TAllele> Join<TGene, TAllele>(
IAlterer<TGene, TAllele> a1,
IAlterer<TGene, TAllele> a2
)
where TGene : IGene<TGene>
where TAllele : IComparable<TAllele>, IConvertible
{
return Of(a1, a2);
}
}
}
|
apache-2.0
|
antonio-castellon/jsStatistics
|
src/JsStatistics.ttest.js
|
3047
|
/* global module */
// # jsStatistics - T_Test
//
// A statistics StatUtils library translated from http://commons.apache.org/.
// An implementation for Student's t-tests..
// more info : http://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/stat/inference/TTest.html
//
// The code below uses the
// [Javascript module pattern](http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth),
// eventually assigning `T_Test` in browsers or the `exports` object for node.js
//
// NOTE: at the moment Only implement the http://en.wikipedia.org/wiki/Welch's_t_test
//
// TODO : To implement the complet ttest ->
/*
TTEST
array1 - The first data set
array2 - The second data set (must have the same length as array1)
tails - The number of tails for the distribution. This must be either :
1 - uses the one-tailed distribution
2 - uses the two-tailed distribution
type - An integer that represents the type of t-test. This can be either :
1 - Paired T-Test
2 - Two-sample equal variance T-Test
3 - Two-sample unequal variance T-Test
WE ARE USING TAILS = 2 + TYPE = 3
return value = 0.00888664
*/
if (typeof module !== 'undefined') {
var FastMath = require('./JsStatistics.fastmath.js');
var StatUtils = require('./JsStatistics.statutils.js');
var Beta = require('./JsStatistics.beta.js');
}
(function() {
var T_Test = {};
if (typeof module !== 'undefined') {
// Assign the `gamma` object to exports, so that you can require
// it in [node.js](http://nodejs.org/)
module.exports = T_Test;
} else {
// Otherwise, in a browser, we assign `T_Test` to the window object,
// so you can simply refer to it as `T_Test`.
this.T_Test = T_Test;
}
// constants
// functions
T_Test.ttest = ttest;
T_Test.df = df;
// functions implementations
// Computes p-value for 2-sided, 2-sample t-test.
function ttest(fArray1,fArray2) {
var mean1=StatUtils.mean(fArray1);
var mean2=StatUtils.mean(fArray2);
var sd1= StatUtils.variance(fArray1,mean1);
var sd2= StatUtils.variance(fArray2,mean2);
var t = FastMath.abs(((mean1-mean2)/FastMath.sqrt((sd1/fArray1.length+sd2/fArray2.length))*10000)/10000);
var degreesOfFreedom = df(sd1,sd2,fArray1.length, fArray2.length);
var x = degreesOfFreedom / (degreesOfFreedom + (t * t)); // 0.03978879649292954;
var a = 0.5 * degreesOfFreedom; // 1.2281758316015892;
var b = 0.5;
return Beta.regularizedBeta(x,a,b);
}
/**
* Computes approximate degrees of freedom for 2-sample t-test.
*
* @param v1 first sample variance
* @param v2 second sample variance
* @param n1 first sample n
* @param n2 second sample n
* @return approximate degrees of freedom
*/
function df( v1, v2, n1, n2) {
return (((v1 / n1) + (v2 / n2)) * ((v1 / n1) + (v2 / n2))) /
((v1 * v1) / (n1 * n1 * (n1 - 1.0)) + (v2 * v2) /
(n2 * n2 * (n2 - 1.0)));
}
})(this);
|
apache-2.0
|
hurzl/dmix
|
JMPDComm/src/test/java/com/anpmech/mpd/commandresponse/ArtistResponseTest.java
|
2731
|
/*
* Copyright (C) 2004 Felipe Gustavo de Almeida
* Copyright (C) 2010-2016 The MPDroid Project
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice,this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.anpmech.mpd.commandresponse;
import com.anpmech.mpd.TestTools;
import com.anpmech.mpd.connection.CommandResult;
import com.anpmech.mpd.item.Artist;
/**
* This class tests the {@link ArtistResponse} class.
*/
public class ArtistResponseTest extends ObjectResponseTest<Artist, ArtistResponse> {
/**
* Sole constructor.
*/
public ArtistResponseTest() {
super();
}
/**
* This returns a empty ObjectResponse for the ObjectResponse subclass.
*
* @return A empty ObjectResponse.
*/
@Override
protected ArtistResponse getEmptyResponse() {
return new ArtistResponse();
}
/**
* This returns a path to a test sample file to construct a CommandResult from.
*
* @return A path to a test sample file.
*/
@Override
protected String getResponsePath() {
return TestTools.FILE_SEPARATED_COMMAND_RESPONSE;
}
/**
* This method instantiates the ObjectResponse type from the {@code CommandResult} parameter.
*
* @param result The {@code CommandResult} to create the ObjectResponse type from.
* @return A ObjectResponse subclass type.
*/
@Override
protected ArtistResponse instantiate(final CommandResult result) {
return new ArtistResponse(result);
}
}
|
apache-2.0
|
myshkin5/go-workshop
|
tour-exercises/exercise-stringer.go
|
322
|
package main
import "fmt"
type IPAddr [4]byte
func (i IPAddr) String() string {
return fmt.Sprintf("%d.%d.%d.%d", i[0], i[1], i[2], i[3])
}
func main() {
hosts := map[string]IPAddr{
"loopback": {127, 0, 0, 1},
"googleDNS": {8, 8, 8, 8},
}
for name, ip := range hosts {
fmt.Printf("%v: %v\n", name, ip)
}
}
|
apache-2.0
|
djhelbert/iclub
|
src/test/java/org/iclub/service/UserServiceTest.java
|
1256
|
package org.iclub.service;
import java.util.Optional;
import org.iclub.model.Role;
import org.iclub.model.User;
import org.iclub.model.UserForm;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@DataJpaTest
public class UserServiceTest {
@Autowired
private UserService userService;
@Test
public void testService() {
userService.save(getUserForm("test@email.net", Role.USER, "pwd"));
final Optional<User> optional = userService.getUserByEmail("test@email.net");
assert optional.isPresent();
}
public UserForm getUserForm(String email, Role role, String password) {
final UserForm user = new UserForm();
user.setEmail(email);
user.setRole(role);
user.setFirstName("First");
user.setLastName("Last");
user.setCellPhone("555-555-5555");
user.setHomePhone("555-555-6666");
user.setPassword(password);
user.setPasswordConfirm(password);
return user;
}
}
|
apache-2.0
|
sleroy/fakesmtp-junit-runner
|
src/main/java/com/github/sleroy/junit/mail/server/events/NewMailEvent.java
|
1327
|
/**
* 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 com.github.sleroy.junit.mail.server.events;
import com.github.sleroy.fakesmtp.model.EmailModel;
/**
* The Class NewMailEvent defines an event when an email model has been
* received.
*/
public class NewMailEvent {
private final EmailModel model;
/**
* Instantiates a new new mail event.
*
* @param model
* the model
*/
public NewMailEvent(final EmailModel model) {
this.model = model;
}
public EmailModel getModel() {
return model;
}
}
|
apache-2.0
|
spring-cloud/spring-cloud-sleuth
|
tests/common/src/main/java/org/springframework/cloud/sleuth/instrument/kafka/KafkaReceiverTest.java
|
6112
|
/*
* Copyright 2013-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 org.springframework.cloud.sleuth.instrument.kafka;
import java.time.Duration;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.assertj.core.api.BDDAssertions;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Answers;
import org.mockito.BDDMockito;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.testcontainers.containers.KafkaContainer;
import org.testcontainers.containers.wait.strategy.Wait;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.utility.DockerImageName;
import reactor.core.Disposable;
import reactor.core.scheduler.Schedulers;
import reactor.kafka.receiver.KafkaReceiver;
import reactor.kafka.receiver.ReceiverOptions;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.cloud.sleuth.Span;
import org.springframework.cloud.sleuth.Tracer;
import org.springframework.cloud.sleuth.exporter.FinishedSpan;
import org.springframework.cloud.sleuth.propagation.Propagator;
import org.springframework.cloud.sleuth.test.TestSpanHandler;
import org.springframework.cloud.sleuth.test.TestTracingAwareSupplier;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.ResolvableType;
import static org.awaitility.Awaitility.await;
@Testcontainers
@ExtendWith(MockitoExtension.class)
@Tag("DockerRequired")
public abstract class KafkaReceiverTest implements TestTracingAwareSupplier {
protected String testTopic;
protected Tracer tracer = tracerTest().tracing().tracer();
protected Propagator propagator = tracerTest().tracing().propagator();
protected TestSpanHandler spans = tracerTest().handler();
private Disposable consumerSubscription;
protected final AtomicInteger receivedCounter = new AtomicInteger(0);
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
BeanFactory beanFactory;
@Container
protected static final KafkaContainer kafkaContainer = new KafkaContainer(
DockerImageName.parse("confluentinc/cp-kafka:6.1.1")).withExposedPorts(9093)
.waitingFor(Wait.forListeningPort());
@BeforeAll
static void setupAll() {
kafkaContainer.start();
}
@AfterAll
static void destroyAll() {
kafkaContainer.stop();
}
@BeforeEach
void setup() {
BDDMockito.given(this.beanFactory.getBean(Propagator.class)).willReturn(this.propagator);
BDDMockito.given(this.beanFactory.getBeanProvider(ResolvableType.forClassWithGenerics(Propagator.Getter.class,
ResolvableType.forType(new ParameterizedTypeReference<ConsumerRecord<?, ?>>() {
}))).getIfAvailable()).willReturn(new TracingKafkaPropagatorGetter());
testTopic = UUID.randomUUID().toString();
Map<String, Object> consumerProperties = new HashMap<>();
consumerProperties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaContainer.getBootstrapServers());
consumerProperties.put(ConsumerConfig.GROUP_ID_CONFIG, "test-consumer-group");
consumerProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
consumerProperties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
consumerProperties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
ReceiverOptions<String, String> options = ReceiverOptions.create(consumerProperties);
options = options.withKeyDeserializer(new StringDeserializer()).withValueDeserializer(new StringDeserializer())
.subscription(Collections.singletonList(testTopic));
KafkaReceiver<String, String> kafkaReceiver = KafkaReceiver.create(new TracingKafkaConsumerFactory(beanFactory),
options);
this.consumerSubscription = kafkaReceiver.receive().subscribeOn(Schedulers.single())
.subscribe(record -> receivedCounter.incrementAndGet());
this.receivedCounter.set(0);
}
@AfterEach
void destroy() {
this.consumerSubscription.dispose();
}
@Test
public void should_create_and_finish_consumer_span() {
KafkaProducer<String, String> kafkaProducer = KafkaTestUtils
.buildTestKafkaProducer(kafkaContainer.getBootstrapServers());
ProducerRecord<String, String> producerRecord = new ProducerRecord<>(testTopic, "test", "test");
kafkaProducer.send(producerRecord);
await().atMost(Duration.ofSeconds(15)).until(() -> receivedCounter.intValue() == 1);
BDDAssertions.then(this.tracer.currentSpan()).isNull();
BDDAssertions.then(this.spans).hasSize(1);
FinishedSpan span = this.spans.get(0);
BDDAssertions.then(span.getKind()).isEqualTo(Span.Kind.CONSUMER);
BDDAssertions.then(span.getTags()).isNotEmpty();
BDDAssertions.then(span.getTags().get("kafka.topic")).isEqualTo(testTopic);
BDDAssertions.then(span.getTags().get("kafka.offset")).isEqualTo("0");
BDDAssertions.then(span.getTags().get("kafka.partition")).isEqualTo("0");
}
@Override
public void cleanUpTracing() {
this.spans.clear();
}
}
|
apache-2.0
|
inbloom/secure-data-service
|
tools/data-tools/src/org/slc/sli/test/edfi/entities/MeetingDaysType.java
|
2429
|
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.12.06 at 10:00:50 AM EST
//
package org.slc.sli.test.edfi.entities;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* The day(s) of the week (e.g., Monday, Wednesday) that the class meets or an indication that a class meets "out-of-school" or "self-paced".
*
* <p>Java class for MeetingDaysType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="MeetingDaysType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="MeetingDay" type="{http://ed-fi.org/0100}MeetingDayItemType" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "MeetingDaysType", propOrder = {
"meetingDay"
})
public class MeetingDaysType {
@XmlElement(name = "MeetingDay")
protected List<MeetingDayItemType> meetingDay;
/**
* Gets the value of the meetingDay property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the meetingDay property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getMeetingDay().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link MeetingDayItemType }
*
*
*/
public List<MeetingDayItemType> getMeetingDay() {
if (meetingDay == null) {
meetingDay = new ArrayList<MeetingDayItemType>();
}
return this.meetingDay;
}
}
|
apache-2.0
|
gurisxie/weex-test
|
test/ios/sword.ios.weex.test/src/test/java/sword/ios/app/test/iOSWXSelectTest.java
|
102
|
package sword.ios.app.test;
/**
* Created by admin on 16/4/20.
*/
public class iOSWXSelectTest {
}
|
apache-2.0
|
DanielTing/presto
|
presto-raptor/src/test/java/com/facebook/presto/raptor/storage/TestShardEjector.java
|
8970
|
/*
* 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.facebook.presto.raptor.storage;
import com.facebook.presto.raptor.backup.BackupStore;
import com.facebook.presto.raptor.metadata.ColumnInfo;
import com.facebook.presto.raptor.metadata.DatabaseShardManager;
import com.facebook.presto.raptor.metadata.MetadataDao;
import com.facebook.presto.raptor.metadata.ShardInfo;
import com.facebook.presto.raptor.metadata.ShardManager;
import com.facebook.presto.raptor.metadata.ShardMetadata;
import com.facebook.presto.spi.HostAddress;
import com.facebook.presto.spi.Node;
import com.facebook.presto.spi.NodeManager;
import com.facebook.presto.spi.TupleDomain;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import io.airlift.units.Duration;
import org.skife.jdbi.v2.DBI;
import org.skife.jdbi.v2.Handle;
import org.skife.jdbi.v2.IDBI;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.io.File;
import java.net.URI;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import static com.facebook.presto.spi.type.BigintType.BIGINT;
import static com.google.common.io.Files.createTempDir;
import static io.airlift.testing.FileUtils.deleteRecursively;
import static java.util.Objects.requireNonNull;
import static java.util.UUID.randomUUID;
import static java.util.concurrent.TimeUnit.HOURS;
import static java.util.stream.Collectors.toSet;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
public class TestShardEjector
{
private IDBI dbi;
private Handle dummyHandle;
private ShardManager shardManager;
private File dataDir;
private StorageService storageService;
@BeforeMethod
public void setup()
throws Exception
{
dbi = new DBI("jdbc:h2:mem:test" + System.nanoTime());
dummyHandle = dbi.open();
shardManager = new DatabaseShardManager(dbi);
dataDir = createTempDir();
storageService = new FileStorageService(dataDir);
storageService.start();
}
@AfterMethod(alwaysRun = true)
public void teardown()
{
if (dummyHandle != null) {
dummyHandle.close();
}
if (dataDir != null) {
deleteRecursively(dataDir);
}
}
@Test(invocationCount = 20)
public void testEjector()
throws Exception
{
NodeManager nodeManager = createNodeManager("node1", "node2", "node3", "node4", "node5");
ShardEjector ejector = new ShardEjector(
nodeManager,
shardManager,
storageService,
new Duration(1, HOURS),
Optional.of(new TestingBackupStore()),
"test");
List<ShardInfo> shards = ImmutableList.<ShardInfo>builder()
.add(shardInfo("node1", 14))
.add(shardInfo("node1", 13))
.add(shardInfo("node1", 12))
.add(shardInfo("node1", 11))
.add(shardInfo("node1", 10))
.add(shardInfo("node1", 10))
.add(shardInfo("node1", 10))
.add(shardInfo("node1", 10))
.add(shardInfo("node2", 5))
.add(shardInfo("node2", 5))
.add(shardInfo("node3", 10))
.add(shardInfo("node4", 10))
.add(shardInfo("node5", 10))
.add(shardInfo("node6", 200))
.build();
long tableId = createTable("test");
List<ColumnInfo> columns = ImmutableList.of(new ColumnInfo(1, BIGINT));
shardManager.createTable(tableId, columns);
shardManager.commitShards(tableId, columns, shards, Optional.empty());
for (ShardInfo shard : shards.subList(0, 8)) {
File file = storageService.getStorageFile(shard.getShardUuid());
storageService.createParents(file);
assertTrue(file.createNewFile());
}
ejector.process();
shardManager.getShardNodes(tableId, TupleDomain.all());
Set<UUID> ejectedShards = shards.subList(0, 4).stream()
.map(ShardInfo::getShardUuid)
.collect(toSet());
Set<UUID> keptShards = shards.subList(4, 8).stream()
.map(ShardInfo::getShardUuid)
.collect(toSet());
Set<UUID> remaining = uuids(shardManager.getNodeShards("node1"));
for (UUID uuid : ejectedShards) {
assertFalse(remaining.contains(uuid));
assertFalse(storageService.getStorageFile(uuid).exists());
}
assertEquals(remaining, keptShards);
for (UUID uuid : keptShards) {
assertTrue(storageService.getStorageFile(uuid).exists());
}
Set<UUID> others = ImmutableSet.<UUID>builder()
.addAll(uuids(shardManager.getNodeShards("node2")))
.addAll(uuids(shardManager.getNodeShards("node3")))
.addAll(uuids(shardManager.getNodeShards("node4")))
.addAll(uuids(shardManager.getNodeShards("node5")))
.build();
assertTrue(others.containsAll(ejectedShards));
}
private long createTable(String name)
{
return dbi.onDemand(MetadataDao.class).insertTable("test", name, false);
}
private static Set<UUID> uuids(Set<ShardMetadata> metadata)
{
return metadata.stream()
.map(ShardMetadata::getShardUuid)
.collect(toSet());
}
private static ShardInfo shardInfo(String node, long size)
{
return new ShardInfo(randomUUID(), ImmutableSet.of(node), ImmutableList.of(), 1, size, size * 2);
}
private static NodeManager createNodeManager(String current, String... others)
{
Node currentNode = new TestingNode(current);
ImmutableSet.Builder<Node> nodes = ImmutableSet.builder();
nodes.add(currentNode);
for (String other : others) {
nodes.add(new TestingNode(other));
}
return new TestingNodeManager(nodes.build(), currentNode);
}
private static class TestingNodeManager
implements NodeManager
{
private final Set<Node> nodes;
private final Node currentNode;
public TestingNodeManager(Set<Node> nodes, Node currentNode)
{
this.nodes = ImmutableSet.copyOf(requireNonNull(nodes, "nodes is null"));
this.currentNode = requireNonNull(currentNode, "currentNode is null");
}
@Override
public Set<Node> getActiveNodes()
{
return nodes;
}
@Override
public Set<Node> getActiveDatasourceNodes(String datasourceName)
{
return nodes;
}
@Override
public Node getCurrentNode()
{
return currentNode;
}
@Override
public Set<Node> getCoordinators()
{
throw new UnsupportedOperationException();
}
}
private static class TestingNode
implements Node
{
private final String identifier;
public TestingNode(String identifier)
{
this.identifier = requireNonNull(identifier, "identifier is null");
}
@Override
public HostAddress getHostAndPort()
{
throw new UnsupportedOperationException();
}
@Override
public URI getHttpUri()
{
throw new UnsupportedOperationException();
}
@Override
public String getNodeIdentifier()
{
return identifier;
}
}
private static class TestingBackupStore
implements BackupStore
{
@Override
public void backupShard(UUID uuid, File source)
{
throw new UnsupportedOperationException();
}
@Override
public void restoreShard(UUID uuid, File target)
{
throw new UnsupportedOperationException();
}
@Override
public void deleteShard(UUID uuid)
{
throw new UnsupportedOperationException();
}
@Override
public boolean shardExists(UUID uuid)
{
return true;
}
}
}
|
apache-2.0
|
leeyazhou/sharding-jdbc
|
sharding-core/sharding-core-merge/src/main/java/org/apache/shardingsphere/sharding/merge/dql/groupby/GroupByStreamMergedResult.java
|
6335
|
/*
* 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.shardingsphere.sharding.merge.dql.groupby;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import org.apache.shardingsphere.sharding.merge.dql.groupby.aggregation.AggregationUnit;
import org.apache.shardingsphere.sharding.merge.dql.groupby.aggregation.AggregationUnitFactory;
import org.apache.shardingsphere.sharding.merge.dql.orderby.OrderByStreamMergedResult;
import org.apache.shardingsphere.sql.parser.binder.metadata.schema.SchemaMetaData;
import org.apache.shardingsphere.sql.parser.binder.segment.select.projection.impl.AggregationDistinctProjection;
import org.apache.shardingsphere.sql.parser.binder.segment.select.projection.impl.AggregationProjection;
import org.apache.shardingsphere.sql.parser.binder.statement.dml.SelectStatementContext;
import org.apache.shardingsphere.underlying.executor.sql.jdbc.queryresult.QueryResult;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* Stream merged result for group by.
*/
public final class GroupByStreamMergedResult extends OrderByStreamMergedResult {
private final SelectStatementContext selectStatementContext;
private final List<Object> currentRow;
private List<?> currentGroupByValues;
public GroupByStreamMergedResult(final Map<String, Integer> labelAndIndexMap, final List<QueryResult> queryResults,
final SelectStatementContext selectStatementContext, final SchemaMetaData schemaMetaData) throws SQLException {
super(queryResults, selectStatementContext, schemaMetaData);
this.selectStatementContext = selectStatementContext;
currentRow = new ArrayList<>(labelAndIndexMap.size());
currentGroupByValues = getOrderByValuesQueue().isEmpty()
? Collections.emptyList() : new GroupByValue(getCurrentQueryResult(), selectStatementContext.getGroupByContext().getItems()).getGroupValues();
}
@Override
public boolean next() throws SQLException {
currentRow.clear();
if (getOrderByValuesQueue().isEmpty()) {
return false;
}
if (isFirstNext()) {
super.next();
}
if (aggregateCurrentGroupByRowAndNext()) {
currentGroupByValues = new GroupByValue(getCurrentQueryResult(), selectStatementContext.getGroupByContext().getItems()).getGroupValues();
}
return true;
}
private boolean aggregateCurrentGroupByRowAndNext() throws SQLException {
boolean result = false;
Map<AggregationProjection, AggregationUnit> aggregationUnitMap = Maps.toMap(
selectStatementContext.getProjectionsContext().getAggregationProjections(), input -> AggregationUnitFactory.create(input.getType(), input instanceof AggregationDistinctProjection));
while (currentGroupByValues.equals(new GroupByValue(getCurrentQueryResult(), selectStatementContext.getGroupByContext().getItems()).getGroupValues())) {
aggregate(aggregationUnitMap);
cacheCurrentRow();
result = super.next();
if (!result) {
break;
}
}
setAggregationValueToCurrentRow(aggregationUnitMap);
return result;
}
private void aggregate(final Map<AggregationProjection, AggregationUnit> aggregationUnitMap) throws SQLException {
for (Entry<AggregationProjection, AggregationUnit> entry : aggregationUnitMap.entrySet()) {
List<Comparable<?>> values = new ArrayList<>(2);
if (entry.getKey().getDerivedAggregationProjections().isEmpty()) {
values.add(getAggregationValue(entry.getKey()));
} else {
for (AggregationProjection each : entry.getKey().getDerivedAggregationProjections()) {
values.add(getAggregationValue(each));
}
}
entry.getValue().merge(values);
}
}
private void cacheCurrentRow() throws SQLException {
for (int i = 0; i < getCurrentQueryResult().getColumnCount(); i++) {
currentRow.add(getCurrentQueryResult().getValue(i + 1, Object.class));
}
}
private Comparable<?> getAggregationValue(final AggregationProjection aggregationProjection) throws SQLException {
Object result = getCurrentQueryResult().getValue(aggregationProjection.getIndex(), Object.class);
Preconditions.checkState(null == result || result instanceof Comparable, "Aggregation value must implements Comparable");
return (Comparable<?>) result;
}
private void setAggregationValueToCurrentRow(final Map<AggregationProjection, AggregationUnit> aggregationUnitMap) {
for (Entry<AggregationProjection, AggregationUnit> entry : aggregationUnitMap.entrySet()) {
currentRow.set(entry.getKey().getIndex() - 1, entry.getValue().getResult());
}
}
@Override
public Object getValue(final int columnIndex, final Class<?> type) {
Object result = currentRow.get(columnIndex - 1);
setWasNull(null == result);
return result;
}
@Override
public Object getCalendarValue(final int columnIndex, final Class<?> type, final Calendar calendar) {
Object result = currentRow.get(columnIndex - 1);
setWasNull(null == result);
return result;
}
}
|
apache-2.0
|
yurloc/assertj-core
|
src/test/java/org/assertj/core/internal/objects/Objects_assertIsNotIn_with_array_Test.java
|
3393
|
/*
* Created on Jan 2, 2010
*
* 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 @2010-2011 the original author or authors.
*/
package org.assertj.core.internal.objects;
import static org.assertj.core.error.ShouldNotBeIn.shouldNotBeIn;
import static org.assertj.core.test.ErrorMessages.*;
import static org.assertj.core.test.ObjectArrays.emptyArray;
import static org.assertj.core.test.TestData.someInfo;
import static org.assertj.core.test.TestFailures.failBecauseExpectedAssertionErrorWasNotThrown;
import static org.assertj.core.util.Arrays.array;
import static org.assertj.core.util.FailureMessages.actualIsNull;
import static org.mockito.Mockito.verify;
import org.assertj.core.api.AssertionInfo;
import org.assertj.core.internal.Objects;
import org.assertj.core.internal.ObjectsBaseTest;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* Tests for <code>{@link Objects#assertIsNotIn(AssertionInfo, Object, Object[])}</code>.
*
* @author Joel Costigliola
* @author Alex Ruiz
* @author Yvonne Wang
*/
public class Objects_assertIsNotIn_with_array_Test extends ObjectsBaseTest {
private static String[] values;
@BeforeClass
public static void setUpOnce() {
values = array("Yoda", "Leia");
}
@Test
public void should_throw_error_if_array_is_null() {
thrown.expectNullPointerException(arrayIsNull());
Object[] array = null;
objects.assertIsNotIn(someInfo(), "Yoda", array);
}
@Test
public void should_throw_error_if_array_is_empty() {
thrown.expectIllegalArgumentException(arrayIsEmpty());
objects.assertIsNotIn(someInfo(), "Yoda", emptyArray());
}
@Test
public void should_pass_if_actual_is_in_not_array() {
objects.assertIsNotIn(someInfo(), "Luke", values);
}
@Test
public void should_fail_if_actual_is_null() {
thrown.expectAssertionError(actualIsNull());
objects.assertIsNotIn(someInfo(), null, values);
}
@Test
public void should_fail_if_actual_is_not_in_array() {
AssertionInfo info = someInfo();
try {
objects.assertIsNotIn(info, "Yoda", values);
} catch (AssertionError e) {
verify(failures).failure(info, shouldNotBeIn("Yoda", values));
return;
}
failBecauseExpectedAssertionErrorWasNotThrown();
}
@Test
public void should_pass_if_actual_is_in_not_array_according_to_custom_comparison_strategy() {
objectsWithCustomComparisonStrategy.assertIsNotIn(someInfo(), "Luke", values);
}
@Test
public void should_fail_if_actual_is_not_in_array_according_to_custom_comparison_strategy() {
AssertionInfo info = someInfo();
try {
objectsWithCustomComparisonStrategy.assertIsNotIn(info, "YODA", values);
} catch (AssertionError e) {
verify(failures).failure(info, shouldNotBeIn("YODA", values, customComparisonStrategy));
return;
}
failBecauseExpectedAssertionErrorWasNotThrown();
}
}
|
apache-2.0
|
togglz/togglz
|
spring-core/src/main/java/org/togglz/spring/activation/SpringEnvironmentPropertyActivationStrategy.java
|
1849
|
package org.togglz.spring.activation;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.togglz.core.Feature;
import org.togglz.core.activation.AbstractPropertyDrivenActivationStrategy;
import org.togglz.core.repository.FeatureState;
import org.togglz.core.user.FeatureUser;
import org.togglz.spring.util.ContextClassLoaderApplicationContextHolder;
/**
* <p>
* An activation strategy based on the values of properties accessible within the Spring environment.
* </p>
* <p>
* It can either be based on a given property name, passed via the "{@value #PARAM_NAME}" parameter, or a property name
* derived from the {@link Feature} itself (e.g. "{@value #DEFAULT_PROPERTY_PREFIX}FEATURE_NAME").
* </p>
*
* @author Alasdair Mercer
* @see AbstractPropertyDrivenActivationStrategy
*/
public class SpringEnvironmentPropertyActivationStrategy extends AbstractPropertyDrivenActivationStrategy {
public static final String ID = "spring-environment-property";
@Override
public String getId() {
return ID;
}
@Override
public String getName() {
return "Spring Environment Property";
}
@Override
protected String getPropertyValue(FeatureState featureState, FeatureUser user, String name) {
ApplicationContext applicationContext = ContextClassLoaderApplicationContextHolder.get();
if (applicationContext == null) {
throw new IllegalStateException("ApplicationContext could not be found, which can occur if there is no "
+ "bean for TogglzApplicationContextBinderApplicationListener when TogglzAutoConfiguration is not "
+ "being used");
}
Environment environment = applicationContext.getEnvironment();
return environment.getProperty(name);
}
}
|
apache-2.0
|
RyanTech/ubivearound_2
|
src/com/ubive/ui/adapter/GirdImageAdapter.java
|
1979
|
package com.ubive.ui.adapter;
import java.util.ArrayList;
import java.util.List;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.ubive.BaseActivity;
import com.ubive.Global;
import com.ubive.R;
import com.ubive.entity.Photo;
import com.ubive.ui.option.DisplayOption;
public class GirdImageAdapter extends BaseAdapter {
private BaseActivity context ;
private List<Photo>list;
private LayoutInflater inflater;
private String TAG = "Adapter";
public GirdImageAdapter(){}
public GirdImageAdapter(BaseActivity context, List<Photo> list) {
this.context = context;
inflater = LayoutInflater.from(context);
if(list==null){
list = new ArrayList<Photo>();
}else{
this.list = list;
}
}
public void updateAdapter(List<Photo> list){
this.list = list;
notifyDataSetChanged();
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View view, ViewGroup parent) {
ViewHolder holder = null;
if(view==null){
holder = new ViewHolder();
view = inflater.inflate(R.layout.item_imageview, null);
holder.iv = (ImageView) view.findViewById(R.id.iv_image);
view.setTag(holder);
}else{
holder = (ViewHolder) view.getTag();
}
Photo photo = list.get(position);
if(photo==null)return view;
while (true) {
context.imageLoader.displayImage(
photo.url,
holder.iv,
DisplayOption.getPicOption(R.drawable.load_image_empty,R.drawable.load_image_empty,R.drawable.load_image_failed,Global.PIC_NOROUNDPIXELS),
new SimpleImageLoadingListener());
return view;
}
}
class ViewHolder{
private ImageView iv;
}
}
|
apache-2.0
|
AdamNachman/continuous_integration_vsdb
|
src/Continuous Integration/Interfaces/ILogger.cs
|
2671
|
// <copyright file="ILogger.cs" company="Adam Nachman">
// Copyright (c) 2009 All Right Reserved Adam Nachman
// 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>
// <author>Adam Nachman</author>
namespace SqlDeployment.Interfaces
{
using System;
/// <summary>
/// A standard interface for a logger class
/// </summary>
public interface ILogger
{
/// <summary>
/// Initializes the logger
/// </summary>
/// <param name="task">The task object with which to iitialize the looger</param>
void Init(object task);
/// <summary>
/// Logs an information message
/// </summary>
/// <param name="message">The message text</param>
void LogInformation(string message);
/// <summary>
/// Logs an information message
/// </summary>
/// <param name="format">The format of the message</param>
/// <param name="args">The arguments</param>
void LogInformation(string format, params object[] args);
/// <summary>
/// Logs a warning message
/// </summary>
/// <param name="message">The message text</param>
void LogWarning(string message);
/// <summary>
/// Logs a warning message
/// </summary>
/// <param name="format">The format of the message</param>
/// <param name="args">The arguments</param>
void LogWarning(string format, params object[] args);
/// <summary>
/// Logs an error
/// </summary>
/// <param name="message">The message text</param>
void LogError(string message);
/// <summary>
/// Logs an error
/// </summary>
/// <param name="format">The format of the message</param>
/// <param name="args">The arguments</param>
void LogError(string format, params object[] args);
/// <summary>
/// Logs an error from an exception
/// </summary>
/// <param name="ex">The exception</param>
/// <returns>False if unsuccessful</returns>
bool LogErrorFromException(Exception ex);
}
}
|
apache-2.0
|
ua-eas/ua-rice-2.1.9
|
sampleapp/src/it/java/edu/samplu/mainmenu/test/AttributeDefinitionLookUpIT.java
|
2091
|
/*
* Copyright 2011 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl1.php
*
* 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 edu.samplu.mainmenu.test;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;
/**
* tests whether the Attribute Definition Look UP is working ok
*
* @author Kuali Rice Team (rice.collab@kuali.org)
*/
public class AttributeDefinitionLookUpIT {
private Selenium selenium;
@Before
public void setUp() throws Exception {
selenium = new DefaultSelenium("localhost", 4444, "*firefox", System.getProperty("remote.public.url"));
selenium.start();
}
@Test
public void testAttributeDefinitionLookUp() throws Exception {
selenium.open(System.getProperty("remote.public.url"));
selenium.type("name=__login_user", "admin");
selenium.click("css=input[type=\"submit\"]");
selenium.waitForPageToLoad("30000");
selenium.click("link=Attribute Definition Lookup");
selenium.waitForPageToLoad("30000");
selenium.selectFrame("iframeportlet");
selenium.click("id=u80");
selenium.waitForPageToLoad("30000");
selenium.click("id=u86");
selenium.waitForPageToLoad("30000");
selenium.selectWindow("null");
selenium.click("xpath=(//input[@name='imageField'])[2]");
selenium.waitForPageToLoad("30000");
}
@After
public void tearDown() throws Exception {
selenium.stop();
}
}
|
apache-2.0
|
citrix-openstack-build/ironic
|
ironic/drivers/modules/fake.py
|
2494
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# -*- encoding: utf-8 -*-
#
# Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# 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.
"""
Fake driver interfaces used in testing.
"""
from ironic.common import exception
from ironic.common import states
from ironic.drivers import base
class FakePower(base.PowerInterface):
"""Example implementation of a simple power interface."""
def validate(self, node):
return True
def get_power_state(self, task, node):
return states.NOSTATE
def set_power_state(self, task, node, power_state):
pass
def reboot(self, task, node):
pass
class FakeDeploy(base.DeployInterface):
"""Example imlementation of a deploy interface that uses a
separate power interface.
"""
def validate(self, node):
return True
def deploy(self, task, node):
pass
def tear_down(self, task, node):
pass
class FakeVendor(base.VendorInterface):
"""Example implementation of a vendor passthru interface."""
def validate(self, node, **kwargs):
method = kwargs.get('method')
if not method:
raise exception.InvalidParameterValue(_(
"Invalid vendor passthru, no 'method' specified."))
if method == 'foo':
bar = kwargs.get('bar')
if not bar:
raise exception.InvalidParameterValue(_(
"Parameter not passed to Ironic."))
else:
raise exception.InvalidParameterValue(_(
"Unsupported method (%s) passed through to vendor extension.")
% method)
return True
def _foo(self, task, node, bar):
return True if bar == 'baz' else False
def vendor_passthru(self, task, node, **kwargs):
method = kwargs.get('method')
if method == 'foo':
bar = kwargs.get('bar')
return self._foo(task, node, bar)
|
apache-2.0
|
jcomtois/CustomExtensions
|
CustomExtensions/Interfaces/IEncrypt.cs
|
1310
|
#region License and Terms
// CustomExtensions - Custom Extension Methods For C#
// Copyright (c) 2011 - 2012 Jonathan Comtois. 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.
#endregion
namespace CustomExtensions.Interfaces
{
/// <summary>
/// Provides AES Decryption function
/// </summary>
public interface IEncrypt : IAESCrypto
{
/// <summary>
/// Encrypts <paramref name="source"/> using provided <paramref name="password"/>
/// </summary>
/// <param name="source">String to Encrypt</param>
/// <param name="password">Password to use for encryption</param>
/// <returns>Encrypted string.</returns>
string EncryptAES(string source, string password);
}
}
|
apache-2.0
|
PowerMogli/Rabbit.Db
|
src/RabbitDB.Contracts/Session/IDbSession.cs
|
2730
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="IDbSession.cs" company="">
//
// </copyright>
// <summary>
// The DbSession interface.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
#region using directives
using System;
using System.Linq.Expressions;
using RabbitDB.Contracts.Entity;
#endregion
namespace RabbitDB.Contracts.Session
{
/// <summary>
/// The DbSession interface.
/// </summary>
internal interface IDbSession : ITransactionalSession,
IDisposable
{
#region Public Methods
/// <summary>
/// The delete.
/// </summary>
/// <param name="entity">
/// The entity.
/// </param>
/// <typeparam name="TEntity">
/// </typeparam>
void Delete<TEntity>(TEntity entity);
/// <summary>
/// The execute command.
/// </summary>
/// <param name="sql">
/// The sql.
/// </param>
/// <param name="args">
/// The args.
/// </param>
void ExecuteCommand(string sql, params object[] args);
/// <summary>
/// The insert.
/// </summary>
/// <param name="data">
/// The data.
/// </param>
/// <typeparam name="T">
/// </typeparam>
void Insert<T>(T data);
/// <summary>
/// The load.
/// </summary>
/// <param name="entity">
/// The entity.
/// </param>
/// <typeparam name="TEntity">
/// </typeparam>
void Load<TEntity>(TEntity entity)
where TEntity : IEntity;
/// <summary>
/// The persist changes.
/// </summary>
/// <param name="entity">
/// The entity.
/// </param>
/// <typeparam name="TEntity">
/// </typeparam>
/// <returns>
/// The <see cref="bool" />.
/// </returns>
bool PersistChanges<TEntity>(TEntity entity)
where TEntity : IEntity;
/// <summary>
/// The update.
/// </summary>
/// <param name="criteria">
/// The criteria.
/// </param>
/// <param name="setArguments">
/// The set arguments.
/// </param>
/// <typeparam name="T">
/// </typeparam>
void Update<T>(Expression<Func<T, bool>> criteria, params object[] setArguments);
#endregion
// void Update<T>(T data);
}
}
|
apache-2.0
|
dmtolpeko/sqlines
|
sqlines-studio-java/src/test/java/com/sqlines/studio/model/tabsdata/ObservableTabsDataTest.java
|
7152
|
/*
* Copyright (c) 2021 SQLines
*
* 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.sqlines.studio.model.tabsdata;
import com.sqlines.studio.model.tabsdata.listener.TabsChangeListener;
import org.junit.Before;
import org.junit.Test;
import java.io.*;
import java.net.URL;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
public class ObservableTabsDataTest {
private ObservableTabsData tabsData;
@Before
public void setUp() {
tabsData = new ObservableTabsData();
}
@Test
public void shouldCount3TabsWhenAdding3Tabs() {
tabsData.openTab(0);
tabsData.openTab(1);
tabsData.openTab(2);
assertThat(tabsData.countTabs(), equalTo(3));
}
@Test
public void shouldCount3TabsWhenDeleting3Tabs() {
tabsData.openTab(0);
tabsData.openTab(1);
tabsData.openTab(2);
tabsData.removeTab(0);
tabsData.removeTab(0);
tabsData.removeTab(0);
assertThat(tabsData.countTabs(), equalTo(0));
}
@Test
public void shouldNotifyWhenAddingTabs() {
AtomicReference<Boolean> notified = new AtomicReference<>(false);
tabsData.addTabsListener((change -> {
if (change.getChangeType() == TabsChangeListener.Change.ChangeType.TAB_ADDED) {
notified.set(true);
}
}));
tabsData.openTab(0);
assertThat(notified.get(), equalTo(true));
}
@Test
public void shouldNotifyWhenDeletingTabs() {
AtomicReference<Boolean> notified = new AtomicReference<>(false);
tabsData.addTabsListener((change -> {
if (change.getChangeType() == TabsChangeListener.Change.ChangeType.TAB_REMOVED) {
notified.set(true);
}
}));
tabsData.openTab(0);
tabsData.removeTab(0);
assertThat(notified.get(), equalTo(true));
}
@Test
public void shouldNotifyWhenSettingCurrTabIndex() {
tabsData.openTab(0);
tabsData.openTab(1);
AtomicReference<Boolean> notified = new AtomicReference<>(false);
tabsData.addTabIndexListener(index -> {
if (index == 0) {
notified.set(true);
}
});
tabsData.setCurrTabIndex(0);
assertThat(notified.get(), equalTo(true));
}
@Test
public void shouldNotifyWhenSettingTabTitle() {
tabsData.openTab(0);
AtomicReference<Boolean> notified = new AtomicReference<>(false);
tabsData.addTabTitleListener((title, index) -> {
if (title.equals("TITLE") && index == 0) {
notified.set(true);
}
});
tabsData.setTabTitle("TITLE", 0);
assertThat(notified.get(), equalTo(true));
}
@Test
public void shouldNotifyWhenSettingSourceText() {
tabsData.openTab(0);
AtomicReference<Boolean> notified = new AtomicReference<>(false);
tabsData.addSourceTextListener((text, index) -> {
if (text.equals("TEXT") && index == 0) {
notified.set(true);
}
});
tabsData.setSourceText("TEXT", 0);
assertThat(notified.get(), equalTo(true));
}
@Test
public void shouldNotifyWhenSettingTargetText() {
tabsData.openTab(0);
AtomicReference<Boolean> notified = new AtomicReference<>(false);
tabsData.addTargetTextListener((text, index) -> {
if (text.equals("TEXT") && index == 0) {
notified.set(true);
}
});
tabsData.setTargetText("TEXT", 0);
assertThat(notified.get(), equalTo(true));
}
@Test
public void shouldNotifyWhenSettingSourceMode() {
tabsData.openTab(0);
AtomicReference<Boolean> notified = new AtomicReference<>(false);
tabsData.addSourceModeListener((mode, index) -> {
if (mode.equals("MODE") && index == 0) {
notified.set(true);
}
});
tabsData.setSourceMode("MODE", 0);
assertThat(notified.get(), equalTo(true));
}
@Test
public void shouldNotifyWhenSettingTargetMode() {
tabsData.openTab(0);
AtomicReference<Boolean> notified = new AtomicReference<>(false);
tabsData.addTargetModeListener((mode, index) -> {
if (mode.equals("MODE") && index == 0) {
notified.set(true);
}
});
tabsData.setTargetMode("MODE", 0);
assertThat(notified.get(), equalTo(true));
}
@Test
public void shouldNotifyWhenSettingSourceFilePath() {
tabsData.openTab(0);
AtomicReference<Boolean> notified = new AtomicReference<>(false);
tabsData.addSourceFilePathListener((path, index) -> {
if (path.equals("PATH") && index == 0) {
notified.set(true);
}
});
tabsData.setSourceFilePath("PATH", 0);
assertThat(notified.get(), equalTo(true));
}
@Test
public void shouldNotifyWhenSettingTargetFilePath() {
tabsData.openTab(0);
AtomicReference<Boolean> notified = new AtomicReference<>(false);
tabsData.addTargetFilePathListener((path, index) -> {
if (path.equals("PATH") && index == 0) {
notified.set(true);
}
});
tabsData.setTargetFilePath("PATH", 0);
assertThat(notified.get(), equalTo(true));
}
@Test
public void shouldWriteToFileWhenSerialized() throws IOException {
tabsData.openTab(0);
tabsData.setCurrTabIndex(0);
tabsData.setTabTitle("TITLE", 0);
tabsData.setSourceMode("SMODE", 0);
tabsData.setTargetMode("TMODE", 0);
tabsData.setSourceText("STEXT", 0);
tabsData.setTargetText("TTEXT", 0);
tabsData.setSourceFilePath("SPATH", 0);
tabsData.setTargetFilePath("TPATH", 0);
URL serialFile = getClass().getResource("/tabsdata.serial");
try (ObjectOutputStream outStream = new ObjectOutputStream(new FileOutputStream(serialFile.getPath()));
ObjectInputStream inStream = new ObjectInputStream(new FileInputStream(serialFile.getPath()))) {
outStream.writeObject(tabsData);
ObservableTabsData data = (ObservableTabsData) inStream.readObject();
assertThat(tabsData.equals(data), equalTo(true));
} catch (FileNotFoundException | SecurityException ignored) {
} catch (ClassNotFoundException e) {
fail(e.getMessage());
}
}
}
|
apache-2.0
|
wlk/xbot
|
src/main/scala/com/wlangiewicz/xbot/util/SimpleSpreadOfferRateEstimator.scala
|
1015
|
package com.wlangiewicz.xbot.util
/**
* This simple offer estimator takes into account threshold, max current BID, min current ASK, it aims to either over or under bid by one unit.
* @param margin
* @param threshold
* @param step
*/
class SimpleSpreadOfferRateEstimator(val margin: Double, val threshold: Double, val step: Long) {
def estimateBidRate(maxCurrentBid: Long, minCurrentAsk: Long): Long = {
val attempt = maxCurrentBid + step
if (attempt * threshold < minCurrentAsk - maxCurrentBid) {
attempt
}
else {
val newBidRate = (minCurrentAsk - (minCurrentAsk * 2 * threshold)).toLong
newBidRate - (newBidRate%step)
}
}
def estimateAskRate(maxCurrentBid: Long, minCurrentAsk: Long): Long = {
val attempt = minCurrentAsk - step
if (attempt * threshold < minCurrentAsk - maxCurrentBid) {
attempt
}
else {
val newAskRate = (maxCurrentBid + (minCurrentAsk * 2 * threshold)).toLong
newAskRate + (step - newAskRate%step)
}
}
}
|
apache-2.0
|
kado-yasuyuki/chatwork4s
|
src/main/scala/com/dys/chatwork4s/log/ChatWorkLazyLogging.scala
|
265
|
package com.dys.chatwork4s.log
import com.typesafe.scalalogging.Logger
import org.slf4j.LoggerFactory
/**
* Created by dys on 2017/02/11.
*/
trait ChatWorkLazyLogging {
protected lazy val logger: Logger = Logger(LoggerFactory.getLogger(getClass.getName))
}
|
apache-2.0
|
orioncode/orionplatform
|
orion_math/orion_math_core/src/main/java/com/orionplatform/math/statistics/regression/lineardiscriminantanalysis/onefeature/LinearDiscriminantAnalysis1FeatureRegressionParameters.java
|
1796
|
package com.orionplatform.math.statistics.regression.lineardiscriminantanalysis.onefeature;
import java.util.List;
import com.orionplatform.core.abstraction.Orion;
import com.orionplatform.math.number.ANumber;
public class LinearDiscriminantAnalysis1FeatureRegressionParameters extends Orion
{
private List<ANumber> averagesOfDataPointsForEachClass;
private ANumber weightedAverageOfDataPointsVariancesForEachClass;
private List<ANumber> probabilityOfEachClass;
public LinearDiscriminantAnalysis1FeatureRegressionParameters(List<ANumber> averagesOfDataPointsForEachClass, ANumber weightedAverageOfDataPointsVariancesForEachClass, List<ANumber> probabilityOfEachClass)
{
this.averagesOfDataPointsForEachClass = averagesOfDataPointsForEachClass;
this.weightedAverageOfDataPointsVariancesForEachClass = weightedAverageOfDataPointsVariancesForEachClass;
this.probabilityOfEachClass = probabilityOfEachClass;
}
public static synchronized LinearDiscriminantAnalysis1FeatureRegressionParameters of(List<ANumber> averagesOfDataPointsForEachClass, ANumber weightedAverageOfDataPointsVariancesForEachClass, List<ANumber> probabilityOfEachClass)
{
return new LinearDiscriminantAnalysis1FeatureRegressionParameters(averagesOfDataPointsForEachClass, weightedAverageOfDataPointsVariancesForEachClass, probabilityOfEachClass);
}
public List<ANumber> getAveragesOfDataPointsForEachClass()
{
return this.averagesOfDataPointsForEachClass;
}
public ANumber getWeightedAverageOfDataPointsVariancesForEachClass()
{
return this.weightedAverageOfDataPointsVariancesForEachClass;
}
public List<ANumber> getProbabilityOfEachClass()
{
return this.probabilityOfEachClass;
}
}
|
apache-2.0
|
google/talkback
|
brailleime/src/phone/java/com/google/android/accessibility/brailleime/translate/EditBufferUeb2.java
|
13590
|
/*
* Copyright 2019 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.
*/
package com.google.android.accessibility.brailleime.translate;
import static com.google.android.accessibility.brailleime.translate.BrailleTranslateUtilsUeb.getTextToSpeak;
import static com.google.common.base.Strings.nullToEmpty;
import android.content.Context;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.inputmethod.CursorAnchorInfo;
import android.view.inputmethod.InputConnection;
import androidx.annotation.VisibleForTesting;
import com.google.android.accessibility.brailleime.BrailleCharacter;
import com.google.android.accessibility.brailleime.BrailleIme.ImeConnection;
import com.google.android.accessibility.brailleime.BrailleWord;
import com.google.android.accessibility.brailleime.R;
import com.google.android.accessibility.brailleime.TalkBackForBrailleImeInternal;
import com.google.android.accessibility.brailleime.Utils;
import com.google.android.accessibility.utils.AccessibilityServiceCompatUtils.Constants;
import com.google.android.accessibility.utils.SpeechCleanupUtils;
import java.util.HashMap;
import java.util.Map;
/**
* Unified English Braille (UEB) Grade 2 EditBuffer.
*
* <p>This class is similar to {@link EditBufferUeb1} but differs in that it only sends the print
* translation of its holdings to the IME Editor once a print word has finished being constructed.
* As a consequence, the real-time reading out of input is handled directly by this class (instead
* of by the framework).
*/
public class EditBufferUeb2 implements EditBuffer {
private static final String TAG = "EditBufferUeb2";
private final Context context;
private final Translator translator;
private final BrailleWord holdings = new BrailleWord();
private final TalkBackForBrailleImeInternal talkBack;
// TODO: Rename these maps and cleanup appendBraille method.
/** Mapping for single braille characters. See: https://en.wikipedia.org/wiki/English_Braille */
private static final Map<String, String> singleBrailleTranslationMap = new HashMap<>();
/** Mapping for braille digraphs. See: https://en.wikipedia.org/wiki/English_Braille */
private static final Map<String, String> digraphBrailleTranslationMap = new HashMap<>();
private static final int DELETE_WORD_MAX = 50;
private int cursorPosition = -1;
public EditBufferUeb2(
Context context, Translator ueb2Translator, TalkBackForBrailleImeInternal talkBack) {
this.context = context;
this.translator = ueb2Translator;
this.talkBack = talkBack;
}
@Override
public String appendBraille(ImeConnection imeConnection, BrailleCharacter brailleCharacter) {
holdings.add(brailleCharacter);
String result = getDigraphBrailleTranslation(brailleCharacter);
if (holdings.size() == 1) {
result = getSingleBrailleTranslation(brailleCharacter);
}
if (result.isEmpty()) {
result = getHoldingsTranslateDifference();
if (result.isEmpty() || isAlphabet(result.charAt(0))) {
result = getDynamicTranslation(brailleCharacter, holdings.size() > 1);
}
}
cursorPosition = getCursorPosition(imeConnection.inputConnection);
boolean emitPerCharacterFeedback =
imeConnection.shouldAnnounceCharacter || !Utils.isTextField(imeConnection.editorInfo);
if (emitPerCharacterFeedback) {
speak(result);
}
return result;
}
/**
* Gets the proper translation for single braille. For example, dot 16 can be "child" or "ch",
* it's better to get "ch" with more use experience.
*/
private String getDynamicTranslation(
BrailleCharacter brailleCharacter, boolean hasOtherHoldings) {
return hasOtherHoldings
? getSingleBrailleTranslation(brailleCharacter)
: getDigraphBrailleTranslation(brailleCharacter);
}
private String getHoldingsTranslateDifference() {
String longerString = translator.translateToPrint(holdings.subword(0, holdings.size()));
String shorterString = translator.translateToPrint(holdings.subword(0, holdings.size() - 1));
if (longerString.startsWith(shorterString)) {
return longerString.substring(shorterString.length());
}
return "";
}
@Override
public void appendSpace(ImeConnection imeConnection) {
clearHoldingsAndSendToEditor(imeConnection);
imeConnection.inputConnection.commitText(" ", 1);
}
@Override
public void appendNewline(ImeConnection imeConnection) {
clearHoldingsAndSendToEditor(imeConnection);
imeConnection.inputConnection.commitText("\n", 1);
}
@Override
public void deleteCharacter(ImeConnection imeConnection) {
if (holdings.isEmpty()) {
imeConnection.inputConnection.sendKeyEvent(
new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL));
imeConnection.inputConnection.sendKeyEvent(
new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL));
return;
}
String holdingsTranslateDifference = getHoldingsTranslateDifference();
BrailleCharacter deletedBrailleCharacter = holdings.remove(holdings.size() - 1);
if (holdings.isEmpty()) {
speakDelete(getSingleBrailleTranslation(deletedBrailleCharacter));
return;
}
String deletedString = getDigraphBrailleTranslation(deletedBrailleCharacter);
if (!deletedString.isEmpty()) {
speakDelete(deletedString);
return;
}
deletedString = holdingsTranslateDifference;
if (deletedString.isEmpty() || isAlphabet(deletedString.charAt(0))) {
deletedString = getDynamicTranslation(deletedBrailleCharacter, !holdings.isEmpty());
}
speakDelete(deletedString);
}
@Override
public void deleteWord(ImeConnection imeConnection) {
// If there is any holdings left, clear it out; otherwise delete at the Editor level.
if (!holdings.isEmpty()) {
String deletedWord = translator.translateToPrint(holdings);
speakDelete(deletedWord);
// speak(context.getString(R.string.read_out_deleted));
holdings.clear();
imeConnection.inputConnection.setComposingText("", 0);
} else {
CharSequence hunkBeforeCursor =
imeConnection.inputConnection.getTextBeforeCursor(DELETE_WORD_MAX, 0);
int charactersToDeleteCount = Utils.getLastWordLengthForDeletion(hunkBeforeCursor);
if (charactersToDeleteCount > 0) {
imeConnection.inputConnection.deleteSurroundingText(charactersToDeleteCount, 0);
}
}
}
@Override
public void commit(ImeConnection imeConnection) {
clearHoldingsAndSendToEditor(imeConnection);
}
@Override
public void onUpdateCursorAnchorInfo(
ImeConnection imeConnection, CursorAnchorInfo cursorAnchorInfo) {
if (!holdings.isEmpty() && cursorPosition >= 0) {
int newPosition = getCursorPosition(imeConnection.inputConnection);
imeConnection.inputConnection.setSelection(cursorPosition, cursorPosition);
commit(imeConnection);
if (newPosition <= cursorPosition) {
// If cursor moved to backward, set cursor position to backward after commit.
imeConnection.inputConnection.setSelection(newPosition, newPosition);
}
cursorPosition = -1;
}
}
@Override
public String toString() {
return holdings.toString();
}
private void clearHoldingsAndSendToEditor(ImeConnection imeConnection) {
if (holdings.isEmpty()) {
return;
}
String currentTranslation = translator.translateToPrint(holdings);
// TODO: remove this condition.
if (Constants.KEEP_NOTES_PACKAGE_NAME.equals(imeConnection.editorInfo.packageName)) {
// Sometimes EditText would lose cursor which causes commitText nowhere to insert text.
// setComposingText will call onUpdateSelection to bring cursor back so we use it here.
imeConnection.inputConnection.setComposingText(currentTranslation, 1);
imeConnection.inputConnection.finishComposingText();
} else {
imeConnection.inputConnection.commitText(currentTranslation, 1);
}
holdings.clear();
}
private static int getCursorPosition(InputConnection inputConnection) {
CharSequence textBeforeCursor =
inputConnection.getTextBeforeCursor(Integer.MAX_VALUE, /* flags= */ 0);
if (TextUtils.isEmpty(textBeforeCursor)) {
return 0;
}
return textBeforeCursor.length();
}
private void speak(String text) {
String speakText = SpeechCleanupUtils.cleanUp(context, text).toString();
talkBack.speakInterrupt(speakText);
}
private void speakDelete(String text) {
String speakText = SpeechCleanupUtils.cleanUp(context, text).toString();
talkBack.speakInterrupt(context.getString(R.string.read_out_deleted, speakText));
}
private static boolean isAlphabet(char character) {
return ('a' <= character && character <= 'z') || ('A' <= character && character <= 'Z');
}
private String getSingleBrailleTranslation(BrailleCharacter brailleCharacter) {
String translation = getTextToSpeak(context.getResources(), brailleCharacter);
if (TextUtils.isEmpty(translation)) {
translation = nullToEmpty(singleBrailleTranslationMap.get(brailleCharacter.toString()));
if (TextUtils.isEmpty(translation)) {
translation = BrailleTranslateUtils.getDotsText(context.getResources(), brailleCharacter);
}
}
return translation;
}
private String getDigraphBrailleTranslation(BrailleCharacter brailleCharacter) {
String translation = getTextToSpeak(context.getResources(), brailleCharacter);
if (TextUtils.isEmpty(translation)) {
translation = nullToEmpty(digraphBrailleTranslationMap.get(brailleCharacter.toString()));
}
return translation;
}
static {
singleBrailleTranslationMap.put("1", "a");
singleBrailleTranslationMap.put("2", ",");
singleBrailleTranslationMap.put("12", "b");
singleBrailleTranslationMap.put("3", "'");
singleBrailleTranslationMap.put("13", "k");
singleBrailleTranslationMap.put("23", "be");
singleBrailleTranslationMap.put("123", "l");
singleBrailleTranslationMap.put("14", "c");
singleBrailleTranslationMap.put("24", "i");
singleBrailleTranslationMap.put("124", "f");
singleBrailleTranslationMap.put("34", "st");
singleBrailleTranslationMap.put("134", "m");
singleBrailleTranslationMap.put("234", "s");
singleBrailleTranslationMap.put("1234", "p");
singleBrailleTranslationMap.put("15", "e");
singleBrailleTranslationMap.put("25", "con");
singleBrailleTranslationMap.put("125", "h");
singleBrailleTranslationMap.put("35", "in");
singleBrailleTranslationMap.put("135", "o");
singleBrailleTranslationMap.put("235", "!");
singleBrailleTranslationMap.put("1235", "r");
singleBrailleTranslationMap.put("45", "^");
singleBrailleTranslationMap.put("145", "d");
singleBrailleTranslationMap.put("245", "j");
singleBrailleTranslationMap.put("1245", "g");
singleBrailleTranslationMap.put("345", "ar");
singleBrailleTranslationMap.put("1345", "n");
singleBrailleTranslationMap.put("2345", "t");
singleBrailleTranslationMap.put("12345", "q");
singleBrailleTranslationMap.put("16", "ch");
singleBrailleTranslationMap.put("26", "en");
singleBrailleTranslationMap.put("126", "gh");
singleBrailleTranslationMap.put("36", "-");
singleBrailleTranslationMap.put("136", "u");
singleBrailleTranslationMap.put("236", "\"");
singleBrailleTranslationMap.put("1236", "v");
singleBrailleTranslationMap.put("146", "sh");
singleBrailleTranslationMap.put("246", "ow");
singleBrailleTranslationMap.put("1246", "ed");
singleBrailleTranslationMap.put("346", "ing");
singleBrailleTranslationMap.put("1346", "x");
singleBrailleTranslationMap.put("2346", "the");
singleBrailleTranslationMap.put("12346", "and");
singleBrailleTranslationMap.put("156", "wh");
singleBrailleTranslationMap.put("256", "dis");
singleBrailleTranslationMap.put("1256", "ou");
singleBrailleTranslationMap.put("356", "\"");
singleBrailleTranslationMap.put("1356", "z");
singleBrailleTranslationMap.put("2356", "'");
singleBrailleTranslationMap.put("12356", "of");
singleBrailleTranslationMap.put("1456", "th");
singleBrailleTranslationMap.put("2456", "w");
singleBrailleTranslationMap.put("12456", "er");
singleBrailleTranslationMap.put("13456", "y");
singleBrailleTranslationMap.put("23456", "with");
singleBrailleTranslationMap.put("123456", "for");
digraphBrailleTranslationMap.put("2", "ea");
digraphBrailleTranslationMap.put("23", "bb");
digraphBrailleTranslationMap.put("25", "cc");
digraphBrailleTranslationMap.put("235", "ff");
digraphBrailleTranslationMap.put("2356", "gg");
digraphBrailleTranslationMap.put("256", ".");
digraphBrailleTranslationMap.put("346", "ing");
}
/**
* For testing, returns true if the holdings matches the given list of {@link BrailleCharacter}.
*/
@VisibleForTesting
boolean testing_holdingsMatches(BrailleWord expectedHoldings) {
return holdings.equals(expectedHoldings);
}
}
|
apache-2.0
|
fieldnation/fieldnation-sdk-php
|
src/FieldNation/CustomFieldInterface.php
|
431
|
<?php
/**
* @author Field Nation <support@fieldnation.com>
* @license Apache 2.0
* @copyright 2017 Field Nation
*/
namespace FieldNation;
interface CustomFieldInterface extends IdentifiableInterface
{
/**
* Set the name
*
* @param string $name
* @return self
*/
public function setName($name);
/**
* Get the name
*
* @return string
*/
public function getName();
}
|
apache-2.0
|
zhiyicx/thinksns-plus
|
packages/slimkit-plus-news/database/seeds/DatabaseSeeder.php
|
1413
|
<?php
declare(strict_types=1);
/*
* +----------------------------------------------------------------------+
* | ThinkSNS Plus |
* +----------------------------------------------------------------------+
* | Copyright (c) 2016-Present ZhiYiChuangXiang Technology Co., Ltd. |
* +----------------------------------------------------------------------+
* | This source file is subject to enterprise private license, that is |
* | bundled with this package in the file LICENSE, and is available |
* | through the world-wide-web at the following url: |
* | https://github.com/slimkit/plus/blob/master/LICENSE |
* +----------------------------------------------------------------------+
* | Author: Slim Kit Group <master@zhiyicx.com> |
* | Homepage: www.thinksns.com |
* +----------------------------------------------------------------------+
*/
namespace SlimKit\Plus\Packages\News\Seeds;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Run the package seeder.
*
* @return void
* @author Seven Du <shiweidu@outlook.com>
*/
public function run()
{
$this->call(AdvertisingSpaceTableSeeder::class);
$this->call(NewsCatesTableSeeder::class);
}
}
|
apache-2.0
|
java110/MicroCommunity
|
java110-generator/src/main/java/com/java110/code/newBack/Data.java
|
4240
|
package com.java110.code.newBack;
import java.util.Map;
/**
* @ClassName Data
* @Description TODO
* @Author wuxw
* @Date 2020/3/22 17:00
* @Version 1.0
* add by wuxw 2020/3/22
**/
public class Data {
private boolean autoMove;
private String packagePath;
private String id;
private String name;
private String desc;
private String newBusinessTypeCd;
private String updateBusinessTypeCd;
private String deleteBusinessTypeCd;
private String newBusinessTypeCdValue;
private String updateBusinessTypeCdValue;
private String deleteBusinessTypeCdValue;
private String businessTableName;
private String tableName;
//分片数据库字段 如community_id
private String shareColumn;
//分片传入参数 如communityId
private String shareParam;
//分片传入参数 如community
private String shareName;
public String getShareName() { return shareName; }
public void setShareName(String shareName) { this.shareName = shareName; }
private Map params;
private String[] requiredParam;
public String getPackagePath() {
return packagePath;
}
public void setPackagePath(String packagePath) {
this.packagePath = packagePath;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map getParams() {
return params;
}
public void setParams(Map params) {
this.params = params;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getBusinessTableName() {
return businessTableName;
}
public void setBusinessTableName(String businessTableName) {
this.businessTableName = businessTableName;
}
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public String getNewBusinessTypeCd() {
return newBusinessTypeCd;
}
public void setNewBusinessTypeCd(String newBusinessTypeCd) {
this.newBusinessTypeCd = newBusinessTypeCd;
}
public String getUpdateBusinessTypeCd() {
return updateBusinessTypeCd;
}
public void setUpdateBusinessTypeCd(String updateBusinessTypeCd) {
this.updateBusinessTypeCd = updateBusinessTypeCd;
}
public String getDeleteBusinessTypeCd() {
return deleteBusinessTypeCd;
}
public void setDeleteBusinessTypeCd(String deleteBusinessTypeCd) {
this.deleteBusinessTypeCd = deleteBusinessTypeCd;
}
public String getNewBusinessTypeCdValue() {
return newBusinessTypeCdValue;
}
public void setNewBusinessTypeCdValue(String newBusinessTypeCdValue) {
this.newBusinessTypeCdValue = newBusinessTypeCdValue;
}
public String getUpdateBusinessTypeCdValue() {
return updateBusinessTypeCdValue;
}
public void setUpdateBusinessTypeCdValue(String updateBusinessTypeCdValue) {
this.updateBusinessTypeCdValue = updateBusinessTypeCdValue;
}
public String getDeleteBusinessTypeCdValue() {
return deleteBusinessTypeCdValue;
}
public void setDeleteBusinessTypeCdValue(String deleteBusinessTypeCdValue) {
this.deleteBusinessTypeCdValue = deleteBusinessTypeCdValue;
}
public String getShareColumn() {
return shareColumn;
}
public void setShareColumn(String shareColumn) {
this.shareColumn = shareColumn;
}
public String getShareParam() {
return shareParam;
}
public void setShareParam(String shareParam) {
this.shareParam = shareParam;
}
public String[] getRequiredParam() {
return requiredParam;
}
public void setRequiredParam(String[] requiredParam) {
this.requiredParam = requiredParam;
}
public boolean isAutoMove() {
return autoMove;
}
public void setAutoMove(boolean autoMove) {
this.autoMove = autoMove;
}
}
|
apache-2.0
|
glorycloud/GloryMail
|
CloudyMail/lib_src/net/fortuna/ical4j/model/ParameterList.java
|
7618
|
/**
* Copyright (c) 2012, Ben Fortuna
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* o Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* o Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* o Neither the name of Ben Fortuna nor the names of any other contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.fortuna.ical4j.model;
import java.io.Serializable;
import java.net.URISyntaxException;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.builder.HashCodeBuilder;
/**
* $Id$ [Apr 5, 2004]
*
* Defines a list of iCalendar parameters. A parameter list may be specified as unmodifiable at instantiation - useful
* for constant properties that you don't want modified.
* @author Ben Fortuna
*/
public class ParameterList implements Serializable {
private static final long serialVersionUID = -1913059830016450169L;
private final List<Parameter> parameters;
/**
* Default constructor. Creates a modifiable parameter list.
*/
public ParameterList() {
this(false);
}
/**
* Constructor.
* @param unmodifiable indicates whether the list should be mutable
*/
public ParameterList(final boolean unmodifiable) {
if (unmodifiable) {
parameters = Collections.emptyList();
}
else {
parameters = new CopyOnWriteArrayList<Parameter>();
}
}
/**
* Creates a deep copy of the specified parameter list. That is, copies of all parameters in the specified list are
* added to this list.
* @param list a parameter list to copy parameters from
* @param unmodifiable indicates whether the list should be mutable
* @throws URISyntaxException where a parameter in the list specifies an invalid URI value
*/
public ParameterList(final ParameterList list, final boolean unmodifiable)
throws URISyntaxException {
final List<Parameter> parameterList = new CopyOnWriteArrayList<Parameter>();
for (final Iterator<Parameter> i = list.iterator(); i.hasNext();) {
final Parameter parameter = (Parameter) i.next();
parameterList.add(parameter.copy());
}
if (unmodifiable) {
parameters = Collections.unmodifiableList(parameterList);
}
else {
parameters = parameterList;
}
}
/**
* {@inheritDoc}
*/
public final String toString() {
final StringBuffer buffer = new StringBuffer();
for (final Parameter parameter : parameters) {
buffer.append(';');
buffer.append(parameter.toString());
}
return buffer.toString();
}
/**
* Returns the first parameter with the specified name.
* @param aName name of the parameter
* @return the first matching parameter or null if no matching parameters
*/
public final Parameter getParameter(final String aName) {
for (final Parameter p : parameters) {
if (aName.equalsIgnoreCase(p.getName())) {
return p;
}
}
return null;
}
/**
* Returns a list of parameters with the specified name.
* @param name name of parameters to return
* @return a parameter list
*/
public final ParameterList getParameters(final String name) {
final ParameterList list = new ParameterList();
for (final Parameter p : parameters) {
if (p.getName().equalsIgnoreCase(name)) {
list.add(p);
}
}
return list;
}
/**
* Add a parameter to the list. Note that this method will not remove existing parameters of the same type. To
* achieve this use {
* @link ParameterList#replace(Parameter) }
* @param parameter the parameter to add
* @return true
* @see List#add(java.lang.Object)
*/
public final boolean add(final Parameter parameter) {
if (parameter == null) {
throw new IllegalArgumentException("Trying to add null Parameter");
}
return parameters.add(parameter);
}
/**
* Replace any parameters of the same type with the one specified.
* @param parameter parameter to add to this list in place of all others with the same name
* @return true if successfully added to this list
*/
public final boolean replace(final Parameter parameter) {
for (final Iterator<Parameter> i = getParameters(parameter.getName()).iterator(); i.hasNext();) {
remove((Parameter) i.next());
}
return add(parameter);
}
/**
* @return boolean indicates if the list is empty
* @see List#isEmpty()
*/
public final boolean isEmpty() {
return parameters.isEmpty();
}
/**
* @return an iterator
* @see List#iterator()
*/
public final Iterator<Parameter> iterator() {
return parameters.iterator();
}
/**
* Remove a parameter from the list.
* @param parameter the parameter to remove
* @return true if the list contained the specified parameter
* @see List#remove(java.lang.Object)
*/
public final boolean remove(final Parameter parameter) {
return parameters.remove(parameter);
}
/**
* Remove all parameters with the specified name.
* @param paramName the name of parameters to remove
*/
public final void removeAll(final String paramName) {
final ParameterList params = getParameters(paramName);
parameters.removeAll(params.parameters);
}
/**
* @return the number of parameters in the list
* @see List#size()
*/
public final int size() {
return parameters.size();
}
/**
* {@inheritDoc}
*/
public final boolean equals(final Object arg0) {
if (arg0 instanceof ParameterList) {
final ParameterList p = (ParameterList) arg0;
return ObjectUtils.equals(parameters, p.parameters);
}
return super.equals(arg0);
}
/**
* {@inheritDoc}
*/
public final int hashCode() {
return new HashCodeBuilder().append(parameters).toHashCode();
}
}
|
apache-2.0
|
bnewcomer/code-samples
|
Apartment_Management_System/res/js/logout.js
|
198
|
function logout(underReview){
$.get('../res/php/login.php',{action:'logout'},function(data){
var loc = (underReview) ? 'login.php?under-review' : 'login.php';
location.href = loc;
});
}
|
apache-2.0
|
coding0011/elasticsearch
|
x-pack/qa/third-party/active-directory/src/test/java/org/elasticsearch/xpack/security/authc/ldap/AbstractActiveDirectoryTestCase.java
|
8828
|
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.security.authc.ldap;
import com.unboundid.ldap.sdk.LDAPConnection;
import com.unboundid.ldap.sdk.LDAPConnectionPool;
import com.unboundid.ldap.sdk.LDAPException;
import com.unboundid.ldap.sdk.LDAPInterface;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.common.Booleans;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.env.TestEnvironment;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.xpack.core.security.authc.RealmConfig;
import org.elasticsearch.xpack.core.security.authc.ldap.ActiveDirectorySessionFactorySettings;
import org.elasticsearch.xpack.core.security.authc.ldap.support.LdapSearchScope;
import org.elasticsearch.xpack.core.security.authc.ldap.support.SessionFactorySettings;
import org.elasticsearch.xpack.core.ssl.SSLConfigurationSettings;
import org.elasticsearch.xpack.core.ssl.SSLService;
import org.elasticsearch.xpack.core.ssl.VerificationMode;
import org.junit.Before;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.List;
import static org.elasticsearch.xpack.core.security.authc.RealmSettings.getFullSettingKey;
public abstract class AbstractActiveDirectoryTestCase extends ESTestCase {
// follow referrals defaults to false here which differs from the default value of the setting
// this is needed to prevent test logs being filled by errors as the default configuration of
// the tests run against a vagrant samba4 instance configured as a domain controller with the
// ports mapped into the ephemeral port range and there is the possibility of incorrect results
// as we cannot control the URL of the referral which may contain a non-resolvable DNS name as
// this name would be served by the samba4 instance
public static final Boolean FOLLOW_REFERRALS = Booleans.parseBoolean(getFromEnv("TESTS_AD_FOLLOW_REFERRALS", "false"));
public static final String AD_LDAP_URL = getFromEnv("TESTS_AD_LDAP_URL", "ldaps://localhost:" + getFromProperty("636"));
public static final String AD_LDAP_GC_URL = getFromEnv("TESTS_AD_LDAP_GC_URL", "ldaps://localhost:" + getFromProperty("3269"));
public static final String PASSWORD = getFromEnv("TESTS_AD_USER_PASSWORD", "Passw0rd");
public static final String AD_LDAP_PORT = getFromEnv("TESTS_AD_LDAP_PORT", getFromProperty("389"));
public static final String AD_LDAPS_PORT = getFromEnv("TESTS_AD_LDAPS_PORT", getFromProperty("636"));
public static final String AD_GC_LDAP_PORT = getFromEnv("TESTS_AD_GC_LDAP_PORT", getFromProperty("3268"));
public static final String AD_GC_LDAPS_PORT = getFromEnv("TESTS_AD_GC_LDAPS_PORT", getFromProperty("3269"));
public static final String AD_DOMAIN = "ad.test.elasticsearch.com";
protected SSLService sslService;
protected Settings globalSettings;
protected List<String> certificatePaths;
@Before
public void initializeSslSocketFactory() throws Exception {
// We use certificates in PEM format and `ssl.certificate_authorities` instead of ssl.trustore
// so that these tests can also run in a FIPS JVM where JKS keystores can't be used.
certificatePaths = new ArrayList<>();
Files.walkFileTree(getDataPath
("../ldap/support"), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
String fileName = file.getFileName().toString();
if (fileName.endsWith(".crt")) {
certificatePaths.add(getDataPath("../ldap/support/" + fileName).toString());
}
return FileVisitResult.CONTINUE;
}
});
/*
* Prior to each test we reinitialize the socket factory with a new SSLService so that we get a new SSLContext.
* If we re-use an SSLContext, previously connected sessions can get re-established which breaks hostname
* verification tests since a re-established connection does not perform hostname verification.
*/
Settings.Builder builder = Settings.builder().put("path.home", createTempDir());
// fake realms so ssl will get loaded
builder.putList("xpack.security.authc.realms.active_directory.foo.ssl.certificate_authorities", certificatePaths);
builder.put("xpack.security.authc.realms.active_directory.foo.ssl.verification_mode", VerificationMode.FULL);
builder.putList("xpack.security.authc.realms.active_directory.bar.ssl.certificate_authorities", certificatePaths);
builder.put("xpack.security.authc.realms.active_directory.bar.ssl.verification_mode", VerificationMode.CERTIFICATE);
globalSettings = builder.build();
Environment environment = TestEnvironment.newEnvironment(globalSettings);
sslService = new SSLService(globalSettings, environment);
}
Settings buildAdSettings(RealmConfig.RealmIdentifier realmId, String ldapUrl, String adDomainName, String userSearchDN,
LdapSearchScope scope, boolean hostnameVerification) {
final String realmName = realmId.getName();
Settings.Builder builder = Settings.builder()
.putList(getFullSettingKey(realmId, SessionFactorySettings.URLS_SETTING), ldapUrl)
.put(getFullSettingKey(realmName, ActiveDirectorySessionFactorySettings.AD_DOMAIN_NAME_SETTING), adDomainName)
.put(getFullSettingKey(realmName, ActiveDirectorySessionFactorySettings.AD_USER_SEARCH_BASEDN_SETTING), userSearchDN)
.put(getFullSettingKey(realmName, ActiveDirectorySessionFactorySettings.AD_USER_SEARCH_SCOPE_SETTING), scope)
.put(getFullSettingKey(realmName, ActiveDirectorySessionFactorySettings.AD_LDAP_PORT_SETTING), AD_LDAP_PORT)
.put(getFullSettingKey(realmName, ActiveDirectorySessionFactorySettings.AD_LDAPS_PORT_SETTING), AD_LDAPS_PORT)
.put(getFullSettingKey(realmName, ActiveDirectorySessionFactorySettings.AD_GC_LDAP_PORT_SETTING), AD_GC_LDAP_PORT)
.put(getFullSettingKey(realmName, ActiveDirectorySessionFactorySettings.AD_GC_LDAPS_PORT_SETTING), AD_GC_LDAPS_PORT)
.put(getFullSettingKey(realmId, SessionFactorySettings.FOLLOW_REFERRALS_SETTING), FOLLOW_REFERRALS)
.putList(getFullSettingKey(realmId, SSLConfigurationSettings.CAPATH_SETTING_REALM), certificatePaths);
if (randomBoolean()) {
builder.put(getFullSettingKey(realmId, SSLConfigurationSettings.VERIFICATION_MODE_SETTING_REALM),
hostnameVerification ? VerificationMode.FULL : VerificationMode.CERTIFICATE);
} else {
builder.put(getFullSettingKey(realmId, SessionFactorySettings.HOSTNAME_VERIFICATION_SETTING), hostnameVerification);
}
return builder.build();
}
protected static void assertConnectionCanReconnect(LDAPInterface conn) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@Override
public Void run() {
try {
if (conn instanceof LDAPConnection) {
((LDAPConnection) conn).reconnect();
} else if (conn instanceof LDAPConnectionPool) {
try (LDAPConnection c = ((LDAPConnectionPool) conn).getConnection()) {
c.reconnect();
}
}
} catch (LDAPException e) {
fail("Connection is not valid. It will not work on follow referral flow." +
System.lineSeparator() + ExceptionsHelper.stackTrace(e));
}
return null;
}
});
}
private static String getFromEnv(String envVar, String defaultValue) {
final String value = System.getenv(envVar);
return value == null ? defaultValue : value;
}
private static String getFromProperty(String port) {
String key = "test.fixtures.smb-fixture.tcp." + port;
final String value = System.getProperty(key);
assertNotNull("Expected the actual value for port " + port + " to be in system property " + key, value);
return value;
}
}
|
apache-2.0
|
hexa00/theia
|
packages/core/src/browser/quick-open/quick-open-model.ts
|
1678
|
/*
* Copyright (C) 2017 TypeFox 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
*/
import URI from "../../common/uri";
import { Keybinding } from '../../common/keybinding';
export interface Highlight {
start: number
end: number
}
export enum QuickOpenMode {
PREVIEW,
OPEN,
OPEN_IN_BACKGROUND
}
export class QuickOpenItem {
getTooltip(): string | undefined {
return this.getLabel();
}
getLabel(): string | undefined {
return undefined;
}
getLabelHighlights(): Highlight[] {
return [];
}
getDescription(): string | undefined {
return undefined;
}
getDescriptionHighlights(): Highlight[] | undefined {
return undefined;
}
getDetail(): string | undefined {
return undefined;
}
getDetailHighlights(): Highlight[] | undefined {
return undefined;
}
isHidden(): boolean {
return false;
}
getUri(): URI | undefined {
return undefined;
}
getIconClass(): string | undefined {
return undefined;
}
getKeybinding(): Keybinding | undefined {
return undefined;
}
run(mode: QuickOpenMode): boolean {
return false;
}
}
export class QuickOpenGroupItem extends QuickOpenItem {
getGroupLabel(): string | undefined {
return undefined;
}
showBorder(): boolean {
return false;
}
}
export interface QuickOpenModel {
getItems(lookFor: string): QuickOpenItem[];
}
|
apache-2.0
|
SpoonLabs/gumtree-spoon-ast-diff
|
src/test/resources/examples/diffOfGenericTypeReferences/multipleNesting/right.java
|
153
|
import java.util.List;
class MultipleNesting<A, B> extends SuperClass<List<B>> {
// 4 levels nested list
List<List<List<List<String>>>> list;
}
|
apache-2.0
|
arthurdarcet/aiohttp
|
aiohttp/helpers.py
|
22478
|
"""Various helper functions"""
import asyncio
import base64
import binascii
import cgi
import functools
import inspect
import netrc
import os
import platform
import re
import sys
import time
import warnings
import weakref
from collections import namedtuple
from contextlib import suppress
from math import ceil
from pathlib import Path
from types import TracebackType
from typing import ( # noqa
Any,
Callable,
Dict,
Iterable,
Iterator,
List,
Mapping,
Optional,
Pattern,
Set,
Tuple,
Type,
TypeVar,
Union,
cast,
)
from urllib.parse import quote
from urllib.request import getproxies
import async_timeout
import attr
from multidict import MultiDict, MultiDictProxy
from yarl import URL
from . import hdrs
from .log import client_logger, internal_logger
from .typedefs import PathLike # noqa
__all__ = ('BasicAuth', 'ChainMapProxy')
PY_36 = sys.version_info >= (3, 6)
PY_37 = sys.version_info >= (3, 7)
if not PY_37:
import idna_ssl
idna_ssl.patch_match_hostname()
try:
from typing import ContextManager
except ImportError:
from typing_extensions import ContextManager
all_tasks = asyncio.Task.all_tasks
if PY_37:
all_tasks = getattr(asyncio, 'all_tasks') # use the trick to cheat mypy
_T = TypeVar('_T')
sentinel = object() # type: Any
NO_EXTENSIONS = bool(os.environ.get('AIOHTTP_NO_EXTENSIONS')) # type: bool
# N.B. sys.flags.dev_mode is available on Python 3.7+, use getattr
# for compatibility with older versions
DEBUG = (getattr(sys.flags, 'dev_mode', False) or
(not sys.flags.ignore_environment and
bool(os.environ.get('PYTHONASYNCIODEBUG')))) # type: bool
CHAR = set(chr(i) for i in range(0, 128))
CTL = set(chr(i) for i in range(0, 32)) | {chr(127), }
SEPARATORS = {'(', ')', '<', '>', '@', ',', ';', ':', '\\', '"', '/', '[', ']',
'?', '=', '{', '}', ' ', chr(9)}
TOKEN = CHAR ^ CTL ^ SEPARATORS
coroutines = asyncio.coroutines
old_debug = coroutines._DEBUG # type: ignore
# prevent "coroutine noop was never awaited" warning.
coroutines._DEBUG = False # type: ignore
@asyncio.coroutine
def noop(*args, **kwargs): # type: ignore
return # type: ignore
async def noop2(*args: Any, **kwargs: Any) -> None:
return
coroutines._DEBUG = old_debug # type: ignore
class BasicAuth(namedtuple('BasicAuth', ['login', 'password', 'encoding'])):
"""Http basic authentication helper."""
def __new__(cls, login: str,
password: str='',
encoding: str='latin1') -> 'BasicAuth':
if login is None:
raise ValueError('None is not allowed as login value')
if password is None:
raise ValueError('None is not allowed as password value')
if ':' in login:
raise ValueError(
'A ":" is not allowed in login (RFC 1945#section-11.1)')
return super().__new__(cls, login, password, encoding)
@classmethod
def decode(cls, auth_header: str, encoding: str='latin1') -> 'BasicAuth':
"""Create a BasicAuth object from an Authorization HTTP header."""
try:
auth_type, encoded_credentials = auth_header.split(' ', 1)
except ValueError:
raise ValueError('Could not parse authorization header.')
if auth_type.lower() != 'basic':
raise ValueError('Unknown authorization method %s' % auth_type)
try:
decoded = base64.b64decode(
encoded_credentials.encode('ascii'), validate=True
).decode(encoding)
except binascii.Error:
raise ValueError('Invalid base64 encoding.')
try:
# RFC 2617 HTTP Authentication
# https://www.ietf.org/rfc/rfc2617.txt
# the colon must be present, but the username and password may be
# otherwise blank.
username, password = decoded.split(':', 1)
except ValueError:
raise ValueError('Invalid credentials.')
return cls(username, password, encoding=encoding)
@classmethod
def from_url(cls, url: URL,
*, encoding: str='latin1') -> Optional['BasicAuth']:
"""Create BasicAuth from url."""
if not isinstance(url, URL):
raise TypeError("url should be yarl.URL instance")
if url.user is None:
return None
return cls(url.user, url.password or '', encoding=encoding)
def encode(self) -> str:
"""Encode credentials."""
creds = ('%s:%s' % (self.login, self.password)).encode(self.encoding)
return 'Basic %s' % base64.b64encode(creds).decode(self.encoding)
def strip_auth_from_url(url: URL) -> Tuple[URL, Optional[BasicAuth]]:
auth = BasicAuth.from_url(url)
if auth is None:
return url, None
else:
return url.with_user(None), auth
def netrc_from_env() -> Optional[netrc.netrc]:
"""Attempt to load the netrc file from the path specified by the env-var
NETRC or in the default location in the user's home directory.
Returns None if it couldn't be found or fails to parse.
"""
netrc_env = os.environ.get('NETRC')
if netrc_env is not None:
netrc_path = Path(netrc_env)
else:
try:
home_dir = Path.home()
except RuntimeError as e: # pragma: no cover
# if pathlib can't resolve home, it may raise a RuntimeError
client_logger.debug('Could not resolve home directory when '
'trying to look for .netrc file: %s', e)
return None
netrc_path = home_dir / (
'_netrc' if platform.system() == 'Windows' else '.netrc')
try:
return netrc.netrc(str(netrc_path))
except netrc.NetrcParseError as e:
client_logger.warning('Could not parse .netrc file: %s', e)
except OSError as e:
# we couldn't read the file (doesn't exist, permissions, etc.)
if netrc_env or netrc_path.is_file():
# only warn if the environment wanted us to load it,
# or it appears like the default file does actually exist
client_logger.warning('Could not read .netrc file: %s', e)
return None
@attr.s(frozen=True, slots=True)
class ProxyInfo:
proxy = attr.ib(type=URL)
proxy_auth = attr.ib(type=Optional[BasicAuth])
def proxies_from_env() -> Dict[str, ProxyInfo]:
proxy_urls = {k: URL(v) for k, v in getproxies().items()
if k in ('http', 'https')}
netrc_obj = netrc_from_env()
stripped = {k: strip_auth_from_url(v) for k, v in proxy_urls.items()}
ret = {}
for proto, val in stripped.items():
proxy, auth = val
if proxy.scheme == 'https':
client_logger.warning(
"HTTPS proxies %s are not supported, ignoring", proxy)
continue
if netrc_obj and auth is None:
auth_from_netrc = None
if proxy.host is not None:
auth_from_netrc = netrc_obj.authenticators(proxy.host)
if auth_from_netrc is not None:
# auth_from_netrc is a (`user`, `account`, `password`) tuple,
# `user` and `account` both can be username,
# if `user` is None, use `account`
*logins, password = auth_from_netrc
login = logins[0] if logins[0] else logins[-1]
auth = BasicAuth(cast(str, login), cast(str, password))
ret[proto] = ProxyInfo(proxy, auth)
return ret
def current_task(loop: Optional[asyncio.AbstractEventLoop]=None) -> asyncio.Task: # type: ignore # noqa # Return type is intentionally Generic here
if PY_37:
return asyncio.current_task(loop=loop) # type: ignore
else:
return asyncio.Task.current_task(loop=loop) # type: ignore
def get_running_loop(
loop: Optional[asyncio.AbstractEventLoop]=None
) -> asyncio.AbstractEventLoop:
if loop is None:
loop = asyncio.get_event_loop()
if not loop.is_running():
warnings.warn("The object should be created from async function",
DeprecationWarning, stacklevel=3)
if loop.get_debug():
internal_logger.warning(
"The object should be created from async function",
stack_info=True)
return loop
def isasyncgenfunction(obj: Any) -> bool:
func = getattr(inspect, 'isasyncgenfunction', None)
if func is not None:
return func(obj)
else:
return False
@attr.s(frozen=True, slots=True)
class MimeType:
type = attr.ib(type=str)
subtype = attr.ib(type=str)
suffix = attr.ib(type=str)
parameters = attr.ib(type=MultiDictProxy) # type: MultiDictProxy[str]
@functools.lru_cache(maxsize=56)
def parse_mimetype(mimetype: str) -> MimeType:
"""Parses a MIME type into its components.
mimetype is a MIME type string.
Returns a MimeType object.
Example:
>>> parse_mimetype('text/html; charset=utf-8')
MimeType(type='text', subtype='html', suffix='',
parameters={'charset': 'utf-8'})
"""
if not mimetype:
return MimeType(type='', subtype='', suffix='',
parameters=MultiDictProxy(MultiDict()))
parts = mimetype.split(';')
params = MultiDict() # type: MultiDict[str]
for item in parts[1:]:
if not item:
continue
key, value = cast(Tuple[str, str],
item.split('=', 1) if '=' in item else (item, ''))
params.add(key.lower().strip(), value.strip(' "'))
fulltype = parts[0].strip().lower()
if fulltype == '*':
fulltype = '*/*'
mtype, stype = (cast(Tuple[str, str], fulltype.split('/', 1))
if '/' in fulltype else (fulltype, ''))
stype, suffix = (cast(Tuple[str, str], stype.split('+', 1))
if '+' in stype else (stype, ''))
return MimeType(type=mtype, subtype=stype, suffix=suffix,
parameters=MultiDictProxy(params))
def guess_filename(obj: Any, default: Optional[str]=None) -> Optional[str]:
name = getattr(obj, 'name', None)
if name and isinstance(name, str) and name[0] != '<' and name[-1] != '>':
return Path(name).name
return default
def content_disposition_header(disptype: str,
quote_fields: bool=True,
**params: str) -> str:
"""Sets ``Content-Disposition`` header.
disptype is a disposition type: inline, attachment, form-data.
Should be valid extension token (see RFC 2183)
params is a dict with disposition params.
"""
if not disptype or not (TOKEN > set(disptype)):
raise ValueError('bad content disposition type {!r}'
''.format(disptype))
value = disptype
if params:
lparams = []
for key, val in params.items():
if not key or not (TOKEN > set(key)):
raise ValueError('bad content disposition parameter'
' {!r}={!r}'.format(key, val))
qval = quote(val, '') if quote_fields else val
lparams.append((key, '"%s"' % qval))
if key == 'filename':
lparams.append(('filename*', "utf-8''" + qval))
sparams = '; '.join('='.join(pair) for pair in lparams)
value = '; '.join((value, sparams))
return value
class reify:
"""Use as a class method decorator. It operates almost exactly like
the Python `@property` decorator, but it puts the result of the
method it decorates into the instance dict after the first call,
effectively replacing the function it decorates with an instance
variable. It is, in Python parlance, a data descriptor.
"""
def __init__(self, wrapped: Callable[..., Any]) -> None:
self.wrapped = wrapped
self.__doc__ = wrapped.__doc__
self.name = wrapped.__name__
def __get__(self, inst: Any, owner: Any) -> Any:
try:
try:
return inst._cache[self.name]
except KeyError:
val = self.wrapped(inst)
inst._cache[self.name] = val
return val
except AttributeError:
if inst is None:
return self
raise
def __set__(self, inst: Any, value: Any) -> None:
raise AttributeError("reified property is read-only")
reify_py = reify
try:
from ._helpers import reify as reify_c
if not NO_EXTENSIONS:
reify = reify_c # type: ignore
except ImportError:
pass
_ipv4_pattern = (r'^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}'
r'(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$')
_ipv6_pattern = (
r'^(?:(?:(?:[A-F0-9]{1,4}:){6}|(?=(?:[A-F0-9]{0,4}:){0,6}'
r'(?:[0-9]{1,3}\.){3}[0-9]{1,3}$)(([0-9A-F]{1,4}:){0,5}|:)'
r'((:[0-9A-F]{1,4}){1,5}:|:)|::(?:[A-F0-9]{1,4}:){5})'
r'(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}'
r'(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])|(?:[A-F0-9]{1,4}:){7}'
r'[A-F0-9]{1,4}|(?=(?:[A-F0-9]{0,4}:){0,7}[A-F0-9]{0,4}$)'
r'(([0-9A-F]{1,4}:){1,7}|:)((:[0-9A-F]{1,4}){1,7}|:)|(?:[A-F0-9]{1,4}:){7}'
r':|:(:[A-F0-9]{1,4}){7})$')
_ipv4_regex = re.compile(_ipv4_pattern)
_ipv6_regex = re.compile(_ipv6_pattern, flags=re.IGNORECASE)
_ipv4_regexb = re.compile(_ipv4_pattern.encode('ascii'))
_ipv6_regexb = re.compile(_ipv6_pattern.encode('ascii'), flags=re.IGNORECASE)
def _is_ip_address(
regex: Pattern[str], regexb: Pattern[bytes],
host: Optional[Union[str, bytes]])-> bool:
if host is None:
return False
if isinstance(host, str):
return bool(regex.match(host))
elif isinstance(host, (bytes, bytearray, memoryview)):
return bool(regexb.match(host))
else:
raise TypeError("{} [{}] is not a str or bytes"
.format(host, type(host)))
is_ipv4_address = functools.partial(_is_ip_address, _ipv4_regex, _ipv4_regexb)
is_ipv6_address = functools.partial(_is_ip_address, _ipv6_regex, _ipv6_regexb)
def is_ip_address(
host: Optional[Union[str, bytes, bytearray, memoryview]]) -> bool:
return is_ipv4_address(host) or is_ipv6_address(host)
_cached_current_datetime = None
_cached_formatted_datetime = None
def rfc822_formatted_time() -> str:
global _cached_current_datetime
global _cached_formatted_datetime
now = int(time.time())
if now != _cached_current_datetime:
# Weekday and month names for HTTP date/time formatting;
# always English!
# Tuples are constants stored in codeobject!
_weekdayname = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
_monthname = ("", # Dummy so we can use 1-based month numbers
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
year, month, day, hh, mm, ss, wd, y, z = time.gmtime(now) # type: ignore # noqa
_cached_formatted_datetime = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
_weekdayname[wd], day, _monthname[month], year, hh, mm, ss
)
_cached_current_datetime = now
return _cached_formatted_datetime # type: ignore
def _weakref_handle(info): # type: ignore
ref, name = info
ob = ref()
if ob is not None:
with suppress(Exception):
getattr(ob, name)()
def weakref_handle(ob, name, timeout, loop, ceil_timeout=True): # type: ignore
if timeout is not None and timeout > 0:
when = loop.time() + timeout
if ceil_timeout:
when = ceil(when)
return loop.call_at(when, _weakref_handle, (weakref.ref(ob), name))
def call_later(cb, timeout, loop): # type: ignore
if timeout is not None and timeout > 0:
when = ceil(loop.time() + timeout)
return loop.call_at(when, cb)
class TimeoutHandle:
""" Timeout handle """
def __init__(self,
loop: asyncio.AbstractEventLoop,
timeout: Optional[float]) -> None:
self._timeout = timeout
self._loop = loop
self._callbacks = [] # type: List[Tuple[Callable[..., None], Tuple[Any, ...], Dict[str, Any]]] # noqa
def register(self, callback: Callable[..., None],
*args: Any, **kwargs: Any) -> None:
self._callbacks.append((callback, args, kwargs))
def close(self) -> None:
self._callbacks.clear()
def start(self) -> Optional[asyncio.Handle]:
if self._timeout is not None and self._timeout > 0:
at = ceil(self._loop.time() + self._timeout)
return self._loop.call_at(at, self.__call__)
else:
return None
def timer(self) -> 'BaseTimerContext':
if self._timeout is not None and self._timeout > 0:
timer = TimerContext(self._loop)
self.register(timer.timeout)
return timer
else:
return TimerNoop()
def __call__(self) -> None:
for cb, args, kwargs in self._callbacks:
with suppress(Exception):
cb(*args, **kwargs)
self._callbacks.clear()
class BaseTimerContext(ContextManager['BaseTimerContext']):
pass
class TimerNoop(BaseTimerContext):
def __enter__(self) -> BaseTimerContext:
return self
def __exit__(self, exc_type: Optional[Type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType]) -> Optional[bool]:
return False
class TimerContext(BaseTimerContext):
""" Low resolution timeout context manager """
def __init__(self, loop: asyncio.AbstractEventLoop) -> None:
self._loop = loop
self._tasks = [] # type: List[asyncio.Task[Any]]
self._cancelled = False
def __enter__(self) -> BaseTimerContext:
task = current_task(loop=self._loop)
if task is None:
raise RuntimeError('Timeout context manager should be used '
'inside a task')
if self._cancelled:
task.cancel()
raise asyncio.TimeoutError from None
self._tasks.append(task)
return self
def __exit__(self, exc_type: Optional[Type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType]) -> Optional[bool]:
if self._tasks:
self._tasks.pop()
if exc_type is asyncio.CancelledError and self._cancelled:
raise asyncio.TimeoutError from None
return None
def timeout(self) -> None:
if not self._cancelled:
for task in set(self._tasks):
task.cancel()
self._cancelled = True
class CeilTimeout(async_timeout.timeout):
def __enter__(self) -> async_timeout.timeout:
if self._timeout is not None:
self._task = current_task(loop=self._loop)
if self._task is None:
raise RuntimeError(
'Timeout context manager should be used inside a task')
self._cancel_handler = self._loop.call_at(
ceil(self._loop.time() + self._timeout), self._cancel_task)
return self
class HeadersMixin:
ATTRS = frozenset([
'_content_type', '_content_dict', '_stored_content_type'])
_content_type = None # type: Optional[str]
_content_dict = None # type: Optional[Dict[str, str]]
_stored_content_type = sentinel
def _parse_content_type(self, raw: str) -> None:
self._stored_content_type = raw
if raw is None:
# default value according to RFC 2616
self._content_type = 'application/octet-stream'
self._content_dict = {}
else:
self._content_type, self._content_dict = cgi.parse_header(raw)
@property
def content_type(self) -> str:
"""The value of content part for Content-Type HTTP header."""
raw = self._headers.get(hdrs.CONTENT_TYPE) # type: ignore
if self._stored_content_type != raw:
self._parse_content_type(raw)
return self._content_type # type: ignore
@property
def charset(self) -> Optional[str]:
"""The value of charset part for Content-Type HTTP header."""
raw = self._headers.get(hdrs.CONTENT_TYPE) # type: ignore
if self._stored_content_type != raw:
self._parse_content_type(raw)
return self._content_dict.get('charset') # type: ignore
@property
def content_length(self) -> Optional[int]:
"""The value of Content-Length HTTP header."""
content_length = self._headers.get(hdrs.CONTENT_LENGTH) # type: ignore
if content_length is not None:
return int(content_length)
else:
return None
def set_result(fut: 'asyncio.Future[_T]', result: _T) -> None:
if not fut.done():
fut.set_result(result)
def set_exception(fut: 'asyncio.Future[_T]', exc: BaseException) -> None:
if not fut.done():
fut.set_exception(exc)
class ChainMapProxy(Mapping[str, Any]):
__slots__ = ('_maps',)
def __init__(self, maps: Iterable[Mapping[str, Any]]) -> None:
self._maps = tuple(maps)
def __init_subclass__(cls) -> None:
raise TypeError("Inheritance class {} from ChainMapProxy "
"is forbidden".format(cls.__name__))
def __getitem__(self, key: str) -> Any:
for mapping in self._maps:
try:
return mapping[key]
except KeyError:
pass
raise KeyError(key)
def get(self, key: str, default: Any=None) -> Any:
return self[key] if key in self else default
def __len__(self) -> int:
# reuses stored hash values if possible
return len(set().union(*self._maps)) # type: ignore
def __iter__(self) -> Iterator[str]:
d = {} # type: Dict[str, Any]
for mapping in reversed(self._maps):
# reuses stored hash values if possible
d.update(mapping)
return iter(d)
def __contains__(self, key: object) -> bool:
return any(key in m for m in self._maps)
def __bool__(self) -> bool:
return any(self._maps)
def __repr__(self) -> str:
content = ", ".join(map(repr, self._maps))
return 'ChainMapProxy({})'.format(content)
|
apache-2.0
|
arangodb/arangodb
|
tests/js/client/shell/shell-check-metrics-move-noncluster.js
|
4545
|
/* jshint globalstrict:false, strict:false, maxlen: 200 */
/* global assertEqual, assertTrue, assertNotEqual, arango */
// //////////////////////////////////////////////////////////////////////////////
// / DISCLAIMER
// /
// / Copyright 2021 ArangoDB 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.
// /
// / @author Max Neunhoeffer
// //////////////////////////////////////////////////////////////////////////////
const jsunity = require('jsunity');
const getMetric = require('@arangodb/test-helper').getMetricSingle;
function checkMetricsMoveSuite() {
'use strict';
return {
testByProtocol: function () {
// Note that this test is "-noncluster", since in the cluster
// all sorts of requests constantly arrive and we can never be
// sure that nothing happens. In a single server, this is OK,
// only our own requests should arrive at the server.
let http1ReqCount = getMetric("arangodb_request_body_size_http1_count");
let http1ReqSum = getMetric("arangodb_request_body_size_http1_sum");
let http2ReqCount = getMetric("arangodb_request_body_size_http2_count");
let http2ReqSum = getMetric("arangodb_request_body_size_http2_sum");
let vstReqCount = getMetric("arangodb_request_body_size_vst_count");
let vstReqSum = getMetric("arangodb_request_body_size_vst_sum");
// Do a few requests:
for (let i = 0; i < 10; ++i) {
let res = arango.GET_RAW("/_api/version");
assertEqual(200, res.code);
}
// Note that GET requests do not have bodies, so they do not move
// the sum of the histogram. So let's do a PUT just for good measure:
let logging = arango.GET("/_admin/log/level");
let res = arango.PUT_RAW("/_admin/log/level", logging);
assertEqual(200, res.code);
// And get the values again:
let http1ReqCount2 = getMetric("arangodb_request_body_size_http1_count");
let http1ReqSum2 = getMetric("arangodb_request_body_size_http1_sum");
let http2ReqCount2 = getMetric("arangodb_request_body_size_http2_count");
let http2ReqSum2 = getMetric("arangodb_request_body_size_http2_sum");
let vstReqCount2 = getMetric("arangodb_request_body_size_vst_count");
let vstReqSum2 = getMetric("arangodb_request_body_size_vst_sum");
if (arango.protocol() === "vst") {
assertNotEqual(vstReqCount, vstReqCount2);
assertNotEqual(vstReqSum, vstReqSum2);
} else {
assertEqual(vstReqCount, vstReqCount2);
assertEqual(vstReqSum, vstReqSum2);
}
if (arango.protocol() === "http") {
assertNotEqual(http1ReqCount, http1ReqCount2);
assertNotEqual(http1ReqSum, http1ReqSum2);
} else {
assertEqual(http1ReqCount, http1ReqCount2);
assertEqual(http1ReqSum, http1ReqSum2);
}
if (arango.protocol() === "http2") {
assertNotEqual(http2ReqCount, http2ReqCount2);
assertNotEqual(http2ReqSum, http2ReqSum2);
} else {
assertEqual(http2ReqCount, http2ReqCount2);
assertEqual(http2ReqSum, http2ReqSum2);
}
},
testConnectionCountByProtocol: function () {
let http2ConnCount = getMetric("arangodb_http2_connections_total");
let vstConnCount = getMetric("arangodb_vst_connections_total");
// I have not found a reliable way to trigger a new connection from
// `arangosh`. `arango.reconnect` does not work since it is caching
// connections and the request timeout is not honoured for HTTP/2
// and VST by fuerte. The idle timeout runs into an assertion failure.
// Therefore, we must be content here to check that the connection
// count is non-zero for the currently underlying protocol:
if (arango.protocol() === "http2") {
assertNotEqual(0, http2ConnCount);
} else if (arango.protocol() === "vst") {
assertNotEqual(0, vstConnCount);
}
},
};
}
jsunity.run(checkMetricsMoveSuite);
return jsunity.done();
|
apache-2.0
|
edisonlz/vue_player
|
music_player/build/api.js
|
112
|
var opn = require('opn')
var path = require('path')
var express = require('express')
var http = require('http')
|
apache-2.0
|
moosbusch/xbLIDO
|
src/net/opengis/gml/impl/CubicSplineDocumentImpl.java
|
2438
|
/*
* Copyright 2013 Gunnar Kappei.
*
* 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.opengis.gml.impl;
/**
* A document containing one CubicSpline(@http://www.opengis.net/gml) element.
*
* This is a complex type.
*/
public class CubicSplineDocumentImpl extends net.opengis.gml.impl.CurveSegmentDocumentImpl implements net.opengis.gml.CubicSplineDocument
{
private static final long serialVersionUID = 1L;
public CubicSplineDocumentImpl(org.apache.xmlbeans.SchemaType sType)
{
super(sType);
}
private static final javax.xml.namespace.QName CUBICSPLINE$0 =
new javax.xml.namespace.QName("http://www.opengis.net/gml", "CubicSpline");
/**
* Gets the "CubicSpline" element
*/
public net.opengis.gml.CubicSplineType getCubicSpline()
{
synchronized (monitor())
{
check_orphaned();
net.opengis.gml.CubicSplineType target = null;
target = (net.opengis.gml.CubicSplineType)get_store().find_element_user(CUBICSPLINE$0, 0);
if (target == null)
{
return null;
}
return target;
}
}
/**
* Sets the "CubicSpline" element
*/
public void setCubicSpline(net.opengis.gml.CubicSplineType cubicSpline)
{
generatedSetterHelperImpl(cubicSpline, CUBICSPLINE$0, 0, org.apache.xmlbeans.impl.values.XmlObjectBase.KIND_SETTERHELPER_SINGLETON);
}
/**
* Appends and returns a new empty "CubicSpline" element
*/
public net.opengis.gml.CubicSplineType addNewCubicSpline()
{
synchronized (monitor())
{
check_orphaned();
net.opengis.gml.CubicSplineType target = null;
target = (net.opengis.gml.CubicSplineType)get_store().add_element_user(CUBICSPLINE$0);
return target;
}
}
}
|
apache-2.0
|
akarnokd/RxJavaFlow
|
src/main/java/rx/disposables/SerialDisposable.java
|
2362
|
/**
* Copyright 2015 David Karnok
*
* 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 rx.disposables;
import static rx.internal.UnsafeAccess.*;
import java.util.Objects;
/**
*
*/
public final class SerialDisposable implements Disposable {
/** Unique terminal state. */
static final Disposable STATE_CANCELLED = new Disposable() {
@Override
public void dispose() {
}
@Override
public boolean isDisposed() {
return true;
}
};
volatile Disposable state;
static final long STATE = addressOf(SerialDisposable.class, "state");
public SerialDisposable() {
}
public SerialDisposable(Disposable disposable) {
Objects.requireNonNull(disposable);
UNSAFE.putOrderedObject(this, STATE, disposable);
}
public void set(Disposable disposable) {
Objects.requireNonNull(disposable);
for (;;) {
Disposable c = state;
if (c == STATE_CANCELLED) {
disposable.dispose();
return;
}
if (UNSAFE.compareAndSwapObject(this, STATE, c, disposable)) {
if (c != null) {
c.dispose();
}
return;
}
}
}
public Disposable get() {
Disposable d = state;
if (d == STATE_CANCELLED) {
return Disposable.DISPOSED;
}
return d;
}
@Override
public void dispose() {
if (state != STATE_CANCELLED) {
Disposable c = (Disposable)UNSAFE.getAndSetObject(this, STATE, STATE_CANCELLED);
if (c != null) {
c.dispose();
}
}
}
@Override
public boolean isDisposed() {
return state == STATE_CANCELLED;
}
}
|
apache-2.0
|
genericsystem/genericsystem2015
|
gs-cv/src/main/java/org/genericsystem/cv/utils/ImageAnnotator.java
|
902
|
package org.genericsystem.cv.utils;
import java.nio.file.Path;
import org.genericsystem.cv.Img;
import org.genericsystem.cv.retriever.DocFields;
import org.opencv.core.Scalar;
import org.opencv.imgcodecs.Imgcodecs;
import io.vertx.core.json.JsonObject;
public class ImageAnnotator {
public static Path annotateImage(Path imgPath, Path resourcesFolder, JsonObject fields) {
String filename = ModelTools.generateFileName(imgPath);
Path savedFile = resourcesFolder.resolve(filename);
DocFields docFields = DocFields.of(fields);
try (Img src = new Img(imgPath.toString()); Img annotated = docFields.annotateImage(src, 2d, new Scalar(0, 0, 255), 2)) {
Imgcodecs.imwrite(savedFile.toString(), annotated.getSrc());
return savedFile;
} catch (Exception e) {
throw new IllegalStateException("An error has occured while saving file " + savedFile + " to resources folder", e);
}
}
}
|
apache-2.0
|
knyga/light-orm
|
lib/typescript/interfaces/DriverInterface.ts
|
251
|
/**
* Interface to Driver
* @author Oleksandr Knyga <oleksandrknyga@gmail.com>
* @license Apache License 2.0 - See file 'LICENSE.md' in this project.
*/
interface DriverInterface {
query(query: string, handler: (err, rows, fields) => void);
}
|
apache-2.0
|
webadvancedservicescom/magento
|
dev/tests/unit/testsuite/Magento/Framework/Config/Composer/PackageTest.php
|
1988
|
<?php
/**
* @copyright Copyright (c) 2014 X.commerce, Inc. (http://www.magentocommerce.com)
*/
namespace Magento\Framework\Config\Composer;
class PackageTest extends \PHPUnit_Framework_TestCase
{
const SAMPLE_DATA =
'{"foo":"1","bar":"2","baz":["3","4"],"nested":{"one":"5","two":"6",
"magento/theme-adminhtml-backend":7, "magento/theme-frontend-luma":8}}';
/**
* @var \StdClass
*/
private $sampleJson;
/**
* @var Package
*/
private $object;
protected function setUp()
{
$this->sampleJson = json_decode(self::SAMPLE_DATA);
$this->object = new Package($this->sampleJson);
}
public function testGetJson()
{
$this->assertInstanceOf('\StdClass', $this->object->getJson(false));
$this->assertEquals($this->sampleJson, $this->object->getJson(false));
$this->assertSame($this->sampleJson, $this->object->getJson(false));
$this->assertEquals(
json_encode($this->sampleJson, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "\n",
$this->object->getJson(true, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)
);
}
public function testGet()
{
$this->assertSame('1', $this->object->get('foo'));
$this->assertSame(['3', '4'], $this->object->get('baz'));
$nested = $this->object->get('nested');
$this->assertInstanceOf('\StdClass', $nested);
$this->assertObjectHasAttribute('one', $nested);
$this->assertEquals('5', $nested->one);
$this->assertEquals('5', $this->object->get('nested->one'));
$this->assertObjectHasAttribute('two', $nested);
$this->assertEquals('6', $nested->two);
$this->assertEquals('6', $this->object->get('nested->two'));
$this->assertEquals(
['magento/theme-adminhtml-backend' => 7, 'magento/theme-frontend-luma' => 8],
(array)$this->object->get('nested', '/^magento\/theme/')
);
}
}
|
apache-2.0
|
shakamunyi/beam
|
sdks/java/core/src/main/java/com/google/cloud/dataflow/sdk/util/DoFnRunners.java
|
5255
|
/*
* 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 com.google.cloud.dataflow.sdk.util;
import com.google.cloud.dataflow.sdk.options.PipelineOptions;
import com.google.cloud.dataflow.sdk.transforms.DoFn;
import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow;
import com.google.cloud.dataflow.sdk.util.DoFnRunner.ReduceFnExecutor;
import com.google.cloud.dataflow.sdk.util.ExecutionContext.StepContext;
import com.google.cloud.dataflow.sdk.util.common.CounterSet;
import com.google.cloud.dataflow.sdk.util.common.CounterSet.AddCounterMutator;
import com.google.cloud.dataflow.sdk.values.KV;
import com.google.cloud.dataflow.sdk.values.TupleTag;
import java.util.List;
/**
* Static utility methods that provide {@link DoFnRunner} implementations.
*/
public class DoFnRunners {
/**
* Information about how to create output receivers and output to them.
*/
public interface OutputManager {
/**
* Outputs a single element to the receiver indicated by the given {@link TupleTag}.
*/
public <T> void output(TupleTag<T> tag, WindowedValue<T> output);
}
/**
* Returns a basic implementation of {@link DoFnRunner} that works for most {@link DoFn DoFns}.
*
* <p>It invokes {@link DoFn#processElement} for each input.
*/
public static <InputT, OutputT> DoFnRunner<InputT, OutputT> simpleRunner(
PipelineOptions options,
DoFn<InputT, OutputT> fn,
SideInputReader sideInputReader,
OutputManager outputManager,
TupleTag<OutputT> mainOutputTag,
List<TupleTag<?>> sideOutputTags,
StepContext stepContext,
CounterSet.AddCounterMutator addCounterMutator,
WindowingStrategy<?, ?> windowingStrategy) {
return new SimpleDoFnRunner<>(
options,
fn,
sideInputReader,
outputManager,
mainOutputTag,
sideOutputTags,
stepContext,
addCounterMutator,
windowingStrategy);
}
/**
* Returns an implementation of {@link DoFnRunner} that handles late data dropping.
*
* <p>It drops elements from expired windows before they reach the underlying {@link DoFn}.
*/
public static <K, InputT, OutputT, W extends BoundedWindow>
DoFnRunner<KeyedWorkItem<K, InputT>, KV<K, OutputT>> lateDataDroppingRunner(
PipelineOptions options,
ReduceFnExecutor<K, InputT, OutputT, W> reduceFnExecutor,
SideInputReader sideInputReader,
OutputManager outputManager,
TupleTag<KV<K, OutputT>> mainOutputTag,
List<TupleTag<?>> sideOutputTags,
StepContext stepContext,
CounterSet.AddCounterMutator addCounterMutator,
WindowingStrategy<?, W> windowingStrategy) {
DoFnRunner<KeyedWorkItem<K, InputT>, KV<K, OutputT>> simpleDoFnRunner =
simpleRunner(
options,
reduceFnExecutor.asDoFn(),
sideInputReader,
outputManager,
mainOutputTag,
sideOutputTags,
stepContext,
addCounterMutator,
windowingStrategy);
return new LateDataDroppingDoFnRunner<>(
simpleDoFnRunner,
windowingStrategy,
stepContext.timerInternals(),
reduceFnExecutor.getDroppedDueToLatenessAggregator());
}
public static <InputT, OutputT> DoFnRunner<InputT, OutputT> createDefault(
PipelineOptions options,
DoFn<InputT, OutputT> doFn,
SideInputReader sideInputReader,
OutputManager outputManager,
TupleTag<OutputT> mainOutputTag,
List<TupleTag<?>> sideOutputTags,
StepContext stepContext,
AddCounterMutator addCounterMutator,
WindowingStrategy<?, ?> windowingStrategy) {
if (doFn instanceof ReduceFnExecutor) {
@SuppressWarnings("rawtypes")
ReduceFnExecutor fn = (ReduceFnExecutor) doFn;
@SuppressWarnings({"unchecked", "cast", "rawtypes"})
DoFnRunner<InputT, OutputT> runner = (DoFnRunner<InputT, OutputT>) lateDataDroppingRunner(
options,
fn,
sideInputReader,
outputManager,
(TupleTag) mainOutputTag,
sideOutputTags,
stepContext,
addCounterMutator,
(WindowingStrategy) windowingStrategy);
return runner;
}
return simpleRunner(
options,
doFn,
sideInputReader,
outputManager,
mainOutputTag,
sideOutputTags,
stepContext,
addCounterMutator,
windowingStrategy);
}
}
|
apache-2.0
|
rutvikd/ak-recipes
|
com_akrecipes-1.0.1/administrator/views/course/view.html.php
|
2353
|
<?php
/**
* @version CVS: 1.0.1
* @package Com_Akrecipes
* @author Rutvik Doshi <rutvik@archanaskitchen.com>
* @copyright Copyright (C) 2015. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
// No direct access
defined('_JEXEC') or die;
jimport('joomla.application.component.view');
/**
* View to edit
*
* @since 1.6
*/
class AkrecipesViewCourse extends JViewLegacy
{
protected $state;
protected $item;
protected $form;
/**
* Display the view
*
* @param string $tpl Template name
*
* @return void
*
* @throws Exception
*/
public function display($tpl = null)
{
$this->state = $this->get('State');
$this->item = $this->get('Item');
$this->form = $this->get('Form');
// Check for errors.
if (count($errors = $this->get('Errors')))
{
throw new Exception(implode("\n", $errors));
}
$this->addToolbar();
parent::display($tpl);
}
/**
* Add the page title and toolbar.
*
* @return void
*
* @throws Exception
*/
protected function addToolbar()
{
JFactory::getApplication()->input->set('hidemainmenu', true);
$user = JFactory::getUser();
$isNew = ($this->item->id == 0);
if (isset($this->item->checked_out))
{
$checkedOut = !($this->item->checked_out == 0 || $this->item->checked_out == $user->get('id'));
}
else
{
$checkedOut = false;
}
$canDo = AkrecipesHelper::getActions();
JToolBarHelper::title(JText::_('COM_AKRECIPES_TITLE_COURSE'), 'course.png');
// If not checked out, can save the item.
if (!$checkedOut && ($canDo->get('core.edit') || ($canDo->get('core.create'))))
{
JToolBarHelper::apply('course.apply', 'JTOOLBAR_APPLY');
JToolBarHelper::save('course.save', 'JTOOLBAR_SAVE');
}
if (!$checkedOut && ($canDo->get('core.create')))
{
JToolBarHelper::custom('course.save2new', 'save-new.png', 'save-new_f2.png', 'JTOOLBAR_SAVE_AND_NEW', false);
}
// If an existing item, can save to a copy.
if (!$isNew && $canDo->get('core.create'))
{
JToolBarHelper::custom('course.save2copy', 'save-copy.png', 'save-copy_f2.png', 'JTOOLBAR_SAVE_AS_COPY', false);
}
if (empty($this->item->id))
{
JToolBarHelper::cancel('course.cancel', 'JTOOLBAR_CANCEL');
}
else
{
JToolBarHelper::cancel('course.cancel', 'JTOOLBAR_CLOSE');
}
}
}
|
apache-2.0
|
Tenor-Inc/tenor-android-core
|
src/main/java/com/tenor/android/core/network/ApiClient.java
|
9082
|
package com.tenor.android.core.network;
import android.app.Application;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.util.ArrayMap;
import android.text.TextUtils;
import com.tenor.android.core.constant.ScreenDensity;
import com.tenor.android.core.constant.StringConstant;
import com.tenor.android.core.constant.ViewAction;
import com.tenor.android.core.measurable.MeasurableViewHolderEvent;
import com.tenor.android.core.model.impl.Result;
import com.tenor.android.core.response.WeakRefCallback;
import com.tenor.android.core.response.impl.AnonIdResponse;
import com.tenor.android.core.service.AaidService;
import com.tenor.android.core.util.AbstractGsonUtils;
import com.tenor.android.core.util.AbstractLocaleUtils;
import com.tenor.android.core.util.AbstractSessionUtils;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import retrofit2.Call;
/**
* API Client to make network calls to retrieve contents
*/
public class ApiClient {
private static volatile IApiService<IApiClient> sApiService;
private static synchronized void init(@NonNull final Context context) {
init(context, new ApiService.Builder<>(context, IApiClient.class));
}
/**
* Initialize the ApiClient instance with your custom interceptor
*
* @param context the context
* @param builder {@link ApiService.IBuilder}
*/
public static synchronized void init(@NonNull final Context context,
@NonNull ApiService.IBuilder<IApiClient> builder) {
init(context, builder, null);
}
public static synchronized void init(@NonNull final Context context,
@NonNull ApiService.IBuilder<IApiClient> builder,
@Nullable IAnonIdListener listener) {
if (sApiService == null) {
sApiService = builder.build();
}
if (!AbstractSessionUtils.hasAnonId(context)) {
getAnonId(context, listener);
}
}
public static String getApiKey() {
if (sApiService == null) {
throw new IllegalStateException("Api service cannot be null");
}
return sApiService.getApiKey();
}
/**
* Retrieve instance of the {@link ApiClient}, and create instance if not already created
*
* @return the {@link ApiClient} instance
*/
@NonNull
public static synchronized IApiClient getInstance() {
if (sApiService == null) {
throw new IllegalStateException("Api service cannot be null");
}
return sApiService.get();
}
/**
* Lazy initialize a {@link IApiClient} with default {@link IApiService} configuration
*/
@NonNull
public static synchronized IApiClient getInstance(@NonNull Context context) {
if (sApiService == null) {
init(context);
}
return sApiService.get();
}
/**
* Get service ids that can delivery a more accurate and better experience
*
* @return a {@link Map} with {@code key} (API Key), {@code anon_id},
* {@code aaid} (Android Advertise Id) and {@code locale } for authentication and better
* content delivery experience
*/
public static Map<String, String> getServiceIds(@NonNull final Context context) {
final ArrayMap<String, String> map = new ArrayMap<>(4);
// API Key
map.put("key", sApiService.getApiKey());
/*
* The following fields work together to delivery a more accurate and better experience
*
* 1. `anon_id`, a non-id or its older version, keyboard is used to roughly identify a user;
* 2. `aaid`, Android Advertise Id, is also used in case "keyboardid" or "anon_id" mutates
* 3. `locale` is used to deliver curated language/regional specific contents to users
* 4. `screen_density` is used to optimize the content size to the device
*/
final String id = AbstractSessionUtils.getAnonId(context);
map.put(id.length() <= 20 ? "keyboardid" : "anon_id", id);
if (TextUtils.isEmpty(AbstractSessionUtils.getAndroidAdvertiseId(context))) {
AaidService.requestAaid(context);
}
map.put("aaid", AbstractSessionUtils.getAndroidAdvertiseId(context));
map.put("locale", AbstractLocaleUtils.getCurrentLocaleName(context));
map.put("screen_density", ScreenDensity.get(context));
return map;
}
/**
* Get a non-id to roughly identify a user for a better content delivery experience
*
* @param context the application context
* @param listener the callback when the asynchronous keyboard id API request is done
* @return {@link Call}<{@link AnonIdResponse}>
*/
public static Call<AnonIdResponse> getAnonId(@NonNull Context context,
@Nullable final IAnonIdListener listener) {
Context app;
if (context instanceof Application) {
app = context;
} else {
app = context.getApplicationContext();
}
// request for new keyboard id
Call<AnonIdResponse> call = ApiClient.getInstance(app)
.getAnonId(sApiService.getApiKey(), AbstractLocaleUtils.getCurrentLocaleName(context));
call.enqueue(new WeakRefCallback<Context, AnonIdResponse>(app) {
@Override
public void success(@NonNull Context app, @Nullable AnonIdResponse response) {
if (response != null && !TextUtils.isEmpty(response.getId())) {
AbstractSessionUtils.setAnonId(app, response.getId());
if (listener == null) {
return;
}
final String id = response.getId();
if (TextUtils.isEmpty(id)) {
listener.onReceiveAnonIdFailed(new IllegalStateException("keyboard id cannot be empty"));
return;
}
listener.onReceiveAnonIdSucceeded(id);
}
}
@Override
public void failure(@NonNull Context app, @Nullable Throwable throwable) {
if (listener != null) {
listener.onReceiveAnonIdFailed(throwable);
}
}
});
// request for aaid
AaidService.requestAaid(context);
return call;
}
/**
* Report shared GIF id for better search experience in the future
*
* @param context the application context
* @param id the gif id
* @param query the search query that led to this GIF, or {@code null} for trending GIFs
* @return {@link Call}<{@link Void}>
*/
public static Call<Void> registerShare(@NonNull Context context,
@NonNull String id,
@Nullable String query) {
Call<Void> call = ApiClient.getInstance(context)
.registerShare(getServiceIds(context), Integer.valueOf(id), StringConstant.getOrEmpty(query));
call.enqueue(new VoidCallBack());
return call;
}
/**
* @param context the application context
* @param sourceId the source id of a {@link Result}
* @param action the action {view|share|tap}
* @return {@link Call}<{@link Void}>
*/
public static Call<Void> registerAction(@NonNull final Context context,
@NonNull String sourceId,
@NonNull String visualPosition,
@ViewAction.Value final String action) {
return registerAction(context, new MeasurableViewHolderEvent(sourceId, action, AbstractLocaleUtils.getUtcOffset(context), visualPosition));
}
/**
* @param context the application context
* @param event the {@link MeasurableViewHolderEvent}
* @return {@link Call}<{@link Void}>
*/
public static Call<Void> registerAction(@NonNull final Context context,
@NonNull MeasurableViewHolderEvent event) {
List<MeasurableViewHolderEvent> actions = Collections.singletonList(event);
return registerActions(context, actions);
}
/**
* @param context the application context
* @param events the {@link MeasurableViewHolderEvent}
* @return {@link Call}<{@link Void}>
*/
public static Call<Void> registerActions(@NonNull final Context context,
@NonNull List<MeasurableViewHolderEvent> events) {
final String data = AbstractGsonUtils.getInstance().toJson(events);
Call<Void> call = ApiClient.getInstance().registerActions(getServiceIds(context), data);
call.enqueue(new VoidCallBack());
return call;
}
}
|
apache-2.0
|
ericnewton76/DataUri
|
src/DataUriTests/DataUri.Parse.Tests.cs
|
3484
|
using System;
using System.Collections.Generic;
using NUnit.Framework;
using DataUri = System.DataUri;
namespace DataUriTests
{
[TestFixture]
public class DataUri_Parse_Tests
{
[Test]
[TestCase("data:;base64,QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVo=", "4142434445464748494A4B4C4D4E4F505152535455565758595A")]
[TestCase("data:;base64,TG9yZW0gaXBzdW0gZG9sYXIgc2l0IGFtb3Q=", "4c6f72656d20697073756d20646f6c61722073697420616d6f74")]
public void Parse_Base64_NoMediaType(string input, string expectedBytesStr)
{
//arrange
byte[] expectedBytes = HexStringToByteArray(expectedBytesStr);
string expected_MediaType = "text/plain"; //if not specified, media type is assumed to be text/plain
//act
var datauri = DataUri.Parse(input);
//assert
Assert.That(datauri, Is.Not.Null);
Assert.That(datauri.Bytes, Is.EqualTo(expectedBytes));
Assert.That(datauri.MediaType, Is.EqualTo(expected_MediaType));
}
[Test]
[TestCase("data:image/jpeg;base64,QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVo=", "4142434445464748494A4B4C4D4E4F505152535455565758595A")]
[TestCase("data:image/jpeg;base64,TG9yZW0gaXBzdW0gZG9sYXIgc2l0IGFtb3Q=", "4c6f72656d20697073756d20646f6c61722073697420616d6f74")]
public void Parse_Base64_Specified_MediaType(string input, string expectedBytesStr)
{
//arrange
byte[] expectedBytes = HexStringToByteArray(expectedBytesStr);
string expected_MediaType = "image/jpeg"; //if not specified, media type is assumed to be text/plain
//act
var datauri = DataUri.Parse(input);
//assert
Assert.That(datauri, Is.Not.Null);
Assert.That(datauri.Bytes, Is.EqualTo(expectedBytes));
Assert.That(datauri.MediaType, Is.EqualTo(expected_MediaType));
}
[Test]
[TestCase("data:base64,QUJDREVGR0h JSktMTU5\nPUFFS\n\tU1RVVldYWVo=", "4142434445464748494A4B4C4D4E4F505152535455565758595A")]
public void Tolerates_whitespace_within_base64(string input, string expectedBytesStr)
{
//arrange
byte[] expectedBytes = HexStringToByteArray(expectedBytesStr);
//act
var datauri = DataUri.Parse(input);
//assert
Assert.That(datauri, Is.Not.Null);
Assert.That(datauri.Bytes, Is.EqualTo(expectedBytes));
Assert.That(datauri.MediaType, Is.EqualTo((string)null));
}
[Test]
[TestCase("DATA:base64,QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVo=")]
[TestCase("http://base64,TG9yZW0gaXBzdW0gZG9sYXIgc2l0IGFtb3Q=")]
[TestCase("data-uri:base64,TASDSDASDASDASDAFEFE=")]
public void Must_start_with_data_throws_ArgumentException(string input)
{
//assert
//act
//assert
Assert.Throws<ArgumentException>(() => {
DataUri.Parse(input);
});
}
[Test]
public void Null_Value_throws_ArgumentNullException()
{
//assert
//act
//assert
Assert.Throws<ArgumentNullException>(() => {
DataUri.Parse((string)null);
});
}
#region test helpers
public static byte[] HexStringToByteArray(string hexString) //http://stackoverflow.com/a/8235530/323456
{
if (hexString.Length % 2 != 0)
{
throw new ArgumentException("The hex values string cannot have an odd number of digits.");
}
byte[] HexAsBytes = new byte[hexString.Length / 2];
for (int index = 0; index < HexAsBytes.Length; index++)
{
string byteValue = hexString.Substring(index * 2, 2);
HexAsBytes[index] = byte.Parse(byteValue, System.Globalization.NumberStyles.HexNumber, System.Globalization.CultureInfo.InvariantCulture);
}
return HexAsBytes;
}
#endregion
}
}
|
apache-2.0
|
spring-cloud/spring-cloud-aws
|
spring-cloud-aws-context/src/main/java/org/springframework/cloud/aws/context/annotation/OnClassCondition.java
|
1481
|
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 org.springframework.cloud.aws.context.annotation;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.util.ClassUtils;
import org.springframework.util.MultiValueMap;
/**
* @author Agim Emruli
*/
public class OnClassCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
MultiValueMap<String, Object> attributes = metadata
.getAllAnnotationAttributes(ConditionalOnClass.class.getName(), true);
String className = String.valueOf(attributes.get(AnnotationUtils.VALUE).get(0));
return ClassUtils.isPresent(className, context.getClassLoader());
}
}
|
apache-2.0
|
b-slim/calcite
|
geode/src/main/java/org/apache/calcite/adapter/geode/util/JavaTypeFactoryExtImpl.java
|
4235
|
/*
* 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.calcite.adapter.geode.util;
import org.apache.calcite.adapter.java.JavaTypeFactory;
import org.apache.calcite.jdbc.JavaRecordType;
import org.apache.calcite.jdbc.JavaTypeFactoryImpl;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rel.type.RelDataTypeField;
import org.apache.calcite.rel.type.RelDataTypeFieldImpl;
import org.apache.calcite.rel.type.RelRecordType;
import org.apache.geode.pdx.PdxInstance;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Implementation of {@link JavaTypeFactory}.
*
* <p><strong>NOTE: This class is experimental and subject to
* change/removal without notice</strong>.</p>
*/
public class JavaTypeFactoryExtImpl
extends JavaTypeFactoryImpl {
/**
* See <a href="http://stackoverflow.com/questions/16966629/what-is-the-difference-between-getfields-and-getdeclaredfields-in-java-reflectio">
* the difference between fields and declared fields</a>.
*/
@Override public RelDataType createStructType(Class type) {
final List<RelDataTypeField> list = new ArrayList<>();
for (Field field : type.getDeclaredFields()) {
if (!Modifier.isStatic(field.getModifiers())) {
// FIXME: watch out for recursion
final Type fieldType = field.getType();
list.add(
new RelDataTypeFieldImpl(
field.getName(),
list.size(),
createType(fieldType)));
}
}
return canonize(new JavaRecordType(list, type));
}
public RelDataType createPdxType(PdxInstance pdxInstance) {
final List<RelDataTypeField> list = new ArrayList<>();
for (String fieldName : pdxInstance.getFieldNames()) {
Object field = pdxInstance.getField(fieldName);
Type fieldType;
if (field == null) {
fieldType = String.class;
} else if (field instanceof PdxInstance) {
// Map Nested PDX structures as String. This relates with
// GeodeUtils.convert case when clazz is Null.
fieldType = Map.class;
// RelDataType boza = createPdxType((PdxInstance) field);
} else {
fieldType = field.getClass();
}
list.add(
new RelDataTypeFieldImpl(
fieldName,
list.size(),
createType(fieldType)));
}
return canonize(new RelRecordType(list));
}
// Experimental flattering the nested structures.
public RelDataType createPdxType2(PdxInstance pdxInstance) {
final List<RelDataTypeField> list = new ArrayList<>();
recursiveCreatePdxType(pdxInstance, list, "");
return canonize(new RelRecordType(list));
}
private void recursiveCreatePdxType(PdxInstance pdxInstance,
List<RelDataTypeField> list, String fieldNamePrefix) {
for (String fieldName : pdxInstance.getFieldNames()) {
Object field = pdxInstance.getField(fieldName);
final Type fieldType = field.getClass();
if (fieldType instanceof PdxInstance) {
recursiveCreatePdxType(
(PdxInstance) field, list, fieldNamePrefix + fieldName + ".");
} else {
list.add(
new RelDataTypeFieldImpl(
fieldNamePrefix + fieldName,
list.size(),
createType(fieldType)));
}
}
}
}
// End JavaTypeFactoryExtImpl.java
|
apache-2.0
|
JamesIry/jADT
|
jADT-samples/src/test/java/com/pogofish/jadt/samples/visitor/ColorEnumExamplesTest.java
|
789
|
package com.pogofish.jadt.samples.visitor;
import static org.junit.Assert.assertEquals;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.junit.Test;
/**
* Make sure ColorEnumExamples does what it says it does
*/
public class ColorEnumExamplesTest {
@Test
public void test() {
check(ColorEnum.Red, "red");
check(ColorEnum.Green, "green");
check(ColorEnum.Blue, "blue");
}
private void check(ColorEnum color, String string) {
final ColorEnumExamples usage = new ColorEnumExamples();
final StringWriter writer = new StringWriter();
final PrintWriter printWriter = new PrintWriter(writer);
usage.printString(color, printWriter);
assertEquals(string, writer.toString());
}
}
|
apache-2.0
|
Bloodpearl/FastSearch
|
FastSearch/Program.cs
|
538
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FastSearch
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new SearchForm());
}
}
}
|
apache-2.0
|
ttx/summitsched
|
cheddar/sched.py
|
4427
|
# Copyright 2015 Thierry Carrez <thierry@openstack.org>
# 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 requests
from cheddar.models import Track
from cheddar.session import Session
from cheddar.tracklead import is_valid_track
class API:
def __init__(self, settings):
self.schedurl = "http://%s/api" % settings.SCHED_SITE
self.api_key = settings.SCHED_API_KEY
def _call_sched(self, operation, **payload):
payload['api_key'] = self.api_key
payload['format'] = "json"
r = requests.post("%s/%s" % (self.schedurl, operation), params=payload)
if r.text != u'Ok':
return r.json()
else:
return {}
def _sched_to_session(self, schedjson):
session = Session(schedjson['event_key'])
session.start = schedjson['event_start']
session.end = schedjson['event_end']
session.room = schedjson['venue']
session.style = 'WORKROOM'
if session.id.startswith("Fish-"):
session.style = 'FISHBOWL'
if session.id.startswith("Meet-"):
session.style = 'MEETUP'
elements = session.id.split("-")
if len(elements) < 2:
session.maintrack = ""
else:
session.maintrack = elements[1]
session.extratracks = schedjson['event_type'].replace(
session.maintrack,"")
session.extratracks = session.extratracks.strip(" ,")
session.set_title(schedjson['name'])
try:
session.set_desc(schedjson['description'])
except KeyError:
session.description = "tbd"
return session
def _all_sessions(self):
ret = self._call_sched('session/list')
sessions = []
for sessionjson in ret:
sessions.append(self._sched_to_session(sessionjson))
return sessions
def list_sessions(self, trackid):
t = Track.objects.get(id=trackid)
def track_match(a):
return a.maintrack == t.name
filtered = filter(track_match, self._all_sessions())
return sorted(filtered, key=lambda x: x.start)
def get_session(self, sessionkey):
for session in self._all_sessions():
if session.id == sessionkey:
return session
raise IndexError
def modify_session(self, sessionkey, session):
# Sched clears "venue" information if you don't pass it again
old_session = self.get_session(sessionkey)
alltracks = session.maintrack
description = session.description
for track in session.extratracks.split(","):
track = track.strip().capitalize()
if is_valid_track(track):
print track
alltracks = "%s, %s" % (alltracks, track)
name = session.get_title()
description = session.get_desc()
self._call_sched('session/mod',
session_key=sessionkey,
name=name,
session_type=alltracks,
description=description,
venue=old_session.room)
def swap_sessions(self, sessionkey, session, session2key, session2):
self.modify_session(sessionkey, session2)
self.modify_session(session2key, session)
def create_session(self, index, day, starttime, endtime, title,
desc, track, room, style):
key = "%s-%s-%d" % (style.lower().capitalize()[0:4], track, index)
self._call_sched('session/add',
session_key=key,
name=title,
session_start=day + " " + starttime,
session_end=day + " " + endtime,
session_type=track,
description=desc,
venue=room)
|
apache-2.0
|
phasenraum2010/twitterwall2
|
src/main/java/org/woehlke/twitterwall/configuration/spring/DataSourceConfig.java
|
809
|
package org.woehlke.twitterwall.configuration.spring;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import javax.sql.DataSource;
/**
* Created by tw on 19.06.17.
*/
@Configuration
@EnableJpaRepositories("org.woehlke.twitterwall.oodm.repositories")
public class DataSourceConfig {
@Bean
@Primary
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
}
|
apache-2.0
|
terascope/teraslice
|
packages/job-components/src/operations/interfaces.ts
|
2317
|
import {
ExecutionConfig,
Context,
OpConfig,
APIConfig,
WorkerContext
} from '../interfaces';
import FetcherCore from './core/fetcher-core';
import SchemaCore, { OpType } from './core/schema-core';
import SlicerCore from './core/slicer-core';
import APICore from './core/api-core';
import ProcessorCore from './core/processor-core';
import Slicer from './slicer';
import ParallelSlicer from './parallel-slicer';
import OperationAPI from './operation-api';
export type APICoreConstructor<U> = {
new (context: WorkerContext, apiConfig: APIConfig, executionConfig: ExecutionConfig): U;
};
export type OperationCoreConstructor<U> = {
new <T = OpConfig>(
context: WorkerContext,
opConfig: OpConfig & T,
executionConfig: ExecutionConfig
): U;
};
export type SlicerCoreConstructor<U> = {
new <T = OpConfig>(
context: WorkerContext,
opConfig: OpConfig & T,
executionConfig: ExecutionConfig
): U;
};
export type SchemaConstructor<T = any> = {
type(): string;
new (context: Context, opType?: OpType): SchemaCore<T>;
};
export type OperationAPIConstructor = APICoreConstructor<OperationAPI>;
export type ObserverConstructor = APICoreConstructor<APICore>;
export type APIConstructor = APICoreConstructor<APICore>;
export type SlicerConstructor = SlicerCoreConstructor<SlicerCore>;
export type SingleSlicerConstructor = SlicerCoreConstructor<Slicer>;
export type ParallelSlicerConstructor = SlicerCoreConstructor<ParallelSlicer>;
export type FetcherConstructor = OperationCoreConstructor<FetcherCore>;
export type ProcessorConstructor = OperationCoreConstructor<ProcessorCore>;
export type CoreOperation = FetcherCore | SlicerCore | ProcessorCore;
export interface OperationModule {
Schema: SchemaConstructor;
API?: OperationAPIConstructor;
}
export interface SchemaModule {
Schema: SchemaConstructor;
}
export type OperationAPIType = 'api' | 'observer';
export interface APIModule extends SchemaModule {
API: OperationAPIConstructor | ObserverConstructor;
type: OperationAPIType;
}
export interface ReaderModule extends OperationModule {
Slicer: SlicerConstructor;
Fetcher: FetcherConstructor;
}
export interface ProcessorModule extends OperationModule {
Processor: ProcessorConstructor;
}
|
apache-2.0
|
Veegn/talon
|
talon-biz/src/main/java/me/veegn/talon/biz/settings/service/SettingsManager.java
|
1635
|
package me.veegn.talon.biz.settings.service;
import me.veegn.talon.biz.settings.bean.SettingsEnv;
import java.io.File;
public interface SettingsManager {
/**
* 获取当前配置环境
* @return
*/
SettingsEnv getCurrentEvn();
String getValue(String name);
/**
* 根据名称获取当前配置
* @param evn 配置环境
* @param name 名称
* @return 配置值
*/
String getValue(SettingsEnv evn, String name);
/**
* 根据名称版本号获取当前配置
* @param evn 配置环境
* @param name 配置名称
* @param version 配置版本号
* @return 配置值
*/
String getValue(SettingsEnv evn, String name, String version);
/**
* 添加配置信息
* @param evn 配置环境
* @param name 配置名称
* @param value 配置值
* @param version 配置版本号
* @return 是否添加成功
*/
Boolean add(SettingsEnv evn, String name, String value, String version);
/**
* 修改配置信息
* @param evn 配置环境
* @param name 配置名称
* @param value 配置值
* @param version 配置版本号
* @return 是否添加成功
*/
Boolean update(SettingsEnv evn, String name, String value, String version);
/**
* 导入配置
* @param evn 环境
* @param file 配置文件
* @return 是否导入成功
*/
Boolean importSettings(SettingsEnv evn, File file);
/**
* 导出配置
* @param evn 环境
* @return 生成的配置文件
*/
File exportSettings(SettingsEnv evn);
}
|
apache-2.0
|
Labs64/NetLicensingClient-java
|
NetLicensingClient/src/main/java/com/labs64/netlicensing/domain/vo/Money.java
|
2746
|
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.labs64.netlicensing.domain.vo;
import java.math.BigDecimal;
import javax.xml.bind.DatatypeConverter;
import org.apache.commons.lang3.StringUtils;
import com.labs64.netlicensing.domain.Constants;
/**
* Holds amount of money with associated currency.
* <p>
* Consider more comprehensive implementation using one of:
* <ul>
* <li>http://joda-money.sourceforge.net/</li>
* <li>http://java.net/projects/javamoney</li>
* </ul>
*/
public class Money {
private BigDecimal amount;
private String currencyCode;
public BigDecimal getAmount() {
return amount;
}
public void setAmount(final BigDecimal amount) {
this.amount = amount;
}
public String getCurrencyCode() {
return currencyCode;
}
public void setCurrencyCode(final String currencyCode) {
this.currencyCode = currencyCode;
}
public static Money convertPrice(final String rawPrice, final String rawCurrency) {
final Money target = new Money();
if (StringUtils.isNotBlank(rawPrice)) {
try {
target.setAmount(DatatypeConverter.parseDecimal(rawPrice));
} catch (final NumberFormatException e) {
throw new IllegalArgumentException("'" + Constants.PRICE
+ "' format is not correct, expected '0.00' format.");
}
if (StringUtils.isNotBlank(rawCurrency)) {
if (Currency.parseValueSafe(rawCurrency) == null) {
throw new IllegalArgumentException("Unsupported currency.");
}
target.setCurrencyCode(rawCurrency);
} else {
throw new IllegalArgumentException("'" + Constants.PRICE + "' field must be accompanied with the '"
+ Constants.CURRENCY + "' field.");
}
} else { // 'price' is not provided
if (StringUtils.isNotBlank(rawCurrency)) {
throw new IllegalArgumentException("'" + Constants.CURRENCY + "' field can not be used without the '"
+ Constants.PRICE + "' field.");
}
}
return target;
}
}
|
apache-2.0
|
cmaere/lwb
|
templates/protostar/index3140.php
|
765
|
<?xml version="1.0" encoding="utf-8"?>
<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/"><ShortName>National Water Supply and Drainage Board</ShortName><Description>National Water Supply and Drainage Board</Description><InputEncoding>UTF-8</InputEncoding><Image type="image/vnd.microsoft.icon" width="16" height="16">http://waterboard.lk/web/templates/poora_temp/favicon.ico</Image><Url type="application/opensearchdescription+xml" rel="self" template="http://waterboard.lk/web/index.php?option=com_search&view=home&defaultmenu=354&Itemid=352&lang=si&format=opensearch"/><Url type="text/html" template="http://waterboard.lk/web/index.php?option=com_search&searchword={searchTerms}&Itemid=188"/></OpenSearchDescription>
|
apache-2.0
|
juanortiz10/ReportApp
|
app/src/main/java/com/example/juan/apportaofficial/Reportes.java
|
31560
|
package com.example.juan.apportaofficial;
import android.annotation.TargetApi;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreProtocolPNames;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
public class Reportes extends android.support.v4.app.Fragment implements View.OnClickListener {
private EditText etNombre,etReferencia, etDescripcion,etEmail,etEntre;
private ImageButton btnCargar, btnEnviar;
private Uri output;
private File file;
private String addressString = "No address found",lat="lat",lon="lon",foto,spnSelection,nameImage,postalCode="";
private String spnSub,idser;
private Spinner spn,spn1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.reportes, null);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
etNombre = (EditText) v.findViewById(R.id.etNombre);
etReferencia = (EditText) v.findViewById(R.id.etReferencia);
etDescripcion = (EditText) v.findViewById(R.id.etDescripcion);
etEmail=(EditText)v.findViewById(R.id.etEmail);
etEntre=(EditText)v.findViewById(R.id.etEntre);
spn=(Spinner)v.findViewById(R.id.spn);
spn.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
spn.setSelection(i);
spnSelection = (String) spn.getSelectedItem();
switch (spnSelection.trim()) {
case "Alumbrado Publico":
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(getActivity(),
R.array.alumbrado, android.R.layout.simple_spinner_item);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spn1.setAdapter(adapter1);
idser="1";
}
});
break;
case "Bacheo":
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(getActivity(),
R.array.bacheo, android.R.layout.simple_spinner_item);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spn1.setAdapter(adapter1);
idser="2";
}
});
break;
case "Contaminacion":
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(getActivity(),
R.array.contaminacion, android.R.layout.simple_spinner_item);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spn1.setAdapter(adapter1);
idser="3";
}
});
break;
case "Desazolve":
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(getActivity(),
R.array.desazolve, android.R.layout.simple_spinner_item);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spn1.setAdapter(adapter1);
idser="4";
}
});
break;
case "Deshierbe":
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(getActivity(),
R.array.deshierbe, android.R.layout.simple_spinner_item);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spn1.setAdapter(adapter1);
idser="5";
}
});
break;
case "Fumigacion":
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(getActivity(),
R.array.fumigacion, android.R.layout.simple_spinner_item);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spn1.setAdapter(adapter1);
idser="6";
}
});
break;
case "Lotes Valdios":
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(getActivity(),
R.array.lotes, android.R.layout.simple_spinner_item);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spn1.setAdapter(adapter1);
idser="7";
}
});
break;
case "Plazas":
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(getActivity(),
R.array.plazas, android.R.layout.simple_spinner_item);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spn1.setAdapter(adapter1);
idser="8";
}
});
break;
case "Obstruccion de Via":
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(getActivity(),
R.array.obstruccion, android.R.layout.simple_spinner_item);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spn1.setAdapter(adapter1);
idser="9";
}
});
break;
case "Puentes Peatonales":
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(getActivity(),
R.array.puentes, android.R.layout.simple_spinner_item);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spn1.setAdapter(adapter1);
idser="10";
}
});
break;
case "Recarpeteo":
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(getActivity(),
R.array.recarpeteo, android.R.layout.simple_spinner_item);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spn1.setAdapter(adapter1);
idser="11";
}
});
break;
case "Basura":
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(getActivity(),
R.array.basura, android.R.layout.simple_spinner_item);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spn1.setAdapter(adapter1);
idser="12";
}
});
break;
case "Ruido Excesivo":
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(getActivity(),
R.array.ruido, android.R.layout.simple_spinner_item);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spn1.setAdapter(adapter1);
idser="13";
}
});
break;
case "Seguridad Publica":
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(getActivity(),
R.array.seguridad, android.R.layout.simple_spinner_item);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spn1.setAdapter(adapter1);
idser="14";
}
});
break;
case "Señalamientos Viales":
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(getActivity(),
R.array.senalamientos, android.R.layout.simple_spinner_item);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spn1.setAdapter(adapter1);
idser="15";
}
});
break;
case "Otros Servicios":
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(getActivity(),
R.array.otros, android.R.layout.simple_spinner_item);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spn1.setAdapter(adapter1);
}
});
break;
}
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.spn_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spn.setAdapter(adapter);
spn1=(Spinner)v.findViewById(R.id.spn1);
spn1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
spn1.setSelection(i);
spnSub = (String) spn1.getSelectedItem();
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(getActivity(),
R.array.defau,android.R.layout.simple_spinner_item);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spn1.setAdapter(adapter1);
btnCargar = (ImageButton) v.findViewById(R.id.btnCargar);
btnEnviar = (ImageButton) v.findViewById(R.id.btnEnviar);
btnEnviar.setOnClickListener(this);
btnCargar.setOnClickListener(this);
LocationManager locationManager;
locationManager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
updateWithNewLocation(location);
return v;
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnCargar:
if (!etNombre.getText().toString().trim().equalsIgnoreCase("")) {
getCamera();
} else {
Toast.makeText(getActivity().getApplicationContext(), "No Agregaste Nombre a la foto", Toast.LENGTH_LONG).show();
}
break;
case R.id.btnEnviar:
if (areFull()) {
InputStream is = null;
String nombre = etEmail.getText().toString();
String refe = etReferencia.getText().toString();
String desc = etDescripcion.getText().toString();
String entre= etEntre.getText().toString();
String cat=spnSelection+spnSub;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("email", nombre));
nameValuePairs.add(new BasicNameValuePair("dire", addressString));
nameValuePairs.add(new BasicNameValuePair("refe", refe));
nameValuePairs.add(new BasicNameValuePair("des", desc));
nameValuePairs.add(new BasicNameValuePair("lat", lat));
nameValuePairs.add(new BasicNameValuePair("lon", lon));
nameValuePairs.add(new BasicNameValuePair("tipo", cat));
nameValuePairs.add(new BasicNameValuePair("nameIm",etNombre.getText().toString().trim() + ".jpg"));
nameValuePairs.add(new BasicNameValuePair("codigo",postalCode));
nameValuePairs.add(new BasicNameValuePair("entre",entre));
nameValuePairs.add(new BasicNameValuePair("id_ser",idser));
try {
if (file.exists()) new ServerUpdate().execute();
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://reportapp.org/connection/connection.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Toast.makeText(getActivity().getApplicationContext(), "Reporte agregado correctamente", Toast.LENGTH_LONG).show();
Intent act = new Intent();
act.setClass(getActivity(), Success.class);
getActivity().startActivity(act);
} catch (Exception ex) {
Log.e("Client Protocol", "Log_Tag");
ex.printStackTrace();
}
}else{
Toast.makeText(getActivity().getApplicationContext(),"Verifica que hayas llenado todos los campos",Toast.LENGTH_SHORT).show();
}
}
}
private void getCamera() {
foto = Environment.getExternalStorageDirectory() + "/" + etNombre.getText().toString().trim() + ".jpg";
file = new File(foto);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
output = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, output);
startActivityForResult(intent, 1);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
ContentResolver cr = getActivity().getContentResolver();
Bitmap bit = null;
try {
bit = android.provider.MediaStore.Images.Media.getBitmap(cr, output);
int rotate = 0;
ExifInterface exif = new ExifInterface(file.getAbsolutePath());
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
}
Matrix matrix = new Matrix();
matrix.postRotate(rotate);
bit = Bitmap.createBitmap(bit, 0, 0, bit.getWidth(), bit.getHeight(), matrix, true);
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void uploadFoto(String imag) {
HttpClient httpClient = new DefaultHttpClient();
httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httpPost = new HttpPost("http://reportapp.org/connection/FileUpload.php");
MultipartEntity mpEntity = new MultipartEntity();
ContentBody foto = new FileBody(file, "imag.jpeg");
mpEntity.addPart("fotoUp", foto);
httpPost.setEntity(mpEntity);
try {
httpClient.execute(httpPost);
httpClient.getConnectionManager().shutdown();
} catch (Exception ex) {
ex.printStackTrace();
}
}
class ServerUpdate extends AsyncTask<String, String, String> {
ProgressDialog progressDialog;
@Override
protected String doInBackground(String... strings) {
uploadFoto(foto);
if(onInsert())
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getActivity().getApplicationContext(), "Error al subir la imagen", Toast.LENGTH_LONG).show();
}
});
return null;
}
protected void onPostExecute(String result){
super.onPostExecute(result);
progressDialog.dismiss();
}
protected void onPreExecute(){
super.onPreExecute();
progressDialog=new ProgressDialog(getActivity());
progressDialog.setMessage("Espera un momento...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.show();
}
}
private boolean onInsert(){
HttpClient httpClient;
List<NameValuePair> nameValuePairs;
HttpPost httpPost;
httpClient=new DefaultHttpClient();
httpPost=new HttpPost("http://reportapp.org/connection/InsertImagen.php");
nameValuePairs=new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("imagen",etNombre.getText().toString().trim()+".jpg"));
nameImage=etNombre.getText().toString().trim()+".jpg";
try{
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpClient.execute(httpPost);
}catch(Exception ex){
ex.printStackTrace();
}
return false;
}
private void updateWithNewLocation(Location location) {
DecimalFormat df = new DecimalFormat("##.00");
if (location != null) {
double lati = location.getLatitude();
double lngi = location.getLongitude();
lat= String.valueOf(lati);
lon= String.valueOf(lngi);
Geocoder gc = new Geocoder(getActivity(), Locale.getDefault());
try {
List<Address> addresses = gc.getFromLocation(lati, lngi, 1);
if (addresses.size() == 1) {
addressString = "";
Address address = addresses.get(0);
addressString = addressString + address.getAddressLine(0) + "\n";
for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
addressString = addressString + address.getAddressLine(i) + "\n";
}
addressString = addressString + address.getCountryName() + "\n"+address.getLocale()+"\n"+address.getSubLocality();
postalCode=address.getPostalCode();
}
} catch (IOException ioe) {
Log.e("Geocoder IOException exception: ", ioe.getMessage());
}
}
}
private boolean areFull(){
boolean request = false;
if (etNombre.getText().toString().trim().equals("") ||etReferencia.getText().toString().trim().equals("") || etDescripcion.getText().toString().trim().equals("") ||etEmail.getText().toString().trim().equals("") ||etEntre.getText().toString().trim().equals("")){
}else{
request=true;
}
return request;
}
}
|
apache-2.0
|
SmartI18N/SmartI18N
|
smarti18n/smarti18n-editor/src/main/java/org/smarti18n/editor/views/ProjectMessageEditView.java
|
2863
|
package org.smarti18n.editor.views;
import com.vaadin.data.Binder;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener;
import com.vaadin.spring.annotation.SpringView;
import com.vaadin.spring.annotation.UIScope;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Panel;
import com.vaadin.ui.VerticalLayout;
import javax.annotation.PostConstruct;
import org.smarti18n.vaadin.components.LabelField;
import org.smarti18n.editor.controller.EditorController;
import org.smarti18n.models.Message;
import org.smarti18n.vaadin.components.CancelButton;
import org.smarti18n.vaadin.components.LocaleTextAreas;
import org.smarti18n.vaadin.components.SaveButton;
/**
* @author Marc Bellmann <marc.bellmann@googlemail.com>
*/
@UIScope
@SpringView(name = ProjectMessageEditView.VIEW_NAME)
public class ProjectMessageEditView extends AbstractProjectView implements View {
public static final String VIEW_NAME = "messages/edit";
private final Binder<Message> binder;
public ProjectMessageEditView(final EditorController editorController) {
super(editorController);
this.binder = new Binder<>(Message.class);
}
@PostConstruct
void init() {
super.init(translate("smarti18n.editor.message-edit.caption"));
setSizeFull();
final LabelField keyField = new LabelField();
final LocaleTextAreas localeTextAreas = new LocaleTextAreas();
this.binder.forField(keyField).bind("key");
this.binder.forMemberField(localeTextAreas).bind("translations");
this.binder.bindInstanceFields(this);
final VerticalLayout layout = new VerticalLayout(keyField, localeTextAreas);
layout.setMargin(true);
final Panel panel = new Panel(layout);
addComponent(panel);
setExpandRatio(panel, 1f);
}
@Override
protected HorizontalLayout createButtonBar() {
final SaveButton buttonSave = new SaveButton(
this.editorController.clickSaveTranslation(binder, projectContext, () -> navigateTo(ProjectMessagesView.VIEW_NAME, projectId()))
);
final CancelButton buttonCancel = new CancelButton(
clickEvent -> navigateTo(ProjectMessagesView.VIEW_NAME, projectId())
);
return new HorizontalLayout(buttonSave, buttonCancel);
}
@Override
public void enter(final ViewChangeListener.ViewChangeEvent viewChangeEvent) {
final String[] parameters = viewChangeEvent.getParameters().split("/");
this.projectContext.setProject(
this.editorController.getProject(parameters[0])
);
this.binder.readBean(
this.editorController.getMessage(projectId(), parameters[1])
);
}
private String projectId() {
return this.projectContext.getProjectId();
}
}
|
apache-2.0
|
jt70471/aws-sdk-cpp
|
aws-cpp-sdk-ecs/source/model/CreateClusterRequest.cpp
|
2827
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/ecs/model/CreateClusterRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::ECS::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
CreateClusterRequest::CreateClusterRequest() :
m_clusterNameHasBeenSet(false),
m_tagsHasBeenSet(false),
m_settingsHasBeenSet(false),
m_capacityProvidersHasBeenSet(false),
m_defaultCapacityProviderStrategyHasBeenSet(false)
{
}
Aws::String CreateClusterRequest::SerializePayload() const
{
JsonValue payload;
if(m_clusterNameHasBeenSet)
{
payload.WithString("clusterName", m_clusterName);
}
if(m_tagsHasBeenSet)
{
Array<JsonValue> tagsJsonList(m_tags.size());
for(unsigned tagsIndex = 0; tagsIndex < tagsJsonList.GetLength(); ++tagsIndex)
{
tagsJsonList[tagsIndex].AsObject(m_tags[tagsIndex].Jsonize());
}
payload.WithArray("tags", std::move(tagsJsonList));
}
if(m_settingsHasBeenSet)
{
Array<JsonValue> settingsJsonList(m_settings.size());
for(unsigned settingsIndex = 0; settingsIndex < settingsJsonList.GetLength(); ++settingsIndex)
{
settingsJsonList[settingsIndex].AsObject(m_settings[settingsIndex].Jsonize());
}
payload.WithArray("settings", std::move(settingsJsonList));
}
if(m_capacityProvidersHasBeenSet)
{
Array<JsonValue> capacityProvidersJsonList(m_capacityProviders.size());
for(unsigned capacityProvidersIndex = 0; capacityProvidersIndex < capacityProvidersJsonList.GetLength(); ++capacityProvidersIndex)
{
capacityProvidersJsonList[capacityProvidersIndex].AsString(m_capacityProviders[capacityProvidersIndex]);
}
payload.WithArray("capacityProviders", std::move(capacityProvidersJsonList));
}
if(m_defaultCapacityProviderStrategyHasBeenSet)
{
Array<JsonValue> defaultCapacityProviderStrategyJsonList(m_defaultCapacityProviderStrategy.size());
for(unsigned defaultCapacityProviderStrategyIndex = 0; defaultCapacityProviderStrategyIndex < defaultCapacityProviderStrategyJsonList.GetLength(); ++defaultCapacityProviderStrategyIndex)
{
defaultCapacityProviderStrategyJsonList[defaultCapacityProviderStrategyIndex].AsObject(m_defaultCapacityProviderStrategy[defaultCapacityProviderStrategyIndex].Jsonize());
}
payload.WithArray("defaultCapacityProviderStrategy", std::move(defaultCapacityProviderStrategyJsonList));
}
return payload.View().WriteReadable();
}
Aws::Http::HeaderValueCollection CreateClusterRequest::GetRequestSpecificHeaders() const
{
Aws::Http::HeaderValueCollection headers;
headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "AmazonEC2ContainerServiceV20141113.CreateCluster"));
return headers;
}
|
apache-2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.