repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
dmDen/StockSharp | Samples/Common/SampleUnit/Program.cs | 3557 | #region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: SampleUnit.SampleUnitPublic
File: Program.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace SampleUnit
{
using System;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
class Program
{
static void Main()
{
// test instrument with pips = 1 cent and points = 10 usd
var security = new Security
{
Id = "AAPL@NASDAQ",
StepPrice = 10,
PriceStep = 0.01m,
};
var absolute = new Unit(30);
var percent = 30.0.Percents();
var pips = 30.0.Pips(security);
var point = 30.0.Points(security);
Console.WriteLine("absolute = " + absolute);
Console.WriteLine("percent = " + percent);
Console.WriteLine("pips = " + pips);
Console.WriteLine("point = " + point);
Console.WriteLine();
// test values as a $90
const decimal testValue = 90m;
// or using this notation
// var testValue = (decimal)new Unit { Value = 90 };
Console.WriteLine("testValue = " + testValue);
Console.WriteLine();
// addition of all values
Console.WriteLine("testValue + absolute = " + (testValue + absolute));
Console.WriteLine("testValue + percent = " + (testValue + percent));
Console.WriteLine("testValue + pips = " + (testValue + pips));
Console.WriteLine("testValue + point = " + (testValue + point));
Console.WriteLine();
// multiplication of all values
Console.WriteLine("testValue * absolute = " + (testValue * absolute));
Console.WriteLine("testValue * percent = " + (testValue * percent));
Console.WriteLine("testValue * pips = " + (testValue * pips));
Console.WriteLine("testValue * point = " + (testValue * point));
Console.WriteLine();
// subtraction of values
Console.WriteLine("testValue - absolute = " + (testValue - absolute));
Console.WriteLine("testValue - percent = " + (testValue - percent));
Console.WriteLine("testValue - pips = " + (testValue - pips));
Console.WriteLine("testValue - point = " + (testValue - point));
Console.WriteLine();
// division of all values
Console.WriteLine("testValue / absolute = " + (testValue / absolute));
Console.WriteLine("testValue / percent = " + (testValue / percent));
Console.WriteLine("testValue / pips = " + (testValue / pips));
Console.WriteLine("testValue / point = " + (testValue / point));
Console.WriteLine();
// addition of pips and points
var resultPipsPoint = pips + point;
// and casting to decimal
var resultPipsPointDecimal = (decimal)resultPipsPoint;
Console.WriteLine("pips + point = " + resultPipsPoint);
Console.WriteLine("(decimal)(pips + point) = " + resultPipsPointDecimal);
Console.WriteLine();
// addition of pips and percents
var resultPipsPercents = pips + percent;
// and casting to decimal
var resultPipsPercentsDecimal = (decimal)resultPipsPercents;
Console.WriteLine("pips + percent = " + resultPipsPercents);
Console.WriteLine("(decimal)(pips + percent) = " + resultPipsPercentsDecimal);
Console.WriteLine();
}
}
} | apache-2.0 |
aosp-mirror/platform_frameworks_support | leanback/src/main/java/androidx/leanback/widget/OnActionClickedListener.java | 895 | /*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package androidx.leanback.widget;
/**
* Interface for receiving notification when an {@link Action} is clicked.
*/
public interface OnActionClickedListener {
/**
* Callback fired when the host fragment receives an action.
*/
void onActionClicked(Action action);
}
| apache-2.0 |
porcelli-forks/uberfire | uberfire-extensions/uberfire-social-activities/uberfire-social-activities-backend/src/main/java/org/ext/uberfire/social/activities/repository/SampleSocialUserEvent.java | 675 | /*
* Copyright 2015 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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.ext.uberfire.social.activities.repository;
public class SampleSocialUserEvent {
}
| apache-2.0 |
gangliao/Paddle | demo/semantic_role_labeling/api_train_v2.py | 6243 | import sys
import math
import numpy as np
import paddle.v2 as paddle
import paddle.v2.dataset.conll05 as conll05
def db_lstm():
word_dict, verb_dict, label_dict = conll05.get_dict()
word_dict_len = len(word_dict)
label_dict_len = len(label_dict)
pred_len = len(verb_dict)
mark_dict_len = 2
word_dim = 32
mark_dim = 5
hidden_dim = 512
depth = 8
#8 features
def d_type(size):
return paddle.data_type.integer_value_sequence(size)
word = paddle.layer.data(name='word_data', type=d_type(word_dict_len))
predicate = paddle.layer.data(name='verb_data', type=d_type(pred_len))
ctx_n2 = paddle.layer.data(name='ctx_n2_data', type=d_type(word_dict_len))
ctx_n1 = paddle.layer.data(name='ctx_n1_data', type=d_type(word_dict_len))
ctx_0 = paddle.layer.data(name='ctx_0_data', type=d_type(word_dict_len))
ctx_p1 = paddle.layer.data(name='ctx_p1_data', type=d_type(word_dict_len))
ctx_p2 = paddle.layer.data(name='ctx_p2_data', type=d_type(word_dict_len))
mark = paddle.layer.data(name='mark_data', type=d_type(mark_dict_len))
target = paddle.layer.data(name='target', type=d_type(label_dict_len))
default_std = 1 / math.sqrt(hidden_dim) / 3.0
emb_para = paddle.attr.Param(name='emb', initial_std=0., learning_rate=0.)
std_0 = paddle.attr.Param(initial_std=0.)
std_default = paddle.attr.Param(initial_std=default_std)
predicate_embedding = paddle.layer.embedding(
size=word_dim,
input=predicate,
param_attr=paddle.attr.Param(
name='vemb', initial_std=default_std))
mark_embedding = paddle.layer.embedding(
size=mark_dim, input=mark, param_attr=std_0)
word_input = [word, ctx_n2, ctx_n1, ctx_0, ctx_p1, ctx_p2]
emb_layers = [
paddle.layer.embedding(
size=word_dim, input=x, param_attr=emb_para) for x in word_input
]
emb_layers.append(predicate_embedding)
emb_layers.append(mark_embedding)
hidden_0 = paddle.layer.mixed(
size=hidden_dim,
bias_attr=std_default,
input=[
paddle.layer.full_matrix_projection(
input=emb, param_attr=std_default) for emb in emb_layers
])
mix_hidden_lr = 1e-3
lstm_para_attr = paddle.attr.Param(initial_std=0.0, learning_rate=1.0)
hidden_para_attr = paddle.attr.Param(
initial_std=default_std, learning_rate=mix_hidden_lr)
lstm_0 = paddle.layer.lstmemory(
input=hidden_0,
act=paddle.activation.Relu(),
gate_act=paddle.activation.Sigmoid(),
state_act=paddle.activation.Sigmoid(),
bias_attr=std_0,
param_attr=lstm_para_attr)
#stack L-LSTM and R-LSTM with direct edges
input_tmp = [hidden_0, lstm_0]
for i in range(1, depth):
mix_hidden = paddle.layer.mixed(
size=hidden_dim,
bias_attr=std_default,
input=[
paddle.layer.full_matrix_projection(
input=input_tmp[0], param_attr=hidden_para_attr),
paddle.layer.full_matrix_projection(
input=input_tmp[1], param_attr=lstm_para_attr)
])
lstm = paddle.layer.lstmemory(
input=mix_hidden,
act=paddle.activation.Relu(),
gate_act=paddle.activation.Sigmoid(),
state_act=paddle.activation.Sigmoid(),
reverse=((i % 2) == 1),
bias_attr=std_0,
param_attr=lstm_para_attr)
input_tmp = [mix_hidden, lstm]
feature_out = paddle.layer.mixed(
size=label_dict_len,
bias_attr=std_default,
input=[
paddle.layer.full_matrix_projection(
input=input_tmp[0], param_attr=hidden_para_attr),
paddle.layer.full_matrix_projection(
input=input_tmp[1], param_attr=lstm_para_attr)
], )
crf_cost = paddle.layer.crf(size=label_dict_len,
input=feature_out,
label=target,
param_attr=paddle.attr.Param(
name='crfw',
initial_std=default_std,
learning_rate=mix_hidden_lr))
crf_dec = paddle.layer.crf_decoding(
name='crf_dec_l',
size=label_dict_len,
input=feature_out,
label=target,
param_attr=paddle.attr.Param(name='crfw'))
return crf_cost, crf_dec
def load_parameter(file_name, h, w):
with open(file_name, 'rb') as f:
f.read(16) # skip header.
return np.fromfile(f, dtype=np.float32).reshape(h, w)
def main():
paddle.init(use_gpu=False, trainer_count=1)
# define network topology
crf_cost, crf_dec = db_lstm()
# create parameters
parameters = paddle.parameters.create([crf_cost, crf_dec])
# create optimizer
optimizer = paddle.optimizer.Momentum(
momentum=0,
learning_rate=2e-2,
regularization=paddle.optimizer.L2Regularization(rate=8e-4),
model_average=paddle.optimizer.ModelAverage(
average_window=0.5, max_average_window=10000), )
def event_handler(event):
if isinstance(event, paddle.event.EndIteration):
if event.batch_id % 100 == 0:
print "Pass %d, Batch %d, Cost %f, %s" % (
event.pass_id, event.batch_id, event.cost, event.metrics)
trainer = paddle.trainer.SGD(cost=crf_cost,
parameters=parameters,
update_equation=optimizer)
parameters.set('emb', load_parameter(conll05.get_embedding(), 44068, 32))
trn_reader = paddle.batch(
paddle.reader.shuffle(
conll05.test(), buf_size=8192), batch_size=10)
feeding = {
'word_data': 0,
'ctx_n2_data': 1,
'ctx_n1_data': 2,
'ctx_0_data': 3,
'ctx_p1_data': 4,
'ctx_p2_data': 5,
'verb_data': 6,
'mark_data': 7,
'target': 8
}
trainer.train(
reader=trn_reader,
event_handler=event_handler,
num_passes=10000,
feeding=feeding)
if __name__ == '__main__':
main()
| apache-2.0 |
ryano144/intellij-community | java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/StandardInstructionVisitor.java | 27474 | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInspection.dataFlow;
import com.intellij.codeInspection.dataFlow.instructions.*;
import com.intellij.codeInspection.dataFlow.value.*;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Pair;
import com.intellij.psi.*;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.TypeConversionUtil;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.FactoryMap;
import com.intellij.util.containers.MultiMap;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import static com.intellij.psi.JavaTokenType.*;
/**
* @author peter
*/
public class StandardInstructionVisitor extends InstructionVisitor {
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInspection.dataFlow.StandardInstructionVisitor");
private static final Object ANY_VALUE = new Object();
private final Set<BinopInstruction> myReachable = new THashSet<BinopInstruction>();
private final Set<BinopInstruction> myCanBeNullInInstanceof = new THashSet<BinopInstruction>();
private final MultiMap<PushInstruction, Object> myPossibleVariableValues = MultiMap.createSet();
private final Set<PsiElement> myNotToReportReachability = new THashSet<PsiElement>();
private final Set<InstanceofInstruction> myUsefulInstanceofs = new THashSet<InstanceofInstruction>();
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
private final FactoryMap<MethodCallInstruction, Nullness> myReturnTypeNullability = new FactoryMap<MethodCallInstruction, Nullness>() {
@Override
protected Nullness create(MethodCallInstruction key) {
final PsiCallExpression callExpression = key.getCallExpression();
if (callExpression instanceof PsiNewExpression) {
return Nullness.NOT_NULL;
}
return callExpression != null ? DfaPsiUtil.getElementNullability(key.getResultType(), callExpression.resolveMethod()) : null;
}
};
@Override
public DfaInstructionState[] visitAssign(AssignInstruction instruction, DataFlowRunner runner, DfaMemoryState memState) {
DfaValue dfaSource = memState.pop();
DfaValue dfaDest = memState.pop();
if (dfaDest instanceof DfaVariableValue) {
DfaVariableValue var = (DfaVariableValue) dfaDest;
DfaValueFactory factory = runner.getFactory();
if (dfaSource instanceof DfaVariableValue && factory.getVarFactory().getAllQualifiedBy(var).contains(dfaSource)) {
Nullness nullability = memState.isNotNull(dfaSource) ? Nullness.NOT_NULL
: ((DfaVariableValue)dfaSource).getInherentNullability();
dfaSource = factory.createTypeValue(((DfaVariableValue)dfaSource).getVariableType(), nullability);
}
if (var.getInherentNullability() == Nullness.NOT_NULL) {
checkNotNullable(memState, dfaSource, NullabilityProblem.assigningToNotNull, instruction.getRExpression());
}
final PsiModifierListOwner psi = var.getPsiVariable();
if (!(psi instanceof PsiField) || !psi.hasModifierProperty(PsiModifier.VOLATILE)) {
memState.setVarValue(var, dfaSource);
}
if (var.getInherentNullability() == Nullness.NULLABLE && !memState.isNotNull(dfaSource) && instruction.isVariableInitializer()) {
DfaMemoryStateImpl stateImpl = (DfaMemoryStateImpl)memState;
stateImpl.setVariableState(var, stateImpl.getVariableState(var).withNullability(Nullness.NULLABLE));
}
} else if (dfaDest instanceof DfaTypeValue && ((DfaTypeValue)dfaDest).isNotNull()) {
checkNotNullable(memState, dfaSource, NullabilityProblem.assigningToNotNull, instruction.getRExpression());
}
memState.push(dfaDest);
return nextInstruction(instruction, runner, memState);
}
@Override
public DfaInstructionState[] visitCheckReturnValue(CheckReturnValueInstruction instruction,
DataFlowRunner runner,
DfaMemoryState memState) {
final DfaValue retValue = memState.pop();
checkNotNullable(memState, retValue, NullabilityProblem.nullableReturn, instruction.getReturn());
return nextInstruction(instruction, runner, memState);
}
@Override
public DfaInstructionState[] visitFieldReference(FieldReferenceInstruction instruction, DataFlowRunner runner, DfaMemoryState memState) {
final DfaValue qualifier = memState.pop();
if (!checkNotNullable(memState, qualifier, NullabilityProblem.fieldAccessNPE, instruction.getElementToAssert())) {
forceNotNull(runner, memState, qualifier);
}
return nextInstruction(instruction, runner, memState);
}
@Override
public DfaInstructionState[] visitPush(PushInstruction instruction, DataFlowRunner runner, DfaMemoryState memState) {
if (!instruction.isReferenceWrite() && instruction.getPlace() instanceof PsiReferenceExpression) {
DfaValue dfaValue = instruction.getValue();
if (dfaValue instanceof DfaVariableValue) {
DfaConstValue constValue = memState.getConstantValue((DfaVariableValue)dfaValue);
myPossibleVariableValues.putValue(instruction, constValue != null && (constValue.getValue() == null || constValue.getValue() instanceof Boolean) ? constValue : ANY_VALUE);
}
}
return super.visitPush(instruction, runner, memState);
}
public List<Pair<PsiReferenceExpression, DfaConstValue>> getConstantReferenceValues() {
List<Pair<PsiReferenceExpression, DfaConstValue>> result = ContainerUtil.newArrayList();
for (PushInstruction instruction : myPossibleVariableValues.keySet()) {
Collection<Object> values = myPossibleVariableValues.get(instruction);
if (values.size() == 1) {
Object singleValue = values.iterator().next();
if (singleValue != ANY_VALUE) {
result.add(Pair.create((PsiReferenceExpression)instruction.getPlace(), (DfaConstValue)singleValue));
}
}
}
return result;
}
@Override
public DfaInstructionState[] visitTypeCast(TypeCastInstruction instruction, DataFlowRunner runner, DfaMemoryState memState) {
final DfaValueFactory factory = runner.getFactory();
DfaValue dfaExpr = factory.createValue(instruction.getCasted());
if (dfaExpr != null) {
DfaTypeValue dfaType = (DfaTypeValue)factory.createTypeValue(instruction.getCastTo(), Nullness.UNKNOWN);
DfaRelationValue dfaInstanceof = factory.getRelationFactory().createRelation(dfaExpr, dfaType, INSTANCEOF_KEYWORD, false);
if (dfaInstanceof != null && !memState.applyInstanceofOrNull(dfaInstanceof)) {
onInstructionProducesCCE(instruction);
}
}
if (instruction.getCastTo() instanceof PsiPrimitiveType) {
memState.push(runner.getFactory().getBoxedFactory().createUnboxed(memState.pop()));
}
return nextInstruction(instruction, runner, memState);
}
protected void onInstructionProducesCCE(TypeCastInstruction instruction) {}
@Override
public DfaInstructionState[] visitMethodCall(final MethodCallInstruction instruction, final DataFlowRunner runner, final DfaMemoryState memState) {
DfaValue[] argValues = popCallArguments(instruction, runner, memState);
final DfaValue qualifier = popQualifier(instruction, runner, memState);
LinkedHashSet<DfaMemoryState> currentStates = ContainerUtil.newLinkedHashSet(memState);
Set<DfaMemoryState> finalStates = ContainerUtil.newLinkedHashSet();
if (argValues != null) {
for (MethodContract contract : instruction.getContracts()) {
currentStates = addContractResults(argValues, contract, currentStates, instruction, runner.getFactory(), finalStates);
if (currentStates.size() + finalStates.size() > DataFlowRunner.MAX_STATES_PER_BRANCH) {
if (LOG.isDebugEnabled()) {
LOG.debug("Too complex contract on " + instruction.getContext() + ", skipping contract processing");
}
finalStates.clear();
currentStates = ContainerUtil.newLinkedHashSet(memState);
break;
}
}
}
for (DfaMemoryState state : currentStates) {
state.push(getMethodResultValue(instruction, qualifier, runner.getFactory()));
finalStates.add(state);
}
DfaInstructionState[] result = new DfaInstructionState[finalStates.size()];
int i = 0;
for (DfaMemoryState state : finalStates) {
if (instruction.shouldFlushFields()) {
state.flushFields();
}
result[i++] = new DfaInstructionState(runner.getInstruction(instruction.getIndex() + 1), state);
}
return result;
}
@Nullable
private DfaValue[] popCallArguments(MethodCallInstruction instruction, DataFlowRunner runner, DfaMemoryState memState) {
final PsiExpression[] args = instruction.getArgs();
PsiMethod method = instruction.getTargetMethod();
boolean varargCall = instruction.isVarArgCall();
DfaValue[] argValues;
if (method == null || instruction.getContracts().isEmpty()) {
argValues = null;
} else {
int paramCount = method.getParameterList().getParametersCount();
if (paramCount == args.length || method.isVarArgs() && args.length >= paramCount - 1) {
argValues = new DfaValue[paramCount];
if (varargCall) {
argValues[paramCount - 1] = DfaUnknownValue.getInstance();
}
} else {
argValues = null;
}
}
for (int i = 0; i < args.length; i++) {
final DfaValue arg = memState.pop();
int paramIndex = args.length - i - 1;
if (argValues != null && (paramIndex < argValues.length - 1 || !varargCall)) {
argValues[paramIndex] = arg;
}
PsiExpression expr = args[paramIndex];
Nullness requiredNullability = instruction.getArgRequiredNullability(expr);
if (requiredNullability == Nullness.NOT_NULL) {
if (!checkNotNullable(memState, arg, NullabilityProblem.passingNullableToNotNullParameter, expr)) {
forceNotNull(runner, memState, arg);
}
}
else if (!instruction.updateOfNullable(memState, arg) && requiredNullability == Nullness.UNKNOWN) {
checkNotNullable(memState, arg, NullabilityProblem.passingNullableArgumentToNonAnnotatedParameter, expr);
}
}
return argValues;
}
private DfaValue popQualifier(MethodCallInstruction instruction, DataFlowRunner runner, DfaMemoryState memState) {
@NotNull final DfaValue qualifier = memState.pop();
boolean unboxing = instruction.getMethodType() == MethodCallInstruction.MethodType.UNBOXING;
NullabilityProblem problem = unboxing ? NullabilityProblem.unboxingNullable : NullabilityProblem.callNPE;
PsiExpression anchor = unboxing ? instruction.getContext() : instruction.getCallExpression();
if (!checkNotNullable(memState, qualifier, problem, anchor)) {
forceNotNull(runner, memState, qualifier);
}
return qualifier;
}
private LinkedHashSet<DfaMemoryState> addContractResults(DfaValue[] argValues,
MethodContract contract,
LinkedHashSet<DfaMemoryState> states,
MethodCallInstruction instruction,
DfaValueFactory factory,
Set<DfaMemoryState> finalStates) {
DfaConstValue.Factory constFactory = factory.getConstFactory();
LinkedHashSet<DfaMemoryState> falseStates = ContainerUtil.newLinkedHashSet();
for (int i = 0; i < argValues.length; i++) {
DfaValue argValue = argValues[i];
MethodContract.ValueConstraint constraint = contract.arguments[i];
DfaConstValue expectedValue = constraint.getComparisonValue(factory);
if (expectedValue == null) continue;
boolean nullContract = expectedValue == constFactory.getNull();
boolean invertCondition = constraint.shouldUseNonEqComparison();
DfaValue condition = factory.getRelationFactory().createRelation(argValue, expectedValue, EQEQ, invertCondition);
if (condition == null) {
if (!(argValue instanceof DfaConstValue)) {
for (DfaMemoryState state : states) {
DfaMemoryState falseCopy = state.createCopy();
if (nullContract) {
(invertCondition ? falseCopy : state).markEphemeral();
}
falseStates.add(falseCopy);
}
continue;
}
condition = constFactory.createFromValue((argValue == expectedValue) != invertCondition, PsiType.BOOLEAN, null);
}
LinkedHashSet<DfaMemoryState> nextStates = ContainerUtil.newLinkedHashSet();
for (DfaMemoryState state : states) {
boolean unknownVsNull = nullContract &&
argValue instanceof DfaVariableValue &&
((DfaMemoryStateImpl)state).getVariableState((DfaVariableValue)argValue).getNullability() == Nullness.UNKNOWN;
DfaMemoryState falseCopy = state.createCopy();
if (state.applyCondition(condition)) {
if (unknownVsNull && !invertCondition) {
state.markEphemeral();
}
nextStates.add(state);
}
if (falseCopy.applyCondition(condition.createNegated())) {
if (unknownVsNull && invertCondition) {
falseCopy.markEphemeral();
}
falseStates.add(falseCopy);
}
}
states = nextStates;
}
for (DfaMemoryState state : states) {
state.push(getDfaContractReturnValue(contract, instruction, factory));
finalStates.add(state);
}
return falseStates;
}
private DfaValue getDfaContractReturnValue(MethodContract contract,
MethodCallInstruction instruction,
DfaValueFactory factory) {
switch (contract.returnValue) {
case NULL_VALUE: return factory.getConstFactory().getNull();
case NOT_NULL_VALUE: return factory.createTypeValue(instruction.getResultType(), Nullness.NOT_NULL);
case TRUE_VALUE: return factory.getConstFactory().getTrue();
case FALSE_VALUE: return factory.getConstFactory().getFalse();
case THROW_EXCEPTION: return factory.getConstFactory().getContractFail();
default: return getMethodResultValue(instruction, null, factory);
}
}
private static void forceNotNull(DataFlowRunner runner, DfaMemoryState memState, DfaValue arg) {
if (arg instanceof DfaVariableValue) {
DfaVariableValue var = (DfaVariableValue)arg;
memState.setVarValue(var, runner.getFactory().createTypeValue(var.getVariableType(), Nullness.NOT_NULL));
}
}
@NotNull
private DfaValue getMethodResultValue(MethodCallInstruction instruction, @Nullable DfaValue qualifierValue, DfaValueFactory factory) {
DfaValue precalculated = instruction.getPrecalculatedReturnValue();
if (precalculated != null) {
return precalculated;
}
final PsiType type = instruction.getResultType();
final MethodCallInstruction.MethodType methodType = instruction.getMethodType();
if (methodType == MethodCallInstruction.MethodType.UNBOXING) {
return factory.getBoxedFactory().createUnboxed(qualifierValue);
}
if (methodType == MethodCallInstruction.MethodType.BOXING) {
DfaValue boxed = factory.getBoxedFactory().createBoxed(qualifierValue);
return boxed == null ? factory.createTypeValue(type, Nullness.NOT_NULL) : boxed;
}
if (methodType == MethodCallInstruction.MethodType.CAST) {
assert qualifierValue != null;
if (qualifierValue instanceof DfaConstValue) {
Object casted = TypeConversionUtil.computeCastTo(((DfaConstValue)qualifierValue).getValue(), type);
return factory.getConstFactory().createFromValue(casted, type, ((DfaConstValue)qualifierValue).getConstant());
}
return qualifierValue;
}
if (type != null && (type instanceof PsiClassType || type.getArrayDimensions() > 0)) {
Nullness nullability = myReturnTypeNullability.get(instruction);
if (nullability == Nullness.UNKNOWN && factory.isUnknownMembersAreNullable()) {
nullability = Nullness.NULLABLE;
}
return factory.createTypeValue(type, nullability);
}
return DfaUnknownValue.getInstance();
}
protected boolean checkNotNullable(DfaMemoryState state,
DfaValue value, NullabilityProblem problem,
PsiElement anchor) {
boolean notNullable = state.checkNotNullable(value);
if (notNullable &&
problem != NullabilityProblem.passingNullableArgumentToNonAnnotatedParameter) {
DfaValueFactory factory = ((DfaMemoryStateImpl)state).getFactory();
state.applyCondition(factory.getRelationFactory().createRelation(value, factory.getConstFactory().getNull(), NE, false));
}
return notNullable;
}
@Override
public DfaInstructionState[] visitBinop(BinopInstruction instruction, DataFlowRunner runner, DfaMemoryState memState) {
myReachable.add(instruction);
DfaValue dfaRight = memState.pop();
DfaValue dfaLeft = memState.pop();
final IElementType opSign = instruction.getOperationSign();
if (opSign != null) {
DfaInstructionState[] states = handleConstantComparison(instruction, runner, memState, dfaRight, dfaLeft, opSign);
if (states == null) {
states = handleRelationBinop(instruction, runner, memState, dfaRight, dfaLeft);
}
if (states != null) {
return states;
}
if (PLUS == opSign) {
memState.push(instruction.getNonNullStringValue(runner.getFactory()));
}
else {
if (instruction instanceof InstanceofInstruction) {
handleInstanceof((InstanceofInstruction)instruction, dfaRight, dfaLeft);
}
memState.push(DfaUnknownValue.getInstance());
}
}
else {
memState.push(DfaUnknownValue.getInstance());
}
instruction.setTrueReachable(); // Not a branching instruction actually.
instruction.setFalseReachable();
return nextInstruction(instruction, runner, memState);
}
@Nullable
private DfaInstructionState[] handleRelationBinop(BinopInstruction instruction,
DataFlowRunner runner,
DfaMemoryState memState,
DfaValue dfaRight, DfaValue dfaLeft) {
DfaValueFactory factory = runner.getFactory();
final Instruction next = runner.getInstruction(instruction.getIndex() + 1);
DfaRelationValue dfaRelation = factory.getRelationFactory().createRelation(dfaLeft, dfaRight, instruction.getOperationSign(), false);
if (dfaRelation == null) {
return null;
}
myCanBeNullInInstanceof.add(instruction);
ArrayList<DfaInstructionState> states = new ArrayList<DfaInstructionState>();
final DfaMemoryState trueCopy = memState.createCopy();
if (trueCopy.applyCondition(dfaRelation)) {
trueCopy.push(factory.getConstFactory().getTrue());
instruction.setTrueReachable();
states.add(new DfaInstructionState(next, trueCopy));
}
//noinspection UnnecessaryLocalVariable
DfaMemoryState falseCopy = memState;
if (falseCopy.applyCondition(dfaRelation.createNegated())) {
falseCopy.push(factory.getConstFactory().getFalse());
instruction.setFalseReachable();
states.add(new DfaInstructionState(next, falseCopy));
if (instruction instanceof InstanceofInstruction && !falseCopy.isNull(dfaLeft)) {
myUsefulInstanceofs.add((InstanceofInstruction)instruction);
}
}
return states.toArray(new DfaInstructionState[states.size()]);
}
public void skipConstantConditionReporting(@Nullable PsiElement anchor) {
ContainerUtil.addIfNotNull(myNotToReportReachability, anchor);
}
private void handleInstanceof(InstanceofInstruction instruction, DfaValue dfaRight, DfaValue dfaLeft) {
if (dfaLeft instanceof DfaTypeValue && dfaRight instanceof DfaTypeValue) {
if (!((DfaTypeValue)dfaLeft).isNotNull()) {
myCanBeNullInInstanceof.add(instruction);
}
if (((DfaTypeValue)dfaRight).getDfaType().isAssignableFrom(((DfaTypeValue)dfaLeft).getDfaType())) {
return;
}
}
myUsefulInstanceofs.add(instruction);
}
@Nullable
private static DfaInstructionState[] handleConstantComparison(BinopInstruction instruction,
DataFlowRunner runner,
DfaMemoryState memState,
DfaValue dfaRight,
DfaValue dfaLeft, IElementType opSign) {
if (dfaRight instanceof DfaConstValue && dfaLeft instanceof DfaVariableValue) {
Object value = ((DfaConstValue)dfaRight).getValue();
if (value instanceof Number) {
DfaInstructionState[] result = checkComparingWithConstant(instruction, runner, memState, (DfaVariableValue)dfaLeft, opSign,
((Number)value).doubleValue());
if (result != null) {
return result;
}
}
}
if (dfaRight instanceof DfaVariableValue && dfaLeft instanceof DfaConstValue) {
return handleConstantComparison(instruction, runner, memState, dfaLeft, dfaRight, DfaRelationValue.getSymmetricOperation(opSign));
}
if (EQEQ != opSign && NE != opSign) {
return null;
}
if (dfaLeft instanceof DfaConstValue && dfaRight instanceof DfaConstValue ||
dfaLeft == runner.getFactory().getConstFactory().getContractFail() ||
dfaRight == runner.getFactory().getConstFactory().getContractFail()) {
boolean negated = (NE == opSign) ^ (DfaMemoryStateImpl.isNaN(dfaLeft) || DfaMemoryStateImpl.isNaN(dfaRight));
if (dfaLeft == dfaRight ^ negated) {
return alwaysTrue(instruction, runner, memState);
}
return alwaysFalse(instruction, runner, memState);
}
return null;
}
@Nullable
private static DfaInstructionState[] checkComparingWithConstant(BinopInstruction instruction,
DataFlowRunner runner,
DfaMemoryState memState,
DfaVariableValue var,
IElementType opSign, double comparedWith) {
DfaConstValue knownConstantValue = memState.getConstantValue(var);
Object knownValue = knownConstantValue == null ? null : knownConstantValue.getValue();
if (knownValue instanceof Number) {
double knownDouble = ((Number)knownValue).doubleValue();
return checkComparisonWithKnownRange(instruction, runner, memState, opSign, comparedWith, knownDouble, knownDouble);
}
PsiType varType = var.getVariableType();
if (!(varType instanceof PsiPrimitiveType)) return null;
if (varType == PsiType.FLOAT || varType == PsiType.DOUBLE) return null;
double minValue = varType == PsiType.BYTE ? Byte.MIN_VALUE :
varType == PsiType.SHORT ? Short.MIN_VALUE :
varType == PsiType.INT ? Integer.MIN_VALUE :
varType == PsiType.CHAR ? Character.MIN_VALUE :
Long.MIN_VALUE;
double maxValue = varType == PsiType.BYTE ? Byte.MAX_VALUE :
varType == PsiType.SHORT ? Short.MAX_VALUE :
varType == PsiType.INT ? Integer.MAX_VALUE :
varType == PsiType.CHAR ? Character.MAX_VALUE :
Long.MAX_VALUE;
return checkComparisonWithKnownRange(instruction, runner, memState, opSign, comparedWith, minValue, maxValue);
}
@Nullable
private static DfaInstructionState[] checkComparisonWithKnownRange(BinopInstruction instruction,
DataFlowRunner runner,
DfaMemoryState memState,
IElementType opSign,
double comparedWith,
double rangeMin,
double rangeMax) {
if (comparedWith < rangeMin || comparedWith > rangeMax) {
if (opSign == EQEQ) return alwaysFalse(instruction, runner, memState);
if (opSign == NE) return alwaysTrue(instruction, runner, memState);
}
if (opSign == LT && comparedWith <= rangeMin) return alwaysFalse(instruction, runner, memState);
if (opSign == LT && comparedWith > rangeMax) return alwaysTrue(instruction, runner, memState);
if (opSign == LE && comparedWith >= rangeMax) return alwaysTrue(instruction, runner, memState);
if (opSign == GT && comparedWith >= rangeMax) return alwaysFalse(instruction, runner, memState);
if (opSign == GT && comparedWith < rangeMin) return alwaysTrue(instruction, runner, memState);
if (opSign == GE && comparedWith <= rangeMin) return alwaysTrue(instruction, runner, memState);
return null;
}
private static DfaInstructionState[] alwaysFalse(BinopInstruction instruction, DataFlowRunner runner, DfaMemoryState memState) {
memState.push(runner.getFactory().getConstFactory().getFalse());
instruction.setFalseReachable();
return nextInstruction(instruction, runner, memState);
}
private static DfaInstructionState[] alwaysTrue(BinopInstruction instruction, DataFlowRunner runner, DfaMemoryState memState) {
memState.push(runner.getFactory().getConstFactory().getTrue());
instruction.setTrueReachable();
return nextInstruction(instruction, runner, memState);
}
public boolean isInstanceofRedundant(InstanceofInstruction instruction) {
return !myUsefulInstanceofs.contains(instruction) && !instruction.isConditionConst() && myReachable.contains(instruction);
}
public boolean canBeNull(BinopInstruction instruction) {
return myCanBeNullInInstanceof.contains(instruction);
}
public boolean silenceConstantCondition(@Nullable PsiElement element) {
for (PsiElement skipped : myNotToReportReachability) {
if (PsiTreeUtil.isAncestor(element, skipped, false)) {
return true;
}
}
return false;
}
}
| apache-2.0 |
leafclick/intellij-community | plugins/editorconfig/gen/org/editorconfig/language/psi/impl/EditorConfigCharClassExclamationImpl.java | 1134 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
// This is a generated file. Not intended for manual editing.
package org.editorconfig.language.psi.impl;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElementVisitor;
import org.editorconfig.language.psi.EditorConfigCharClassExclamation;
import org.editorconfig.language.psi.EditorConfigVisitor;
import org.editorconfig.language.psi.base.EditorConfigHeaderElementBase;
import org.jetbrains.annotations.NotNull;
public class EditorConfigCharClassExclamationImpl extends EditorConfigHeaderElementBase implements EditorConfigCharClassExclamation {
public EditorConfigCharClassExclamationImpl(@NotNull ASTNode node) {
super(node);
}
public void accept(@NotNull EditorConfigVisitor visitor) {
visitor.visitCharClassExclamation(this);
}
@Override
public void accept(@NotNull PsiElementVisitor visitor) {
if (visitor instanceof EditorConfigVisitor) {
accept((EditorConfigVisitor)visitor);
}
else {
super.accept(visitor);
}
}
}
| apache-2.0 |
pickettd/code-dot-org | apps/src/flappy/skins.js | 5946 | /**
* Load Skin for Flappy.
*/
// background: Number of 400x400 background images. Randomly select one if
// specified, otherwise, use background.png.
// graph: Colour of optional grid lines, or false.
var skinsBase = require('../skins');
var CONFIGS = {
flappy: {
}
};
exports.load = function (assetUrl, id) {
var skin = skinsBase.load(assetUrl, id);
var config = CONFIGS[skin.id];
// todo: the way these are organized ends up being a little bit ugly as
// lot of our assets are individual items not necessarily attached to a
// specific theme
skin.scifi = {
background: skin.assetUrl('background_scifi.png'),
avatar: skin.assetUrl('avatar_scifi.png'),
obstacle_bottom: skin.assetUrl('obstacle_bottom_scifi.png'),
obstacle_bottom_thumb: skin.assetUrl('obstacle_bottom_scifi_thumb.png'),
obstacle_top: skin.assetUrl('obstacle_top_scifi.png'),
ground: skin.assetUrl('ground_scifi.png'),
ground_thumb: skin.assetUrl('ground_scifi_thumb.png')
};
skin.underwater = {
background: skin.assetUrl('background_underwater.png'),
avatar: skin.assetUrl('avatar_underwater.png'),
obstacle_bottom: skin.assetUrl('obstacle_bottom_underwater.png'),
obstacle_bottom_thumb: skin.assetUrl('obstacle_bottom_underwater_thumb.png'),
obstacle_top: skin.assetUrl('obstacle_top_underwater.png'),
ground: skin.assetUrl('ground_underwater.png'),
ground_thumb: skin.assetUrl('ground_underwater_thumb.png')
};
skin.cave = {
background: skin.assetUrl('background_cave.png'),
avatar: skin.assetUrl('avatar_cave.png'),
obstacle_bottom: skin.assetUrl('obstacle_bottom_cave.png'),
obstacle_bottom_thumb: skin.assetUrl('obstacle_bottom_cave_thumb.png'),
obstacle_top: skin.assetUrl('obstacle_top_cave.png'),
ground: skin.assetUrl('ground_cave.png'),
ground_thumb: skin.assetUrl('ground_cave_thumb.png')
};
skin.santa = {
background: skin.assetUrl('background_santa.png'),
avatar: skin.assetUrl('santa.png'),
obstacle_bottom: skin.assetUrl('obstacle_bottom_santa.png'),
obstacle_bottom_thumb: skin.assetUrl('obstacle_bottom_santa_thumb.png'),
obstacle_top: skin.assetUrl('obstacle_top_santa.png'),
ground: skin.assetUrl('ground_santa.png'),
ground_thumb: skin.assetUrl('ground_santa_thumb.png')
};
skin.night = {
background: skin.assetUrl('background_night.png')
};
skin.redbird = {
avatar: skin.assetUrl('avatar_redbird.png')
};
skin.laser = {
obstacle_bottom: skin.assetUrl('obstacle_bottom_laser.png'),
obstacle_bottom_thumb: skin.assetUrl('obstacle_bottom_laser_thumb.png'),
obstacle_top: skin.assetUrl('obstacle_top_laser.png')
};
skin.lava = {
ground: skin.assetUrl('ground_lava.png'),
ground_thumb: skin.assetUrl('ground_lava_thumb.png')
};
skin.shark = {
avatar: skin.assetUrl('shark.png')
};
skin.easter = {
avatar: skin.assetUrl('easterbunny.png')
};
skin.batman = {
avatar: skin.assetUrl('batman.png')
};
skin.submarine = {
avatar: skin.assetUrl('submarine.png')
};
skin.unicorn = {
avatar: skin.assetUrl('unicorn.png')
};
skin.fairy = {
avatar: skin.assetUrl('fairy.png')
};
skin.superman = {
avatar: skin.assetUrl('superman.png')
};
skin.turkey = {
avatar: skin.assetUrl('turkey.png')
};
// Images
skin.ground = skin.assetUrl('ground.png');
skin.ground_thumb = skin.assetUrl('ground_thumb.png');
skin.obstacle_top = skin.assetUrl('obstacle_top.png');
skin.obstacle_bottom = skin.assetUrl('obstacle_bottom.png');
skin.obstacle_bottom_thumb = skin.assetUrl('obstacle_bottom_thumb.png');
skin.instructions = skin.assetUrl('instructions.png');
skin.clickrun = skin.assetUrl('clickrun.png');
skin.getready = skin.assetUrl('getready.png');
skin.gameover = skin.assetUrl('gameover.png');
skin.flapIcon = skin.assetUrl('flap-bird.png');
skin.crashIcon = skin.assetUrl('when-crash.png');
skin.collideObstacleIcon = skin.assetUrl('when-obstacle.png');
skin.collideGroundIcon = skin.assetUrl('when-crash.png');
skin.enterObstacleIcon = skin.assetUrl('when-pass.png');
skin.tiles = skin.assetUrl('tiles.png');
skin.goal = skin.assetUrl('goal.png');
skin.goalSuccess = skin.assetUrl('goal_success.png');
skin.obstacle = skin.assetUrl('obstacle.png');
skin.obstacleScale = config.obstacleScale || 1.0;
skin.largerObstacleAnimationTiles =
skin.assetUrl(config.largerObstacleAnimationTiles);
skin.hittingWallAnimation =
skin.assetUrl(config.hittingWallAnimation);
skin.approachingGoalAnimation =
skin.assetUrl(config.approachingGoalAnimation);
// Sounds
skin.obstacleSound =
[skin.assetUrl('obstacle.mp3'), skin.assetUrl('obstacle.ogg')];
skin.wallSound = [skin.assetUrl('wall.mp3'), skin.assetUrl('wall.ogg')];
skin.winGoalSound = [skin.assetUrl('win_goal.mp3'),
skin.assetUrl('win_goal.ogg')];
skin.wall0Sound = [skin.assetUrl('wall0.mp3'), skin.assetUrl('wall0.ogg')];
skin.dieSound = [skin.assetUrl('sfx_die.mp3'), skin.assetUrl('sfx_die.ogg')];
skin.hitSound = [skin.assetUrl('sfx_hit.mp3'), skin.assetUrl('sfx_hit.ogg')];
skin.pointSound = [skin.assetUrl('sfx_point.mp3'), skin.assetUrl('sfx_point.ogg')];
skin.swooshingSound = [skin.assetUrl('sfx_swooshing.mp3'), skin.assetUrl('sfx_swooshing.ogg')];
skin.wingSound = [skin.assetUrl('sfx_wing.mp3'), skin.assetUrl('sfx_wing.ogg')];
skin.jetSound = [skin.assetUrl('jet.mp3'), skin.assetUrl('jet.ogg')];
skin.crashSound = [skin.assetUrl('crash.mp3'), skin.assetUrl('crash.ogg')];
skin.jingleSound = [skin.assetUrl('jingle.mp3'), skin.assetUrl('jingle.ogg')];
skin.laserSound = [skin.assetUrl('laser.mp3'), skin.assetUrl('laser.ogg')];
skin.splashSound = [skin.assetUrl('splash.mp3'), skin.assetUrl('splash.ogg')];
// Settings
skin.graph = config.graph;
skin.background = skin.assetUrl('background.png');
return skin;
};
| apache-2.0 |
ryanemerson/activemq-artemis | tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsBenchmark.java | 8077 | /**
* 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.activemq;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import javax.jms.BytesMessage;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Session;
import junit.framework.Test;
import org.apache.activemq.broker.BrokerFactory;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.command.ActiveMQQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Benchmarks the broker by starting many consumer and producers against the
* same destination. Make sure you run with jvm option -server (makes a big
* difference). The tests simulate storing 1000 1k jms messages to see the rate
* of processing msg/sec.
*
*
*/
public class JmsBenchmark extends JmsTestSupport {
private static final transient Logger LOG = LoggerFactory.getLogger(JmsBenchmark.class);
private static final long SAMPLE_DELAY = Integer.parseInt(System.getProperty("SAMPLE_DELAY", "" + 1000 * 5));
private static final long SAMPLES = Integer.parseInt(System.getProperty("SAMPLES", "10"));
private static final long SAMPLE_DURATION = Integer.parseInt(System.getProperty("SAMPLES_DURATION", "" + 1000 * 60));
private static final int PRODUCER_COUNT = Integer.parseInt(System.getProperty("PRODUCER_COUNT", "10"));
private static final int CONSUMER_COUNT = Integer.parseInt(System.getProperty("CONSUMER_COUNT", "10"));
public ActiveMQDestination destination;
public static Test suite() {
return suite(JmsBenchmark.class);
}
public static void main(String[] args) {
junit.textui.TestRunner.run(JmsBenchmark.class);
}
public void initCombos() {
addCombinationValues("destination", new Object[] {new ActiveMQQueue("TEST")});
}
@Override
protected BrokerService createBroker() throws Exception {
return BrokerFactory.createBroker(new URI("broker://(tcp://localhost:0)?persistent=false"));
}
@Override
protected ConnectionFactory createConnectionFactory() throws URISyntaxException, IOException {
return new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getServer().getConnectURI());
}
/**
* @throws Throwable
*/
public void testConcurrentSendReceive() throws Throwable {
final Semaphore connectionsEstablished = new Semaphore(1 - (CONSUMER_COUNT + PRODUCER_COUNT));
final Semaphore workerDone = new Semaphore(1 - (CONSUMER_COUNT + PRODUCER_COUNT));
final CountDownLatch sampleTimeDone = new CountDownLatch(1);
final AtomicInteger producedMessages = new AtomicInteger(0);
final AtomicInteger receivedMessages = new AtomicInteger(0);
final Callable<Object> producer = new Callable<Object>() {
@Override
public Object call() throws JMSException, InterruptedException {
Connection connection = factory.createConnection();
connections.add(connection);
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = session.createProducer(destination);
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
BytesMessage message = session.createBytesMessage();
message.writeBytes(new byte[1024]);
connection.start();
connectionsEstablished.release();
while (!sampleTimeDone.await(0, TimeUnit.MILLISECONDS)) {
producer.send(message);
producedMessages.incrementAndGet();
}
connection.close();
workerDone.release();
return null;
}
};
final Callable<Object> consumer = new Callable<Object>() {
@Override
public Object call() throws JMSException, InterruptedException {
Connection connection = factory.createConnection();
connections.add(connection);
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageConsumer consumer = session.createConsumer(destination);
consumer.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message msg) {
receivedMessages.incrementAndGet();
}
});
connection.start();
connectionsEstablished.release();
sampleTimeDone.await();
connection.close();
workerDone.release();
return null;
}
};
final Throwable workerError[] = new Throwable[1];
for (int i = 0; i < PRODUCER_COUNT; i++) {
new Thread("Producer:" + i) {
@Override
public void run() {
try {
producer.call();
} catch (Throwable e) {
e.printStackTrace();
workerError[0] = e;
}
}
}.start();
}
for (int i = 0; i < CONSUMER_COUNT; i++) {
new Thread("Consumer:" + i) {
@Override
public void run() {
try {
consumer.call();
} catch (Throwable e) {
e.printStackTrace();
workerError[0] = e;
}
}
}.start();
}
LOG.info(getName() + ": Waiting for Producers and Consumers to startup.");
connectionsEstablished.acquire();
LOG.info("Producers and Consumers are now running. Waiting for system to reach steady state: " + (SAMPLE_DELAY / 1000.0f) + " seconds");
Thread.sleep(1000 * 10);
LOG.info("Starting sample: " + SAMPLES + " each lasting " + (SAMPLE_DURATION / 1000.0f) + " seconds");
for (int i = 0; i < SAMPLES; i++) {
long start = System.currentTimeMillis();
producedMessages.set(0);
receivedMessages.set(0);
Thread.sleep(SAMPLE_DURATION);
long end = System.currentTimeMillis();
int r = receivedMessages.get();
int p = producedMessages.get();
LOG.info("published: " + p + " msgs at " + (p * 1000f / (end - start)) + " msgs/sec, " + "consumed: " + r + " msgs at " + (r * 1000f / (end - start)) + " msgs/sec");
}
LOG.info("Sample done.");
sampleTimeDone.countDown();
workerDone.acquire();
if (workerError[0] != null) {
throw workerError[0];
}
}
}
| apache-2.0 |
AlanJager/zstack | core/src/main/java/org/zstack/core/config/RBACInfo.java | 770 | package org.zstack.core.config;
import org.zstack.header.identity.rbac.RBACDescription;
import org.zstack.header.vo.ResourceVO;
public class RBACInfo implements RBACDescription {
@Override
public void permissions() {
permissionBuilder()
.name("global-config")
.adminOnlyAPIs("org.zstack.core.config.**")
.normalAPIs(APIQueryGlobalConfigMsg.class)
.build();
}
@Override
public void contributeToRoles() {
roleContributorBuilder()
.roleName("other")
.actions(APIQueryGlobalConfigMsg.class)
.build();
}
@Override
public void roles() {
}
@Override
public void globalReadableResources() {
}
}
| apache-2.0 |
leftathome/supermarket | app/controllers/contributors_controller.rb | 1153 | class ContributorsController < ApplicationController
before_filter :find_contributor, only: [:update, :destroy]
#
# PATCH /organizations/:organization_id/contributors/:id
#
# Update a single contributor.
#
def update
authorize! @contributor
@contributor.update_attributes(contributor_params)
head 204
end
#
# DELETE /organizations/:organization_id/contributors/:id
#
# Remove a single contributor.
#
def destroy
authorize! @contributor
@contributor.destroy
redirect_to :back, notice: t('contributor.removed')
end
#
# GET /become-a-contributor
#
# Display information related to becoming a contributor.
#
def become_a_contributor
store_location!
end
#
# GET /contributors
#
# Display all of the users who are authorized to contribute
#
def index
@contributors = User.authorized_contributors.page(params[:page]).per(20)
@contributor_list = ContributorList.new(@contributors)
end
private
def find_contributor
@contributor = Contributor.find(params[:id])
end
def contributor_params
params.require(:contributor).permit(:admin)
end
end
| apache-2.0 |
fogbeam/Heceta_solr | solr/core/src/java/org/apache/solr/cloud/CloudDescriptor.java | 4578 | package org.apache.solr.cloud;
/*
* 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.
*/
import org.apache.solr.common.cloud.Slice;
import org.apache.solr.common.cloud.ZkStateReader;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.core.CoreDescriptor;
import org.apache.solr.util.PropertiesUtil;
import java.util.Properties;
public class CloudDescriptor {
private final CoreDescriptor cd;
private String shardId;
private String collectionName;
private SolrParams params;
private String roles = null;
private Integer numShards;
private String nodeName = null;
/* shardRange and shardState are used once-only during sub shard creation for shard splits
* Use the values from {@link Slice} instead */
volatile String shardRange = null;
volatile String shardState = Slice.ACTIVE;
volatile String shardParent = null;
volatile boolean isLeader = false;
volatile String lastPublished = ZkStateReader.ACTIVE;
public static final String SHARD_STATE = "shardState";
public static final String NUM_SHARDS = "numShards";
public static final String SHARD_RANGE = "shardRange";
public static final String SHARD_PARENT = "shardParent";
public CloudDescriptor(String coreName, Properties props, CoreDescriptor cd) {
this.cd = cd;
this.shardId = props.getProperty(CoreDescriptor.CORE_SHARD, null);
// If no collection name is specified, we default to the core name
this.collectionName = props.getProperty(CoreDescriptor.CORE_COLLECTION, coreName);
this.roles = props.getProperty(CoreDescriptor.CORE_ROLES, null);
this.nodeName = props.getProperty(CoreDescriptor.CORE_NODE_NAME);
this.shardState = props.getProperty(CloudDescriptor.SHARD_STATE, Slice.ACTIVE);
this.numShards = PropertiesUtil.toInteger(props.getProperty(CloudDescriptor.NUM_SHARDS), null);
this.shardRange = props.getProperty(CloudDescriptor.SHARD_RANGE, null);
this.shardParent = props.getProperty(CloudDescriptor.SHARD_PARENT, null);
}
public String getLastPublished() {
return lastPublished;
}
public boolean isLeader() {
return isLeader;
}
public void setLeader(boolean isLeader) {
this.isLeader = isLeader;
}
public void setShardId(String shardId) {
this.shardId = shardId;
}
public String getShardId() {
return shardId;
}
public String getCollectionName() {
return collectionName;
}
public void setCollectionName(String collectionName) {
this.collectionName = collectionName;
}
public String getRoles(){
return roles;
}
public void setRoles(String roles){
this.roles = roles;
}
/** Optional parameters that can change how a core is created. */
public SolrParams getParams() {
return params;
}
public void setParams(SolrParams params) {
this.params = params;
}
// setting only matters on core creation
public Integer getNumShards() {
return numShards;
}
public void setNumShards(int numShards) {
this.numShards = numShards;
}
public String getCoreNodeName() {
return nodeName;
}
public void setCoreNodeName(String nodeName) {
this.nodeName = nodeName;
if(nodeName==null) cd.getPersistableStandardProperties().remove(CoreDescriptor.CORE_NODE_NAME);
else cd.getPersistableStandardProperties().setProperty(CoreDescriptor.CORE_NODE_NAME, nodeName);
}
public String getShardRange() {
return shardRange;
}
public void setShardRange(String shardRange) {
this.shardRange = shardRange;
}
public String getShardState() {
return shardState;
}
public void setShardState(String shardState) {
this.shardState = shardState;
}
public String getShardParent() {
return shardParent;
}
public void setShardParent(String shardParent) {
this.shardParent = shardParent;
}
}
| apache-2.0 |
MadMikeyB/HotOrNot | lib/Cake/Test/Case/Model/Behavior/TreeBehaviorUuidTest.php | 8544 | <?php
/**
* TreeBehaviorUuidTest file
*
* Tree test using UUIDs
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/view/1196/Testing>
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/view/1196/Testing CakePHP(tm) Tests
* @package Cake.Test.Case.Model.Behavior
* @since CakePHP(tm) v 1.2.0.5330
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('Model', 'Model');
App::uses('AppModel', 'Model');
require_once(dirname(dirname(__FILE__)) . DS . 'models.php');
/**
* TreeBehaviorUuidTest class
*
* @package Cake.Test.Case.Model.Behavior
*/
class TreeBehaviorUuidTest extends CakeTestCase {
/**
* Whether backup global state for each test method or not
*
* @var bool false
*/
public $backupGlobals = false;
/**
* settings property
*
* @var array
*/
public $settings = array(
'modelClass' => 'UuidTree',
'leftField' => 'lft',
'rightField' => 'rght',
'parentField' => 'parent_id'
);
/**
* fixtures property
*
* @var array
*/
public $fixtures = array('core.uuid_tree');
/**
* testMovePromote method
*
* @return void
*/
public function testMovePromote() {
extract($this->settings);
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$this->Tree->id = null;
$parent = $this->Tree->find('first', array('conditions' => array($modelClass . '.name' => '1. Root')));
$parent_id = $parent[$modelClass]['id'];
$data = $this->Tree->find('first', array('fields' => array('id'), 'conditions' => array($modelClass . '.name' => '1.1.1')));
$this->Tree->id= $data[$modelClass]['id'];
$this->Tree->saveField($parentField, $parent_id);
$direct = $this->Tree->children($parent_id, true, array('name', $leftField, $rightField));
$expects = array(array($modelClass => array('name' => '1.1', $leftField => 2, $rightField => 5)),
array($modelClass => array('name' => '1.2', $leftField => 6, $rightField => 11)),
array($modelClass => array('name' => '1.1.1', $leftField => 12, $rightField => 13)));
$this->assertEqual($direct, $expects);
$validTree = $this->Tree->verify();
$this->assertIdentical($validTree, true);
}
/**
* testMoveWithWhitelist method
*
* @return void
*/
public function testMoveWithWhitelist() {
extract($this->settings);
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$this->Tree->id = null;
$parent = $this->Tree->find('first', array('conditions' => array($modelClass . '.name' => '1. Root')));
$parent_id = $parent[$modelClass]['id'];
$data = $this->Tree->find('first', array('fields' => array('id'), 'conditions' => array($modelClass . '.name' => '1.1.1')));
$this->Tree->id = $data[$modelClass]['id'];
$this->Tree->whitelist = array($parentField, 'name', 'description');
$this->Tree->saveField($parentField, $parent_id);
$result = $this->Tree->children($parent_id, true, array('name', $leftField, $rightField));
$expected = array(array($modelClass => array('name' => '1.1', $leftField => 2, $rightField => 5)),
array($modelClass => array('name' => '1.2', $leftField => 6, $rightField => 11)),
array($modelClass => array('name' => '1.1.1', $leftField => 12, $rightField => 13)));
$this->assertEqual($expected, $result);
$this->assertTrue($this->Tree->verify());
}
/**
* testRemoveNoChildren method
*
* @return void
*/
public function testRemoveNoChildren() {
extract($this->settings);
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$initialCount = $this->Tree->find('count');
$result = $this->Tree->findByName('1.1.1');
$this->Tree->removeFromTree($result[$modelClass]['id']);
$laterCount = $this->Tree->find('count');
$this->assertEqual($initialCount, $laterCount);
$nodes = $this->Tree->find('list', array('order' => $leftField));
$expects = array(
'1. Root',
'1.1',
'1.1.2',
'1.2',
'1.2.1',
'1.2.2',
'1.1.1',
);
$this->assertEqual(array_values($nodes), $expects);
$validTree = $this->Tree->verify();
$this->assertIdentical($validTree, true);
}
/**
* testRemoveAndDeleteNoChildren method
*
* @return void
*/
public function testRemoveAndDeleteNoChildren() {
extract($this->settings);
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$initialCount = $this->Tree->find('count');
$result = $this->Tree->findByName('1.1.1');
$this->Tree->removeFromTree($result[$modelClass]['id'], true);
$laterCount = $this->Tree->find('count');
$this->assertEqual($initialCount - 1, $laterCount);
$nodes = $this->Tree->find('list', array('order' => $leftField));
$expects = array(
'1. Root',
'1.1',
'1.1.2',
'1.2',
'1.2.1',
'1.2.2',
);
$this->assertEqual(array_values($nodes), $expects);
$validTree = $this->Tree->verify();
$this->assertIdentical($validTree, true);
}
/**
* testChildren method
*
* @return void
*/
public function testChildren() {
extract($this->settings);
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$data = $this->Tree->find('first', array('conditions' => array($modelClass . '.name' => '1. Root')));
$this->Tree->id = $data[$modelClass]['id'];
$direct = $this->Tree->children(null, true, array('name', $leftField, $rightField));
$expects = array(array($modelClass => array('name' => '1.1', $leftField => 2, $rightField => 7)),
array($modelClass => array('name' => '1.2', $leftField => 8, $rightField => 13)));
$this->assertEqual($direct, $expects);
$total = $this->Tree->children(null, null, array('name', $leftField, $rightField));
$expects = array(array($modelClass => array('name' => '1.1', $leftField => 2, $rightField => 7)),
array($modelClass => array('name' => '1.1.1', $leftField => 3, $rightField => 4)),
array($modelClass => array('name' => '1.1.2', $leftField => 5, $rightField => 6)),
array($modelClass => array('name' => '1.2', $leftField => 8, $rightField => 13)),
array($modelClass => array('name' => '1.2.1', $leftField => 9, $rightField => 10)),
array($modelClass => array('name' => '1.2.2', $leftField => 11, $rightField => 12)));
$this->assertEqual($total, $expects);
}
/**
* testNoAmbiguousColumn method
*
* @return void
*/
public function testNoAmbiguousColumn() {
extract($this->settings);
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$this->Tree->bindModel(array('belongsTo' => array('Dummy' =>
array('className' => $modelClass, 'foreignKey' => $parentField, 'conditions' => array('Dummy.id' => null)))), false);
$data = $this->Tree->find('first', array('conditions' => array($modelClass . '.name' => '1. Root')));
$this->Tree->id = $data[$modelClass]['id'];
$direct = $this->Tree->children(null, true, array('name', $leftField, $rightField));
$expects = array(array($modelClass => array('name' => '1.1', $leftField => 2, $rightField => 7)),
array($modelClass => array('name' => '1.2', $leftField => 8, $rightField => 13)));
$this->assertEqual($direct, $expects);
$total = $this->Tree->children(null, null, array('name', $leftField, $rightField));
$expects = array(
array($modelClass => array('name' => '1.1', $leftField => 2, $rightField => 7)),
array($modelClass => array('name' => '1.1.1', $leftField => 3, $rightField => 4)),
array($modelClass => array('name' => '1.1.2', $leftField => 5, $rightField => 6)),
array($modelClass => array('name' => '1.2', $leftField => 8, $rightField => 13)),
array($modelClass => array('name' => '1.2.1', $leftField => 9, $rightField => 10)),
array($modelClass => array('name' => '1.2.2', $leftField => 11, $rightField => 12))
);
$this->assertEqual($total, $expects);
}
/**
* testGenerateTreeListWithSelfJoin method
*
* @return void
*/
public function testGenerateTreeListWithSelfJoin() {
extract($this->settings);
$this->Tree = new $modelClass();
$this->Tree->bindModel(array('belongsTo' => array('Dummy' =>
array('className' => $modelClass, 'foreignKey' => $parentField, 'conditions' => array('Dummy.id' => null)))), false);
$this->Tree->initialize(2, 2);
$result = $this->Tree->generateTreeList();
$expected = array('1. Root', '_1.1', '__1.1.1', '__1.1.2', '_1.2', '__1.2.1', '__1.2.2');
$this->assertIdentical(array_values($result), $expected);
}
}
| bsd-2-clause |
PrFalken/exaproxy | lib/exaproxy/util/messagequeue.py | 968 | from collections import deque
import time
class Empty (Exception):
pass
class Queue():
def __init__ (self):
self.queue = deque()
def qsize (self):
return len(self.queue)
def isempty (self):
return len(self.queue) == 0
def put (self, message):
self.queue.append(message)
def get (self, timeout=None):
try:
if self.queue:
return self.queue.popleft()
except IndexError:
pass
delay = 0.0005
start = time.time()
running = True
while running:
try:
while True:
if timeout:
if time.time() > start + timeout:
running = False
break
delay = min(0.05, 2*delay)
time.sleep(delay)
if self.queue:
return self.queue.popleft()
except IndexError:
pass
raise Empty
if __name__ == '__main__':
q = Queue()
q.put('foo')
q.put('bar')
print q.get(1)
print q.get(1)
try:
q.put('yay')
print q.get(1)
print q.get(2)
except:
print 'forever - print ^C'
print q.get()
| bsd-2-clause |
alphaleonis/clide | Src/IntegrationPackage/FooOptionsPage.cs | 1738 | #region BSD License
/*
Copyright (c) 2012, Clarius Consulting
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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.
*/
#endregion
namespace IntegrationPackage
{
using Clide;
using System.ComponentModel;
[Category("My Package")]
[DisplayName("Server Settings")]
[OptionsPage]
public class FooOptionsPage : OptionsPage<FooView, FooSettings>
{
public FooOptionsPage(IOptionsPageWindowFactory windowFactory, FooSettings settings)
: base(windowFactory, settings)
{
}
}
}
| bsd-2-clause |
daldegam/effectweb-project | src/cache/lang_cache/pt-BR/admin_core/admin_auth.php | 1390 | <?php
/*****************************************************/
/* Cetemaster Board - Language Words System */
/* Package: Effect Web v2.x - ACP */
/*****************************************************/
/* Language: Blazilian Portuguese */
/* File: Authentication Module */
/*****************************************************/
/* Author: Erick-Master */
/* Last Update: 01/05/2012 - 19:15h */
/*****************************************************/
$CTM_LANG = array
(
"Auth" => array
(
"Login" => array
(
"Form" => array
(
"Title" => "Login",
"Login" => "Login:",
"Password" => "Senha:",
"Button" => "Logar",
),
"Process" => array
(
"EmptyFields" => "Preencha todos os campos.",
"LoginFailed" => "Login ou senha inválidos.",
"NoPermission" => "Login sem permissão de acesso ao AdminCP.",
),
"Messages" => array
(
"NoLogged" => "Para acessar o AdminCP é preciso estar logado.",
"NoPermission" => "Conta sem permissão de acesso ao AdminCP.",
"SessionExpired" => "Você ficou inativo por 30 minutos ou mais.",
),
),
"Redirect" => array
(
"Login" => "Você foi logado com sucesso!",
"Logout" => "Você foi deslogado com sucesso!",
),
),
); | bsd-2-clause |
ericbn/homebrew-cask | Casks/insomnia-designer.rb | 922 | cask "insomnia-designer" do
version "2020.4.1"
sha256 "362d08630292af722c2ff5f7563dcfccbb3d151fa6184ea8dcfabb33260226d5"
# github.com/Kong/insomnia/ was verified as official when first introduced to the cask
url "https://github.com/Kong/insomnia/releases/download/designer%40#{version}/Insomnia.Designer-#{version}.dmg"
appcast "https://api.insomnia.rest/changelog.json?app=com.insomnia.designer"
name "Insomnia Designer"
desc "API design platform for GraphQL and REST"
homepage "https://insomnia.rest/"
auto_updates true
app "Insomnia Designer.app"
zap trash: [
"~/Library/Application Support/Insomnia Designer",
"~/Library/Caches/com.insomnia.designer",
"~/Library/Caches/com.insomnia.designer.ShipIt",
"~/Library/Logs/Insomnia Designer",
"~/Library/Preferences/com.insomnia.designer.plist",
"~/Library/Saved Application State/com.insomnia.designer.savedState",
]
end
| bsd-2-clause |
mtmarsh2/vislab | vislab/tests/_template.py | 346 | import logging
import unittest
import test_context
import vislab.predict
class TestX(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.temp_dirname = vislab.util.cleardirs(
test_context.temp_dirname + '/test_X')
if __name__ == '__main__':
logging.getLogger().setLevel(logging.INFO)
unittest.main()
| bsd-2-clause |
attilaz/bgfx | examples/common/ps/particle_system.cpp | 18567 | /*
* Copyright 2011-2019 Branimir Karadzic. All rights reserved.
* License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
*/
#include <bgfx/bgfx.h>
#include <bgfx/embedded_shader.h>
#include "particle_system.h"
#include "../bgfx_utils.h"
#include "../packrect.h"
#include <bx/easing.h>
#include <bx/handlealloc.h>
#include "vs_particle.bin.h"
#include "fs_particle.bin.h"
static const bgfx::EmbeddedShader s_embeddedShaders[] =
{
BGFX_EMBEDDED_SHADER(vs_particle),
BGFX_EMBEDDED_SHADER(fs_particle),
BGFX_EMBEDDED_SHADER_END()
};
struct PosColorTexCoord0Vertex
{
float m_x;
float m_y;
float m_z;
uint32_t m_abgr;
float m_u;
float m_v;
float m_blend;
float m_angle;
static void init()
{
ms_decl
.begin()
.add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float)
.add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true)
.add(bgfx::Attrib::TexCoord0, 4, bgfx::AttribType::Float)
.end();
}
static bgfx::VertexDecl ms_decl;
};
bgfx::VertexDecl PosColorTexCoord0Vertex::ms_decl;
void EmitterUniforms::reset()
{
m_position[0] = 0.0f;
m_position[1] = 0.0f;
m_position[2] = 0.0f;
m_angle[0] = 0.0f;
m_angle[1] = 0.0f;
m_angle[2] = 0.0f;
m_particlesPerSecond = 0;
m_offsetStart[0] = 0.0f;
m_offsetStart[1] = 1.0f;
m_offsetEnd[0] = 2.0f;
m_offsetEnd[1] = 3.0f;
m_rgba[0] = 0x00ffffff;
m_rgba[1] = UINT32_MAX;
m_rgba[2] = UINT32_MAX;
m_rgba[3] = UINT32_MAX;
m_rgba[4] = 0x00ffffff;
m_blendStart[0] = 0.8f;
m_blendStart[1] = 1.0f;
m_blendEnd[0] = 0.0f;
m_blendEnd[1] = 0.2f;
m_scaleStart[0] = 0.1f;
m_scaleStart[1] = 0.2f;
m_scaleEnd[0] = 0.3f;
m_scaleEnd[1] = 0.4f;
m_lifeSpan[0] = 1.0f;
m_lifeSpan[1] = 2.0f;
m_gravityScale = 0.0f;
m_easePos = bx::Easing::Linear;
m_easeRgba = bx::Easing::Linear;
m_easeBlend = bx::Easing::Linear;
m_easeScale = bx::Easing::Linear;
}
namespace ps
{
struct Particle
{
bx::Vec3 start;
bx::Vec3 end[2];
float blendStart;
float blendEnd;
float scaleStart;
float scaleEnd;
uint32_t rgba[5];
float life;
float lifeSpan;
};
struct ParticleSort
{
float dist;
uint32_t idx;
};
inline uint32_t toAbgr(const float* _rgba)
{
return 0
| (uint8_t(_rgba[0]*255.0f)<< 0)
| (uint8_t(_rgba[1]*255.0f)<< 8)
| (uint8_t(_rgba[2]*255.0f)<<16)
| (uint8_t(_rgba[3]*255.0f)<<24)
;
}
inline uint32_t toAbgr(float _rr, float _gg, float _bb, float _aa)
{
return 0
| (uint8_t(_rr*255.0f)<< 0)
| (uint8_t(_gg*255.0f)<< 8)
| (uint8_t(_bb*255.0f)<<16)
| (uint8_t(_aa*255.0f)<<24)
;
}
#define SPRITE_TEXTURE_SIZE 1024
template<uint16_t MaxHandlesT = 256, uint16_t TextureSizeT = 1024>
struct SpriteT
{
SpriteT()
: m_ra(TextureSizeT, TextureSizeT)
{
}
EmitterSpriteHandle create(uint16_t _width, uint16_t _height)
{
EmitterSpriteHandle handle = { bx::kInvalidHandle };
if (m_handleAlloc.getNumHandles() < m_handleAlloc.getMaxHandles() )
{
Pack2D pack;
if (m_ra.find(_width, _height, pack) )
{
handle.idx = m_handleAlloc.alloc();
m_pack[handle.idx] = pack;
}
}
return handle;
}
void destroy(EmitterSpriteHandle _sprite)
{
const Pack2D& pack = m_pack[_sprite.idx];
m_ra.clear(pack);
m_handleAlloc.free(_sprite.idx);
}
const Pack2D& get(EmitterSpriteHandle _sprite) const
{
return m_pack[_sprite.idx];
}
bx::HandleAllocT<MaxHandlesT> m_handleAlloc;
Pack2D m_pack[MaxHandlesT];
RectPack2DT<256> m_ra;
};
struct Emitter
{
void create(EmitterShape::Enum _shape, EmitterDirection::Enum _direction, uint32_t _maxParticles);
void destroy();
void reset()
{
m_dt = 0.0f;
m_uniforms.reset();
m_num = 0;
bx::memSet(&m_aabb, 0, sizeof(Aabb) );
m_rng.reset();
}
void update(float _dt)
{
uint32_t num = m_num;
for (uint32_t ii = 0; ii < num; ++ii)
{
Particle& particle = m_particles[ii];
particle.life += _dt * 1.0f/particle.lifeSpan;
if (particle.life > 1.0f)
{
if (ii != num-1)
{
bx::memCopy(&particle, &m_particles[num-1], sizeof(Particle) );
--ii;
}
--num;
}
}
m_num = num;
if (0 < m_uniforms.m_particlesPerSecond)
{
spawn(_dt);
}
}
void spawn(float _dt)
{
float mtx[16];
bx::mtxSRT(mtx
, 1.0f, 1.0f, 1.0f
, m_uniforms.m_angle[0], m_uniforms.m_angle[1], m_uniforms.m_angle[2]
, m_uniforms.m_position[0], m_uniforms.m_position[1], m_uniforms.m_position[2]
);
const float timePerParticle = 1.0f/m_uniforms.m_particlesPerSecond;
m_dt += _dt;
const uint32_t numParticles = uint32_t(m_dt / timePerParticle);
m_dt -= numParticles * timePerParticle;
constexpr bx::Vec3 up = { 0.0f, 1.0f, 0.0f };
float time = 0.0f;
for (uint32_t ii = 0
; ii < numParticles && m_num < m_max
; ++ii
)
{
Particle& particle = m_particles[m_num];
m_num++;
bx::Vec3 pos;
switch (m_shape)
{
default:
case EmitterShape::Sphere:
pos = bx::randUnitSphere(&m_rng);
break;
case EmitterShape::Hemisphere:
pos = bx::randUnitHemisphere(&m_rng, up);
break;
case EmitterShape::Circle:
pos = bx::randUnitCircle(&m_rng);
break;
case EmitterShape::Disc:
{
const bx::Vec3 tmp = bx::randUnitCircle(&m_rng);
pos = bx::mul(tmp, bx::frnd(&m_rng) );
}
break;
case EmitterShape::Rect:
pos =
{
bx::frndh(&m_rng),
0.0f,
bx::frndh(&m_rng),
};
break;
}
bx::Vec3 dir;
switch (m_direction)
{
default:
case EmitterDirection::Up:
dir = up;
break;
case EmitterDirection::Outward:
dir = bx::normalize(pos);
break;
}
const float startOffset = bx::lerp(m_uniforms.m_offsetStart[0], m_uniforms.m_offsetStart[1], bx::frnd(&m_rng) );
const bx::Vec3 start = bx::mul(pos, startOffset);
const float endOffset = bx::lerp(m_uniforms.m_offsetEnd[0], m_uniforms.m_offsetEnd[1], bx::frnd(&m_rng) );
const bx::Vec3 tmp1 = bx::mul(dir, endOffset);
const bx::Vec3 end = bx::add(tmp1, start);
particle.life = time;
particle.lifeSpan = bx::lerp(m_uniforms.m_lifeSpan[0], m_uniforms.m_lifeSpan[1], bx::frnd(&m_rng) );
const bx::Vec3 gravity = { 0.0f, -9.81f * m_uniforms.m_gravityScale * bx::square(particle.lifeSpan), 0.0f };
particle.start = bx::mul(start, mtx);
particle.end[0] = bx::mul(end, mtx);
particle.end[1] = bx::add(particle.end[0], gravity);
bx::memCopy(particle.rgba, m_uniforms.m_rgba, BX_COUNTOF(m_uniforms.m_rgba)*sizeof(uint32_t) );
particle.blendStart = bx::lerp(m_uniforms.m_blendStart[0], m_uniforms.m_blendStart[1], bx::frnd(&m_rng) );
particle.blendEnd = bx::lerp(m_uniforms.m_blendEnd[0], m_uniforms.m_blendEnd[1], bx::frnd(&m_rng) );
particle.scaleStart = bx::lerp(m_uniforms.m_scaleStart[0], m_uniforms.m_scaleStart[1], bx::frnd(&m_rng) );
particle.scaleEnd = bx::lerp(m_uniforms.m_scaleEnd[0], m_uniforms.m_scaleEnd[1], bx::frnd(&m_rng) );
time += timePerParticle;
}
}
uint32_t render(const float _uv[4], const float* _mtxView, const bx::Vec3& _eye, uint32_t _first, uint32_t _max, ParticleSort* _outSort, PosColorTexCoord0Vertex* _outVertices)
{
bx::EaseFn easeRgba = bx::getEaseFunc(m_uniforms.m_easeRgba);
bx::EaseFn easePos = bx::getEaseFunc(m_uniforms.m_easePos);
bx::EaseFn easeBlend = bx::getEaseFunc(m_uniforms.m_easeBlend);
bx::EaseFn easeScale = bx::getEaseFunc(m_uniforms.m_easeScale);
Aabb aabb =
{
{ bx::kInfinity, bx::kInfinity, bx::kInfinity },
{ -bx::kInfinity, -bx::kInfinity, -bx::kInfinity },
};
for (uint32_t jj = 0, num = m_num, current = _first
; jj < num && current < _max
; ++jj, ++current
)
{
const Particle& particle = m_particles[jj];
const float ttPos = easePos(particle.life);
const float ttScale = easeScale(particle.life);
const float ttBlend = bx::clamp(easeBlend(particle.life), 0.0f, 1.0f);
const float ttRgba = bx::clamp(easeRgba(particle.life), 0.0f, 1.0f);
const bx::Vec3 p0 = bx::lerp(particle.start, particle.end[0], ttPos);
const bx::Vec3 p1 = bx::lerp(particle.end[0], particle.end[1], ttPos);
const bx::Vec3 pos = bx::lerp(p0, p1, ttPos);
ParticleSort& sort = _outSort[current];
const bx::Vec3 tmp0 = bx::sub(_eye, pos);
sort.dist = bx::length(tmp0);
sort.idx = current;
uint32_t idx = uint32_t(ttRgba*4);
float ttmod = bx::mod(ttRgba, 0.25f)/0.25f;
uint32_t rgbaStart = particle.rgba[idx];
uint32_t rgbaEnd = particle.rgba[idx+1];
float rr = bx::lerp( ( (uint8_t*)&rgbaStart)[0], ( (uint8_t*)&rgbaEnd)[0], ttmod)/255.0f;
float gg = bx::lerp( ( (uint8_t*)&rgbaStart)[1], ( (uint8_t*)&rgbaEnd)[1], ttmod)/255.0f;
float bb = bx::lerp( ( (uint8_t*)&rgbaStart)[2], ( (uint8_t*)&rgbaEnd)[2], ttmod)/255.0f;
float aa = bx::lerp( ( (uint8_t*)&rgbaStart)[3], ( (uint8_t*)&rgbaEnd)[3], ttmod)/255.0f;
float blend = bx::lerp(particle.blendStart, particle.blendEnd, ttBlend);
float scale = bx::lerp(particle.scaleStart, particle.scaleEnd, ttScale);
uint32_t abgr = toAbgr(rr, gg, bb, aa);
const bx::Vec3 udir = { _mtxView[0]*scale, _mtxView[4]*scale, _mtxView[8]*scale };
const bx::Vec3 vdir = { _mtxView[1]*scale, _mtxView[5]*scale, _mtxView[9]*scale };
PosColorTexCoord0Vertex* vertex = &_outVertices[current*4];
const bx::Vec3 ul = bx::sub(bx::sub(pos, udir), vdir);
bx::store(&vertex->m_x, ul);
aabbExpand(aabb, ul);
vertex->m_abgr = abgr;
vertex->m_u = _uv[0];
vertex->m_v = _uv[1];
vertex->m_blend = blend;
++vertex;
const bx::Vec3 ur = bx::sub(bx::add(pos, udir), vdir);
bx::store(&vertex->m_x, ur);
aabbExpand(aabb, ur);
vertex->m_abgr = abgr;
vertex->m_u = _uv[2];
vertex->m_v = _uv[1];
vertex->m_blend = blend;
++vertex;
const bx::Vec3 br = bx::add(bx::add(pos, udir), vdir);
bx::store(&vertex->m_x, br);
aabbExpand(aabb, br);
vertex->m_abgr = abgr;
vertex->m_u = _uv[2];
vertex->m_v = _uv[3];
vertex->m_blend = blend;
++vertex;
const bx::Vec3 bl = bx::add(bx::sub(pos, udir), vdir);
bx::store(&vertex->m_x, bl);
aabbExpand(aabb, bl);
vertex->m_abgr = abgr;
vertex->m_u = _uv[0];
vertex->m_v = _uv[3];
vertex->m_blend = blend;
++vertex;
}
m_aabb = aabb;
return m_num;
}
EmitterShape::Enum m_shape;
EmitterDirection::Enum m_direction;
float m_dt;
bx::RngMwc m_rng;
EmitterUniforms m_uniforms;
Aabb m_aabb;
Particle* m_particles;
uint32_t m_num;
uint32_t m_max;
};
static int32_t particleSortFn(const void* _lhs, const void* _rhs)
{
const ParticleSort& lhs = *(const ParticleSort*)_lhs;
const ParticleSort& rhs = *(const ParticleSort*)_rhs;
return lhs.dist > rhs.dist ? -1 : 1;
}
struct ParticleSystem
{
void init(uint16_t _maxEmitters, bx::AllocatorI* _allocator)
{
m_allocator = _allocator;
if (NULL == _allocator)
{
static bx::DefaultAllocator allocator;
m_allocator = &allocator;
}
m_emitterAlloc = bx::createHandleAlloc(m_allocator, _maxEmitters);
m_emitter = (Emitter*)BX_ALLOC(m_allocator, sizeof(Emitter)*_maxEmitters);
PosColorTexCoord0Vertex::init();
m_num = 0;
s_texColor = bgfx::createUniform("s_texColor", bgfx::UniformType::Sampler);
m_texture = bgfx::createTexture2D(
SPRITE_TEXTURE_SIZE
, SPRITE_TEXTURE_SIZE
, false
, 1
, bgfx::TextureFormat::BGRA8
);
bgfx::RendererType::Enum type = bgfx::getRendererType();
m_particleProgram = bgfx::createProgram(
bgfx::createEmbeddedShader(s_embeddedShaders, type, "vs_particle")
, bgfx::createEmbeddedShader(s_embeddedShaders, type, "fs_particle")
, true
);
}
void shutdown()
{
bgfx::destroy(m_particleProgram);
bgfx::destroy(m_texture);
bgfx::destroy(s_texColor);
bx::destroyHandleAlloc(m_allocator, m_emitterAlloc);
BX_FREE(m_allocator, m_emitter);
m_allocator = NULL;
}
EmitterSpriteHandle createSprite(uint16_t _width, uint16_t _height, const void* _data)
{
EmitterSpriteHandle handle = m_sprite.create(_width, _height);
if (isValid(handle) )
{
const Pack2D& pack = m_sprite.get(handle);
bgfx::updateTexture2D(
m_texture
, 0
, 0
, pack.m_x
, pack.m_y
, pack.m_width
, pack.m_height
, bgfx::copy(_data, pack.m_width*pack.m_height*4)
);
}
return handle;
}
void destroy(EmitterSpriteHandle _handle)
{
m_sprite.destroy(_handle);
}
void update(float _dt)
{
uint32_t numParticles = 0;
for (uint16_t ii = 0, num = m_emitterAlloc->getNumHandles(); ii < num; ++ii)
{
const uint16_t idx = m_emitterAlloc->getHandleAt(ii);
Emitter& emitter = m_emitter[idx];
emitter.update(_dt);
numParticles += emitter.m_num;
}
m_num = numParticles;
}
void render(uint8_t _view, const float* _mtxView, const bx::Vec3& _eye)
{
if (0 != m_num)
{
bgfx::TransientVertexBuffer tvb;
bgfx::TransientIndexBuffer tib;
const uint32_t numVertices = bgfx::getAvailTransientVertexBuffer(m_num*4, PosColorTexCoord0Vertex::ms_decl);
const uint32_t numIndices = bgfx::getAvailTransientIndexBuffer(m_num*6);
const uint32_t max = bx::uint32_min(numVertices/4, numIndices/6);
BX_WARN(m_num == max
, "Truncating transient buffer for particles to maximum available (requested %d, available %d)."
, m_num
, max
);
if (0 < max)
{
bgfx::allocTransientBuffers(&tvb
, PosColorTexCoord0Vertex::ms_decl
, max*4
, &tib
, max*6
);
PosColorTexCoord0Vertex* vertices = (PosColorTexCoord0Vertex*)tvb.data;
ParticleSort* particleSort = (ParticleSort*)BX_ALLOC(m_allocator, max*sizeof(ParticleSort) );
uint32_t pos = 0;
for (uint16_t ii = 0, numEmitters = m_emitterAlloc->getNumHandles(); ii < numEmitters; ++ii)
{
const uint16_t idx = m_emitterAlloc->getHandleAt(ii);
Emitter& emitter = m_emitter[idx];
const Pack2D& pack = m_sprite.get(emitter.m_uniforms.m_handle);
const float invTextureSize = 1.0f/SPRITE_TEXTURE_SIZE;
const float uv[4] =
{
pack.m_x * invTextureSize,
pack.m_y * invTextureSize,
(pack.m_x + pack.m_width ) * invTextureSize,
(pack.m_y + pack.m_height) * invTextureSize,
};
pos += emitter.render(uv, _mtxView, _eye, pos, max, particleSort, vertices);
}
qsort(particleSort
, max
, sizeof(ParticleSort)
, particleSortFn
);
uint16_t* indices = (uint16_t*)tib.data;
for (uint32_t ii = 0; ii < max; ++ii)
{
const ParticleSort& sort = particleSort[ii];
uint16_t* index = &indices[ii*6];
uint16_t idx = (uint16_t)sort.idx;
index[0] = idx*4+0;
index[1] = idx*4+1;
index[2] = idx*4+2;
index[3] = idx*4+2;
index[4] = idx*4+3;
index[5] = idx*4+0;
}
BX_FREE(m_allocator, particleSort);
bgfx::setState(0
| BGFX_STATE_WRITE_RGB
| BGFX_STATE_WRITE_A
| BGFX_STATE_DEPTH_TEST_LESS
| BGFX_STATE_CULL_CW
| BGFX_STATE_BLEND_NORMAL
);
bgfx::setVertexBuffer(0, &tvb);
bgfx::setIndexBuffer(&tib);
bgfx::setTexture(0, s_texColor, m_texture);
bgfx::submit(_view, m_particleProgram);
}
}
}
EmitterHandle createEmitter(EmitterShape::Enum _shape, EmitterDirection::Enum _direction, uint32_t _maxParticles)
{
EmitterHandle handle = { m_emitterAlloc->alloc() };
if (UINT16_MAX != handle.idx)
{
m_emitter[handle.idx].create(_shape, _direction, _maxParticles);
}
return handle;
}
void updateEmitter(EmitterHandle _handle, const EmitterUniforms* _uniforms)
{
BX_CHECK(m_emitterAlloc.isValid(_handle.idx)
, "destroyEmitter handle %d is not valid."
, _handle.idx
);
Emitter& emitter = m_emitter[_handle.idx];
if (NULL == _uniforms)
{
emitter.reset();
}
else
{
bx::memCopy(&emitter.m_uniforms, _uniforms, sizeof(EmitterUniforms) );
}
}
void getAabb(EmitterHandle _handle, Aabb& _outAabb)
{
BX_CHECK(m_emitterAlloc.isValid(_handle.idx)
, "getAabb handle %d is not valid."
, _handle.idx
);
_outAabb = m_emitter[_handle.idx].m_aabb;
}
void destroyEmitter(EmitterHandle _handle)
{
BX_CHECK(m_emitterAlloc.isValid(_handle.idx)
, "destroyEmitter handle %d is not valid."
, _handle.idx
);
m_emitter[_handle.idx].destroy();
m_emitterAlloc->free(_handle.idx);
}
bx::AllocatorI* m_allocator;
bx::HandleAlloc* m_emitterAlloc;
Emitter* m_emitter;
typedef SpriteT<256, SPRITE_TEXTURE_SIZE> Sprite;
Sprite m_sprite;
bgfx::UniformHandle s_texColor;
bgfx::TextureHandle m_texture;
bgfx::ProgramHandle m_particleProgram;
uint32_t m_num;
};
static ParticleSystem s_ctx;
void Emitter::create(EmitterShape::Enum _shape, EmitterDirection::Enum _direction, uint32_t _maxParticles)
{
reset();
m_shape = _shape;
m_direction = _direction;
m_max = _maxParticles;
m_particles = (Particle*)BX_ALLOC(s_ctx.m_allocator, m_max*sizeof(Particle) );
}
void Emitter::destroy()
{
BX_FREE(s_ctx.m_allocator, m_particles);
m_particles = NULL;
}
} // namespace ps
using namespace ps;
void psInit(uint16_t _maxEmitters, bx::AllocatorI* _allocator)
{
s_ctx.init(_maxEmitters, _allocator);
}
void psShutdown()
{
s_ctx.shutdown();
}
EmitterSpriteHandle psCreateSprite(uint16_t _width, uint16_t _height, const void* _data)
{
return s_ctx.createSprite(_width, _height, _data);
}
void psDestroy(EmitterSpriteHandle _handle)
{
s_ctx.destroy(_handle);
}
EmitterHandle psCreateEmitter(EmitterShape::Enum _shape, EmitterDirection::Enum _direction, uint32_t _maxParticles)
{
return s_ctx.createEmitter(_shape, _direction, _maxParticles);
}
void psUpdateEmitter(EmitterHandle _handle, const EmitterUniforms* _uniforms)
{
s_ctx.updateEmitter(_handle, _uniforms);
}
void psGetAabb(EmitterHandle _handle, Aabb& _outAabb)
{
s_ctx.getAabb(_handle, _outAabb);
}
void psDestroyEmitter(EmitterHandle _handle)
{
s_ctx.destroyEmitter(_handle);
}
void psUpdate(float _dt)
{
s_ctx.update(_dt);
}
void psRender(uint8_t _view, const float* _mtxView, const bx::Vec3& _eye)
{
s_ctx.render(_view, _mtxView, _eye);
}
| bsd-2-clause |
retronym/slick | src/main/scala/scala/slick/ast/ColumnOption.scala | 433 | package scala.slick.ast
abstract class ColumnOption[+T]
object ColumnOption {
case object NotNull extends ColumnOption[Nothing]
case object Nullable extends ColumnOption[Nothing]
case object PrimaryKey extends ColumnOption[Nothing]
case class Default[T](val defaultValue: T) extends ColumnOption[T]
case class DBType(val dbType: String) extends ColumnOption[Nothing]
case object AutoInc extends ColumnOption[Nothing]
}
| bsd-2-clause |
dezon/homebrew-cask | Casks/sococo.rb | 328 | cask :v1 => 'sococo' do
version '3.2.7'
sha256 '6772f2c2ef5c7b046612de408b79a71ed0936041fb9286785af69d862f653d1f'
url "http://download.sococo.com/10069/Sococo_#{version.gsub('.','_')}_10069.dmg"
homepage 'http://www.sococo.com'
license :unknown # todo: improve this machine-generated value
app 'Sococo.app'
end
| bsd-2-clause |
sebastienros/jint | Jint.Tests.Test262/test/built-ins/DataView/prototype/setFloat64/range-check-after-value-conversion.js | 1225 | // Copyright (C) 2015 André Bargull. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
esid: sec-dataview.prototype.setfloat64
description: >
Index bounds checks are performed after value conversion.
info: |
...
3. Return SetViewValue(v, byteOffset, littleEndian, "Float64", value).
24.2.1.2 SetViewValue ( view, requestIndex, isLittleEndian, type, value )
...
3. Let numberIndex be ToNumber(requestIndex).
4. Let getIndex be ? ToInteger(numberIndex).
...
6. Let numberValue be ? ToNumber(value).
...
11. Let viewSize be the value of view's [[ByteLength]] internal slot.
12. Let elementSize be the Number value of the Element Size value specified in Table 49 for Element Type type.
13. If getIndex + elementSize > viewSize, throw a RangeError exception.
...
---*/
var dataView = new DataView(new ArrayBuffer(8), 0);
var poisoned = {
valueOf: function() {
throw new Test262Error();
}
};
assert.throws(Test262Error, function() {
dataView.setFloat64(100, poisoned);
}, "setFloat64(100, poisoned)");
assert.throws(Test262Error, function() {
dataView.setFloat64('100', poisoned);
}, "setFloat64('100', poisoned)");
| bsd-2-clause |
bcg62/homebrew-core | Formula/pure-ftpd.rb | 2040 | class PureFtpd < Formula
desc "Secure and efficient FTP server"
homepage "https://www.pureftpd.org/"
url "https://download.pureftpd.org/pub/pure-ftpd/releases/pure-ftpd-1.0.47.tar.gz"
sha256 "4740c316f5df879a2d68464489fb9b8b90113fe7dce58e2cdd2054a4768f27ad"
bottle do
sha256 "f848669051fc9f2dcd98373a5c2c12029c3f59cc4cebae13bb246164650c0fa3" => :mojave
sha256 "3ee0ae276bad11f6459e2a866f96f7618a12b8625e69dd1d2b3fbcb3c7f3d3fe" => :high_sierra
sha256 "fcde5497abd815c560b9b8dc1bcb40d1018e378e16fcbc04cb942d244a64c972" => :sierra
sha256 "db8752838fcba745378a65f79c40ee8e573f50cd648d48b23b47b813dfb5cba1" => :el_capitan
end
depends_on "libsodium"
depends_on "openssl"
def install
args = %W[
--disable-dependency-tracking
--prefix=#{prefix}
--mandir=#{man}
--sysconfdir=#{etc}
--with-everything
--with-pam
--with-tls
--with-bonjour
]
system "./configure", *args
system "make", "install"
end
plist_options :manual => "pure-ftpd"
def plist; <<~EOS
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>KeepAlive</key>
<true/>
<key>Label</key>
<string>#{plist_name}</string>
<key>ProgramArguments</key>
<array>
<string>#{opt_sbin}/pure-ftpd</string>
<string>--chrooteveryone</string>
<string>--createhomedir</string>
<string>--allowdotfiles</string>
<string>--login=puredb:#{etc}/pureftpd.pdb</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>WorkingDirectory</key>
<string>#{var}</string>
<key>StandardErrorPath</key>
<string>#{var}/log/pure-ftpd.log</string>
<key>StandardOutPath</key>
<string>#{var}/log/pure-ftpd.log</string>
</dict>
</plist>
EOS
end
test do
system bin/"pure-pw", "--help"
end
end
| bsd-2-clause |
libin/presto | test/test-test/rakefile.rb | 113 | require "rake/testtask"
Rake::TestTask.new do |t|
t.test_files = FileList["*.test.rb"]
t.verbose = true
end
| bsd-3-clause |
wholmgren/pvlib-python | pvlib/tests/test_singlediode.py | 11085 | """
testing single-diode methods using JW Bishop 1988
"""
import numpy as np
from pvlib import pvsystem
from pvlib.singlediode import (bishop88_mpp, estimate_voc, VOLTAGE_BUILTIN,
bishop88, bishop88_i_from_v, bishop88_v_from_i)
import pytest
POA = 888
TCELL = 55
@pytest.mark.parametrize('method', ['brentq', 'newton'])
def test_method_spr_e20_327(method, cec_module_spr_e20_327):
"""test pvsystem.singlediode with different methods on SPR-E20-327"""
spr_e20_327 = cec_module_spr_e20_327
x = pvsystem.calcparams_desoto(
effective_irradiance=POA, temp_cell=TCELL,
alpha_sc=spr_e20_327['alpha_sc'], a_ref=spr_e20_327['a_ref'],
I_L_ref=spr_e20_327['I_L_ref'], I_o_ref=spr_e20_327['I_o_ref'],
R_sh_ref=spr_e20_327['R_sh_ref'], R_s=spr_e20_327['R_s'],
EgRef=1.121, dEgdT=-0.0002677)
il, io, rs, rsh, nnsvt = x
pvs = pvsystem.singlediode(*x, method='lambertw')
out = pvsystem.singlediode(*x, method=method)
isc, voc, imp, vmp, pmp, ix, ixx = out.values()
assert np.isclose(pvs['i_sc'], isc)
assert np.isclose(pvs['v_oc'], voc)
# the singlediode method doesn't actually get the MPP correct
pvs_imp = pvsystem.i_from_v(rsh, rs, nnsvt, vmp, io, il, method='lambertw')
pvs_vmp = pvsystem.v_from_i(rsh, rs, nnsvt, imp, io, il, method='lambertw')
assert np.isclose(pvs_imp, imp)
assert np.isclose(pvs_vmp, vmp)
assert np.isclose(pvs['p_mp'], pmp)
assert np.isclose(pvs['i_x'], ix)
pvs_ixx = pvsystem.i_from_v(rsh, rs, nnsvt, (voc + vmp)/2, io, il,
method='lambertw')
assert np.isclose(pvs_ixx, ixx)
@pytest.mark.parametrize('method', ['brentq', 'newton'])
def test_newton_fs_495(method, cec_module_fs_495):
"""test pvsystem.singlediode with different methods on FS495"""
fs_495 = cec_module_fs_495
x = pvsystem.calcparams_desoto(
effective_irradiance=POA, temp_cell=TCELL,
alpha_sc=fs_495['alpha_sc'], a_ref=fs_495['a_ref'],
I_L_ref=fs_495['I_L_ref'], I_o_ref=fs_495['I_o_ref'],
R_sh_ref=fs_495['R_sh_ref'], R_s=fs_495['R_s'],
EgRef=1.475, dEgdT=-0.0003)
il, io, rs, rsh, nnsvt = x
x += (101, )
pvs = pvsystem.singlediode(*x, method='lambertw')
out = pvsystem.singlediode(*x, method=method)
isc, voc, imp, vmp, pmp, ix, ixx, i, v = out.values()
assert np.isclose(pvs['i_sc'], isc)
assert np.isclose(pvs['v_oc'], voc)
# the singlediode method doesn't actually get the MPP correct
pvs_imp = pvsystem.i_from_v(rsh, rs, nnsvt, vmp, io, il, method='lambertw')
pvs_vmp = pvsystem.v_from_i(rsh, rs, nnsvt, imp, io, il, method='lambertw')
assert np.isclose(pvs_imp, imp)
assert np.isclose(pvs_vmp, vmp)
assert np.isclose(pvs['p_mp'], pmp)
assert np.isclose(pvs['i_x'], ix)
pvs_ixx = pvsystem.i_from_v(rsh, rs, nnsvt, (voc + vmp)/2, io, il,
method='lambertw')
assert np.isclose(pvs_ixx, ixx)
def get_pvsyst_fs_495():
"""
PVsyst parameters for First Solar FS-495 module from PVSyst-6.7.2 database.
I_L_ref derived from Isc_ref conditions::
I_L_ref = (I_sc_ref + Id + Ish) / (1 - d2mutau/(Vbi*N_s - Vd))
where::
Vd = I_sc_ref * R_s
Id = I_o_ref * (exp(Vd / nNsVt) - 1)
Ish = Vd / R_sh_ref
"""
return {
'd2mutau': 1.31, 'alpha_sc': 0.00039, 'gamma_ref': 1.48,
'mu_gamma': 0.001, 'I_o_ref': 9.62e-10, 'R_sh_ref': 5000,
'R_sh_0': 12500, 'R_sh_exp': 3.1, 'R_s': 4.6, 'beta_oc': -0.2116,
'EgRef': 1.5, 'cells_in_series': 108, 'cells_in_parallel': 2,
'I_sc_ref': 1.55, 'V_oc_ref': 86.5, 'I_mp_ref': 1.4, 'V_mp_ref': 67.85,
'temp_ref': 25, 'irrad_ref': 1000, 'I_L_ref': 1.5743233463848496
}
# DeSoto @(888[W/m**2], 55[degC]) = {Pmp: 72.71, Isc: 1.402, Voc: 75.42)
@pytest.mark.parametrize(
'poa, temp_cell, expected, tol', [
# reference conditions
(
get_pvsyst_fs_495()['irrad_ref'],
get_pvsyst_fs_495()['temp_ref'],
{
'pmp': (get_pvsyst_fs_495()['I_mp_ref'] *
get_pvsyst_fs_495()['V_mp_ref']),
'isc': get_pvsyst_fs_495()['I_sc_ref'],
'voc': get_pvsyst_fs_495()['V_oc_ref']
},
(5e-4, 0.04)
),
# other conditions
(
POA,
TCELL,
{
'pmp': 76.262,
'isc': 1.3868,
'voc': 79.292
},
(1e-4, 1e-4)
)
]
)
@pytest.mark.parametrize('method', ['newton', 'brentq'])
def test_pvsyst_recombination_loss(method, poa, temp_cell, expected, tol):
"""test PVSst recombination loss"""
pvsyst_fs_495 = get_pvsyst_fs_495()
# first evaluate PVSyst model with thin-film recombination loss current
# at reference conditions
x = pvsystem.calcparams_pvsyst(
effective_irradiance=poa, temp_cell=temp_cell,
alpha_sc=pvsyst_fs_495['alpha_sc'],
gamma_ref=pvsyst_fs_495['gamma_ref'],
mu_gamma=pvsyst_fs_495['mu_gamma'], I_L_ref=pvsyst_fs_495['I_L_ref'],
I_o_ref=pvsyst_fs_495['I_o_ref'], R_sh_ref=pvsyst_fs_495['R_sh_ref'],
R_sh_0=pvsyst_fs_495['R_sh_0'], R_sh_exp=pvsyst_fs_495['R_sh_exp'],
R_s=pvsyst_fs_495['R_s'],
cells_in_series=pvsyst_fs_495['cells_in_series'],
EgRef=pvsyst_fs_495['EgRef']
)
il_pvsyst, io_pvsyst, rs_pvsyst, rsh_pvsyst, nnsvt_pvsyst = x
voc_est_pvsyst = estimate_voc(photocurrent=il_pvsyst,
saturation_current=io_pvsyst,
nNsVth=nnsvt_pvsyst)
vd_pvsyst = np.linspace(0, voc_est_pvsyst, 1000)
pvsyst = bishop88(
diode_voltage=vd_pvsyst, photocurrent=il_pvsyst,
saturation_current=io_pvsyst, resistance_series=rs_pvsyst,
resistance_shunt=rsh_pvsyst, nNsVth=nnsvt_pvsyst,
d2mutau=pvsyst_fs_495['d2mutau'],
NsVbi=VOLTAGE_BUILTIN*pvsyst_fs_495['cells_in_series']
)
# test max power
assert np.isclose(max(pvsyst[2]), expected['pmp'], *tol)
# test short circuit current
isc_pvsyst = np.interp(0, pvsyst[1], pvsyst[0])
assert np.isclose(isc_pvsyst, expected['isc'], *tol)
# test open circuit voltage
voc_pvsyst = np.interp(0, pvsyst[0][::-1], pvsyst[1][::-1])
assert np.isclose(voc_pvsyst, expected['voc'], *tol)
# repeat tests as above with specialized bishop88 functions
y = dict(d2mutau=pvsyst_fs_495['d2mutau'],
NsVbi=VOLTAGE_BUILTIN*pvsyst_fs_495['cells_in_series'])
mpp_88 = bishop88_mpp(*x, **y, method=method)
assert np.isclose(mpp_88[2], expected['pmp'], *tol)
isc_88 = bishop88_i_from_v(0, *x, **y, method=method)
assert np.isclose(isc_88, expected['isc'], *tol)
voc_88 = bishop88_v_from_i(0, *x, **y, method=method)
assert np.isclose(voc_88, expected['voc'], *tol)
ioc_88 = bishop88_i_from_v(voc_88, *x, **y, method=method)
assert np.isclose(ioc_88, 0.0, *tol)
vsc_88 = bishop88_v_from_i(isc_88, *x, **y, method=method)
assert np.isclose(vsc_88, 0.0, *tol)
@pytest.mark.parametrize(
'brk_params, recomb_params, poa, temp_cell, expected, tol', [
# reference conditions without breakdown model
(
(0., -5.5, 3.28),
(get_pvsyst_fs_495()['d2mutau'],
VOLTAGE_BUILTIN * get_pvsyst_fs_495()['cells_in_series']),
get_pvsyst_fs_495()['irrad_ref'],
get_pvsyst_fs_495()['temp_ref'],
{
'pmp': (get_pvsyst_fs_495()['I_mp_ref'] * # noqa: W504
get_pvsyst_fs_495()['V_mp_ref']),
'isc': get_pvsyst_fs_495()['I_sc_ref'],
'voc': get_pvsyst_fs_495()['V_oc_ref']
},
(5e-4, 0.04)
),
# other conditions with breakdown model on and recombination model off
(
(1.e-4, -5.5, 3.28),
(0., np.Inf),
POA,
TCELL,
{
'pmp': 79.723,
'isc': 1.4071,
'voc': 79.646
},
(1e-4, 1e-4)
)
]
)
@pytest.mark.parametrize('method', ['newton', 'brentq'])
def test_pvsyst_breakdown(method, brk_params, recomb_params, poa, temp_cell,
expected, tol):
"""test PVSyst recombination loss"""
pvsyst_fs_495 = get_pvsyst_fs_495()
# first evaluate PVSyst model with thin-film recombination loss current
# at reference conditions
x = pvsystem.calcparams_pvsyst(
effective_irradiance=poa, temp_cell=temp_cell,
alpha_sc=pvsyst_fs_495['alpha_sc'],
gamma_ref=pvsyst_fs_495['gamma_ref'],
mu_gamma=pvsyst_fs_495['mu_gamma'], I_L_ref=pvsyst_fs_495['I_L_ref'],
I_o_ref=pvsyst_fs_495['I_o_ref'], R_sh_ref=pvsyst_fs_495['R_sh_ref'],
R_sh_0=pvsyst_fs_495['R_sh_0'], R_sh_exp=pvsyst_fs_495['R_sh_exp'],
R_s=pvsyst_fs_495['R_s'],
cells_in_series=pvsyst_fs_495['cells_in_series'],
EgRef=pvsyst_fs_495['EgRef']
)
il_pvsyst, io_pvsyst, rs_pvsyst, rsh_pvsyst, nnsvt_pvsyst = x
d2mutau, NsVbi = recomb_params
breakdown_factor, breakdown_voltage, breakdown_exp = brk_params
voc_est_pvsyst = estimate_voc(photocurrent=il_pvsyst,
saturation_current=io_pvsyst,
nNsVth=nnsvt_pvsyst)
vd_pvsyst = np.linspace(0, voc_est_pvsyst, 1000)
pvsyst = bishop88(
diode_voltage=vd_pvsyst, photocurrent=il_pvsyst,
saturation_current=io_pvsyst, resistance_series=rs_pvsyst,
resistance_shunt=rsh_pvsyst, nNsVth=nnsvt_pvsyst,
d2mutau=d2mutau, NsVbi=NsVbi,
breakdown_factor=breakdown_factor, breakdown_voltage=breakdown_voltage,
breakdown_exp=breakdown_exp
)
# test max power
assert np.isclose(max(pvsyst[2]), expected['pmp'], *tol)
# test short circuit current
isc_pvsyst = np.interp(0, pvsyst[1], pvsyst[0])
assert np.isclose(isc_pvsyst, expected['isc'], *tol)
# test open circuit voltage
voc_pvsyst = np.interp(0, pvsyst[0][::-1], pvsyst[1][::-1])
assert np.isclose(voc_pvsyst, expected['voc'], *tol)
# repeat tests as above with specialized bishop88 functions
y = {'d2mutau': recomb_params[0], 'NsVbi': recomb_params[1],
'breakdown_factor': brk_params[0], 'breakdown_voltage': brk_params[1],
'breakdown_exp': brk_params[2]}
mpp_88 = bishop88_mpp(*x, **y, method=method)
assert np.isclose(mpp_88[2], expected['pmp'], *tol)
isc_88 = bishop88_i_from_v(0, *x, **y, method=method)
assert np.isclose(isc_88, expected['isc'], *tol)
voc_88 = bishop88_v_from_i(0, *x, **y, method=method)
assert np.isclose(voc_88, expected['voc'], *tol)
ioc_88 = bishop88_i_from_v(voc_88, *x, **y, method=method)
assert np.isclose(ioc_88, 0.0, *tol)
vsc_88 = bishop88_v_from_i(isc_88, *x, **y, method=method)
assert np.isclose(vsc_88, 0.0, *tol)
| bsd-3-clause |
mwhudson/go | src/strings/strings.go | 19311 | // Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package strings implements simple functions to manipulate UTF-8 encoded strings.
//
// For information about UTF-8 strings in Go, see https://blog.golang.org/strings.
package strings
import (
"unicode"
"unicode/utf8"
)
// explode splits s into an array of UTF-8 sequences, one per Unicode character (still strings) up to a maximum of n (n < 0 means no limit).
// Invalid UTF-8 sequences become correct encodings of U+FFF8.
func explode(s string, n int) []string {
if n == 0 {
return nil
}
l := utf8.RuneCountInString(s)
if n <= 0 || n > l {
n = l
}
a := make([]string, n)
var size int
var ch rune
i, cur := 0, 0
for ; i+1 < n; i++ {
ch, size = utf8.DecodeRuneInString(s[cur:])
if ch == utf8.RuneError {
a[i] = string(utf8.RuneError)
} else {
a[i] = s[cur : cur+size]
}
cur += size
}
// add the rest, if there is any
if cur < len(s) {
a[i] = s[cur:]
}
return a
}
// primeRK is the prime base used in Rabin-Karp algorithm.
const primeRK = 16777619
// hashStr returns the hash and the appropriate multiplicative
// factor for use in Rabin-Karp algorithm.
func hashStr(sep string) (uint32, uint32) {
hash := uint32(0)
for i := 0; i < len(sep); i++ {
hash = hash*primeRK + uint32(sep[i])
}
var pow, sq uint32 = 1, primeRK
for i := len(sep); i > 0; i >>= 1 {
if i&1 != 0 {
pow *= sq
}
sq *= sq
}
return hash, pow
}
// hashStrRev returns the hash of the reverse of sep and the
// appropriate multiplicative factor for use in Rabin-Karp algorithm.
func hashStrRev(sep string) (uint32, uint32) {
hash := uint32(0)
for i := len(sep) - 1; i >= 0; i-- {
hash = hash*primeRK + uint32(sep[i])
}
var pow, sq uint32 = 1, primeRK
for i := len(sep); i > 0; i >>= 1 {
if i&1 != 0 {
pow *= sq
}
sq *= sq
}
return hash, pow
}
// Count counts the number of non-overlapping instances of sep in s.
// If sep is an empty string, Count returns 1 + the number of Unicode code points in s.
func Count(s, sep string) int {
n := 0
// special cases
switch {
case len(sep) == 0:
return utf8.RuneCountInString(s) + 1
case len(sep) == 1:
// special case worth making fast
c := sep[0]
for i := 0; i < len(s); i++ {
if s[i] == c {
n++
}
}
return n
case len(sep) > len(s):
return 0
case len(sep) == len(s):
if sep == s {
return 1
}
return 0
}
// Rabin-Karp search
hashsep, pow := hashStr(sep)
h := uint32(0)
for i := 0; i < len(sep); i++ {
h = h*primeRK + uint32(s[i])
}
lastmatch := 0
if h == hashsep && s[:len(sep)] == sep {
n++
lastmatch = len(sep)
}
for i := len(sep); i < len(s); {
h *= primeRK
h += uint32(s[i])
h -= pow * uint32(s[i-len(sep)])
i++
if h == hashsep && lastmatch <= i-len(sep) && s[i-len(sep):i] == sep {
n++
lastmatch = i
}
}
return n
}
// Contains reports whether substr is within s.
func Contains(s, substr string) bool {
return Index(s, substr) >= 0
}
// ContainsAny reports whether any Unicode code points in chars are within s.
func ContainsAny(s, chars string) bool {
return IndexAny(s, chars) >= 0
}
// ContainsRune reports whether the Unicode code point r is within s.
func ContainsRune(s string, r rune) bool {
return IndexRune(s, r) >= 0
}
// LastIndex returns the index of the last instance of sep in s, or -1 if sep is not present in s.
func LastIndex(s, sep string) int {
n := len(sep)
switch {
case n == 0:
return len(s)
case n == 1:
return LastIndexByte(s, sep[0])
case n == len(s):
if sep == s {
return 0
}
return -1
case n > len(s):
return -1
}
// Rabin-Karp search from the end of the string
hashsep, pow := hashStrRev(sep)
last := len(s) - n
var h uint32
for i := len(s) - 1; i >= last; i-- {
h = h*primeRK + uint32(s[i])
}
if h == hashsep && s[last:] == sep {
return last
}
for i := last - 1; i >= 0; i-- {
h *= primeRK
h += uint32(s[i])
h -= pow * uint32(s[i+n])
if h == hashsep && s[i:i+n] == sep {
return i
}
}
return -1
}
// IndexRune returns the index of the first instance of the Unicode code point
// r, or -1 if rune is not present in s.
func IndexRune(s string, r rune) int {
switch {
case r < utf8.RuneSelf:
return IndexByte(s, byte(r))
default:
for i, c := range s {
if c == r {
return i
}
}
}
return -1
}
// IndexAny returns the index of the first instance of any Unicode code point
// from chars in s, or -1 if no Unicode code point from chars is present in s.
func IndexAny(s, chars string) int {
if len(chars) > 0 {
for i, c := range s {
for _, m := range chars {
if c == m {
return i
}
}
}
}
return -1
}
// LastIndexAny returns the index of the last instance of any Unicode code
// point from chars in s, or -1 if no Unicode code point from chars is
// present in s.
func LastIndexAny(s, chars string) int {
if len(chars) > 0 {
for i := len(s); i > 0; {
rune, size := utf8.DecodeLastRuneInString(s[0:i])
i -= size
for _, m := range chars {
if rune == m {
return i
}
}
}
}
return -1
}
// LastIndexByte returns the index of the last instance of c in s, or -1 if c is not present in s.
func LastIndexByte(s string, c byte) int {
for i := len(s) - 1; i >= 0; i-- {
if s[i] == c {
return i
}
}
return -1
}
// Generic split: splits after each instance of sep,
// including sepSave bytes of sep in the subarrays.
func genSplit(s, sep string, sepSave, n int) []string {
if n == 0 {
return nil
}
if sep == "" {
return explode(s, n)
}
if n < 0 {
n = Count(s, sep) + 1
}
c := sep[0]
start := 0
a := make([]string, n)
na := 0
for i := 0; i+len(sep) <= len(s) && na+1 < n; i++ {
if s[i] == c && (len(sep) == 1 || s[i:i+len(sep)] == sep) {
a[na] = s[start : i+sepSave]
na++
start = i + len(sep)
i += len(sep) - 1
}
}
a[na] = s[start:]
return a[0 : na+1]
}
// SplitN slices s into substrings separated by sep and returns a slice of
// the substrings between those separators.
// If sep is empty, SplitN splits after each UTF-8 sequence.
// The count determines the number of substrings to return:
// n > 0: at most n substrings; the last substring will be the unsplit remainder.
// n == 0: the result is nil (zero substrings)
// n < 0: all substrings
func SplitN(s, sep string, n int) []string { return genSplit(s, sep, 0, n) }
// SplitAfterN slices s into substrings after each instance of sep and
// returns a slice of those substrings.
// If sep is empty, SplitAfterN splits after each UTF-8 sequence.
// The count determines the number of substrings to return:
// n > 0: at most n substrings; the last substring will be the unsplit remainder.
// n == 0: the result is nil (zero substrings)
// n < 0: all substrings
func SplitAfterN(s, sep string, n int) []string {
return genSplit(s, sep, len(sep), n)
}
// Split slices s into all substrings separated by sep and returns a slice of
// the substrings between those separators.
// If sep is empty, Split splits after each UTF-8 sequence.
// It is equivalent to SplitN with a count of -1.
func Split(s, sep string) []string { return genSplit(s, sep, 0, -1) }
// SplitAfter slices s into all substrings after each instance of sep and
// returns a slice of those substrings.
// If sep is empty, SplitAfter splits after each UTF-8 sequence.
// It is equivalent to SplitAfterN with a count of -1.
func SplitAfter(s, sep string) []string {
return genSplit(s, sep, len(sep), -1)
}
// Fields splits the string s around each instance of one or more consecutive white space
// characters, as defined by unicode.IsSpace, returning an array of substrings of s or an
// empty list if s contains only white space.
func Fields(s string) []string {
return FieldsFunc(s, unicode.IsSpace)
}
// FieldsFunc splits the string s at each run of Unicode code points c satisfying f(c)
// and returns an array of slices of s. If all code points in s satisfy f(c) or the
// string is empty, an empty slice is returned.
// FieldsFunc makes no guarantees about the order in which it calls f(c).
// If f does not return consistent results for a given c, FieldsFunc may crash.
func FieldsFunc(s string, f func(rune) bool) []string {
// First count the fields.
n := 0
inField := false
for _, rune := range s {
wasInField := inField
inField = !f(rune)
if inField && !wasInField {
n++
}
}
// Now create them.
a := make([]string, n)
na := 0
fieldStart := -1 // Set to -1 when looking for start of field.
for i, rune := range s {
if f(rune) {
if fieldStart >= 0 {
a[na] = s[fieldStart:i]
na++
fieldStart = -1
}
} else if fieldStart == -1 {
fieldStart = i
}
}
if fieldStart >= 0 { // Last field might end at EOF.
a[na] = s[fieldStart:]
}
return a
}
// Join concatenates the elements of a to create a single string. The separator string
// sep is placed between elements in the resulting string.
func Join(a []string, sep string) string {
if len(a) == 0 {
return ""
}
if len(a) == 1 {
return a[0]
}
n := len(sep) * (len(a) - 1)
for i := 0; i < len(a); i++ {
n += len(a[i])
}
b := make([]byte, n)
bp := copy(b, a[0])
for _, s := range a[1:] {
bp += copy(b[bp:], sep)
bp += copy(b[bp:], s)
}
return string(b)
}
// HasPrefix tests whether the string s begins with prefix.
func HasPrefix(s, prefix string) bool {
return len(s) >= len(prefix) && s[0:len(prefix)] == prefix
}
// HasSuffix tests whether the string s ends with suffix.
func HasSuffix(s, suffix string) bool {
return len(s) >= len(suffix) && s[len(s)-len(suffix):] == suffix
}
// Map returns a copy of the string s with all its characters modified
// according to the mapping function. If mapping returns a negative value, the character is
// dropped from the string with no replacement.
func Map(mapping func(rune) rune, s string) string {
// In the worst case, the string can grow when mapped, making
// things unpleasant. But it's so rare we barge in assuming it's
// fine. It could also shrink but that falls out naturally.
maxbytes := len(s) // length of b
nbytes := 0 // number of bytes encoded in b
// The output buffer b is initialized on demand, the first
// time a character differs.
var b []byte
for i, c := range s {
r := mapping(c)
if b == nil {
if r == c {
continue
}
b = make([]byte, maxbytes)
nbytes = copy(b, s[:i])
}
if r >= 0 {
wid := 1
if r >= utf8.RuneSelf {
wid = utf8.RuneLen(r)
}
if nbytes+wid > maxbytes {
// Grow the buffer.
maxbytes = maxbytes*2 + utf8.UTFMax
nb := make([]byte, maxbytes)
copy(nb, b[0:nbytes])
b = nb
}
nbytes += utf8.EncodeRune(b[nbytes:maxbytes], r)
}
}
if b == nil {
return s
}
return string(b[0:nbytes])
}
// Repeat returns a new string consisting of count copies of the string s.
func Repeat(s string, count int) string {
b := make([]byte, len(s)*count)
bp := copy(b, s)
for bp < len(b) {
copy(b[bp:], b[:bp])
bp *= 2
}
return string(b)
}
// ToUpper returns a copy of the string s with all Unicode letters mapped to their upper case.
func ToUpper(s string) string { return Map(unicode.ToUpper, s) }
// ToLower returns a copy of the string s with all Unicode letters mapped to their lower case.
func ToLower(s string) string { return Map(unicode.ToLower, s) }
// ToTitle returns a copy of the string s with all Unicode letters mapped to their title case.
func ToTitle(s string) string { return Map(unicode.ToTitle, s) }
// ToUpperSpecial returns a copy of the string s with all Unicode letters mapped to their
// upper case, giving priority to the special casing rules.
func ToUpperSpecial(_case unicode.SpecialCase, s string) string {
return Map(func(r rune) rune { return _case.ToUpper(r) }, s)
}
// ToLowerSpecial returns a copy of the string s with all Unicode letters mapped to their
// lower case, giving priority to the special casing rules.
func ToLowerSpecial(_case unicode.SpecialCase, s string) string {
return Map(func(r rune) rune { return _case.ToLower(r) }, s)
}
// ToTitleSpecial returns a copy of the string s with all Unicode letters mapped to their
// title case, giving priority to the special casing rules.
func ToTitleSpecial(_case unicode.SpecialCase, s string) string {
return Map(func(r rune) rune { return _case.ToTitle(r) }, s)
}
// isSeparator reports whether the rune could mark a word boundary.
// TODO: update when package unicode captures more of the properties.
func isSeparator(r rune) bool {
// ASCII alphanumerics and underscore are not separators
if r <= 0x7F {
switch {
case '0' <= r && r <= '9':
return false
case 'a' <= r && r <= 'z':
return false
case 'A' <= r && r <= 'Z':
return false
case r == '_':
return false
}
return true
}
// Letters and digits are not separators
if unicode.IsLetter(r) || unicode.IsDigit(r) {
return false
}
// Otherwise, all we can do for now is treat spaces as separators.
return unicode.IsSpace(r)
}
// Title returns a copy of the string s with all Unicode letters that begin words
// mapped to their title case.
//
// BUG(rsc): The rule Title uses for word boundaries does not handle Unicode punctuation properly.
func Title(s string) string {
// Use a closure here to remember state.
// Hackish but effective. Depends on Map scanning in order and calling
// the closure once per rune.
prev := ' '
return Map(
func(r rune) rune {
if isSeparator(prev) {
prev = r
return unicode.ToTitle(r)
}
prev = r
return r
},
s)
}
// TrimLeftFunc returns a slice of the string s with all leading
// Unicode code points c satisfying f(c) removed.
func TrimLeftFunc(s string, f func(rune) bool) string {
i := indexFunc(s, f, false)
if i == -1 {
return ""
}
return s[i:]
}
// TrimRightFunc returns a slice of the string s with all trailing
// Unicode code points c satisfying f(c) removed.
func TrimRightFunc(s string, f func(rune) bool) string {
i := lastIndexFunc(s, f, false)
if i >= 0 && s[i] >= utf8.RuneSelf {
_, wid := utf8.DecodeRuneInString(s[i:])
i += wid
} else {
i++
}
return s[0:i]
}
// TrimFunc returns a slice of the string s with all leading
// and trailing Unicode code points c satisfying f(c) removed.
func TrimFunc(s string, f func(rune) bool) string {
return TrimRightFunc(TrimLeftFunc(s, f), f)
}
// IndexFunc returns the index into s of the first Unicode
// code point satisfying f(c), or -1 if none do.
func IndexFunc(s string, f func(rune) bool) int {
return indexFunc(s, f, true)
}
// LastIndexFunc returns the index into s of the last
// Unicode code point satisfying f(c), or -1 if none do.
func LastIndexFunc(s string, f func(rune) bool) int {
return lastIndexFunc(s, f, true)
}
// indexFunc is the same as IndexFunc except that if
// truth==false, the sense of the predicate function is
// inverted.
func indexFunc(s string, f func(rune) bool, truth bool) int {
start := 0
for start < len(s) {
wid := 1
r := rune(s[start])
if r >= utf8.RuneSelf {
r, wid = utf8.DecodeRuneInString(s[start:])
}
if f(r) == truth {
return start
}
start += wid
}
return -1
}
// lastIndexFunc is the same as LastIndexFunc except that if
// truth==false, the sense of the predicate function is
// inverted.
func lastIndexFunc(s string, f func(rune) bool, truth bool) int {
for i := len(s); i > 0; {
r, size := utf8.DecodeLastRuneInString(s[0:i])
i -= size
if f(r) == truth {
return i
}
}
return -1
}
func makeCutsetFunc(cutset string) func(rune) bool {
return func(r rune) bool { return IndexRune(cutset, r) >= 0 }
}
// Trim returns a slice of the string s with all leading and
// trailing Unicode code points contained in cutset removed.
func Trim(s string, cutset string) string {
if s == "" || cutset == "" {
return s
}
return TrimFunc(s, makeCutsetFunc(cutset))
}
// TrimLeft returns a slice of the string s with all leading
// Unicode code points contained in cutset removed.
func TrimLeft(s string, cutset string) string {
if s == "" || cutset == "" {
return s
}
return TrimLeftFunc(s, makeCutsetFunc(cutset))
}
// TrimRight returns a slice of the string s, with all trailing
// Unicode code points contained in cutset removed.
func TrimRight(s string, cutset string) string {
if s == "" || cutset == "" {
return s
}
return TrimRightFunc(s, makeCutsetFunc(cutset))
}
// TrimSpace returns a slice of the string s, with all leading
// and trailing white space removed, as defined by Unicode.
func TrimSpace(s string) string {
return TrimFunc(s, unicode.IsSpace)
}
// TrimPrefix returns s without the provided leading prefix string.
// If s doesn't start with prefix, s is returned unchanged.
func TrimPrefix(s, prefix string) string {
if HasPrefix(s, prefix) {
return s[len(prefix):]
}
return s
}
// TrimSuffix returns s without the provided trailing suffix string.
// If s doesn't end with suffix, s is returned unchanged.
func TrimSuffix(s, suffix string) string {
if HasSuffix(s, suffix) {
return s[:len(s)-len(suffix)]
}
return s
}
// Replace returns a copy of the string s with the first n
// non-overlapping instances of old replaced by new.
// If old is empty, it matches at the beginning of the string
// and after each UTF-8 sequence, yielding up to k+1 replacements
// for a k-rune string.
// If n < 0, there is no limit on the number of replacements.
func Replace(s, old, new string, n int) string {
if old == new || n == 0 {
return s // avoid allocation
}
// Compute number of replacements.
if m := Count(s, old); m == 0 {
return s // avoid allocation
} else if n < 0 || m < n {
n = m
}
// Apply replacements to buffer.
t := make([]byte, len(s)+n*(len(new)-len(old)))
w := 0
start := 0
for i := 0; i < n; i++ {
j := start
if len(old) == 0 {
if i > 0 {
_, wid := utf8.DecodeRuneInString(s[start:])
j += wid
}
} else {
j += Index(s[start:], old)
}
w += copy(t[w:], s[start:j])
w += copy(t[w:], new)
start = j + len(old)
}
w += copy(t[w:], s[start:])
return string(t[0:w])
}
// EqualFold reports whether s and t, interpreted as UTF-8 strings,
// are equal under Unicode case-folding.
func EqualFold(s, t string) bool {
for s != "" && t != "" {
// Extract first rune from each string.
var sr, tr rune
if s[0] < utf8.RuneSelf {
sr, s = rune(s[0]), s[1:]
} else {
r, size := utf8.DecodeRuneInString(s)
sr, s = r, s[size:]
}
if t[0] < utf8.RuneSelf {
tr, t = rune(t[0]), t[1:]
} else {
r, size := utf8.DecodeRuneInString(t)
tr, t = r, t[size:]
}
// If they match, keep going; if not, return false.
// Easy case.
if tr == sr {
continue
}
// Make sr < tr to simplify what follows.
if tr < sr {
tr, sr = sr, tr
}
// Fast check for ASCII.
if tr < utf8.RuneSelf && 'A' <= sr && sr <= 'Z' {
// ASCII, and sr is upper case. tr must be lower case.
if tr == sr+'a'-'A' {
continue
}
return false
}
// General case. SimpleFold(x) returns the next equivalent rune > x
// or wraps around to smaller values.
r := unicode.SimpleFold(sr)
for r != sr && r < tr {
r = unicode.SimpleFold(r)
}
if r == tr {
continue
}
return false
}
// One string is empty. Are both?
return s == t
}
| bsd-3-clause |
ltilve/ChromiumGStreamerBackend | chrome/browser/resources/extensions/extension_list.js | 42365 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
<include src="extension_error.js">
cr.define('extensions', function() {
'use strict';
/**
* @param {string} name The name of the template to clone.
* @return {!Element} The freshly cloned template.
*/
function cloneTemplate(name) {
var node = $('templates').querySelector('.' + name).cloneNode(true);
return assertInstanceof(node, Element);
}
/**
* @extends {HTMLElement}
* @constructor
*/
function ExtensionWrapper() {
var wrapper = cloneTemplate('extension-list-item-wrapper');
wrapper.__proto__ = ExtensionWrapper.prototype;
wrapper.initialize();
return wrapper;
}
ExtensionWrapper.prototype = {
__proto__: HTMLElement.prototype,
initialize: function() {
var boundary = $('extension-settings-list');
/** @private {!extensions.FocusRow} */
this.focusRow_ = new extensions.FocusRow(this, boundary);
},
/** @return {!cr.ui.FocusRow} */
getFocusRow: function() {
return this.focusRow_;
},
/**
* Add an item to the focus row and listen for |eventType| events.
* @param {string} focusType A tag used to identify equivalent elements when
* changing focus between rows.
* @param {string} query A query to select the element to set up.
* @param {string=} opt_eventType The type of event to listen to.
* @param {function(Event)=} opt_handler The function that should be called
* by the event.
* @private
*/
setupColumn: function(focusType, query, opt_eventType, opt_handler) {
assert(this.focusRow_.addItem(focusType, query));
if (opt_eventType) {
assert(opt_handler);
this.querySelector(query).addEventListener(opt_eventType, opt_handler);
}
},
};
var ExtensionCommandsOverlay = extensions.ExtensionCommandsOverlay;
/**
* Compares two extensions for the order they should appear in the list.
* @param {ExtensionInfo} a The first extension.
* @param {ExtensionInfo} b The second extension.
* returns {number} -1 if A comes before B, 1 if A comes after B, 0 if equal.
*/
function compareExtensions(a, b) {
function compare(x, y) {
return x < y ? -1 : (x > y ? 1 : 0);
}
function compareLocation(x, y) {
if (x.location == y.location)
return 0;
if (x.location == chrome.developerPrivate.Location.UNPACKED)
return -1;
if (y.location == chrome.developerPrivate.Location.UNPACKED)
return 1;
return 0;
}
return compareLocation(a, b) ||
compare(a.name.toLowerCase(), b.name.toLowerCase()) ||
compare(a.id, b.id);
}
/** @interface */
function ExtensionListDelegate() {}
ExtensionListDelegate.prototype = {
/**
* Called when the number of extensions in the list has changed.
*/
onExtensionCountChanged: assertNotReached,
};
/**
* Creates a new list of extensions.
* @param {extensions.ExtensionListDelegate} delegate
* @constructor
* @extends {HTMLDivElement}
*/
function ExtensionList(delegate) {
var div = document.createElement('div');
div.__proto__ = ExtensionList.prototype;
div.initialize(delegate);
return div;
}
ExtensionList.prototype = {
__proto__: HTMLDivElement.prototype,
/**
* Indicates whether an embedded options page that was navigated to through
* the '?options=' URL query has been shown to the user. This is necessary
* to prevent showExtensionNodes_ from opening the options more than once.
* @type {boolean}
* @private
*/
optionsShown_: false,
/** @private {!cr.ui.FocusGrid} */
focusGrid_: new cr.ui.FocusGrid(),
/**
* Indicates whether an uninstall dialog is being shown to prevent multiple
* dialogs from being displayed.
* @private {boolean}
*/
uninstallIsShowing_: false,
/**
* Indicates whether a permissions prompt is showing.
* @private {boolean}
*/
permissionsPromptIsShowing_: false,
/**
* Necessary to only show the butterbar once.
* @private {boolean}
*/
butterbarShown_: false,
/**
* Whether or not any initial navigation (like scrolling to an extension,
* or opening an options page) has occurred.
* @private {boolean}
*/
didInitialNavigation_: false,
/**
* Whether or not incognito mode is available.
* @private {boolean}
*/
incognitoAvailable_: false,
/**
* Whether or not the app info dialog is enabled.
* @private {boolean}
*/
enableAppInfoDialog_: false,
/**
* Initializes the list.
* @param {!extensions.ExtensionListDelegate} delegate
*/
initialize: function(delegate) {
/** @private {!Array<ExtensionInfo>} */
this.extensions_ = [];
/** @private {!extensions.ExtensionListDelegate} */
this.delegate_ = delegate;
this.resetLoadFinished();
chrome.developerPrivate.onItemStateChanged.addListener(
function(eventData) {
var EventType = chrome.developerPrivate.EventType;
switch (eventData.event_type) {
case EventType.VIEW_REGISTERED:
case EventType.VIEW_UNREGISTERED:
case EventType.INSTALLED:
case EventType.LOADED:
case EventType.UNLOADED:
case EventType.ERROR_ADDED:
case EventType.ERRORS_REMOVED:
case EventType.PREFS_CHANGED:
if (eventData.extensionInfo) {
this.updateOrCreateWrapper_(eventData.extensionInfo);
this.focusGrid_.ensureRowActive();
}
break;
case EventType.UNINSTALLED:
var index = this.getIndexOfExtension_(eventData.item_id);
this.extensions_.splice(index, 1);
this.removeWrapper_(getRequiredElement(eventData.item_id));
break;
default:
assertNotReached();
}
if (eventData.event_type == EventType.UNLOADED)
this.hideEmbeddedExtensionOptions_(eventData.item_id);
if (eventData.event_type == EventType.INSTALLED ||
eventData.event_type == EventType.UNINSTALLED) {
this.delegate_.onExtensionCountChanged();
}
if (eventData.event_type == EventType.LOADED ||
eventData.event_type == EventType.UNLOADED ||
eventData.event_type == EventType.PREFS_CHANGED ||
eventData.event_type == EventType.UNINSTALLED) {
// We update the commands overlay whenever an extension is added or
// removed (other updates wouldn't affect command-ly things). We
// need both UNLOADED and UNINSTALLED since the UNLOADED event results
// in an extension losing active keybindings, and UNINSTALLED can
// result in the "Keyboard shortcuts" link being removed.
ExtensionCommandsOverlay.updateExtensionsData(this.extensions_);
}
}.bind(this));
},
/**
* Resets the |loadFinished| promise so that it can be used again; this
* is useful if the page updates and tests need to wait for it to finish.
*/
resetLoadFinished: function() {
/**
* |loadFinished| should be used for testing purposes and will be
* fulfilled when this list has finished loading the first time.
* @type {Promise}
* */
this.loadFinished = new Promise(function(resolve, reject) {
/** @private {function(?)} */
this.resolveLoadFinished_ = resolve;
}.bind(this));
},
/**
* Updates the extensions on the page.
* @param {boolean} incognitoAvailable Whether or not incognito is allowed.
* @param {boolean} enableAppInfoDialog Whether or not the app info dialog
* is enabled.
* @return {Promise} A promise that is resolved once the extensions data is
* fully updated.
*/
updateExtensionsData: function(incognitoAvailable, enableAppInfoDialog) {
// If we start to need more information about the extension configuration,
// consider passing in the full object from the ExtensionSettings.
this.incognitoAvailable_ = incognitoAvailable;
this.enableAppInfoDialog_ = enableAppInfoDialog;
/** @private {Promise} */
this.extensionsUpdated_ = new Promise(function(resolve, reject) {
chrome.developerPrivate.getExtensionsInfo(
{includeDisabled: true, includeTerminated: true},
function(extensions) {
// Sort in order of unpacked vs. packed, followed by name, followed by
// id.
extensions.sort(compareExtensions);
this.extensions_ = extensions;
this.showExtensionNodes_();
// We keep the commands overlay's extension info in sync, so that we
// don't duplicate the same querying logic there.
ExtensionCommandsOverlay.updateExtensionsData(this.extensions_);
resolve();
// |resolve| is async so it's necessary to use |then| here in order to
// do work after other |then|s have finished. This is important so
// elements are visible when these updates happen.
this.extensionsUpdated_.then(function() {
this.onUpdateFinished_();
this.resolveLoadFinished_();
}.bind(this));
}.bind(this));
}.bind(this));
return this.extensionsUpdated_;
},
/**
* Updates elements that need to be visible in order to update properly.
* @private
*/
onUpdateFinished_: function() {
// Cannot focus or highlight a extension if there are none, and we should
// only scroll to a particular extension or open the options page once.
if (this.extensions_.length == 0 || this.didInitialNavigation_)
return;
this.didInitialNavigation_ = true;
assert(!this.hidden);
assert(!this.parentElement.hidden);
var idToHighlight = this.getIdQueryParam_();
if (idToHighlight) {
var wrapper = $(idToHighlight);
if (wrapper) {
this.scrollToWrapper_(idToHighlight);
var focusRow = wrapper.getFocusRow();
(focusRow.getFirstFocusable('enabled') ||
focusRow.getFirstFocusable('remove-enterprise') ||
focusRow.getFirstFocusable('website') ||
focusRow.getFirstFocusable('details')).focus();
}
}
var idToOpenOptions = this.getOptionsQueryParam_();
if (idToOpenOptions && $(idToOpenOptions))
this.showEmbeddedExtensionOptions_(idToOpenOptions, true);
},
/** @return {number} The number of extensions being displayed. */
getNumExtensions: function() {
return this.extensions_.length;
},
/**
* @param {string} id The id of the extension.
* @return {number} The index of the extension with the given id.
* @private
*/
getIndexOfExtension_: function(id) {
for (var i = 0; i < this.extensions_.length; ++i) {
if (this.extensions_[i].id == id)
return i;
}
return -1;
},
getIdQueryParam_: function() {
return parseQueryParams(document.location)['id'];
},
getOptionsQueryParam_: function() {
return parseQueryParams(document.location)['options'];
},
/**
* Creates or updates all extension items from scratch.
* @private
*/
showExtensionNodes_: function() {
// Any node that is not updated will be removed.
var seenIds = [];
// Iterate over the extension data and add each item to the list.
this.extensions_.forEach(function(extension) {
seenIds.push(extension.id);
this.updateOrCreateWrapper_(extension);
}, this);
this.focusGrid_.ensureRowActive();
// Remove extensions that are no longer installed.
var wrappers = document.querySelectorAll(
'.extension-list-item-wrapper[id]');
Array.prototype.forEach.call(wrappers, function(wrapper) {
if (seenIds.indexOf(wrapper.id) < 0)
this.removeWrapper_(wrapper);
}, this);
},
/**
* Removes the wrapper from the DOM and updates the focused element if
* needed.
* @param {!Element} wrapper
* @private
*/
removeWrapper_: function(wrapper) {
// If focus is in the wrapper about to be removed, move it first. This
// happens when clicking the trash can to remove an extension.
if (wrapper.contains(document.activeElement)) {
var wrappers = document.querySelectorAll(
'.extension-list-item-wrapper[id]');
var index = Array.prototype.indexOf.call(wrappers, wrapper);
assert(index != -1);
var focusableWrapper = wrappers[index + 1] || wrappers[index - 1];
if (focusableWrapper) {
var newFocusRow = focusableWrapper.getFocusRow();
newFocusRow.getEquivalentElement(document.activeElement).focus();
}
}
var focusRow = wrapper.getFocusRow();
this.focusGrid_.removeRow(focusRow);
this.focusGrid_.ensureRowActive();
focusRow.destroy();
wrapper.parentNode.removeChild(wrapper);
},
/**
* Scrolls the page down to the extension node with the given id.
* @param {string} extensionId The id of the extension to scroll to.
* @private
*/
scrollToWrapper_: function(extensionId) {
// Scroll offset should be calculated slightly higher than the actual
// offset of the element being scrolled to, so that it ends up not all
// the way at the top. That way it is clear that there are more elements
// above the element being scrolled to.
var wrapper = $(extensionId);
var scrollFudge = 1.2;
var scrollTop = wrapper.offsetTop - scrollFudge * wrapper.clientHeight;
setScrollTopForDocument(document, scrollTop);
},
/**
* Synthesizes and initializes an HTML element for the extension metadata
* given in |extension|.
* @param {!ExtensionInfo} extension A dictionary of extension metadata.
* @param {?Element} nextWrapper The newly created wrapper will be inserted
* before |nextWrapper| if non-null (else it will be appended to the
* wrapper list).
* @private
*/
createWrapper_: function(extension, nextWrapper) {
var wrapper = new ExtensionWrapper;
wrapper.id = extension.id;
// The 'Permissions' link.
wrapper.setupColumn('details', '.permissions-link', 'click', function(e) {
if (!this.permissionsPromptIsShowing_) {
chrome.developerPrivate.showPermissionsDialog(extension.id,
function() {
this.permissionsPromptIsShowing_ = false;
}.bind(this));
this.permissionsPromptIsShowing_ = true;
}
e.preventDefault();
});
wrapper.setupColumn('options', '.options-button', 'click', function(e) {
this.showEmbeddedExtensionOptions_(extension.id, false);
e.preventDefault();
}.bind(this));
// The 'Options' button or link, depending on its behaviour.
// Set an href to get the correct mouse-over appearance (link,
// footer) - but the actual link opening is done through developerPrivate
// API with a preventDefault().
wrapper.querySelector('.options-link').href =
extension.optionsPage ? extension.optionsPage.url : '';
wrapper.setupColumn('options', '.options-link', 'click', function(e) {
chrome.developerPrivate.showOptions(extension.id);
e.preventDefault();
});
// The 'View in Web Store/View Web Site' link.
wrapper.setupColumn('website', '.site-link');
// The 'Launch' link.
wrapper.setupColumn('launch', '.launch-link', 'click', function(e) {
chrome.management.launchApp(extension.id);
});
// The 'Reload' link.
wrapper.setupColumn('localReload', '.reload-link', 'click', function(e) {
chrome.developerPrivate.reload(extension.id, {failQuietly: true});
});
wrapper.setupColumn('errors', '.errors-link', 'click', function(e) {
var extensionId = extension.id;
assert(this.extensions_.length > 0);
var newEx = this.extensions_.filter(function(e) {
return e.state == chrome.developerPrivate.ExtensionState.ENABLED &&
e.id == extensionId;
})[0];
var errors = newEx.manifestErrors.concat(newEx.runtimeErrors);
extensions.ExtensionErrorOverlay.getInstance().setErrorsAndShowOverlay(
errors, extensionId, newEx.name);
}.bind(this));
wrapper.setupColumn('suspiciousLearnMore',
'.suspicious-install-message .learn-more-link');
// The path, if provided by unpacked extension.
wrapper.setupColumn('loadPath', '.load-path a:first-of-type', 'click',
function(e) {
chrome.developerPrivate.showPath(extension.id);
e.preventDefault();
});
// The 'Show Browser Action' button.
wrapper.setupColumn('showButton', '.show-button', 'click', function(e) {
chrome.developerPrivate.updateExtensionConfiguration({
extensionId: extension.id,
showActionButton: true
});
});
// The 'allow in incognito' checkbox.
wrapper.setupColumn('incognito', '.incognito-control input', 'change',
function(e) {
var butterBar = wrapper.querySelector('.butter-bar');
var checked = e.target.checked;
if (!this.butterbarShown_) {
butterBar.hidden = !checked ||
extension.type ==
chrome.developerPrivate.ExtensionType.HOSTED_APP;
this.butterbarShown_ = !butterBar.hidden;
} else {
butterBar.hidden = true;
}
chrome.developerPrivate.updateExtensionConfiguration({
extensionId: extension.id,
incognitoAccess: e.target.checked
});
}.bind(this));
// The 'collect errors' checkbox. This should only be visible if the
// error console is enabled - we can detect this by the existence of the
// |errorCollectionEnabled| property.
wrapper.setupColumn('collectErrors', '.error-collection-control input',
'change', function(e) {
chrome.developerPrivate.updateExtensionConfiguration({
extensionId: extension.id,
errorCollection: e.target.checked
});
});
// The 'allow on all urls' checkbox. This should only be visible if
// active script restrictions are enabled. If they are not enabled, no
// extensions should want all urls.
wrapper.setupColumn('allUrls', '.all-urls-control input', 'click',
function(e) {
chrome.developerPrivate.updateExtensionConfiguration({
extensionId: extension.id,
runOnAllUrls: e.target.checked
});
});
// The 'allow file:// access' checkbox.
wrapper.setupColumn('localUrls', '.file-access-control input', 'click',
function(e) {
chrome.developerPrivate.updateExtensionConfiguration({
extensionId: extension.id,
fileAccess: e.target.checked
});
});
// The 'Reload' terminated link.
wrapper.setupColumn('terminatedReload', '.terminated-reload-link',
'click', function(e) {
chrome.developerPrivate.reload(extension.id, {failQuietly: true});
});
// The 'Repair' corrupted link.
wrapper.setupColumn('repair', '.corrupted-repair-button', 'click',
function(e) {
chrome.developerPrivate.repairExtension(extension.id);
});
// The 'Enabled' checkbox.
wrapper.setupColumn('enabled', '.enable-checkbox input', 'change',
function(e) {
var checked = e.target.checked;
// TODO(devlin): What should we do if this fails?
chrome.management.setEnabled(extension.id, checked);
// This may seem counter-intuitive (to not set/clear the checkmark)
// but this page will be updated asynchronously if the extension
// becomes enabled/disabled. It also might not become enabled or
// disabled, because the user might e.g. get prompted when enabling
// and choose not to.
e.preventDefault();
});
// 'Remove' button.
var trash = cloneTemplate('trash');
trash.title = loadTimeData.getString('extensionUninstall');
wrapper.querySelector('.enable-controls').appendChild(trash);
wrapper.setupColumn('remove-enterprise', '.trash', 'click', function(e) {
trash.classList.add('open');
trash.classList.toggle('mouse-clicked', e.detail > 0);
if (this.uninstallIsShowing_)
return;
this.uninstallIsShowing_ = true;
chrome.management.uninstall(extension.id,
{showConfirmDialog: true},
function() {
// TODO(devlin): What should we do if the uninstall fails?
this.uninstallIsShowing_ = false;
if (trash.classList.contains('mouse-clicked'))
trash.blur();
if (chrome.runtime.lastError) {
// The uninstall failed (e.g. a cancel). Allow the trash to close.
trash.classList.remove('open');
} else {
// Leave the trash open if the uninstall succeded. Otherwise it can
// half-close right before it's removed when the DOM is modified.
}
}.bind(this));
}.bind(this));
// Maintain the order that nodes should be in when creating as well as
// when adding only one new wrapper.
this.insertBefore(wrapper, nextWrapper);
this.updateWrapper_(extension, wrapper);
var nextRow = this.focusGrid_.getRowForRoot(nextWrapper); // May be null.
this.focusGrid_.addRowBefore(wrapper.getFocusRow(), nextRow);
},
/**
* Updates an HTML element for the extension metadata given in |extension|.
* @param {!ExtensionInfo} extension A dictionary of extension metadata.
* @param {!Element} wrapper The extension wrapper element to update.
* @private
*/
updateWrapper_: function(extension, wrapper) {
var isActive =
extension.state == chrome.developerPrivate.ExtensionState.ENABLED;
wrapper.classList.toggle('inactive-extension', !isActive);
wrapper.classList.remove('controlled', 'may-not-remove');
if (extension.controlledInfo) {
wrapper.classList.add('controlled');
} else if (!extension.userMayModify ||
extension.mustRemainInstalled ||
extension.dependentExtensions.length > 0) {
wrapper.classList.add('may-not-remove');
}
var item = wrapper.querySelector('.extension-list-item');
item.style.backgroundImage = 'url(' + extension.iconUrl + ')';
this.setText_(wrapper, '.extension-title', extension.name);
this.setText_(wrapper, '.extension-version', extension.version);
this.setText_(wrapper, '.location-text', extension.locationText || '');
this.setText_(wrapper, '.blacklist-text', extension.blacklistText || '');
this.setText_(wrapper, '.extension-description', extension.description);
// The 'Show Browser Action' button.
this.updateVisibility_(wrapper, '.show-button',
isActive && extension.actionButtonHidden);
// The 'allow in incognito' checkbox.
this.updateVisibility_(wrapper, '.incognito-control',
isActive && this.incognitoAvailable_,
function(item) {
var incognito = item.querySelector('input');
incognito.disabled = !extension.incognitoAccess.isEnabled;
incognito.checked = extension.incognitoAccess.isActive;
});
// Hide butterBar if incognito is not enabled for the extension.
var butterBar = wrapper.querySelector('.butter-bar');
butterBar.hidden =
butterBar.hidden || !extension.incognitoAccess.isEnabled;
// The 'collect errors' checkbox. This should only be visible if the
// error console is enabled - we can detect this by the existence of the
// |errorCollectionEnabled| property.
this.updateVisibility_(
wrapper, '.error-collection-control',
isActive && extension.errorCollection.isEnabled,
function(item) {
item.querySelector('input').checked =
extension.errorCollection.isActive;
});
// The 'allow on all urls' checkbox. This should only be visible if
// active script restrictions are enabled. If they are not enabled, no
// extensions should want all urls.
this.updateVisibility_(
wrapper, '.all-urls-control',
isActive && extension.runOnAllUrls.isEnabled,
function(item) {
item.querySelector('input').checked = extension.runOnAllUrls.isActive;
});
// The 'allow file:// access' checkbox.
this.updateVisibility_(wrapper, '.file-access-control',
isActive && extension.fileAccess.isEnabled,
function(item) {
item.querySelector('input').checked = extension.fileAccess.isActive;
});
// The 'Options' button or link, depending on its behaviour.
var optionsEnabled = isActive && !!extension.optionsPage;
this.updateVisibility_(wrapper, '.options-link', optionsEnabled &&
extension.optionsPage.openInTab);
this.updateVisibility_(wrapper, '.options-button', optionsEnabled &&
!extension.optionsPage.openInTab);
// The 'View in Web Store/View Web Site' link.
var siteLinkEnabled = !!extension.homePage.url &&
!this.enableAppInfoDialog_;
this.updateVisibility_(wrapper, '.site-link', siteLinkEnabled,
function(item) {
item.href = extension.homePage.url;
item.textContent = loadTimeData.getString(
extension.homePage.specified ? 'extensionSettingsVisitWebsite' :
'extensionSettingsVisitWebStore');
});
var isUnpacked =
extension.location == chrome.developerPrivate.Location.UNPACKED;
// The 'Reload' link.
this.updateVisibility_(wrapper, '.reload-link', isUnpacked);
// The 'Launch' link.
this.updateVisibility_(
wrapper, '.launch-link',
isUnpacked && extension.type ==
chrome.developerPrivate.ExtensionType.PLATFORM_APP);
// The 'Errors' link.
var hasErrors = extension.runtimeErrors.length > 0 ||
extension.manifestErrors.length > 0;
this.updateVisibility_(wrapper, '.errors-link', hasErrors,
function(item) {
var Level = chrome.developerPrivate.ErrorLevel;
var map = {};
map[Level.LOG] = {weight: 0, name: 'extension-error-info-icon'};
map[Level.WARN] = {weight: 1, name: 'extension-error-warning-icon'};
map[Level.ERROR] = {weight: 2, name: 'extension-error-fatal-icon'};
// Find the highest severity of all the errors; manifest errors all have
// a 'warning' level severity.
var highestSeverity = extension.runtimeErrors.reduce(
function(prev, error) {
return map[error.severity].weight > map[prev].weight ?
error.severity : prev;
}, extension.manifestErrors.length ? Level.WARN : Level.LOG);
// Adjust the class on the icon.
var icon = item.querySelector('.extension-error-icon');
// TODO(hcarmona): Populate alt text with a proper description since
// this icon conveys the severity of the error. (info, warning, fatal).
icon.alt = '';
icon.className = 'extension-error-icon'; // Remove other classes.
icon.classList.add(map[highestSeverity].name);
});
// The 'Reload' terminated link.
var isTerminated =
extension.state == chrome.developerPrivate.ExtensionState.TERMINATED;
this.updateVisibility_(wrapper, '.terminated-reload-link', isTerminated);
// The 'Repair' corrupted link.
var canRepair = !isTerminated &&
extension.disableReasons.corruptInstall &&
extension.location ==
chrome.developerPrivate.Location.FROM_STORE;
this.updateVisibility_(wrapper, '.corrupted-repair-button', canRepair);
// The 'Enabled' checkbox.
var isOK = !isTerminated && !canRepair;
this.updateVisibility_(wrapper, '.enable-checkbox', isOK, function(item) {
var enableCheckboxDisabled =
!extension.userMayModify ||
extension.disableReasons.suspiciousInstall ||
extension.disableReasons.corruptInstall ||
extension.disableReasons.updateRequired ||
extension.dependentExtensions.length > 0;
item.querySelector('input').disabled = enableCheckboxDisabled;
item.querySelector('input').checked = isActive;
});
// Indicator for extensions controlled by policy.
var controlNode = wrapper.querySelector('.enable-controls');
var indicator =
controlNode.querySelector('.controlled-extension-indicator');
var needsIndicator = isOK && extension.controlledInfo;
if (needsIndicator && !indicator) {
indicator = new cr.ui.ControlledIndicator();
indicator.classList.add('controlled-extension-indicator');
var ControllerType = chrome.developerPrivate.ControllerType;
var controlledByStr = '';
switch (extension.controlledInfo.type) {
case ControllerType.POLICY:
controlledByStr = 'policy';
break;
case ControllerType.CHILD_CUSTODIAN:
controlledByStr = 'child-custodian';
break;
case ControllerType.SUPERVISED_USER_CUSTODIAN:
controlledByStr = 'supervised-user-custodian';
break;
}
indicator.setAttribute('controlled-by', controlledByStr);
var text = extension.controlledInfo.text;
indicator.setAttribute('text' + controlledByStr, text);
indicator.image.setAttribute('aria-label', text);
controlNode.appendChild(indicator);
wrapper.setupColumn('remove-enterprise', '[controlled-by] div');
} else if (!needsIndicator && indicator) {
controlNode.removeChild(indicator);
}
// Developer mode ////////////////////////////////////////////////////////
// First we have the id.
var idLabel = wrapper.querySelector('.extension-id');
idLabel.textContent = ' ' + extension.id;
// Then the path, if provided by unpacked extension.
this.updateVisibility_(wrapper, '.load-path', isUnpacked,
function(item) {
item.querySelector('a:first-of-type').textContent =
' ' + extension.prettifiedPath;
});
// Then the 'managed, cannot uninstall/disable' message.
// We would like to hide managed installed message since this
// extension is disabled.
var isRequired =
!extension.userMayModify || extension.mustRemainInstalled;
this.updateVisibility_(wrapper, '.managed-message', isRequired &&
!extension.disableReasons.updateRequired);
// Then the 'This isn't from the webstore, looks suspicious' message.
var isSuspicious = extension.disableReasons.suspiciousInstall;
this.updateVisibility_(wrapper, '.suspicious-install-message',
!isRequired && isSuspicious);
// Then the 'This is a corrupt extension' message.
this.updateVisibility_(wrapper, '.corrupt-install-message', !isRequired &&
extension.disableReasons.corruptInstall);
// Then the 'An update required by enterprise policy' message. Note that
// a force-installed extension might be disabled due to being outdated
// as well.
this.updateVisibility_(wrapper, '.update-required-message',
extension.disableReasons.updateRequired);
// The 'following extensions depend on this extension' list.
var hasDependents = extension.dependentExtensions.length > 0;
wrapper.classList.toggle('developer-extras', hasDependents);
this.updateVisibility_(wrapper, '.dependent-extensions-message',
hasDependents, function(item) {
var dependentList = item.querySelector('ul');
dependentList.textContent = '';
extension.dependentExtensions.forEach(function(dependentId) {
var dependentExtension = null;
for (var i = 0; i < this.extensions_.length; ++i) {
if (this.extensions_[i].id == dependentId) {
dependentExtension = this.extensions_[i];
break;
}
}
if (!dependentExtension)
return;
var depNode = cloneTemplate('dependent-list-item');
depNode.querySelector('.dep-extension-title').textContent =
dependentExtension.name;
depNode.querySelector('.dep-extension-id').textContent =
dependentExtension.id;
dependentList.appendChild(depNode);
}, this);
}.bind(this));
// The active views.
this.updateVisibility_(wrapper, '.active-views',
extension.views.length > 0, function(item) {
var link = item.querySelector('a');
// Link needs to be an only child before the list is updated.
while (link.nextElementSibling)
item.removeChild(link.nextElementSibling);
// Link needs to be cleaned up if it was used before.
link.textContent = '';
if (link.clickHandler)
link.removeEventListener('click', link.clickHandler);
extension.views.forEach(function(view, i) {
if (view.type == chrome.developerPrivate.ViewType.EXTENSION_DIALOG ||
view.type == chrome.developerPrivate.ViewType.EXTENSION_POPUP) {
return;
}
var displayName;
if (view.url.indexOf('chrome-extension://') == 0) {
var pathOffset = 'chrome-extension://'.length + 32 + 1;
displayName = view.url.substring(pathOffset);
if (displayName == '_generated_background_page.html')
displayName = loadTimeData.getString('backgroundPage');
} else {
displayName = view.url;
}
var label = displayName +
(view.incognito ?
' ' + loadTimeData.getString('viewIncognito') : '') +
(view.renderProcessId == -1 ?
' ' + loadTimeData.getString('viewInactive') : '');
link.textContent = label;
link.clickHandler = function(e) {
chrome.developerPrivate.openDevTools({
extensionId: extension.id,
renderProcessId: view.renderProcessId,
renderViewId: view.renderViewId,
incognito: view.incognito
});
};
link.addEventListener('click', link.clickHandler);
if (i < extension.views.length - 1) {
link = link.cloneNode(true);
item.appendChild(link);
}
wrapper.setupColumn('activeView', '.active-views a:last-of-type');
});
});
// The extension warnings (describing runtime issues).
this.updateVisibility_(wrapper, '.extension-warnings',
extension.runtimeWarnings.length > 0,
function(item) {
var warningList = item.querySelector('ul');
warningList.textContent = '';
extension.runtimeWarnings.forEach(function(warning) {
var li = document.createElement('li');
warningList.appendChild(li).innerText = warning;
});
});
// Install warnings.
this.updateVisibility_(wrapper, '.install-warnings',
extension.installWarnings.length > 0,
function(item) {
var installWarningList = item.querySelector('ul');
installWarningList.textContent = '';
if (extension.installWarnings) {
extension.installWarnings.forEach(function(warning) {
var li = document.createElement('li');
li.innerText = warning;
installWarningList.appendChild(li);
});
}
});
if (location.hash.substr(1) == extension.id) {
// Scroll beneath the fixed header so that the extension is not
// obscured.
var topScroll = wrapper.offsetTop - $('page-header').offsetHeight;
var pad = parseInt(window.getComputedStyle(wrapper).marginTop, 10);
if (!isNaN(pad))
topScroll -= pad / 2;
setScrollTopForDocument(document, topScroll);
}
},
/**
* Updates an element's textContent.
* @param {Node} node Ancestor of the element specified by |query|.
* @param {string} query A query to select an element in |node|.
* @param {string} textContent
* @private
*/
setText_: function(node, query, textContent) {
node.querySelector(query).textContent = textContent;
},
/**
* Updates an element's visibility and calls |shownCallback| if it is
* visible.
* @param {Node} node Ancestor of the element specified by |query|.
* @param {string} query A query to select an element in |node|.
* @param {boolean} visible Whether the element should be visible or not.
* @param {function(Element)=} opt_shownCallback Callback if the element is
* visible. The element passed in will be the element specified by
* |query|.
* @private
*/
updateVisibility_: function(node, query, visible, opt_shownCallback) {
var element = assertInstanceof(node.querySelector(query), Element);
element.hidden = !visible;
if (visible && opt_shownCallback)
opt_shownCallback(element);
},
/**
* Opens the extension options overlay for the extension with the given id.
* @param {string} extensionId The id of extension whose options page should
* be displayed.
* @param {boolean} scroll Whether the page should scroll to the extension
* @private
*/
showEmbeddedExtensionOptions_: function(extensionId, scroll) {
if (this.optionsShown_)
return;
// Get the extension from the given id.
var extension = this.extensions_.filter(function(extension) {
return extension.state ==
chrome.developerPrivate.ExtensionState.ENABLED &&
extension.id == extensionId;
})[0];
if (!extension)
return;
if (scroll)
this.scrollToWrapper_(extensionId);
// Add the options query string. Corner case: the 'options' query string
// will clobber the 'id' query string if the options link is clicked when
// 'id' is in the URL, or if both query strings are in the URL.
uber.replaceState({}, '?options=' + extensionId);
var overlay = extensions.ExtensionOptionsOverlay.getInstance();
var shownCallback = function() {
// This overlay doesn't get focused automatically as <extensionoptions>
// is created after the overlay is shown.
if (cr.ui.FocusOutlineManager.forDocument(document).visible)
overlay.setInitialFocus();
};
overlay.setExtensionAndShow(extensionId, extension.name,
extension.iconUrl, shownCallback);
this.optionsShown_ = true;
var self = this;
$('overlay').addEventListener('cancelOverlay', function f() {
self.optionsShown_ = false;
$('overlay').removeEventListener('cancelOverlay', f);
// Remove the options query string.
uber.replaceState({}, '');
});
// TODO(dbeam): why do we need to focus <extensionoptions> before and
// after its showing animation? Makes very little sense to me.
overlay.setInitialFocus();
},
/**
* Hides the extension options overlay for the extension with id
* |extensionId|. If there is an overlay showing for a different extension,
* nothing happens.
* @param {string} extensionId ID of the extension to hide.
* @private
*/
hideEmbeddedExtensionOptions_: function(extensionId) {
if (!this.optionsShown_)
return;
var overlay = extensions.ExtensionOptionsOverlay.getInstance();
if (overlay.getExtensionId() == extensionId)
overlay.close();
},
/**
* Updates or creates a wrapper for |extension|.
* @param {!ExtensionInfo} extension The information about the extension to
* update.
* @private
*/
updateOrCreateWrapper_: function(extension) {
var currIndex = this.getIndexOfExtension_(extension.id);
if (currIndex != -1) {
// If there is a current version of the extension, update it with the
// new version.
this.extensions_[currIndex] = extension;
} else {
// If the extension isn't found, push it back and sort. Technically, we
// could optimize by inserting it at the right location, but since this
// only happens on extension install, it's not worth it.
this.extensions_.push(extension);
this.extensions_.sort(compareExtensions);
}
var wrapper = $(extension.id);
if (wrapper) {
this.updateWrapper_(extension, wrapper);
} else {
var nextExt = this.extensions_[this.extensions_.indexOf(extension) + 1];
this.createWrapper_(extension, nextExt ? $(nextExt.id) : null);
}
}
};
return {
ExtensionList: ExtensionList,
ExtensionListDelegate: ExtensionListDelegate
};
});
| bsd-3-clause |
youtube/cobalt | third_party/v8/test/mjsunit/regress/regress-v8-10568.js | 283 | // Copyright 2020 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
assertEquals(/[--]/u.exec("Hr3QoS3KCWXQ2yjBoDIK")[0], "H");
assertEquals(/[0-\u{10000}]/u.exec("A0")[0], "A");
| bsd-3-clause |
wisonwang/django-lfs | lfs/core/models.py | 9087 | # django imports
from django.conf import settings
from django.core.cache import cache
from django.db import models
from django.utils.translation import ugettext_lazy as _
# lfs imports
from lfs.checkout.settings import CHECKOUT_TYPES
from lfs.checkout.settings import CHECKOUT_TYPE_SELECT
from lfs.core.fields.thumbs import ImageWithThumbsField
from lfs.catalog.models import DeliveryTime
from lfs.catalog.models import StaticBlock
class Country(models.Model):
"""Holds country relevant data for the shop.
"""
code = models.CharField(_(u"Country code"), max_length=2)
name = models.CharField(_(u"Name"), max_length=100)
def __unicode__(self):
return self.name
class Meta:
verbose_name_plural = 'Countries'
ordering = ("name", )
app_label = 'core'
class ActionGroup(models.Model):
"""Actions of a action group can be displayed on several parts of the web
page.
**Attributes**:
name
The name of the group.
"""
name = models.CharField(_(u"Name"), blank=True, max_length=100, unique=True)
class Meta:
ordering = ("name", )
app_label = 'core'
def __unicode__(self):
return self.name
def get_actions(self):
"""Returns the actions of this group.
"""
return self.actions.filter(active=True)
class Action(models.Model):
"""A action is a link which belongs to a action groups.
**Attributes**:
group
The belonging group.
title
The title of the menu tab.
link
The link to the object.
active
If true the tab is displayed.
position
the position of the tab within the menu.
parent
Parent tab to create a tree.
"""
active = models.BooleanField(_(u"Active"), default=False)
title = models.CharField(_(u"Title"), max_length=40)
link = models.CharField(_(u"Link"), blank=True, max_length=100)
group = models.ForeignKey(ActionGroup, verbose_name=_(u"Group"), related_name="actions")
position = models.IntegerField(_(u"Position"), default=999)
parent = models.ForeignKey("self", verbose_name=_(u"Parent"), blank=True, null=True)
def __unicode__(self):
return self.title
class Meta:
ordering = ("position", )
app_label = 'core'
class Shop(models.Model):
"""
Holds all shop related information.
name
The name of the shop. This is used for the the title of the HTML pages
shop_owner
The shop owner. This is displayed within several places for instance the
checkout page
from_email
This e-mail address is used for the from header of all outgoing e-mails
notification_emails
This e-mail addresses are used for incoming notification e-mails, e.g.
received an order. One e-mail address per line.
description
A description of the shop
image
An image which can be used as default image if a category doesn't have one
product_cols, product_rows, category_cols
Upmost format information, which defines how products and categories are
displayed within several views. These may be inherited by categories and
sub categories.
delivery_time
The default delivery time, which is used if no delivery time can be
calculated for a product.
google_analytics_id
Used to generate google analytics tracker code and e-commerce code. the
id has the format UA-xxxxxxx-xx and is provided by Google.
ga_site_tracking
If selected and the google_analytics_id is given google analytics site
tracking code is inserted into the HTML source code.
ga_ecommerce_tracking
If selected and the google_analytics_id is given google analytics
e-commerce tracking code is inserted into the HTML source code.
countries
Selected countries will be offered to the shop customer tho choose for
shipping and invoice address.
default_country
This country will be used to calculate shipping price if the shop
customer doesn't have select a country yet.
use_international_currency_code
If this is True the international currency code from the current locale
is used.
price_calculator
Class that implements lfs.price.PriceCalculator for calculating product
price. This is the default price calculator for all products.
checkout_type
Decides whether the customer has to login, has not to login or has the
choice to to login or not to be able to check out.
confirm_toc
If this is activated the shop customer has to confirm terms and
conditions to checkout.
meta*
This information is used within HTML meta tags of the shop view.
"""
name = models.CharField(_(u"Name"), max_length=30)
shop_owner = models.CharField(_(u"Shop owner"), max_length=100, blank=True)
from_email = models.EmailField(_(u"From e-mail address"))
notification_emails = models.TextField(_(u"Notification email addresses"))
description = models.TextField(_(u"Description"), blank=True)
image = ImageWithThumbsField(_(u"Image"), upload_to="images", blank=True, null=True, sizes=((60, 60), (100, 100), (200, 200), (400, 400)))
static_block = models.ForeignKey(StaticBlock, verbose_name=_(u"Static block"), blank=True, null=True, related_name="shops")
product_cols = models.IntegerField(_(u"Product cols"), default=1)
product_rows = models.IntegerField(_(u"Product rows"), default=10)
category_cols = models.IntegerField(_(u"Category cols"), default=1)
delivery_time = models.ForeignKey(DeliveryTime, verbose_name=_(u"Delivery time"), blank=True, null=True)
google_analytics_id = models.CharField(_(u"Google Analytics ID"), blank=True, max_length=20)
ga_site_tracking = models.BooleanField(_(u"Google Analytics Site Tracking"), default=False)
ga_ecommerce_tracking = models.BooleanField(_(u"Google Analytics E-Commerce Tracking"), default=False)
invoice_countries = models.ManyToManyField(Country, verbose_name=_(u"Invoice countries"), related_name="invoice")
shipping_countries = models.ManyToManyField(Country, verbose_name=_(u"Shipping countries"), related_name="shipping")
default_country = models.ForeignKey(Country, verbose_name=_(u"Default shipping country"))
use_international_currency_code = models.BooleanField(_(u"Use international currency codes"), default=False)
price_calculator = models.CharField(choices=settings.LFS_PRICE_CALCULATORS, max_length=255,
default=settings.LFS_PRICE_CALCULATORS[0][0],
verbose_name=_(u"Price calculator"))
checkout_type = models.PositiveSmallIntegerField(_(u"Checkout type"), choices=CHECKOUT_TYPES, default=CHECKOUT_TYPE_SELECT)
confirm_toc = models.BooleanField(_(u"Confirm TOC"), default=False)
meta_title = models.CharField(_(u"Meta title"), blank=True, default="<name>", max_length=80)
meta_keywords = models.TextField(_(u"Meta keywords"), blank=True)
meta_description = models.TextField(_(u"Meta description"), blank=True)
class Meta:
permissions = (("manage_shop", "Manage shop"),)
app_label = 'core'
def __unicode__(self):
return self.name
def get_format_info(self):
"""Returns the global format info.
"""
return {
"product_cols": self.product_cols,
"product_rows": self.product_rows,
"category_cols": self.category_cols,
}
def get_default_country(self):
"""Returns the default country of the shop.
"""
cache_key = "%s-default-country-%s" % (settings.CACHE_MIDDLEWARE_KEY_PREFIX, self.id)
default_country = cache.get(cache_key)
if default_country:
return default_country
default_country = self.default_country
cache.set(cache_key, default_country)
return default_country
def get_notification_emails(self):
"""Returns the notification e-mail addresses as list
"""
import re
adresses = re.split("[\s,]+", self.notification_emails)
return adresses
def get_parent_for_portlets(self):
"""Implements contract for django-portlets. Returns always None as there
is no parent for a shop.
"""
return None
def get_meta_title(self):
"""Returns the meta title of the shop.
"""
return self.meta_title.replace("<name>", self.name)
def get_meta_keywords(self):
"""Returns the meta keywords of the shop.
"""
return self.meta_keywords.replace("<name>", self.name)
def get_meta_description(self):
"""Returns the meta description of the shop.
"""
return self.meta_description.replace("<name>", self.name)
class Application(models.Model):
version = models.CharField(_("Version"), blank=True, max_length=10)
class Meta:
app_label = 'core'
from monkeys import *
| bsd-3-clause |
Craigspaz/Flying-Ferris-Wheel-Engine | Tables/lwjgl-2.9.1/src/src/templates/org/lwjgl/opencl/KHR_global_int32_extended_atomics.java | 1730 | /*
* Copyright (c) 2002-2010 LWJGL 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:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.opencl;
import org.lwjgl.util.generator.opencl.CLDeviceExtension;
@CLDeviceExtension
public interface KHR_global_int32_extended_atomics {
} | bsd-3-clause |
rgarro/zf2 | library/Zend/Filter/HtmlEntities.php | 4875 | <?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Filter
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
/**
* @namespace
*/
namespace Zend\Filter;
/**
* @uses Zend\Filter\AbstractFilter
* @category Zend
* @package Zend_Filter
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class HtmlEntities extends AbstractFilter
{
/**
* Corresponds to the second htmlentities() argument
*
* @var integer
*/
protected $_quoteStyle;
/**
* Corresponds to the third htmlentities() argument
*
* @var string
*/
protected $_encoding;
/**
* Corresponds to the forth htmlentities() argument
*
* @var unknown_type
*/
protected $_doubleQuote;
/**
* Sets filter options
*
* @param integer|array $quoteStyle
* @param string $charSet
* @return void
*/
public function __construct($options = array())
{
if ($options instanceof \Zend\Config\Config) {
$options = $options->toArray();
} elseif (!is_array($options)) {
$options = func_get_args();
$temp['quotestyle'] = array_shift($options);
if (!empty($options)) {
$temp['charset'] = array_shift($options);
}
$options = $temp;
}
if (!isset($options['quotestyle'])) {
$options['quotestyle'] = ENT_COMPAT;
}
if (!isset($options['encoding'])) {
$options['encoding'] = 'UTF-8';
}
if (isset($options['charset'])) {
$options['encoding'] = $options['charset'];
}
if (!isset($options['doublequote'])) {
$options['doublequote'] = true;
}
$this->setQuoteStyle($options['quotestyle']);
$this->setEncoding($options['encoding']);
$this->setDoubleQuote($options['doublequote']);
}
/**
* Returns the quoteStyle option
*
* @return integer
*/
public function getQuoteStyle()
{
return $this->_quoteStyle;
}
/**
* Sets the quoteStyle option
*
* @param integer $quoteStyle
* @return \Zend\Filter\HtmlEntities Provides a fluent interface
*/
public function setQuoteStyle($quoteStyle)
{
$this->_quoteStyle = $quoteStyle;
return $this;
}
/**
* Get encoding
*
* @return string
*/
public function getEncoding()
{
return $this->_encoding;
}
/**
* Set encoding
*
* @param string $value
* @return \Zend\Filter\HtmlEntities
*/
public function setEncoding($value)
{
$this->_encoding = (string) $value;
return $this;
}
/**
* Returns the charSet option
*
* Proxies to {@link getEncoding()}
*
* @return string
*/
public function getCharSet()
{
return $this->getEncoding();
}
/**
* Sets the charSet option
*
* Proxies to {@link setEncoding()}
*
* @param string $charSet
* @return \Zend\Filter\HtmlEntities Provides a fluent interface
*/
public function setCharSet($charSet)
{
return $this->setEncoding($charSet);
}
/**
* Returns the doubleQuote option
*
* @return boolean
*/
public function getDoubleQuote()
{
return $this->_doubleQuote;
}
/**
* Sets the doubleQuote option
*
* @param boolean $doubleQuote
* @return \Zend\Filter\HtmlEntities Provides a fluent interface
*/
public function setDoubleQuote($doubleQuote)
{
$this->_doubleQuote = (boolean) $doubleQuote;
return $this;
}
/**
* Defined by Zend_Filter_Interface
*
* Returns the string $value, converting characters to their corresponding HTML entity
* equivalents where they exist
*
* @param string $value
* @return string
*/
public function filter($value)
{
return htmlentities(
(string) $value,
$this->getQuoteStyle(),
$this->getEncoding(),
$this->getDoubleQuote()
);
}
}
| bsd-3-clause |
alex-my/keyread | web/index.php | 417 | <?php
// comment out the following two lines when deployed to production
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');
require(__DIR__ . '/../vendor/autoload.php');
require(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');
require(__DIR__ . '/../config/bootstrap.php');
$config = require(__DIR__ . '/../config/web.php');
(new yii\web\Application($config))->run();
| bsd-3-clause |
vincentml/basex | basex-core/src/main/java/org/basex/query/expr/gflwor/GroupBy.java | 12441 | package org.basex.query.expr.gflwor;
import static org.basex.query.QueryText.*;
import java.util.*;
import org.basex.query.*;
import org.basex.query.expr.*;
import org.basex.query.expr.gflwor.GFLWOR.Clause;
import org.basex.query.expr.gflwor.GFLWOR.Eval;
import org.basex.query.util.*;
import org.basex.query.util.collation.*;
import org.basex.query.value.*;
import org.basex.query.value.item.*;
import org.basex.query.value.node.*;
import org.basex.query.value.seq.*;
import org.basex.query.value.type.*;
import org.basex.query.value.type.SeqType.Occ;
import org.basex.query.var.*;
import org.basex.util.*;
import org.basex.util.hash.*;
/**
* The GFLWOR {@code group by} expression.
*
* @author BaseX Team 2005-16, BSD License
* @author Leo Woerteler
*/
public final class GroupBy extends Clause {
/** Grouping specs. */
private final Spec[] specs;
/** Non-grouping variable expressions. */
private Expr[] preExpr;
/** Non-grouping variables. */
private Var[] post;
/** Number of non-occluded grouping variables. */
private final int nonOcc;
/**
* Constructor.
* @param specs grouping specs
* @param pre references to pre-grouping variables
* @param post post-grouping variables
* @param info input info
*/
public GroupBy(final Spec[] specs, final VarRef[] pre, final Var[] post, final InputInfo info) {
super(info, vars(specs, post));
this.specs = specs;
this.post = post;
preExpr = new Expr[pre.length];
System.arraycopy(pre, 0, preExpr, 0, pre.length);
int n = 0;
for(final Spec spec : specs) if(!spec.occluded) n++;
nonOcc = n;
}
/**
* Copy constructor.
* @param specs grouping specs
* @param pre pre-grouping expressions
* @param post post-grouping variables
* @param nonOcc number of non-occluded grouping variables
* @param info input info
*/
private GroupBy(final Spec[] specs, final Expr[] pre, final Var[] post, final int nonOcc,
final InputInfo info) {
super(info, vars(specs, post));
this.specs = specs;
preExpr = pre;
this.post = post;
this.nonOcc = nonOcc;
}
/**
* Gathers all declared variables.
* @param gs grouping specs
* @param vs non-grouping variables
* @return declared variables
*/
private static Var[] vars(final Spec[] gs, final Var[] vs) {
final int gl = gs.length, vl = vs.length;
final Var[] res = new Var[gl + vl];
for(int g = 0; g < gl; g++) res[g] = gs[g].var;
System.arraycopy(vs, 0, res, gl, vl);
return res;
}
@Override
Eval eval(final Eval sub) {
return new Eval() {
/** Groups to iterate over. */
private Group[] groups;
/** Current position. */
private int pos;
@Override
public boolean next(final QueryContext qc) throws QueryException {
if(groups == null) groups = init(qc);
if(pos == groups.length) return false;
final Group curr = groups[pos];
// be nice to the garbage collector
groups[pos++] = null;
int p = 0;
for(final Spec spec : specs) {
if(!spec.occluded) {
final Item key = curr.key[p++];
qc.set(spec.var, key == null ? Empty.SEQ : key, info);
}
}
final int pl = post.length;
for(int i = 0; i < pl; i++) qc.set(post[i], curr.ngv[i].value(), info);
return true;
}
/**
* Builds up the groups.
* @param qc query context
* @throws QueryException query exception
*/
private Group[] init(final QueryContext qc) throws QueryException {
final ArrayList<Group> grps = new ArrayList<>();
final IntObjMap<Group> map = new IntObjMap<>();
final Collation[] colls = new Collation[nonOcc];
int c = 0;
for(final Spec spec : specs) {
if(!spec.occluded) colls[c++] = spec.coll;
}
while(sub.next(qc)) {
final Item[] key = new Item[nonOcc];
int p = 0, hash = 1;
for(final Spec spec : specs) {
final Item atom = spec.atomItem(qc, info);
if(!spec.occluded) {
key[p++] = atom;
// If the values are compared using a special collation, we let them collide
// here and let the comparison do all the work later.
// This enables other non-collation specs to avoid the collision.
hash = 31 * hash + (atom == null || spec.coll != null ? 0 : atom.hash(info));
}
qc.set(spec.var, atom == null ? Empty.SEQ : atom, info);
}
// find the group for this key
final Group fst;
Group grp = null;
// no collations, so we can use hashing
for(Group g = fst = map.get(hash); g != null; g = g.next) {
if(eq(key, g.key, colls)) {
grp = g;
break;
}
}
final int pl = preExpr.length;
if(grp == null) {
// new group, add it to the list
final ValueBuilder[] ngs = new ValueBuilder[pl];
final int nl = ngs.length;
for(int n = 0; n < nl; n++) ngs[n] = new ValueBuilder();
grp = new Group(key, ngs);
grps.add(grp);
// insert the group into the hash table
if(fst == null) {
map.put(hash, grp);
} else {
final Group nxt = fst.next;
fst.next = grp;
grp.next = nxt;
}
}
// add values of non-grouping variables to the group
for(int g = 0; g < pl; g++) grp.ngv[g].add(preExpr[g].value(qc));
}
// we're finished, copy the array so the list can be garbage-collected
return grps.toArray(new Group[grps.size()]);
}
};
}
/**
* Checks two keys for equality.
* @param its1 first keys
* @param its2 second keys
* @param coll collations
* @return {@code true} if the compare as equal, {@code false} otherwise
* @throws QueryException query exception
*/
private boolean eq(final Item[] its1, final Item[] its2, final Collation[] coll)
throws QueryException {
final int il = its1.length;
for(int i = 0; i < il; i++) {
final Item it1 = its1[i], it2 = its2[i];
if(it1 == null ^ it2 == null || it1 != null && !it1.equiv(it2, coll[i], info)) return false;
}
return true;
}
@Override
public boolean has(final Flag flag) {
for(final Spec sp : specs) if(sp.has(flag)) return true;
return false;
}
@Override
public GroupBy compile(final QueryContext qc, final VarScope sc) throws QueryException {
for(final Expr e : preExpr) e.compile(qc, sc);
for(final Spec b : specs) b.compile(qc, sc);
return optimize(qc, sc);
}
@Override
public GroupBy optimize(final QueryContext qc, final VarScope scp) throws QueryException {
final int pl = preExpr.length;
for(int p = 0; p < pl; p++) {
final SeqType it = preExpr[p].seqType();
post[p].refineType(it.withOcc(it.mayBeZero() ? Occ.ZERO_MORE : Occ.ONE_MORE), qc, info);
}
return this;
}
@Override
public boolean removable(final Var var) {
for(final Spec b : specs) if(!b.removable(var)) return false;
return true;
}
@Override
public VarUsage count(final Var var) {
return VarUsage.sum(var, specs).plus(VarUsage.sum(var, preExpr));
}
@Override
public Clause inline(final QueryContext qc, final VarScope scp, final Var var,
final Expr ex) throws QueryException {
final boolean b = inlineAll(qc, scp, specs, var, ex), p = inlineAll(qc, scp, preExpr, var, ex);
return b || p ? optimize(qc, scp) : null;
}
@Override
public GroupBy copy(final QueryContext qc, final VarScope scp, final IntObjMap<Var> vs) {
// copy the pre-grouping expressions
final Expr[] pEx = Arr.copyAll(qc, scp, vs, preExpr);
// create fresh copies of the post-grouping variables
final Var[] ps = new Var[post.length];
final int pl = ps.length;
for(int p = 0; p < pl; p++) {
final Var old = post[p];
ps[p] = scp.newCopyOf(qc, old);
vs.put(old.id, ps[p]);
}
// done
return new GroupBy(Arr.copyAll(qc, scp, vs, specs), pEx, ps, nonOcc, info);
}
@Override
public boolean accept(final ASTVisitor visitor) {
if(!visitAll(visitor, specs)) return false;
for(final Expr ng : preExpr) if(!ng.accept(visitor)) return false;
for(final Var ng : post) if(!visitor.declared(ng)) return false;
return true;
}
@Override
boolean clean(final IntObjMap<Var> decl, final BitArray used) {
// [LW] does not fix {@link #vars}
final int len = preExpr.length;
for(int p = 0; p < post.length; p++) {
if(!used.get(post[p].id)) {
preExpr = Array.delete(preExpr, p);
post = Array.delete(post, p--);
}
}
return preExpr.length < len;
}
@Override
boolean skippable(final Clause cl) {
return false;
}
@Override
public void checkUp() throws QueryException {
checkNoneUp(preExpr);
checkNoneUp(specs);
}
@Override
void calcSize(final long[] minMax) {
minMax[0] = Math.min(minMax[0], 1);
}
@Override
public int exprSize() {
int sz = 0;
for(final Expr e : preExpr) sz += e.exprSize();
for(final Expr e : specs) sz += e.exprSize();
return sz;
}
@Override
public void plan(final FElem plan) {
final FElem e = planElem();
for(final Spec spec : specs) spec.plan(e);
plan.add(e);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
final int pl = post.length;
for(int p = 0; p < pl; p++) {
sb.append(LET).append(" (: post-group :) ").append(post[p]);
sb.append(' ').append(ASSIGN).append(' ').append(preExpr[p]).append(' ');
}
sb.append(GROUP).append(' ').append(BY);
final int sl = specs.length;
for(int s = 0; s < sl; s++) sb.append(s == 0 ? " " : SEP).append(specs[s]);
return sb.toString();
}
/**
* Grouping spec.
*
* @author BaseX Team 2005-16, BSD License
* @author Leo Woerteler
*/
public static final class Spec extends Single {
/** Grouping variable. */
public final Var var;
/** Occlusion flag, {@code true} if another grouping variable shadows this one. */
public boolean occluded;
/** Collation. */
private final Collation coll;
/**
* Constructor.
*
* @param info input info
* @param var grouping variable
* @param expr grouping expression
* @param coll collation
*/
public Spec(final InputInfo info, final Var var, final Expr expr, final Collation coll) {
super(info, expr);
this.var = var;
this.coll = coll;
}
@Override
public Item item(final QueryContext qc, final InputInfo ii) throws QueryException {
return expr.item(qc, ii);
}
@Override
public Expr copy(final QueryContext qc, final VarScope scp, final IntObjMap<Var> vs) {
final Var v = scp.newCopyOf(qc, var);
vs.put(var.id, v);
final Spec spec = new Spec(info, v, expr.copy(qc, scp, vs), coll);
spec.occluded = occluded;
return spec;
}
@Override
public boolean accept(final ASTVisitor visitor) {
return expr.accept(visitor) && visitor.declared(var);
}
@Override
public int exprSize() {
return expr.exprSize();
}
@Override
public void plan(final FElem plan) {
final FElem e = planElem();
var.plan(e);
expr.plan(e);
plan.add(e);
}
@Override
public String toString() {
final TokenBuilder tb = new TokenBuilder().add(var.toString()).add(' ').add(ASSIGN);
tb.add(' ').add(expr.toString());
if(coll != null) tb.add(' ').add(COLLATION).add(" \"").add(coll.uri()).add('"');
return tb.toString();
}
}
/**
* A group of tuples of post-grouping variables.
*
* @author BaseX Team 2005-16, BSD License
* @author Leo Woerteler
*/
private static final class Group {
/** Grouping key, may contain {@code null} values. */
final Item[] key;
/** Non-grouping variables. */
final ValueBuilder[] ngv;
/** Overflow list. */
Group next;
/**
* Constructor.
* @param k grouping key
* @param ng non-grouping variables
*/
Group(final Item[] k, final ValueBuilder[] ng) {
key = k;
ngv = ng;
}
}
}
| bsd-3-clause |
pkdevbox/flynn | router/http_test.go | 33082 | package main
import (
"bufio"
"crypto/tls"
"crypto/x509"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/http/httptest"
"strings"
"time"
. "github.com/flynn/flynn/Godeps/_workspace/src/github.com/flynn/go-check"
"github.com/flynn/flynn/Godeps/_workspace/src/golang.org/x/net/websocket"
"github.com/flynn/flynn/discoverd/testutil/etcdrunner"
"github.com/flynn/flynn/pkg/httpclient"
"github.com/flynn/flynn/router/types"
)
const UUIDRegex = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"
var httpClient = newHTTPClient("example.com")
// borrowed from net/http/httptest/server.go
// localhostCert is a PEM-encoded TLS cert with SAN IPs
// "127.0.0.1" and "[::1]", expiring at the last second of 2049 (the end
// of ASN.1 time).
// generated from src/pkg/crypto/tls:
// go run generate_cert.go --rsa-bits 512 --host 127.0.0.1,::1,example.com,*.example.com --ca --start-date "Jan 1 00:00:00 1970" --duration=1000000h
var localhostCert = []byte(`-----BEGIN CERTIFICATE-----
MIIBmjCCAUagAwIBAgIRAP5DRqWA/pgvAnbC6gnl82kwCwYJKoZIhvcNAQELMBIx
EDAOBgNVBAoTB0FjbWUgQ28wIBcNNzAwMTAxMDAwMDAwWhgPMjA4NDAxMjkxNjAw
MDBaMBIxEDAOBgNVBAoTB0FjbWUgQ28wXDANBgkqhkiG9w0BAQEFAANLADBIAkEA
t9JXJg6fCMxvBKfLCukH7dnF1nIdCBuurjXxVM69E2+97G3aDBTIm7rXtxilAYib
BwzBtgqPzUVngbmK25cguQIDAQABo3cwdTAOBgNVHQ8BAf8EBAMCAKQwEwYDVR0l
BAwwCgYIKwYBBQUHAwEwDwYDVR0TAQH/BAUwAwEB/zA9BgNVHREENjA0ggtleGFt
cGxlLmNvbYINKi5leGFtcGxlLmNvbYcEfwAAAYcQAAAAAAAAAAAAAAAAAAAAATAL
BgkqhkiG9w0BAQsDQQBJxy1zotHYLZpyoockAlJWRa88hs1PrroUNMlueRtzNkpx
9heaebvotwUkFlnNYJZsfPnO23R0lUlzLJ3p1RNz
-----END CERTIFICATE-----`)
// localhostKey is the private key for localhostCert.
var localhostKey = []byte(`-----BEGIN RSA PRIVATE KEY-----
MIIBOQIBAAJBALfSVyYOnwjMbwSnywrpB+3ZxdZyHQgbrq418VTOvRNvvext2gwU
yJu617cYpQGImwcMwbYKj81FZ4G5ituXILkCAwEAAQJAXvmhp3skdkJSFgCv6qou
O5kqG7uH/nl3DnG2iA/tJw3SlEPftQyzNk5jcIFSxvr8pu1pj+L1vw5pR68/7fre
xQIhAMM0/bYtVbzW+PPjqAev3TKhMyWkY3t9Qvw5OtgmBQ+PAiEA8RGk9OvMxBbR
8zJmOXminEE2VVE1VF0K0OiFLDG+JzcCIHurptE0B42L5E0ffeTg1hKtben7K8ug
oD+LQmyOKcahAiB05Btab2QQyQfwpsWOpP5GShCwefoj+CGgfr7kWRJdLQIgTMZe
++SKD8ascROyDnZ0Td8wbrFnO0YRPEkwlhn6h0U=
-----END RSA PRIVATE KEY-----`)
func httpTestHandler(id string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
w.Write([]byte(id))
})
}
func newHTTPClient(serverName string) *http.Client {
pool := x509.NewCertPool()
pool.AppendCertsFromPEM(localhostCert)
if strings.Contains(serverName, ":") {
serverName, _, _ = net.SplitHostPort(serverName)
}
return &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{ServerName: serverName, RootCAs: pool},
},
}
}
func (s *S) newHTTPListener(t etcdrunner.TestingT) *HTTPListener {
pair, err := tls.X509KeyPair(localhostCert, localhostKey)
if err != nil {
t.Fatal(err)
}
l := &HTTPListener{
Addr: "127.0.0.1:0",
TLSAddr: "127.0.0.1:0",
keypair: pair,
ds: NewPostgresDataStore("http", s.pgx),
discoverd: s.discoverd,
}
if err := l.Start(); err != nil {
t.Fatal(err)
}
return l
}
// https://code.google.com/p/go/issues/detail?id=5381
func (s *S) TestIssue5381(c *C) {
srv := httptest.NewServer(httpTestHandler(""))
defer srv.Close()
l := s.newHTTPListener(c)
defer l.Close()
addHTTPRoute(c, l)
discoverdRegisterHTTP(c, l, srv.Listener.Addr().String())
assertGet(c, "http://"+l.Addr, "example.com", "")
}
func (s *S) TestAddHTTPRoute(c *C) {
srv1 := httptest.NewServer(httpTestHandler("1"))
srv2 := httptest.NewServer(httpTestHandler("2"))
defer srv1.Close()
defer srv2.Close()
l := s.newHTTPListener(c)
defer l.Close()
r := addHTTPRoute(c, l)
unregister := discoverdRegisterHTTP(c, l, srv1.Listener.Addr().String())
assertGet(c, "http://"+l.Addr, "example.com", "1")
assertGet(c, "https://"+l.TLSAddr, "example.com", "1")
unregister()
discoverdRegisterHTTP(c, l, srv2.Listener.Addr().String())
// Close the connection we just used to trigger a new backend choice
httpClient.Transport.(*http.Transport).CloseIdleConnections()
assertGet(c, "http://"+l.Addr, "example.com", "2")
assertGet(c, "https://"+l.TLSAddr, "example.com", "2")
res, err := httpClient.Do(newReq("http://"+l.Addr, "example2.com"))
c.Assert(err, IsNil)
c.Assert(res.StatusCode, Equals, 404)
res.Body.Close()
_, err = (&http.Client{
Transport: &http.Transport{TLSClientConfig: &tls.Config{ServerName: "example2.com"}},
}).Do(newReq("https://"+l.TLSAddr, "example2.com"))
c.Assert(err, Not(IsNil))
wait := waitForEvent(c, l, "remove", r.ID)
err = l.RemoveRoute(r.ID)
c.Assert(err, IsNil)
wait()
httpClient.Transport.(*http.Transport).CloseIdleConnections()
res, err = httpClient.Do(newReq("http://"+l.Addr, "example.com"))
c.Assert(err, IsNil)
c.Assert(res.StatusCode, Equals, 404)
res.Body.Close()
}
func newReq(url, host string) *http.Request {
req, _ := http.NewRequest("GET", url, nil)
req.Host = host
return req
}
func assertGet(c *C, url, host, expected string) []*http.Cookie {
return assertGetCookies(c, url, host, expected, nil)
}
func assertGetCookies(c *C, url, host, expected string, cookies []*http.Cookie) []*http.Cookie {
req := newReq(url, host)
for _, cookie := range cookies {
req.AddCookie(cookie)
}
res, err := newHTTPClient(host).Do(req)
c.Assert(err, IsNil)
defer res.Body.Close()
c.Assert(res.StatusCode, Equals, 200)
data, err := ioutil.ReadAll(res.Body)
c.Assert(err, IsNil)
c.Assert(string(data), Equals, expected)
return res.Cookies()
}
func addHTTPRoute(c *C, l *HTTPListener) *router.Route {
return addRoute(c, l, router.HTTPRoute{
Domain: "example.com",
Service: "test",
TLSCert: string(localhostCert),
TLSKey: string(localhostKey),
}.ToRoute())
}
func removeHTTPRoute(c *C, l *HTTPListener, id string) {
removeRoute(c, l, id)
}
func addStickyHTTPRoute(c *C, l *HTTPListener) *router.Route {
return addRoute(c, l, router.HTTPRoute{
Domain: "example.com",
Service: "test",
Sticky: true,
}.ToRoute())
}
func (s *S) TestWildcardRouting(c *C) {
srv1 := httptest.NewServer(httpTestHandler("1"))
srv2 := httptest.NewServer(httpTestHandler("2"))
srv3 := httptest.NewServer(httpTestHandler("3"))
defer srv1.Close()
defer srv2.Close()
defer srv3.Close()
l := s.newHTTPListener(c)
defer l.Close()
addRoute(c, l, router.HTTPRoute{
Domain: "foo.bar",
Service: "1",
}.ToRoute())
addRoute(c, l, router.HTTPRoute{
Domain: "*.foo.bar",
Service: "2",
}.ToRoute())
addRoute(c, l, router.HTTPRoute{
Domain: "dev.foo.bar",
Service: "3",
}.ToRoute())
discoverdRegisterHTTPService(c, l, "1", srv1.Listener.Addr().String())
discoverdRegisterHTTPService(c, l, "2", srv2.Listener.Addr().String())
discoverdRegisterHTTPService(c, l, "3", srv3.Listener.Addr().String())
assertGet(c, "http://"+l.Addr, "foo.bar", "1")
assertGet(c, "http://"+l.Addr, "flynn.foo.bar", "2")
assertGet(c, "http://"+l.Addr, "dev.foo.bar", "3")
}
func (s *S) TestHTTPInitialSync(c *C) {
l := s.newHTTPListener(c)
addHTTPRoute(c, l)
l.Close()
srv := httptest.NewServer(httpTestHandler("1"))
defer srv.Close()
l = s.newHTTPListener(c)
defer l.Close()
discoverdRegisterHTTP(c, l, srv.Listener.Addr().String())
assertGet(c, "http://"+l.Addr, "example.com", "1")
assertGet(c, "https://"+l.TLSAddr, "example.com", "1")
}
// issue #26
func (s *S) TestHTTPServiceHandlerBackendConnectionClosed(c *C) {
srv := httptest.NewServer(httpTestHandler("1"))
l := s.newHTTPListener(c)
defer l.Close()
addHTTPRoute(c, l)
discoverdRegisterHTTP(c, l, srv.Listener.Addr().String())
// a single request is allowed to successfully get issued
assertGet(c, "http://"+l.Addr, "example.com", "1")
// the backend server's connection gets closed, but router is
// able to recover
srv.CloseClientConnections()
// Though we've closed the conn on the server, the client might not have
// handled the FIN yet. The Transport offers no way to safely retry in those
// scenarios, so instead we just sleep long enough to handle the FIN.
// https://golang.org/issue/4677
time.Sleep(500 * time.Microsecond)
assertGet(c, "http://"+l.Addr, "example.com", "1")
}
// Act as an app to test HTTP headers
func httpHeaderTestHandler(c *C, ip, port string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
c.Assert(req.Header["X-Forwarded-Port"][0], Equals, port)
c.Assert(req.Header["X-Forwarded-Proto"][0], Equals, "http")
c.Assert(len(req.Header["X-Request-Start"][0]), Equals, 13)
c.Assert(req.Header["X-Forwarded-For"][0], Equals, ip)
c.Assert(req.Header["X-Request-Id"][0], Matches, UUIDRegex)
w.Write([]byte("1"))
})
}
// issue #105
func (s *S) TestHTTPHeaders(c *C) {
l := s.newHTTPListener(c)
defer l.Close()
addHTTPRoute(c, l)
port := mustPortFromAddr(l.listener.Addr().String())
srv := httptest.NewServer(httpHeaderTestHandler(c, "127.0.0.1", port))
discoverdRegisterHTTP(c, l, srv.Listener.Addr().String())
assertGet(c, "http://"+l.Addr, "example.com", "1")
}
func (s *S) TestHTTPHeadersFromClient(c *C) {
l := s.newHTTPListener(c)
defer l.Close()
addHTTPRoute(c, l)
port := mustPortFromAddr(l.listener.Addr().String())
srv := httptest.NewServer(httpHeaderTestHandler(c, "192.168.1.1, 127.0.0.1", port))
discoverdRegisterHTTP(c, l, srv.Listener.Addr().String())
req := newReq("http://"+l.Addr, "example.com")
req.Header.Set("X-Forwarded-For", "192.168.1.1")
req.Header.Set("X-Request-Id", "asdf1234asdf")
res, err := httpClient.Do(req)
c.Assert(err, IsNil)
defer res.Body.Close()
c.Assert(res.StatusCode, Equals, 200)
}
func (s *S) TestHTTPProxyHeadersFromClient(c *C) {
h := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
c.Assert(req.Header.Get("Proxy-Authenticate"), Equals, "fake")
c.Assert(req.Header.Get("Proxy-Authorization"), Equals, "not-empty")
})
srv := httptest.NewServer(h)
defer srv.Close()
l := s.newHTTPListener(c)
defer l.Close()
addHTTPRoute(c, l)
discoverdRegisterHTTP(c, l, srv.Listener.Addr().String())
tests := []struct {
upgrade bool
}{
{upgrade: false}, // regular path
{upgrade: true}, // tcp/websocket path
}
for _, test := range tests {
req := newReq("http://"+l.Addr, "example.com")
req.Header.Set("Proxy-Authenticate", "fake")
req.Header.Set("Proxy-Authorization", "not-empty")
if test.upgrade {
req.Header.Set("Connection", "upgrade")
}
res, err := httpClient.Do(req)
c.Assert(err, IsNil)
defer res.Body.Close()
c.Assert(res.StatusCode, Equals, 200)
}
}
func (s *S) TestConnectionCloseHeaderFromClient(c *C) {
h := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
// Connection: close header should be stripped by the reverse proxy so it
// always does keep-alive with backends.
c.Assert(req.Close, Equals, false)
})
srv := httptest.NewServer(h)
defer srv.Close()
l := s.newHTTPListener(c)
defer l.Close()
addHTTPRoute(c, l)
discoverdRegisterHTTP(c, l, srv.Listener.Addr().String())
req := newReq("http://"+l.Addr, "example.com")
req.Header.Set("Connection", "close")
res, err := httpClient.Do(req)
c.Assert(err, IsNil)
defer res.Body.Close()
c.Assert(res.StatusCode, Equals, 200)
c.Assert(res.Close, Equals, true)
}
func (s *S) TestConnectionHeaders(c *C) {
srv := httptest.NewServer(httpTestHandler("ok"))
defer srv.Close()
l := s.newHTTPListener(c)
defer l.Close()
addHTTPRoute(c, l)
discoverdRegisterHTTP(c, l, srv.Listener.Addr().String())
tests := []struct {
conn string // connection header string to send, if any
upgradeFromClient bool // for server tests, whether to send an upgrade request
emptyHeaders []string // headers that shouldn't be set
presentHeaders []string // headers that should be set
}{
{
conn: "",
// Upgrade header must be deleted if Connection header != "upgrade".
// Transfer-Encoding is always deleted before forwarding.
emptyHeaders: []string{"Transfer-Encoding", "Upgrade"},
// Keep all others
presentHeaders: []string{"Another-Option", "Custom-Conn-Header", "Keep-Alive"},
},
{
conn: "keep-alive",
// Keep-Alive header should be deleted because that's a conn-specific
// header here. Upgrade still gets deleted b/c Connection != "upgrade".
emptyHeaders: []string{"Keep-Alive", "Transfer-Encoding", "Upgrade"},
presentHeaders: []string{"Another-Option", "Custom-Conn-Header"},
},
{
conn: "custom-conn-header",
emptyHeaders: []string{"Custom-Conn-Header", "Transfer-Encoding", "Upgrade"},
presentHeaders: []string{"Another-Option", "Keep-Alive"},
},
{ // test multiple connection-options
conn: "custom-conn-header, ,another-option ",
emptyHeaders: []string{"Another-Option", "Custom-Conn-Header", "Transfer-Encoding", "Upgrade"},
presentHeaders: []string{"Keep-Alive"},
},
{
// tcp/websocket path, all headers should be sent to backend (except
// Transfer-Encoding)
conn: "upgrade",
upgradeFromClient: true,
emptyHeaders: []string{"Transfer-Encoding"},
presentHeaders: []string{"Custom-Conn-Header", "Keep-Alive", "Upgrade"},
},
{
// tcp/websocket path, all headers should be sent to backend (except
// Transfer-Encoding)
conn: "upGrade, custom-Conn-header, ,Another-option ",
upgradeFromClient: true,
emptyHeaders: []string{"Transfer-Encoding"},
presentHeaders: []string{"Another-Option", "Custom-Conn-Header", "Keep-Alive", "Upgrade"},
},
}
for _, test := range tests {
c.Logf("testing client with Connection: %q", test.conn)
srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
for _, k := range test.emptyHeaders {
c.Assert(req.Header.Get(k), Equals, "", Commentf("header = %s", k))
}
for _, k := range test.presentHeaders {
c.Assert(req.Header.Get(k), Not(Equals), "", Commentf("header = %s", k))
}
})
req := newReq("http://"+l.Addr, "example.com")
if test.conn != "" {
req.Header.Set("Connection", test.conn)
}
req.Header.Set("Another-Option", "test-another-option")
req.Header.Set("Custom-Conn-Header", "test-custom-conn-header")
req.Header.Set("Keep-Alive", "test-keep-alive")
req.Header.Set("Transfer-Encoding", "test-transfer-encoding")
req.Header.Set("Upgrade", "test-upgrade")
res, err := httpClient.Do(req)
c.Assert(err, IsNil)
res.Body.Close()
c.Assert(res.StatusCode, Equals, 200)
}
for _, test := range tests {
c.Logf("testing server with Connection: %q", test.conn)
srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
if test.conn != "" {
w.Header().Set("Connection", test.conn)
}
w.Header().Set("Keep-Alive", "test-keep-alive")
w.Header().Set("Another-Option", "test-another-option")
w.Header().Set("Custom-Conn-Header", "test-custom-conn-header")
w.Header().Set("Upgrade", "test-upgrade")
})
req := newReq("http://"+l.Addr, "example.com")
if test.upgradeFromClient {
req.Header.Set("Connection", "upgrade")
req.Header.Set("Upgrade", "special-proto")
}
res, err := httpClient.Do(req)
c.Assert(err, IsNil)
res.Body.Close()
c.Assert(res.StatusCode, Equals, 200)
for _, k := range test.emptyHeaders {
c.Assert(res.Header.Get(k), Equals, "", Commentf("header = %s", k))
}
for _, k := range test.presentHeaders {
c.Assert(res.Header.Get(k), Not(Equals), "", Commentf("header = %s", k))
}
}
}
func (s *S) TestHTTPWebsocket(c *C) {
done := make(chan struct{})
h := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
if req.URL.Path != "/websocket" {
w.Write([]byte("not a websocket upgrade\n"))
return
}
websocket.Handler(func(conn *websocket.Conn) {
_, err := conn.Write([]byte("1"))
c.Assert(err, IsNil)
res := make([]byte, 1)
_, err = conn.Read(res)
c.Assert(err, IsNil)
c.Assert(res[0], Equals, byte('2'))
done <- struct{}{}
}).ServeHTTP(w, req)
})
srv := httptest.NewServer(h)
defer srv.Close()
l := s.newHTTPListener(c)
defer l.Close()
addHTTPRoute(c, l)
discoverdRegisterHTTP(c, l, srv.Listener.Addr().String())
tests := []struct {
afterKeepAlive bool
}{
{afterKeepAlive: false},
{afterKeepAlive: true}, // ensure that upgrade still works on reused conn
}
for _, test := range tests {
conn, err := net.Dial("tcp", l.Addr)
c.Assert(err, IsNil)
defer conn.Close()
if test.afterKeepAlive {
req, err := http.NewRequest("GET", "http://example.com", nil)
c.Assert(err, IsNil)
err = req.Write(conn)
c.Assert(err, IsNil)
res, err := http.ReadResponse(bufio.NewReader(conn), req)
c.Assert(err, IsNil)
data, err := ioutil.ReadAll(res.Body)
c.Assert(err, IsNil)
res.Body.Close()
c.Assert(res.StatusCode, Equals, 200)
c.Assert(string(data), Equals, "not a websocket upgrade\n")
}
conf, err := websocket.NewConfig("ws://example.com/websocket", "http://example.net")
c.Assert(err, IsNil)
wc, err := websocket.NewClient(conf, conn)
c.Assert(err, IsNil)
res := make([]byte, 1)
_, err = wc.Read(res)
c.Assert(err, IsNil)
c.Assert(res[0], Equals, byte('1'))
_, err = wc.Write([]byte("2"))
c.Assert(err, IsNil)
<-done
}
}
func (s *S) TestUpgradeHeaderIsCaseInsensitive(c *C) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
c.Assert(strings.ToLower(req.Header.Get("Connection")), Equals, "upgrade")
// ensure that Upgrade header is passed along intact
c.Assert(req.Header.Get("Upgrade"), Equals, "Some-proto-2")
w.Write([]byte("ok\n"))
}))
defer srv.Close()
l := s.newHTTPListener(c)
url := "http://" + l.Addr
defer l.Close()
addHTTPRoute(c, l)
discoverdRegisterHTTP(c, l, srv.Listener.Addr().String())
values := []string{"upgrade", "Upgrade", "upGradE"}
for _, value := range values {
req := newReq(url, "example.com")
req.Header.Set("Connection", value)
req.Header.Set("Upgrade", "Some-proto-2")
res, err := httpClient.Do(req)
defer res.Body.Close()
c.Assert(err, IsNil)
c.Assert(res.StatusCode, Equals, 200)
data, err := ioutil.ReadAll(res.Body)
c.Assert(err, IsNil)
c.Assert(string(data), Equals, "ok\n")
}
httpClient.Transport.(*http.Transport).CloseIdleConnections()
}
func (s *S) TestStickyHTTPRoute(c *C) {
srv1 := httptest.NewServer(httpTestHandler("1"))
srv2 := httptest.NewServer(httpTestHandler("2"))
defer srv1.Close()
defer srv2.Close()
l := s.newHTTPListener(c)
defer l.Close()
addStickyHTTPRoute(c, l)
unregister := discoverdRegisterHTTP(c, l, srv1.Listener.Addr().String())
cookies := assertGet(c, "http://"+l.Addr, "example.com", "1")
discoverdRegisterHTTP(c, l, srv2.Listener.Addr().String())
for i := 0; i < 10; i++ {
resCookies := assertGetCookies(c, "http://"+l.Addr, "example.com", "1", cookies)
c.Assert(resCookies, HasLen, 0)
httpClient.Transport.(*http.Transport).CloseIdleConnections()
}
unregister()
for i := 0; i < 10; i++ {
resCookies := assertGetCookies(c, "http://"+l.Addr, "example.com", "2", cookies)
c.Assert(resCookies, Not(HasLen), 0)
}
}
func wsHandshakeTestHandler(id string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
if strings.ToLower(req.Header.Get("Connection")) == "upgrade" {
w.Header().Set("Connection", "Upgrade")
w.Header().Set("Upgrade", "websocket")
w.Header().Set("Backend-Id", id)
w.WriteHeader(http.StatusSwitchingProtocols)
} else {
http.NotFound(w, req)
}
})
}
func (s *S) TestStickyHTTPRouteWebsocket(c *C) {
srv1 := httptest.NewServer(wsHandshakeTestHandler("1"))
srv2 := httptest.NewServer(wsHandshakeTestHandler("2"))
defer srv1.Close()
defer srv2.Close()
l := s.newHTTPListener(c)
url := "http://" + l.Addr
defer l.Close()
addStickyHTTPRoute(c, l)
var unregister func()
steps := []struct {
do func()
backend string
setCookie bool
}{
// step 1: register srv1, assert requests to srv1
{
do: func() { unregister = discoverdRegisterHTTP(c, l, srv1.Listener.Addr().String()) },
backend: "1",
setCookie: true,
},
// step 2: register srv2, assert requests stay with srv1
{
do: func() { discoverdRegisterHTTP(c, l, srv2.Listener.Addr().String()) },
backend: "1",
},
// step 3: unregister srv1, assert requests switch to srv2
{
do: func() { unregister() },
backend: "2",
setCookie: true,
},
}
var sessionCookies []*http.Cookie
for _, step := range steps {
step.do()
cookieSet := false
for i := 0; i < 10; i++ {
req := newReq(url, "example.com")
for _, cookie := range sessionCookies {
req.AddCookie(cookie)
}
req.Header.Set("Connection", "Upgrade")
req.Header.Set("Upgrade", "websocket")
res, err := httpClient.Do(req)
defer res.Body.Close()
c.Assert(err, IsNil)
c.Assert(res.StatusCode, Equals, 101)
c.Assert(res.Header.Get("Backend-Id"), Equals, step.backend)
// reuse the session cookie if present
if len(res.Cookies()) > 0 {
// TODO(benburkert): instead of assuming that a session cookie is set
// if a response has cookies, switch back to checking for the session
// cookie once this test can access proxy.stickyCookie
sessionCookies = res.Cookies()
cookieSet = true
}
}
c.Assert(cookieSet, Equals, step.setCookie)
httpClient.Transport.(*http.Transport).CloseIdleConnections()
}
}
func (s *S) TestNoBackends(c *C) {
l := s.newHTTPListener(c)
defer l.Close()
addRoute(c, l, router.HTTPRoute{
Domain: "example.com",
Service: "example-com",
}.ToRoute())
req := newReq("http://"+l.Addr, "example.com")
res, err := newHTTPClient("example.com").Do(req)
c.Assert(err, IsNil)
defer res.Body.Close()
c.Assert(res.StatusCode, Equals, 503)
data, err := ioutil.ReadAll(res.Body)
c.Assert(err, IsNil)
c.Assert(string(data), Equals, "Service Unavailable\n")
}
func (s *S) TestNoResponsiveBackends(c *C) {
l := s.newHTTPListener(c)
defer l.Close()
// close both servers immediately
srv1 := httptest.NewServer(httpTestHandler("1"))
srv1.Close()
srv2 := httptest.NewServer(httpTestHandler("2"))
srv2.Close()
addRoute(c, l, router.HTTPRoute{
Domain: "example.com",
Service: "example-com",
Sticky: true,
}.ToRoute())
discoverdRegisterHTTPService(c, l, "example-com", srv1.Listener.Addr().String())
discoverdRegisterHTTPService(c, l, "example-com", srv2.Listener.Addr().String())
type ts struct{ upgrade bool }
tests := []ts{
{upgrade: false}, // regular path
{upgrade: true}, // tcp/websocket path
}
runTest := func(test ts) {
c.Log("upgrade:", test.upgrade)
req := newReq("http://"+l.Addr, "example.com")
if test.upgrade {
req.Header.Set("Connection", "Upgrade")
}
res, err := newHTTPClient("example.com").Do(req)
c.Assert(err, IsNil)
defer res.Body.Close()
c.Assert(res.StatusCode, Equals, 503)
data, err := ioutil.ReadAll(res.Body)
c.Assert(err, IsNil)
c.Assert(string(data), Equals, "Service Unavailable\n")
}
for _, test := range tests {
runTest(test)
}
}
func (s *S) TestClosedBackendRetriesAnotherBackend(c *C) {
l := s.newHTTPListener(c)
defer l.Close()
srv1 := httptest.NewServer(httpTestHandler("1"))
srv2 := httptest.NewServer(httpTestHandler("2"))
defer srv2.Close()
addRoute(c, l, router.HTTPRoute{
Domain: "example.com",
Service: "example-com",
Sticky: true,
}.ToRoute())
discoverdRegisterHTTPService(c, l, "example-com", srv1.Listener.Addr().String())
cookies := assertGet(c, "http://"+l.Addr, "example.com", "1")
// close srv1, register srv2
srv1.Close()
discoverdRegisterHTTPService(c, l, "example-com", srv2.Listener.Addr().String())
type ts struct {
method string
upgrade bool // whether to trigger the Upgrade/websocket path
}
tests := []ts{
{method: "GET", upgrade: false},
{method: "GET", upgrade: true},
{method: "POST", upgrade: false},
{method: "POST", upgrade: true},
}
runTest := func(test ts) {
c.Log("method:", test.method, "upgrade:", test.upgrade)
var body io.Reader
if test.method == "POST" {
body = strings.NewReader("A not-so-large Flynn test body...")
}
req, _ := http.NewRequest(test.method, "http://"+l.Addr, body)
req.Host = "example.com"
if test.upgrade {
req.Header.Set("Connection", "upgrade")
}
// add cookies to stick to srv1
for _, cookie := range cookies {
req.AddCookie(cookie)
}
res, err := newHTTPClient("example.com").Do(req)
c.Assert(err, IsNil)
defer res.Body.Close()
c.Assert(res.StatusCode, Equals, 200)
data, err := ioutil.ReadAll(res.Body)
c.Assert(err, IsNil)
c.Assert(string(data), Equals, "2")
// ensure that unsuccessful upgrades are closed, and non-upgrades aren't.
c.Assert(res.Close, Equals, test.upgrade)
}
for _, test := range tests {
runTest(test)
}
}
// Note: this behavior may change if the following issue is fixed, in which case
// this behavior would only apply to non-idempotent requests (i.e. POST):
// https://golang.org/issue/4677
func (s *S) TestErrorAfterConnOnlyHitsOneBackend(c *C) {
tests := []struct {
upgrade bool
}{
{upgrade: false}, // regular path
{upgrade: true}, // tcp/websocket path
}
for _, test := range tests {
s.runTestErrorAfterConnOnlyHitsOneBackend(c, test.upgrade)
}
}
func (s *S) runTestErrorAfterConnOnlyHitsOneBackend(c *C, upgrade bool) {
c.Log("upgrade:", upgrade)
closec := make(chan struct{})
defer close(closec)
hitCount := 0
acceptOnlyOnce := func(listener net.Listener) {
for {
conn, err := listener.Accept()
select {
case <-closec:
return
default:
c.Assert(err, IsNil)
hitCount++
conn.Close()
if hitCount > 1 {
c.Fatal("received a second conn")
}
}
}
}
srv1, err := net.Listen("tcp", "127.0.0.1:0")
c.Assert(err, IsNil)
defer srv1.Close()
srv2, err := net.Listen("tcp", "127.0.0.1:0")
c.Assert(err, IsNil)
defer srv2.Close()
go acceptOnlyOnce(srv1)
go acceptOnlyOnce(srv2)
l := s.newHTTPListener(c)
defer l.Close()
defer removeHTTPRoute(c, l, addHTTPRoute(c, l).ID)
discoverdRegisterHTTP(c, l, srv1.Addr().String())
discoverdRegisterHTTP(c, l, srv2.Addr().String())
req := newReq("http://"+l.Addr, "example.com")
if upgrade {
req.Header.Set("Connection", "Upgrade")
req.Header.Set("Upgrade", "websocket")
}
res, err := newHTTPClient("example.com").Do(req)
c.Assert(err, IsNil)
defer res.Body.Close()
c.Assert(res.StatusCode, Equals, 503)
data, err := ioutil.ReadAll(res.Body)
c.Assert(err, IsNil)
c.Assert(string(data), Equals, "Service Unavailable\n")
}
// issue #152
func (s *S) TestKeepaliveHostname(c *C) {
srv1 := httptest.NewServer(httpTestHandler("1"))
srv2 := httptest.NewServer(httpTestHandler("2"))
defer srv1.Close()
defer srv2.Close()
l := s.newHTTPListener(c)
defer l.Close()
addRoute(c, l, router.HTTPRoute{
Domain: "example.com",
Service: "example-com",
}.ToRoute())
addRoute(c, l, router.HTTPRoute{
Domain: "example.org",
Service: "example-org",
}.ToRoute())
discoverdRegisterHTTPService(c, l, "example-com", srv1.Listener.Addr().String())
discoverdRegisterHTTPService(c, l, "example-org", srv2.Listener.Addr().String())
assertGet(c, "http://"+l.Addr, "example.com", "1")
assertGet(c, "http://"+l.Addr, "example.org", "2")
}
// issue #177
func (s *S) TestRequestURIEscaping(c *C) {
l := s.newHTTPListener(c)
defer l.Close()
var prefix string
uri := "/O08YqxVCf6KRJM6I8p594tzJizQ=/200x300/filters:no_upscale()/http://i.imgur.com/Wru0cNM.jpg?foo=bar"
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
c.Assert(req.RequestURI, Equals, prefix+uri)
}))
defer srv.Close()
addHTTPRoute(c, l)
discoverdRegisterHTTP(c, l, srv.Listener.Addr().String())
for _, prefix = range []string{"", "http://example.com"} {
conn, err := net.Dial("tcp", l.Addr)
c.Assert(err, IsNil)
defer conn.Close()
fmt.Fprintf(conn, "GET %s HTTP/1.1\r\nHost: example.com\r\n\r\n", prefix+uri)
res, err := http.ReadResponse(bufio.NewReader(conn), nil)
c.Assert(err, IsNil)
c.Assert(res.StatusCode, Equals, 200)
}
}
func (s *S) TestRequestQueryParams(c *C) {
l := s.newHTTPListener(c)
defer l.Close()
req := newReq(fmt.Sprintf("http://%s/query", l.Addr), "example.com")
req.URL.RawQuery = "first=this+is+a+field&second=was+it+clear+%28already%29%3F"
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, inreq *http.Request) {
c.Assert(inreq.URL.RawQuery, Not(Equals), "")
c.Assert(inreq.URL.RawQuery, Equals, req.URL.RawQuery)
c.Assert(inreq.URL.Query().Encode(), Equals, req.URL.Query().Encode())
c.Assert(inreq.URL.Query().Get("first"), Equals, "this is a field")
c.Assert(inreq.URL.Query().Get("second"), Equals, "was it clear (already)?")
}))
defer srv.Close()
addHTTPRoute(c, l)
discoverdRegisterHTTP(c, l, srv.Listener.Addr().String())
res, err := newHTTPClient("example.com").Do(req)
c.Assert(err, IsNil)
c.Assert(res.StatusCode, Equals, 200)
}
func (s *S) TestDefaultServerKeypair(c *C) {
srv1 := httptest.NewServer(httpTestHandler("1"))
srv2 := httptest.NewServer(httpTestHandler("2"))
defer srv1.Close()
defer srv2.Close()
l := s.newHTTPListener(c)
defer l.Close()
addRoute(c, l, router.HTTPRoute{
Domain: "example.com",
Service: "example-com",
}.ToRoute())
addRoute(c, l, router.HTTPRoute{
Domain: "foo.example.com",
Service: "foo-example-com",
}.ToRoute())
discoverdRegisterHTTPService(c, l, "example-com", srv1.Listener.Addr().String())
discoverdRegisterHTTPService(c, l, "foo-example-com", srv2.Listener.Addr().String())
assertGet(c, "https://"+l.TLSAddr, "example.com", "1")
assertGet(c, "https://"+l.TLSAddr, "foo.example.com", "2")
}
func (s *S) TestCaseInsensitiveDomain(c *C) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
w.Write([]byte(req.Host))
}))
defer srv.Close()
l := s.newHTTPListener(c)
defer l.Close()
addRoute(c, l, router.HTTPRoute{
Domain: "exaMple.com",
Service: "example-com",
}.ToRoute())
discoverdRegisterHTTPService(c, l, "example-com", srv.Listener.Addr().String())
assertGet(c, "http://"+l.Addr, "Example.com", "Example.com")
assertGet(c, "https://"+l.TLSAddr, "ExamPle.cOm", "ExamPle.cOm")
}
func (s *S) TestHostPortStripping(c *C) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
w.Write([]byte(req.Host))
}))
defer srv.Close()
l := s.newHTTPListener(c)
defer l.Close()
addRoute(c, l, router.HTTPRoute{
Domain: "example.com",
Service: "example-com",
}.ToRoute())
discoverdRegisterHTTPService(c, l, "example-com", srv.Listener.Addr().String())
assertGet(c, "http://"+l.Addr, "example.com:80", "example.com:80")
assertGet(c, "https://"+l.TLSAddr, "example.com:443", "example.com:443")
}
func (s *S) TestHTTPResponseStreaming(c *C) {
done := make(chan struct{})
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
if req.URL.Path == "/body" {
w.Write([]byte("a"))
} else {
w.WriteHeader(200)
}
w.(http.Flusher).Flush()
<-done
}))
defer srv.Close()
defer close(done)
l := s.newHTTPListener(c)
defer l.Close()
addRoute(c, l, router.HTTPRoute{
Domain: "example.com",
Service: "example-com",
}.ToRoute())
discoverdRegisterHTTPService(c, l, "example-com", srv.Listener.Addr().String())
client := newHTTPClient("example.com")
client.Timeout = 1 * time.Second
// ensure that we get a flushed response header with no body written immediately
req := newReq(fmt.Sprintf("http://%s/header", l.Addr), "example.com")
res, err := client.Do(req)
c.Assert(err, IsNil)
defer res.Body.Close()
// ensure that we get a body write immediately
req = newReq(fmt.Sprintf("http://%s/body", l.Addr), "example.com")
res, err = client.Do(req)
c.Assert(err, IsNil)
defer res.Body.Close()
buf := make([]byte, 1)
_, err = res.Body.Read(buf)
c.Assert(err, IsNil)
c.Assert(string(buf), Equals, "a")
}
func (s *S) TestHTTPHijackUpgrade(c *C) {
h := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.Header().Set("Connection", "upgrade")
rw.Header().Set("Upgrade", "pinger")
rw.WriteHeader(101)
conn, bufrw, err := rw.(http.Hijacker).Hijack()
defer conn.Close()
line, _, err := bufrw.ReadLine()
c.Assert(err, IsNil)
c.Assert(string(line), Equals, "ping!")
bufrw.Write([]byte("pong!\n"))
bufrw.Flush()
})
srv := httptest.NewServer(http.HandlerFunc(h))
defer srv.Close()
l := s.newHTTPListener(c)
defer l.Close()
addRoute(c, l, router.HTTPRoute{
Domain: "127.0.0.1", // TODO: httpclient overrides the Host header
Service: "example-com",
}.ToRoute())
discoverdRegisterHTTPService(c, l, "example-com", srv.Listener.Addr().String())
client := httpclient.Client{
URL: "http://" + l.Addr,
HTTP: http.DefaultClient,
}
rwc, err := client.Hijack("GET", "/", nil, nil)
c.Assert(err, IsNil)
rwc.Write([]byte("ping!\n"))
pong, err := ioutil.ReadAll(rwc)
c.Assert(err, IsNil)
c.Assert(string(pong), Equals, "pong!\n")
}
| bsd-3-clause |
yashu-seth/BinPy | BinPy/examples/source/analog/Analog Buffers.py | 881 | # -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <headingcell level=2>
# Example usage for Analog Buffers
# <codecell>
from BinPy import *
# Source Bus
a = Bus(4)
a.set_type(analog=True)
a.set_voltage_all(3.5, 6.7, 2.2, 1.1)
# Ouput Bus
b = Bus(4)
b.set_type(analog=True)
# Enable input
e = Bus(1)
e.set_logic_all(1)
# <codecell>
# Initializing an analog Buffer
# With an attenuation of 0.8, relay the input to the output
buff1 = AnalogBuffer(a, b, e, 0.8)
# <codecell>
print b.get_voltage_all()
# <codecell>
# BinPy automatically converts the voltage to logic state based on 5v-0v logic
print b.get_logic_all()
# <codecell>
print b.get_voltage_all()
# <codecell>
# Changing the input
a.set_voltage_all(1, 1, 1, 1)
# <codecell>
b.get_voltage_all()
# <codecell>
# Changing the attenuation level
buff1.set_attenuation(0)
# <codecell>
b.get_voltage_all()
| bsd-3-clause |
axinging/chromium-crosswalk | content/browser/accessibility/hit_testing_browsertest.cc | 6489 | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <set>
#include <string>
#include <vector>
#include "base/command_line.h"
#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/strings/string16.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "content/browser/accessibility/accessibility_tree_formatter.h"
#include "content/browser/accessibility/browser_accessibility.h"
#include "content/browser/accessibility/browser_accessibility_manager.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_paths.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/url_constants.h"
#include "content/public/test/content_browser_test.h"
#include "content/public/test/content_browser_test_utils.h"
#include "content/shell/browser/shell.h"
#include "content/test/accessibility_browser_test_utils.h"
#include "net/dns/mock_host_resolver.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace content {
namespace {
bool AXTreeContainsNodeWithName(BrowserAccessibility* node,
const std::string& name) {
if (node->GetStringAttribute(ui::AX_ATTR_NAME) == name)
return true;
for (unsigned i = 0; i < node->PlatformChildCount(); i++) {
if (AXTreeContainsNodeWithName(node->PlatformGetChild(i), name))
return true;
}
return false;
}
} // namespace
class AccessibilityHitTestingBrowserTest : public ContentBrowserTest {
public:
AccessibilityHitTestingBrowserTest() {}
~AccessibilityHitTestingBrowserTest() override {}
protected:
BrowserAccessibility* HitTestAndWaitForResult(const gfx::Point& point) {
WebContentsImpl* web_contents =
static_cast<WebContentsImpl*>(shell()->web_contents());
FrameTree* frame_tree = web_contents->GetFrameTree();
BrowserAccessibilityManager* manager =
web_contents->GetRootBrowserAccessibilityManager();
AccessibilityNotificationWaiter hover_waiter(
shell(), AccessibilityModeComplete, ui::AX_EVENT_HOVER);
for (FrameTreeNode* node : frame_tree->Nodes())
hover_waiter.ListenToAdditionalFrame(node->current_frame_host());
manager->delegate()->AccessibilityHitTest(point);
hover_waiter.WaitForNotification();
RenderFrameHostImpl* target_frame = hover_waiter.event_render_frame_host();
BrowserAccessibilityManager* target_manager =
target_frame->browser_accessibility_manager();
int hover_target_id = hover_waiter.event_target_id();
BrowserAccessibility* hovered_node =
target_manager->GetFromID(hover_target_id);
return hovered_node;
}
};
IN_PROC_BROWSER_TEST_F(AccessibilityHitTestingBrowserTest,
HitTestOutsideDocumentBoundsReturnsRoot) {
NavigateToURL(shell(), GURL(url::kAboutBlankURL));
// Load the page.
AccessibilityNotificationWaiter waiter(shell(), AccessibilityModeComplete,
ui::AX_EVENT_LOAD_COMPLETE);
const char url_str[] =
"data:text/html,"
"<!doctype html>"
"<html><head><title>Accessibility Test</title></head>"
"<body>"
"<a href='#'>"
"This is some text in a link"
"</a>"
"</body></html>";
GURL url(url_str);
NavigateToURL(shell(), url);
waiter.WaitForNotification();
BrowserAccessibility* hovered_node =
HitTestAndWaitForResult(gfx::Point(-1, -1));
ASSERT_TRUE(hovered_node != NULL);
ASSERT_EQ(ui::AX_ROLE_ROOT_WEB_AREA, hovered_node->GetRole());
}
IN_PROC_BROWSER_TEST_F(AccessibilityHitTestingBrowserTest,
HitTestingInIframes) {
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(embedded_test_server()->Start());
NavigateToURL(shell(), GURL(url::kAboutBlankURL));
AccessibilityNotificationWaiter waiter(shell(), AccessibilityModeComplete,
ui::AX_EVENT_LOAD_COMPLETE);
GURL url(embedded_test_server()->GetURL(
"/accessibility/html/iframe-coordinates.html"));
NavigateToURL(shell(), url);
waiter.WaitForNotification();
WebContentsImpl* web_contents =
static_cast<WebContentsImpl*>(shell()->web_contents());
FrameTree* frame_tree = web_contents->GetFrameTree();
BrowserAccessibilityManager* manager =
web_contents->GetRootBrowserAccessibilityManager();
BrowserAccessibility* root = manager->GetRoot();
while (!AXTreeContainsNodeWithName(root, "Ordinary Button") ||
!AXTreeContainsNodeWithName(root, "Scrolled Button")) {
AccessibilityNotificationWaiter waiter(shell(), AccessibilityModeComplete,
ui::AX_EVENT_NONE);
for (FrameTreeNode* node : frame_tree->Nodes())
waiter.ListenToAdditionalFrame(node->current_frame_host());
waiter.WaitForNotification();
}
// Send a series of hit test requests, and for each one
// wait for the hover event in response, verifying we hit the
// correct object.
// (50, 50) -> "Button"
BrowserAccessibility* hovered_node;
hovered_node = HitTestAndWaitForResult(gfx::Point(50, 50));
ASSERT_TRUE(hovered_node != NULL);
ASSERT_EQ(ui::AX_ROLE_BUTTON, hovered_node->GetRole());
ASSERT_EQ("Button", hovered_node->GetStringAttribute(ui::AX_ATTR_NAME));
// (50, 305) -> div in first iframe
hovered_node = HitTestAndWaitForResult(gfx::Point(50, 305));
ASSERT_TRUE(hovered_node != NULL);
ASSERT_EQ(ui::AX_ROLE_DIV, hovered_node->GetRole());
// (50, 350) -> "Ordinary Button"
hovered_node = HitTestAndWaitForResult(gfx::Point(50, 350));
ASSERT_TRUE(hovered_node != NULL);
ASSERT_EQ(ui::AX_ROLE_BUTTON, hovered_node->GetRole());
ASSERT_EQ("Ordinary Button",
hovered_node->GetStringAttribute(ui::AX_ATTR_NAME));
// (50, 455) -> "Scrolled Button"
hovered_node = HitTestAndWaitForResult(gfx::Point(50, 455));
ASSERT_TRUE(hovered_node != NULL);
ASSERT_EQ(ui::AX_ROLE_BUTTON, hovered_node->GetRole());
ASSERT_EQ("Scrolled Button",
hovered_node->GetStringAttribute(ui::AX_ATTR_NAME));
// (50, 505) -> div in second iframe
hovered_node = HitTestAndWaitForResult(gfx::Point(50, 505));
ASSERT_TRUE(hovered_node != NULL);
ASSERT_EQ(ui::AX_ROLE_DIV, hovered_node->GetRole());
}
} // namespace content
| bsd-3-clause |
aYukiSekiguchi/ACCESS-Chromium | chrome/browser/autofill/autofill_feedback_infobar_delegate.cc | 1781 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/autofill/autofill_feedback_infobar_delegate.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/infobars/infobar_tab_helper.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/webui/feedback_ui.h"
#include "chrome/browser/feedback/proto/extension.pb.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/navigation_details.h"
#include "content/public/browser/web_contents.h"
#include "googleurl/src/gurl.h"
const char kCategoryTagAutofill[] = "Autofill";
AutofillFeedbackInfoBarDelegate::AutofillFeedbackInfoBarDelegate(
InfoBarTabHelper* infobar_helper,
const string16& message,
const string16& link_text,
const std::string& feedback_message)
: LinkInfoBarDelegate(infobar_helper),
message_(message),
link_text_(link_text),
feedback_message_(feedback_message),
link_clicked_(false) {
}
AutofillFeedbackInfoBarDelegate::~AutofillFeedbackInfoBarDelegate() {
}
string16 AutofillFeedbackInfoBarDelegate::GetMessageTextWithOffset(
size_t* link_offset) const {
string16 message = message_ + ASCIIToUTF16(" ");
*link_offset = message.size();
return message;
}
string16 AutofillFeedbackInfoBarDelegate::GetLinkText() const {
return link_text_;
}
bool AutofillFeedbackInfoBarDelegate::LinkClicked(
WindowOpenDisposition disposition) {
browser::ShowHtmlFeedbackView(
Browser::GetBrowserForController(
&owner()->web_contents()->GetController(), NULL),
feedback_message_,
std::string(kCategoryTagAutofill));
return true;
}
| bsd-3-clause |
petuum/strads | apps/medlda_release/ll-worker.cpp | 2115 | #include <stdio.h>
#include <strads/include/common.hpp>
#include <strads/include/child-thread.hpp>
#include <strads/util/utility.hpp>
#include <iostream> // std::cout
#include <algorithm> // std::for_each
#include <vector> // std::vector
#include <glog/logging.h>
#include <gflags/gflags.h>
#include <mpi.h>
#include <assert.h>
#include "ldall.hpp"
#include <mutex>
#include <thread>
#include <strads/ps/strads-ps.hpp>
#include "medlda-ps.hpp"
#include "trainer.hpp"
#include "tester.hpp"
using namespace std;
DEFINE_string(train_prefix, "/tmp/train", "Prefix to libsvm format file");
DEFINE_string(test_prefix, "", "Prefix to libsvm format file");
DEFINE_string(dump_prefix, "/tmp/dump", "Prefix for training results");
DEFINE_int32(num_thread, 2, "Number of worker threads");
void *worker_mach(void *arg){
sharedctx *ctx = (sharedctx *)arg;
strads_msg(ERR, "[worker(%d)] boot up out of %d workers \n", ctx->rank, ctx->m_worker_machines);
init_ps(ctx,
put_get_async_callback,
NULL, NULL, NULL, NULL);
// last argument of init_ps is ptr of your data structure that callback function migt need to access
// if not, NULL is fine.
// callback function can access registered data structure via ctx->table
psbgthreadctx *bctx = (psbgthreadctx *)calloc(sizeof(psbgthreadctx), 1);
bctx->parentctx = ctx;
pthread_attr_t m_attr;
pthread_t m_pthid;
int rc = pthread_attr_init(&m_attr);
checkResults("pthread attr init m_attr failed", rc);
rc = pthread_create(&m_pthid, &m_attr, ps_client_recvthread, (void *)bctx);
checkResults("pthread create failed in scheduler_threadctx", rc);
FLAGS_logtostderr = true;
FLAGS_colorlogtostderr = true;
print_flags();
if (google::GetCommandLineFlagInfoOrDie("test_prefix").is_default) {
Trainer trainer(ctx);
trainer.ReadData(FLAGS_train_prefix);
trainer.Train();
trainer.SaveResult(FLAGS_dump_prefix);
}
else {
Tester tester(ctx);
tester.LoadModel(FLAGS_dump_prefix);
tester.ReadData(FLAGS_test_prefix);
tester.Infer();
tester.SaveResult(FLAGS_dump_prefix);
}
return NULL;
}
| bsd-3-clause |
vincentml/basex | basex-core/src/main/java/org/basex/query/func/file/FileResolvePath.java | 909 | package org.basex.query.func.file;
import static org.basex.query.QueryError.*;
import static org.basex.util.Token.*;
import java.nio.file.*;
import org.basex.query.*;
import org.basex.query.value.item.*;
/**
* Function implementation.
*
* @author BaseX Team 2005-16, BSD License
* @author Christian Gruen
*/
public final class FileResolvePath extends FileFn {
@Override
public Item item(final QueryContext qc) throws QueryException {
final Path path = toPath(string(toToken(exprs[0], qc))), abs;
if(exprs.length < 2) {
abs = absolute(path);
} else {
final String file = string(toToken(exprs[1], qc));
Path base = toPath(file);
if(!base.isAbsolute()) throw FILE_IS_RELATIVE_X.get(info, base);
if(!file.endsWith("/") && !file.endsWith("\\")) base = base.getParent();
abs = base.resolve(path);
}
return get(abs, Files.isDirectory(abs));
}
}
| bsd-3-clause |
onyx-intl/p400_hg | misc/cgo/test/basic.go | 2362 | // Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Basic test cases for cgo.
package cgotest
/*
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <errno.h>
#define SHIFT(x, y) ((x)<<(y))
#define KILO SHIFT(1, 10)
enum E {
Enum1 = 1,
Enum2 = 2,
};
typedef unsigned char uuid_t[20];
void uuid_generate(uuid_t x) {
x[0] = 0;
}
struct S {
int x;
};
extern enum E myConstFunc(struct S* const ctx, int const id, struct S **const filter);
enum E myConstFunc(struct S *const ctx, int const id, struct S **const filter) { return 0; }
// issue 1222
typedef union {
long align;
} xxpthread_mutex_t;
struct ibv_async_event {
union {
int x;
} element;
};
struct ibv_context {
xxpthread_mutex_t mutex;
};
int add(int x, int y) {
return x+y;
};
*/
import "C"
import (
"syscall"
"testing"
"unsafe"
)
const EINVAL = C.EINVAL /* test #define */
var KILO = C.KILO
func uuidgen() {
var uuid C.uuid_t
C.uuid_generate(&uuid[0])
}
func Strtol(s string, base int) (int, error) {
p := C.CString(s)
n, err := C.strtol(p, nil, C.int(base))
C.free(unsafe.Pointer(p))
return int(n), err
}
func Atol(s string) int {
p := C.CString(s)
n := C.atol(p)
C.free(unsafe.Pointer(p))
return int(n)
}
func testConst(t *testing.T) {
C.myConstFunc(nil, 0, nil)
}
func testEnum(t *testing.T) {
if C.Enum1 != 1 || C.Enum2 != 2 {
t.Error("bad enum", C.Enum1, C.Enum2)
}
}
func testAtol(t *testing.T) {
l := Atol("123")
if l != 123 {
t.Error("Atol 123: ", l)
}
}
func testErrno(t *testing.T) {
p := C.CString("no-such-file")
m := C.CString("r")
f, err := C.fopen(p, m)
C.free(unsafe.Pointer(p))
C.free(unsafe.Pointer(m))
if err == nil {
C.fclose(f)
t.Fatalf("C.fopen: should fail")
}
if err != syscall.ENOENT {
t.Fatalf("C.fopen: unexpected error: %v", err)
}
}
func testMultipleAssign(t *testing.T) {
p := C.CString("234")
n, m := C.strtol(p, nil, 345), C.strtol(p, nil, 10)
if n != 0 || m != 234 {
t.Fatal("Strtol x2: ", n, m)
}
C.free(unsafe.Pointer(p))
}
var (
cuint = (C.uint)(0)
culong C.ulong
cchar C.char
)
type Context struct {
ctx *C.struct_ibv_context
}
func benchCgoCall(b *testing.B) {
const x = C.int(2)
const y = C.int(3)
for i := 0; i < b.N; i++ {
C.add(x, y)
}
}
| bsd-3-clause |
Telrik/komimport-2.0 | themes/komimport/views/site/view.php | 921 | <?php
$this->breadcrumbs = array(
$model->title,
);
$this->pageTitle = $model->name;
?>
<?php $this->renderPartial('_view', array('data' => $model)); ?>
<div id="comments">
<?php if ($model->commentCount >= 1): ?>
<h3><?php echo ($model->commentCount > 1) ? $model->commentCount . ' comments' : 'One comment'; ?></h3>
<?php $this->renderPartial(
'_comments',
array(
'post' => $model,
'comments' => $model->comments,
)
); ?>
<?php endif; ?>
<h3>Leave a Comment</h3>
<?php if (Yii::app()->user->hasFlash('commentSubmitted')): ?>
<div class="flash-success">
<?php echo Yii::app()->user->getFlash('commentSubmitted'); ?>
</div>
<?php else: ?>
<?php $this->renderPartial('/comment/_form', array('model' => $comment)); ?>
<?php endif; ?>
</div><!-- comments -->
| bsd-3-clause |
Umisoft/umi.framework-dev | library/hmvc/model/IModelFactory.php | 1130 | <?php
/**
* UMI.Framework (http://umi-framework.ru/)
*
* @link http://github.com/Umisoft/framework for the canonical source repository
* @copyright Copyright (c) 2007-2013 Umisoft ltd. (http://umisoft.ru/)
* @license http://umi-framework.ru/license/bsd-3 BSD-3 License
*/
namespace umi\hmvc\model;
/**
* Интерфейс фабрики для создания моделей.
* Хранит список моделей и предоставляет к ним доступ.
*/
interface IModelFactory
{
/**
* Создает новую модель по символическому имени.
* @param string $name символическое имя
* @param array $args аргументы конструктора
* @return IModel|object
*/
public function createByName($name, $args = []);
/**
* Создает новую модель по имени класса.
* @param string $class класс
* @param array $args аргументы конструктора
* @return IModel|object
*/
public function createByClass($class, $args = []);
} | bsd-3-clause |
mbirth/spotweb | lib/services/Actions/Services_Actions_GetComments.php | 4177 | <?php
class Services_Actions_GetComments {
/**
* Define what we think is the native language of the Spots, if we get
* asked to provide comments in our 'native' language, we just skip translation.
*/
const nativeLanguage = 'nl';
/**
* @var Services_Settings_Base
*/
private $_settings;
/**
* @var Dao_Factory
*/
private $_daoFactory;
/**
* @var Dao_Cache
*/
private $_cacheDao;
/**
* @var SpotSecurity
*/
private $_spotSec;
/**
* @var Services_Translation_Microsoft
*/
private $_svcTranslate;
function __construct(Services_Settings_Container $settings, Dao_Factory $daoFactory, SpotSecurity $spotSec) {
$this->_settings = $settings;
$this->_daoFactory = $daoFactory;
$this->_spotSec = $spotSec;
$this->_cacheDao = $daoFactory->getCacheDao();
$this->_svcTranslate = new Services_Translation_Microsoft($settings, $daoFactory->getCacheDao());
} # ctor
/*
* Returns the spot comments, and translates them when asked to,
* tries to minimize the amount of requests to the translator API
*/
public function getSpotComments($msgId, $prevMsgids, $userId, $start, $length, $language) {
# Check users' permissions
$this->_spotSec->fatalPermCheck(SpotSecurity::spotsec_view_comments, '');
$svcNntpSpotReading = new Services_Nntp_SpotReading(Services_Nntp_EnginePool::pool($this->_settings, 'hdr'));
$svcProvComments = new Services_Providers_Comments($this->_daoFactory->getCommentDao(), $svcNntpSpotReading);
$tryTranslate = (Services_Actions_GetComments::nativeLanguage !== $language);
/*
* Basically we are retrieving the comments from the database, for them to be translated
* if necessary
*/
$comments = $svcProvComments->fetchSpotComments($msgId, $prevMsgids, $userId, $start, $length);
if (!$tryTranslate) {
return $comments;
} # if
/*
* In our cache, we store an key => value pair with the original string and
* the translation, so we can do very quick lookups.
*/
$toBeTranslated = array();
$translated = $this->_cacheDao->getCachedTranslatedComments($msgId, $language);
if ($translated === false) {
$translated = array();
} # if
foreach($comments as &$comment) {
$tmpBody = $comment['body'];
if (isset($translated[$tmpBody])) {
$comment['body_translated'] = $translated[$tmpBody];
} else {
$toBeTranslated[] = $comment;
} # else
} # foreach
/*
* Actually translate our list of comments, and merge
* them with the actual comments
*/
if (!empty($toBeTranslated)) {
$svcTranslate = new Services_Translation_Microsoft($this->_settings, $this->_cacheDao);
if (!$svcTranslate->isAvailable()) {
return $comments;
} # if
$translations = $svcTranslate->translateMultiple($language, $toBeTranslated, 'body');
/*
* copy the translations into the cache
*/
if (!empty($translations)) {
foreach($translations as $v) {
$tmpBody = $v['body'];
$translated[$tmpBody] = $v['body_translated'];
} # foreach
/*
* Convert the comments once again
*/
foreach($comments as &$comment) {
$tmpBody = $comment['body'];
if (isset($translated[$tmpBody])) {
$comment['body_translated'] = $translated[$tmpBody];
} # else
} # foreach
} # if
/*
* and save the translated bodies into the cache
*/
$this->_cacheDao->saveTranslatedCommentCache($msgId, $language, $translated);
} # if
return $comments;
} # getSpotComments
} # Services_Actions_GetComments
| bsd-3-clause |
dsipasseuth/dataloader | src/test/java/com/salesforce/dataloader/process/NAProcessTest.java | 11725 | /*
* Copyright (c) 2015, salesforce.com, inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided
* that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* Neither the name of salesforce.com, inc. nor the names of its contributors may be used to endorse or
* promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.salesforce.dataloader.process;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.Map;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import com.salesforce.dataloader.TestSetting;
import com.salesforce.dataloader.TestVariant;
import com.salesforce.dataloader.action.OperationInfo;
import com.salesforce.dataloader.config.Config;
import com.salesforce.dataloader.controller.Controller;
import com.salesforce.dataloader.dao.csv.CSVFileReader;
import com.salesforce.dataloader.dao.csv.CSVFileWriter;
import com.salesforce.dataloader.model.NATextValue;
import com.salesforce.dataloader.model.Row;
import com.sforce.soap.partner.QueryResult;
import com.sforce.soap.partner.SaveResult;
import com.sforce.soap.partner.sobject.SObject;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/**
* This class test that #N/A can be used to set fields to null when Use Bulk Api is enabled.
* It also validates that empty fields are not handled in the same way as #N/A
*
* @author Jeff Lai
* @since 25.0
*/
@RunWith(Parameterized.class)
public class NAProcessTest extends ProcessTestBase {
private static final String TASK_SUBJECT = "NATest";
private static final String TARGET_DIR = getProperty("target.dir").trim();
private static final String CSV_DIR_PATH = TARGET_DIR + File.separator + NAProcessTest.class.getSimpleName();
private static final String CSV_FILE_PATH = CSV_DIR_PATH + File.separator + "na.csv";
private String userId;
public NAProcessTest(Map<String, String> config) {
super(config);
}
@Before
public void populateUserId() throws Exception {
if (userId == null) {
userId = getUserId();
}
}
@Parameterized.Parameters(name = "{0}")
public static Collection<Object[]> getConfigGeneratorParams() {
return Arrays.asList(
TestVariant.forSettings(TestSetting.BULK_API_ENABLED),
TestVariant.forSettings(TestSetting.BULK_API_DISABLED));
}
@Test
public void testTextFieldInsert() throws Exception {
runNAtest("Description", false, OperationInfo.insert);
}
@Test
public void testTextFieldUpdate() throws Exception {
runNAtest("Description", false, OperationInfo.update);
}
@Test
public void testDateTimeFieldInsert() throws Exception {
runNAtest("ReminderDateTime", true, OperationInfo.insert);
}
@Test
public void testDateTimeFieldUpdate() throws Exception {
runNAtest("ReminderDateTime", true, OperationInfo.update);
}
@Test
public void testDateFieldInsert() throws Exception {
runNAtest("ActivityDate", true, OperationInfo.insert);
}
@Test
public void testDateFieldUpdate() throws Exception {
runNAtest("ActivityDate", true, OperationInfo.update);
}
@Test
public void testTextEmptyFieldIsNotHandledAsNAUpdate() throws Exception {
runEmptyFieldUpdateTest("Description", false);
}
@Test
public void testTextEmptyFieldIsNotHandledAsNAInsert() throws Exception {
runEmptyFieldInsertTest("Description");
}
@Test
public void testDateEmptyFieldIsNotHandledAsNAUpdate() throws Exception {
runEmptyFieldUpdateTest("ActivityDate", true);
}
@Test
public void testDateEmptyFieldIsNotHandledAsNAInsert() throws Exception {
runEmptyFieldInsertTest("ActivityDate");
}
private void runNAtest(String nullFieldName, boolean isDateField, OperationInfo operation) throws Exception {
String taskId = null;
if (!operation.equals(OperationInfo.insert)) {
taskId = createTask(nullFieldName, isDateField);
}
generateCsvWithNAField(nullFieldName, taskId);
Map<String, String> argMap = getArgMap(operation);
Controller controller;
if (!getController().getConfig().getBoolean(Config.BULK_API_ENABLED) && isDateField) {
controller = runProcess(argMap, true, null, 0, 0, 1, false);
String errorFile = controller.getConfig().getStringRequired(Config.OUTPUT_ERROR);
String errorMessage = getCsvFieldValue(errorFile, "ERROR");
assertEquals("unexpected error message",
"Error converting value to correct data type: Failed to parse date: #N/A", errorMessage);
} else {
int numInsert = operation.equals(OperationInfo.insert) ? 1 : 0;
int numUpdate = operation.equals(OperationInfo.update) ? 1 : 0;
controller = runProcess(argMap, true, null, numInsert, numUpdate, 0, false);
String actualNullFieldValue = getFieldValueAfterOperation(nullFieldName, controller);
String expectedNullFieldValue = getController().getConfig().getBoolean(Config.BULK_API_ENABLED) ? null : NATextValue.getInstance().toString();
assertEquals("unexpected field value", expectedNullFieldValue, actualNullFieldValue);
}
}
private void runEmptyFieldInsertTest(String emtpyFieldName) throws Exception {
generateCsvWithEmptyField(emtpyFieldName, null);
Controller controller = runProcess(getArgMap(OperationInfo.insert), true, null, 1, 0, 0, false);
String actualValue = getFieldValueAfterOperation(emtpyFieldName, controller);
assertNull("Empty field values in CSV shouldn't have been inserted with values", actualValue);
}
private void runEmptyFieldUpdateTest(String nullFieldName, boolean isDateField) throws Exception {
String taskId = createTask(nullFieldName, isDateField);
generateCsvWithEmptyField(nullFieldName, taskId);
Controller controller = runProcess(getArgMap(OperationInfo.update), true, null, 0, 1, 0, false);
String actualValue = getFieldValueAfterOperation(nullFieldName, controller);
assertNotNull("Empty field values in CSV should have been ignored", actualValue);
}
private String getFieldValueAfterOperation(String nullFieldName, Controller controller) throws Exception {
String successFile = controller.getConfig().getStringRequired(Config.OUTPUT_SUCCESS);
String taskId = getCsvFieldValue(successFile, "ID");
QueryResult result = getController().getPartnerClient().query("select " + nullFieldName + " from Task where Id='" + taskId + "'");
assertEquals(1, result.getSize());
return (String)result.getRecords()[0].getField(nullFieldName);
}
private Map<String, String> getArgMap(OperationInfo operation) {
Map<String, String> argMap = getTestConfig(operation, CSV_FILE_PATH, getTestDataDir() + File.separator + "NAProcessTest.sdl", false);
argMap.put(Config.ENTITY, "Task");
argMap.remove(Config.EXTERNAL_ID_FIELD);
return argMap;
}
private String createTask(String fieldToNullName, boolean isDateField) throws Exception {
Object fieldToNullValue = isDateField ? new Date() : "asdf";
SObject task = new SObject();
task.setType("Task");
task.setField("OwnerId", userId);
task.setField("Subject", TASK_SUBJECT);
task.setField(fieldToNullName, fieldToNullValue);
SaveResult[] result = getController().getPartnerClient().getClient().create(new SObject[] { task });
assertEquals(1, result.length);
if (!result[0].getSuccess())
Assert.fail("creation of task failed with error " + result[0].getErrors()[0].getMessage());
return result[0].getId();
}
private String getCsvFieldValue(String csvFile, String fieldName) throws Exception {
CSVFileReader reader = new CSVFileReader(csvFile, getController());
reader.open();
assertEquals(1, reader.getTotalRows());
String fieldValue = (String)reader.readRow().get(fieldName);
reader.close();
return fieldValue;
}
private String getUserId() throws Exception {
QueryResult result = getController().getPartnerClient().query(
"select id from user where username='" + getController().getConfig().getString(Config.USERNAME) + "'");
assertEquals(1, result.getSize());
return result.getRecords()[0].getId();
}
private void generateCsvWithNAField(String nullFieldName, String id) throws Exception {
generateCsv(nullFieldName, NATextValue.getInstance(), id);
}
private void generateCsvWithEmptyField(String emptyFieldName, String id) throws Exception {
generateCsv(emptyFieldName, null, id);
}
/**
* We have to generate the csv file because the user id will change.
*/
private void generateCsv(String nullFieldName, Object nullFieldValue, String id) throws Exception {
File csvDir = new File(CSV_DIR_PATH);
if (!csvDir.exists()) {
boolean deleteCsvDirOk = csvDir.mkdirs();
assertTrue("Could not delete directory: " + CSV_DIR_PATH, deleteCsvDirOk);
}
File csvFile = new File(CSV_FILE_PATH);
if (csvFile.exists()) {
boolean deleteCsvFileOk = csvFile.delete();
assertTrue("Could not delete existing CSV file: " + CSV_FILE_PATH, deleteCsvFileOk);
}
Row row = new Row();
row.put("OwnerId", userId);
row.put("Subject", TASK_SUBJECT);
row.put(nullFieldName, nullFieldValue);
if (id != null) row.put("Id", id);
CSVFileWriter writer = null;
try {
writer = new CSVFileWriter(CSV_FILE_PATH, getController().getConfig());
writer.open();
writer.setColumnNames(new ArrayList<String>(row.keySet()));
writer.writeRow(row);
} finally {
if (writer != null) writer.close();
}
}
@Override
public void cleanRecords() {
deleteSfdcRecords("Task", "Subject='" + TASK_SUBJECT + "'", 0);
}
}
| bsd-3-clause |
leighpauls/k2cro4 | chrome/common/extensions/docs/server2/appengine_url_fetcher.py | 1443 | # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from appengine_wrappers import urlfetch
from future import Future
class _AsyncFetchDelegate(object):
def __init__(self, rpc):
self._rpc = rpc
def Get(self):
return self._rpc.get_result()
class AppEngineUrlFetcher(object):
"""A wrapper around the App Engine urlfetch module that allows for easy
async fetches.
"""
def __init__(self, base_path):
self._base_path = base_path
def Fetch(self, url):
"""Fetches a file synchronously.
"""
if self._base_path is not None:
return urlfetch.fetch(self._base_path + '/' + url,
headers={ 'Cache-Control': 'max-age=0' })
else:
return urlfetch.fetch(url, headers={ 'Cache-Control': 'max-age=0' })
def FetchAsync(self, url):
"""Fetches a file asynchronously, and returns a Future with the result.
"""
rpc = urlfetch.create_rpc()
if self._base_path is not None:
urlfetch.make_fetch_call(rpc,
self._base_path + '/' + url,
headers={ 'Cache-Control': 'max-age=0' })
else:
urlfetch.make_fetch_call(rpc,
url,
headers={ 'Cache-Control': 'max-age=0' })
return Future(delegate=_AsyncFetchDelegate(rpc))
| bsd-3-clause |
deforay/odkdash | vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/DefinedNames.php | 8153 | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\DefinedName;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class DefinedNames
{
private $objWriter;
private $spreadsheet;
public function __construct(XMLWriter $objWriter, Spreadsheet $spreadsheet)
{
$this->objWriter = $objWriter;
$this->spreadsheet = $spreadsheet;
}
public function write(): void
{
// Write defined names
$this->objWriter->startElement('definedNames');
// Named ranges
if (count($this->spreadsheet->getDefinedNames()) > 0) {
// Named ranges
$this->writeNamedRangesAndFormulae();
}
// Other defined names
$sheetCount = $this->spreadsheet->getSheetCount();
for ($i = 0; $i < $sheetCount; ++$i) {
// NamedRange for autoFilter
$this->writeNamedRangeForAutofilter($this->spreadsheet->getSheet($i), $i);
// NamedRange for Print_Titles
$this->writeNamedRangeForPrintTitles($this->spreadsheet->getSheet($i), $i);
// NamedRange for Print_Area
$this->writeNamedRangeForPrintArea($this->spreadsheet->getSheet($i), $i);
}
$this->objWriter->endElement();
}
/**
* Write defined names.
*/
private function writeNamedRangesAndFormulae(): void
{
// Loop named ranges
$definedNames = $this->spreadsheet->getDefinedNames();
foreach ($definedNames as $definedName) {
$this->writeDefinedName($definedName);
}
}
/**
* Write Defined Name for named range.
*/
private function writeDefinedName(DefinedName $pDefinedName): void
{
// definedName for named range
$this->objWriter->startElement('definedName');
$this->objWriter->writeAttribute('name', $pDefinedName->getName());
if ($pDefinedName->getLocalOnly() && $pDefinedName->getScope() !== null) {
$this->objWriter->writeAttribute(
'localSheetId',
$pDefinedName->getScope()->getParent()->getIndex($pDefinedName->getScope())
);
}
$definedRange = $this->getDefinedRange($pDefinedName);
$this->objWriter->writeRawData($definedRange);
$this->objWriter->endElement();
}
/**
* Write Defined Name for autoFilter.
*/
private function writeNamedRangeForAutofilter(Worksheet $pSheet, int $pSheetId = 0): void
{
// NamedRange for autoFilter
$autoFilterRange = $pSheet->getAutoFilter()->getRange();
if (!empty($autoFilterRange)) {
$this->objWriter->startElement('definedName');
$this->objWriter->writeAttribute('name', '_xlnm._FilterDatabase');
$this->objWriter->writeAttribute('localSheetId', $pSheetId);
$this->objWriter->writeAttribute('hidden', '1');
// Create absolute coordinate and write as raw text
$range = Coordinate::splitRange($autoFilterRange);
$range = $range[0];
// Strip any worksheet ref so we can make the cell ref absolute
[, $range[0]] = Worksheet::extractSheetTitle($range[0], true);
$range[0] = Coordinate::absoluteCoordinate($range[0]);
$range[1] = Coordinate::absoluteCoordinate($range[1]);
$range = implode(':', $range);
$this->objWriter->writeRawData('\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!' . $range);
$this->objWriter->endElement();
}
}
/**
* Write Defined Name for PrintTitles.
*/
private function writeNamedRangeForPrintTitles(Worksheet $pSheet, int $pSheetId = 0): void
{
// NamedRange for PrintTitles
if ($pSheet->getPageSetup()->isColumnsToRepeatAtLeftSet() || $pSheet->getPageSetup()->isRowsToRepeatAtTopSet()) {
$this->objWriter->startElement('definedName');
$this->objWriter->writeAttribute('name', '_xlnm.Print_Titles');
$this->objWriter->writeAttribute('localSheetId', $pSheetId);
// Setting string
$settingString = '';
// Columns to repeat
if ($pSheet->getPageSetup()->isColumnsToRepeatAtLeftSet()) {
$repeat = $pSheet->getPageSetup()->getColumnsToRepeatAtLeft();
$settingString .= '\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!$' . $repeat[0] . ':$' . $repeat[1];
}
// Rows to repeat
if ($pSheet->getPageSetup()->isRowsToRepeatAtTopSet()) {
if ($pSheet->getPageSetup()->isColumnsToRepeatAtLeftSet()) {
$settingString .= ',';
}
$repeat = $pSheet->getPageSetup()->getRowsToRepeatAtTop();
$settingString .= '\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!$' . $repeat[0] . ':$' . $repeat[1];
}
$this->objWriter->writeRawData($settingString);
$this->objWriter->endElement();
}
}
/**
* Write Defined Name for PrintTitles.
*/
private function writeNamedRangeForPrintArea(Worksheet $pSheet, int $pSheetId = 0): void
{
// NamedRange for PrintArea
if ($pSheet->getPageSetup()->isPrintAreaSet()) {
$this->objWriter->startElement('definedName');
$this->objWriter->writeAttribute('name', '_xlnm.Print_Area');
$this->objWriter->writeAttribute('localSheetId', $pSheetId);
// Print area
$printArea = Coordinate::splitRange($pSheet->getPageSetup()->getPrintArea());
$chunks = [];
foreach ($printArea as $printAreaRect) {
$printAreaRect[0] = Coordinate::absoluteReference($printAreaRect[0]);
$printAreaRect[1] = Coordinate::absoluteReference($printAreaRect[1]);
$chunks[] = '\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!' . implode(':', $printAreaRect);
}
$this->objWriter->writeRawData(implode(',', $chunks));
$this->objWriter->endElement();
}
}
private function getDefinedRange(DefinedName $pDefinedName): string
{
$definedRange = $pDefinedName->getValue();
$splitCount = preg_match_all(
'/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/mui',
$definedRange,
$splitRanges,
PREG_OFFSET_CAPTURE
);
$lengths = array_map('strlen', array_column($splitRanges[0], 0));
$offsets = array_column($splitRanges[0], 1);
$worksheets = $splitRanges[2];
$columns = $splitRanges[6];
$rows = $splitRanges[7];
while ($splitCount > 0) {
--$splitCount;
$length = $lengths[$splitCount];
$offset = $offsets[$splitCount];
$worksheet = $worksheets[$splitCount][0];
$column = $columns[$splitCount][0];
$row = $rows[$splitCount][0];
$newRange = '';
if (empty($worksheet)) {
if (($offset === 0) || ($definedRange[$offset - 1] !== ':')) {
// We should have a worksheet
$worksheet = $pDefinedName->getWorksheet() ? $pDefinedName->getWorksheet()->getTitle() : null;
}
} else {
$worksheet = str_replace("''", "'", trim($worksheet, "'"));
}
if (!empty($worksheet)) {
$newRange = "'" . str_replace("'", "''", $worksheet) . "'!";
}
$newRange = "{$newRange}{$column}{$row}";
$definedRange = substr($definedRange, 0, $offset) . $newRange . substr($definedRange, $offset + $length);
}
if (substr($definedRange, 0, 1) === '=') {
$definedRange = substr($definedRange, 1);
}
return $definedRange;
}
}
| bsd-3-clause |
wifang/fmi | module/IvelinaVelcheva/config/module.config.php | 1229 | <?php
return array(
'controllers' => array(
'invokables' => array(
'IvelinaVelcheva\Controller\Index' => 'IvelinaVelcheva\Controller\IndexController',
),
),
// The following section is new and should be added to your file
'router' => array(
'routes' => array(
'ivelina_velcheva' => array(
'type' => 'segment',
'options' => array(
'route' => '/ivelina-velcheva[/:action][/:id]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
),
'defaults' => array(
'controller' => 'IvelinaVelcheva\Controller\Index',
'action' => 'index',
),
),
),
),
),
'view_manager' => array(
'template_map' => array(
'layout/IvelinaVelcheva' => __DIR__ . '/../view/layout/IvelinaVelcheva.phtml',
),
'template_path_stack' => array(
'ivelina_velcheva' => __DIR__ . '/../view',
),
),
); | bsd-3-clause |
yuecong/dd-agent | util.py | 17272 | # stdlib
from hashlib import md5
import logging
import math
import os
import platform
import re
import signal
import socket
import sys
import time
import types
import urllib2
import uuid
# 3p
import simplejson as json
import yaml # noqa, let's guess, probably imported somewhere
from tornado import ioloop
try:
from yaml import CLoader as yLoader
from yaml import CDumper as yDumper
except ImportError:
# On source install C Extensions might have not been built
from yaml import Loader as yLoader # noqa, imported from here elsewhere
from yaml import Dumper as yDumper # noqa, imported from here elsewhere
# These classes are now in utils/, they are just here for compatibility reasons,
# if a user actually uses them in a custom check
# If you're this user, please use utils.pidfile or utils.platform instead
# FIXME: remove them at a point (6.x)
from utils.pidfile import PidFile # noqa, see ^^^
from utils.platform import Platform
from utils.subprocess_output import subprocess
VALID_HOSTNAME_RFC_1123_PATTERN = re.compile(r"^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$")
MAX_HOSTNAME_LEN = 255
COLON_NON_WIN_PATH = re.compile(':(?!\\\\)')
log = logging.getLogger(__name__)
NumericTypes = (float, int, long)
def plural(count):
if count == 1:
return ""
return "s"
def get_tornado_ioloop():
return ioloop.IOLoop.current()
def get_uuid():
# Generate a unique name that will stay constant between
# invocations, such as platform.node() + uuid.getnode()
# Use uuid5, which does not depend on the clock and is
# recommended over uuid3.
# This is important to be able to identify a server even if
# its drives have been wiped clean.
# Note that this is not foolproof but we can reconcile servers
# on the back-end if need be, based on mac addresses.
return uuid.uuid5(uuid.NAMESPACE_DNS, platform.node() + str(uuid.getnode())).hex
def get_os():
"Human-friendly OS name"
if sys.platform == 'darwin':
return 'mac'
elif sys.platform.find('freebsd') != -1:
return 'freebsd'
elif sys.platform.find('linux') != -1:
return 'linux'
elif sys.platform.find('win32') != -1:
return 'windows'
elif sys.platform.find('sunos') != -1:
return 'solaris'
else:
return sys.platform
def headers(agentConfig):
# Build the request headers
return {
'User-Agent': 'Datadog Agent/%s' % agentConfig['version'],
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'text/html, */*',
}
def windows_friendly_colon_split(config_string):
'''
Perform a split by ':' on the config_string
without splitting on the start of windows path
'''
if Platform.is_win32():
# will split on path/to/module.py:blabla but not on C:\\path
return COLON_NON_WIN_PATH.split(config_string)
else:
return config_string.split(':')
def getTopIndex():
macV = None
if sys.platform == 'darwin':
macV = platform.mac_ver()
# Output from top is slightly modified on OS X 10.6 (case #28239)
if macV and macV[0].startswith('10.6.'):
return 6
else:
return 5
def isnan(val):
if hasattr(math, 'isnan'):
return math.isnan(val)
# for py < 2.6, use a different check
# http://stackoverflow.com/questions/944700/how-to-check-for-nan-in-python
return str(val) == str(1e400*0)
def cast_metric_val(val):
# ensure that the metric value is a numeric type
if not isinstance(val, NumericTypes):
# Try the int conversion first because want to preserve
# whether the value is an int or a float. If neither work,
# raise a ValueError to be handled elsewhere
for cast in [int, float]:
try:
val = cast(val)
return val
except ValueError:
continue
raise ValueError
return val
_IDS = {}
def get_next_id(name):
global _IDS
current_id = _IDS.get(name, 0)
current_id += 1
_IDS[name] = current_id
return current_id
def is_valid_hostname(hostname):
if hostname.lower() in set([
'localhost',
'localhost.localdomain',
'localhost6.localdomain6',
'ip6-localhost',
]):
log.warning("Hostname: %s is local" % hostname)
return False
if len(hostname) > MAX_HOSTNAME_LEN:
log.warning("Hostname: %s is too long (max length is %s characters)" % (hostname, MAX_HOSTNAME_LEN))
return False
if VALID_HOSTNAME_RFC_1123_PATTERN.match(hostname) is None:
log.warning("Hostname: %s is not complying with RFC 1123" % hostname)
return False
return True
def get_hostname(config=None):
"""
Get the canonical host name this agent should identify as. This is
the authoritative source of the host name for the agent.
Tries, in order:
* agent config (datadog.conf, "hostname:")
* 'hostname -f' (on unix)
* socket.gethostname()
"""
hostname = None
# first, try the config
if config is None:
from config import get_config
config = get_config(parse_args=True)
config_hostname = config.get('hostname')
if config_hostname and is_valid_hostname(config_hostname):
return config_hostname
#Try to get GCE instance name
if hostname is None:
gce_hostname = GCE.get_hostname(config)
if gce_hostname is not None:
if is_valid_hostname(gce_hostname):
return gce_hostname
# then move on to os-specific detection
if hostname is None:
def _get_hostname_unix():
try:
# try fqdn
p = subprocess.Popen(['/bin/hostname', '-f'], stdout=subprocess.PIPE)
out, err = p.communicate()
if p.returncode == 0:
return out.strip()
except Exception:
return None
os_name = get_os()
if os_name in ['mac', 'freebsd', 'linux', 'solaris']:
unix_hostname = _get_hostname_unix()
if unix_hostname and is_valid_hostname(unix_hostname):
hostname = unix_hostname
# if we have an ec2 default hostname, see if there's an instance-id available
if hostname is not None and True in [hostname.lower().startswith(p) for p in [u'ip-', u'domu']]:
instanceid = EC2.get_instance_id(config)
if instanceid:
hostname = instanceid
# fall back on socket.gethostname(), socket.getfqdn() is too unreliable
if hostname is None:
try:
socket_hostname = socket.gethostname()
except socket.error, e:
socket_hostname = None
if socket_hostname and is_valid_hostname(socket_hostname):
hostname = socket_hostname
if hostname is None:
log.critical('Unable to reliably determine host name. You can define one in datadog.conf or in your hosts file')
raise Exception('Unable to reliably determine host name. You can define one in datadog.conf or in your hosts file')
else:
return hostname
class GCE(object):
URL = "http://169.254.169.254/computeMetadata/v1/?recursive=true"
TIMEOUT = 0.1 # second
SOURCE_TYPE_NAME = 'google cloud platform'
metadata = None
EXCLUDED_ATTRIBUTES = ["sshKeys"]
@staticmethod
def _get_metadata(agentConfig):
if GCE.metadata is not None:
return GCE.metadata
if not agentConfig['collect_instance_metadata']:
log.info("Instance metadata collection is disabled. Not collecting it.")
GCE.metadata = {}
return GCE.metadata
socket_to = None
try:
socket_to = socket.getdefaulttimeout()
socket.setdefaulttimeout(GCE.TIMEOUT)
except Exception:
pass
try:
opener = urllib2.build_opener()
opener.addheaders = [('X-Google-Metadata-Request','True')]
GCE.metadata = json.loads(opener.open(GCE.URL).read().strip())
except Exception:
GCE.metadata = {}
try:
if socket_to is None:
socket_to = 3
socket.setdefaulttimeout(socket_to)
except Exception:
pass
return GCE.metadata
@staticmethod
def get_tags(agentConfig):
if not agentConfig['collect_instance_metadata']:
return None
try:
host_metadata = GCE._get_metadata(agentConfig)
tags = []
for key, value in host_metadata['instance'].get('attributes', {}).iteritems():
if key in GCE.EXCLUDED_ATTRIBUTES:
continue
tags.append("%s:%s" % (key, value))
tags.extend(host_metadata['instance'].get('tags', []))
tags.append('zone:%s' % host_metadata['instance']['zone'].split('/')[-1])
tags.append('instance-type:%s' % host_metadata['instance']['machineType'].split('/')[-1])
tags.append('internal-hostname:%s' % host_metadata['instance']['hostname'])
tags.append('instance-id:%s' % host_metadata['instance']['id'])
tags.append('project:%s' % host_metadata['project']['projectId'])
tags.append('numeric_project_id:%s' % host_metadata['project']['numericProjectId'])
GCE.metadata['hostname'] = host_metadata['instance']['hostname'].split('.')[0]
return tags
except Exception:
return None
@staticmethod
def get_hostname(agentConfig):
try:
host_metadata = GCE._get_metadata(agentConfig)
return host_metadata['instance']['hostname'].split('.')[0]
except Exception:
return None
class EC2(object):
"""Retrieve EC2 metadata
"""
EC2_METADATA_HOST = "http://169.254.169.254"
METADATA_URL_BASE = EC2_METADATA_HOST + "/latest/meta-data"
INSTANCE_IDENTITY_URL = EC2_METADATA_HOST + "/latest/dynamic/instance-identity/document"
TIMEOUT = 0.1 # second
metadata = {}
@staticmethod
def get_tags(agentConfig):
if not agentConfig['collect_instance_metadata']:
log.info("Instance metadata collection is disabled. Not collecting it.")
return []
socket_to = None
try:
socket_to = socket.getdefaulttimeout()
socket.setdefaulttimeout(EC2.TIMEOUT)
except Exception:
pass
try:
iam_role = urllib2.urlopen(EC2.METADATA_URL_BASE + "/iam/security-credentials").read().strip()
iam_params = json.loads(urllib2.urlopen(EC2.METADATA_URL_BASE + "/iam/security-credentials" + "/" + unicode(iam_role)).read().strip())
instance_identity = json.loads(urllib2.urlopen(EC2.INSTANCE_IDENTITY_URL).read().strip())
region = instance_identity['region']
import boto.ec2
connection = boto.ec2.connect_to_region(region, aws_access_key_id=iam_params['AccessKeyId'], aws_secret_access_key=iam_params['SecretAccessKey'], security_token=iam_params['Token'])
tag_object = connection.get_all_tags({'resource-id': EC2.metadata['instance-id']})
EC2_tags = [u"%s:%s" % (tag.name, tag.value) for tag in tag_object]
except Exception:
log.exception("Problem retrieving custom EC2 tags")
EC2_tags = []
try:
if socket_to is None:
socket_to = 3
socket.setdefaulttimeout(socket_to)
except Exception:
pass
return EC2_tags
@staticmethod
def get_metadata(agentConfig):
"""Use the ec2 http service to introspect the instance. This adds latency if not running on EC2
"""
# >>> import urllib2
# >>> urllib2.urlopen('http://169.254.169.254/latest/', timeout=1).read()
# 'meta-data\nuser-data'
# >>> urllib2.urlopen('http://169.254.169.254/latest/meta-data', timeout=1).read()
# 'ami-id\nami-launch-index\nami-manifest-path\nhostname\ninstance-id\nlocal-ipv4\npublic-keys/\nreservation-id\nsecurity-groups'
# >>> urllib2.urlopen('http://169.254.169.254/latest/meta-data/instance-id', timeout=1).read()
# 'i-deadbeef'
# Every call may add TIMEOUT seconds in latency so don't abuse this call
# python 2.4 does not support an explicit timeout argument so force it here
# Rather than monkey-patching urllib2, just lower the timeout globally for these calls
if not agentConfig['collect_instance_metadata']:
log.info("Instance metadata collection is disabled. Not collecting it.")
return {}
socket_to = None
try:
socket_to = socket.getdefaulttimeout()
socket.setdefaulttimeout(EC2.TIMEOUT)
except Exception:
pass
for k in ('instance-id', 'hostname', 'local-hostname', 'public-hostname', 'ami-id', 'local-ipv4', 'public-keys', 'public-ipv4', 'reservation-id', 'security-groups'):
try:
v = urllib2.urlopen(EC2.METADATA_URL_BASE + "/" + unicode(k)).read().strip()
assert type(v) in (types.StringType, types.UnicodeType) and len(v) > 0, "%s is not a string" % v
EC2.metadata[k] = v
except Exception:
pass
try:
if socket_to is None:
socket_to = 3
socket.setdefaulttimeout(socket_to)
except Exception:
pass
return EC2.metadata
@staticmethod
def get_instance_id(agentConfig):
try:
return EC2.get_metadata(agentConfig).get("instance-id", None)
except Exception:
return None
class Watchdog(object):
"""Simple signal-based watchdog that will scuttle the current process
if it has not been reset every N seconds, or if the processes exceeds
a specified memory threshold.
Can only be invoked once per process, so don't use with multiple threads.
If you instantiate more than one, you're also asking for trouble.
"""
def __init__(self, duration, max_mem_mb = None):
import resource
#Set the duration
self._duration = int(duration)
signal.signal(signal.SIGALRM, Watchdog.self_destruct)
# cap memory usage
if max_mem_mb is not None:
self._max_mem_kb = 1024 * max_mem_mb
max_mem_bytes = 1024 * self._max_mem_kb
resource.setrlimit(resource.RLIMIT_AS, (max_mem_bytes, max_mem_bytes))
self.memory_limit_enabled = True
else:
self.memory_limit_enabled = False
@staticmethod
def self_destruct(signum, frame):
try:
import traceback
log.error("Self-destructing...")
log.error(traceback.format_exc())
finally:
os.kill(os.getpid(), signal.SIGKILL)
def reset(self):
# self destruct if using too much memory, as tornado will swallow MemoryErrors
if self.memory_limit_enabled:
mem_usage_kb = int(os.popen('ps -p %d -o %s | tail -1' % (os.getpid(), 'rss')).read())
if mem_usage_kb > (0.95 * self._max_mem_kb):
Watchdog.self_destruct(signal.SIGKILL, sys._getframe(0))
log.debug("Resetting watchdog for %d" % self._duration)
signal.alarm(self._duration)
class LaconicFilter(logging.Filter):
"""
Filters messages, only print them once while keeping memory under control
"""
LACONIC_MEM_LIMIT = 1024
def __init__(self, name=""):
logging.Filter.__init__(self, name)
self.hashed_messages = {}
def hash(self, msg):
return md5(msg).hexdigest()
def filter(self, record):
try:
h = self.hash(record.getMessage())
if h in self.hashed_messages:
return 0
else:
# Don't blow up our memory
if len(self.hashed_messages) >= LaconicFilter.LACONIC_MEM_LIMIT:
self.hashed_messages.clear()
self.hashed_messages[h] = True
return 1
except Exception:
return 1
class Timer(object):
""" Helper class """
def __init__(self):
self.start()
def _now(self):
return time.time()
def start(self):
self.started = self._now()
self.last = self.started
return self
def step(self):
now = self._now()
step = now - self.last
self.last = now
return step
def total(self, as_sec=True):
return self._now() - self.started
"""
Iterable Recipes
"""
def chunks(iterable, chunk_size):
"""Generate sequences of `chunk_size` elements from `iterable`."""
iterable = iter(iterable)
while True:
chunk = [None] * chunk_size
count = 0
try:
for _ in range(chunk_size):
chunk[count] = iterable.next()
count += 1
yield chunk[:count]
except StopIteration:
if count:
yield chunk[:count]
break
| bsd-3-clause |
ranierimachado/pos | core/lib/Drupal/Core/EventSubscriber/EntityRouteProviderSubscriber.php | 2073 | <?php
namespace Drupal\Core\EventSubscriber;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Routing\RouteBuildEvent;
use Drupal\Core\Routing\RoutingEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Routing\RouteCollection;
/**
* Ensures that routes can be provided by entity types.
*/
class EntityRouteProviderSubscriber implements EventSubscriberInterface {
/**
* The entity manager.
*
* @var \Drupal\Core\Entity\EntityManagerInterface
*/
protected $entityManager;
/**
* Constructs a new EntityRouteProviderSubscriber instance.
*
* @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
* The entity manager.
*/
public function __construct(EntityManagerInterface $entity_manager) {
$this->entityManager = $entity_manager;
}
/**
* Provides routes on route rebuild time.
*
* @param \Drupal\Core\Routing\RouteBuildEvent $event
* The route build event.
*/
public function onDynamicRouteEvent(RouteBuildEvent $event) {
$route_collection = $event->getRouteCollection();
foreach ($this->entityManager->getDefinitions() as $entity_type) {
if ($entity_type->hasRouteProviders()) {
foreach ($this->entityManager->getRouteProviders($entity_type->id()) as $route_provider) {
// Allow to both return an array of routes or a route collection,
// like route_callbacks in the routing.yml file.
$routes = $route_provider->getRoutes($entity_type);
if ($routes instanceof RouteCollection) {
$routes = $routes->all();
}
foreach ($routes as $route_name => $route) {
// Don't override existing routes.
if (!$route_collection->get($route_name)) {
$route_collection->add($route_name, $route);
}
}
}
}
}
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
$events[RoutingEvents::DYNAMIC][] = ['onDynamicRouteEvent'];
return $events;
}
}
| gpl-2.0 |
kepta/iD | test/spec/core/entity.js | 9262 | describe('iD.Entity', function () {
it("returns a subclass of the appropriate type", function () {
expect(iD.Entity({type: 'node'})).be.an.instanceOf(iD.Node);
expect(iD.Entity({type: 'way'})).be.an.instanceOf(iD.Way);
expect(iD.Entity({type: 'relation'})).be.an.instanceOf(iD.Relation);
expect(iD.Entity({id: 'n1'})).be.an.instanceOf(iD.Node);
expect(iD.Entity({id: 'w1'})).be.an.instanceOf(iD.Way);
expect(iD.Entity({id: 'r1'})).be.an.instanceOf(iD.Relation);
});
if (iD.debug) {
it("is frozen", function () {
expect(Object.isFrozen(iD.Entity())).to.be.true;
});
it("freezes tags", function () {
expect(Object.isFrozen(iD.Entity().tags)).to.be.true;
});
}
describe(".id", function () {
it("generates unique IDs", function () {
expect(iD.Entity.id('node')).not.to.equal(iD.Entity.id('node'));
});
describe(".fromOSM", function () {
it("returns a ID string unique across entity types", function () {
expect(iD.Entity.id.fromOSM('node', '1')).to.equal("n1");
});
});
describe(".toOSM", function () {
it("reverses fromOSM", function () {
expect(iD.Entity.id.toOSM(iD.Entity.id.fromOSM('node', '1'))).to.equal('1');
});
});
});
describe("#copy", function () {
it("returns a new Entity", function () {
var n = iD.Entity({id: 'n'}),
result = n.copy(null, {});
expect(result).to.be.an.instanceof(iD.Entity);
expect(result).not.to.equal(n);
});
it("adds the new Entity to input object", function () {
var n = iD.Entity({id: 'n'}),
copies = {},
result = n.copy(null, copies);
expect(Object.keys(copies)).to.have.length(1);
expect(copies.n).to.equal(result);
});
it("returns an existing copy in input object", function () {
var n = iD.Entity({id: 'n'}),
copies = {},
result1 = n.copy(null, copies),
result2 = n.copy(null, copies);
expect(Object.keys(copies)).to.have.length(1);
expect(result1).to.equal(result2);
});
it("resets 'id', 'user', and 'version' properties", function () {
var n = iD.Entity({id: 'n', version: 10, user: 'user'}),
copies = {};
n.copy(null, copies);
expect(copies.n.isNew()).to.be.ok;
expect(copies.n.version).to.be.undefined;
expect(copies.n.user).to.be.undefined;
});
it("copies tags", function () {
var n = iD.Entity({id: 'n', tags: {foo: 'foo'}}),
copies = {};
n.copy(null, copies);
expect(copies.n.tags).to.equal(n.tags);
});
});
describe("#update", function () {
it("returns a new Entity", function () {
var a = iD.Entity(),
b = a.update({});
expect(b instanceof iD.Entity).to.be.true;
expect(a).not.to.equal(b);
});
it("updates the specified attributes", function () {
var tags = {foo: 'bar'},
e = iD.Entity().update({tags: tags});
expect(e.tags).to.equal(tags);
});
it("preserves existing attributes", function () {
var e = iD.Entity({id: 'w1'}).update({});
expect(e.id).to.equal('w1');
});
it("doesn't modify the input", function () {
var attrs = {tags: {foo: 'bar'}},
e = iD.Entity().update(attrs);
expect(attrs).to.eql({tags: {foo: 'bar'}});
});
it("doesn't copy prototype properties", function () {
expect(iD.Entity().update({})).not.to.have.ownProperty('update');
});
it("sets v to 1 if previously undefined", function() {
expect(iD.Entity().update({}).v).to.equal(1);
});
it("increments v", function() {
expect(iD.Entity({v: 1}).update({}).v).to.equal(2);
});
});
describe("#mergeTags", function () {
it("returns self if unchanged", function () {
var a = iD.Entity({tags: {a: 'a'}}),
b = a.mergeTags({a: 'a'});
expect(a).to.equal(b);
});
it("returns a new Entity if changed", function () {
var a = iD.Entity({tags: {a: 'a'}}),
b = a.mergeTags({a: 'b'});
expect(b instanceof iD.Entity).to.be.true;
expect(a).not.to.equal(b);
});
it("merges tags", function () {
var a = iD.Entity({tags: {a: 'a'}}),
b = a.mergeTags({b: 'b'});
expect(b.tags).to.eql({a: 'a', b: 'b'});
});
it("combines non-conflicting tags", function () {
var a = iD.Entity({tags: {a: 'a'}}),
b = a.mergeTags({a: 'a'});
expect(b.tags).to.eql({a: 'a'});
});
it("combines conflicting tags with semicolons", function () {
var a = iD.Entity({tags: {a: 'a'}}),
b = a.mergeTags({a: 'b'});
expect(b.tags).to.eql({a: 'a;b'});
});
it("combines combined tags", function () {
var a = iD.Entity({tags: {a: 'a;b'}}),
b = iD.Entity({tags: {a: 'b'}});
expect(a.mergeTags(b.tags).tags).to.eql({a: 'a;b'});
expect(b.mergeTags(a.tags).tags).to.eql({a: 'b;a'});
});
it("combines combined tags with whitespace", function () {
var a = iD.Entity({tags: {a: 'a; b'}}),
b = iD.Entity({tags: {a: 'b'}});
expect(a.mergeTags(b.tags).tags).to.eql({a: 'a;b'});
expect(b.mergeTags(a.tags).tags).to.eql({a: 'b;a'});
});
});
describe("#osmId", function () {
it("returns an OSM ID as a string", function () {
expect(iD.Entity({id: 'w1234'}).osmId()).to.eql('1234');
expect(iD.Entity({id: 'n1234'}).osmId()).to.eql('1234');
expect(iD.Entity({id: 'r1234'}).osmId()).to.eql('1234');
});
});
describe("#intersects", function () {
it("returns true for a way with a node within the given extent", function () {
var node = iD.Node({loc: [0, 0]}),
way = iD.Way({nodes: [node.id]}),
graph = iD.Graph([node, way]);
expect(way.intersects([[-5, -5], [5, 5]], graph)).to.equal(true);
});
it("returns false for way with no nodes within the given extent", function () {
var node = iD.Node({loc: [6, 6]}),
way = iD.Way({nodes: [node.id]}),
graph = iD.Graph([node, way]);
expect(way.intersects([[-5, -5], [5, 5]], graph)).to.equal(false);
});
});
describe("#isUsed", function () {
it("returns false for an entity without tags", function () {
var node = iD.Node(),
graph = iD.Graph([node]);
expect(node.isUsed(graph)).to.equal(false);
});
it("returns true for an entity with tags", function () {
var node = iD.Node({tags: {foo: 'bar'}}),
graph = iD.Graph([node]);
expect(node.isUsed(graph)).to.equal(true);
});
it("returns false for an entity with only an area=yes tag", function () {
var node = iD.Node({tags: {area: 'yes'}}),
graph = iD.Graph([node]);
expect(node.isUsed(graph)).to.equal(false);
});
it("returns true for an entity that is a relation member", function () {
var node = iD.Node(),
relation = iD.Relation({members: [{id: node.id}]}),
graph = iD.Graph([node, relation]);
expect(node.isUsed(graph)).to.equal(true);
});
});
describe("#hasDeprecatedTags", function () {
it("returns false if entity has no tags", function () {
expect(iD.Entity().deprecatedTags()).to.eql({});
});
it("returns true if entity has deprecated tags", function () {
expect(iD.Entity({ tags: { barrier: 'wire_fence' } }).deprecatedTags()).to.eql({ barrier: 'wire_fence' });
});
});
describe("#hasInterestingTags", function () {
it("returns false if the entity has no tags", function () {
expect(iD.Entity().hasInterestingTags()).to.equal(false);
});
it("returns true if the entity has tags other than 'attribution', 'created_by', 'source', 'odbl' and tiger tags", function () {
expect(iD.Entity({tags: {foo: 'bar'}}).hasInterestingTags()).to.equal(true);
});
it("return false if the entity has only uninteresting tags", function () {
expect(iD.Entity({tags: {source: 'Bing'}}).hasInterestingTags()).to.equal(false);
});
it("return false if the entity has only tiger tags", function () {
expect(iD.Entity({tags: {'tiger:source': 'blah', 'tiger:foo': 'bar'}}).hasInterestingTags()).to.equal(false);
});
});
});
| isc |
wieslawsoltes/Perspex | src/Windows/Avalonia.Win32/WinRT/WinRTInspectable.cs | 1203 | using System;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Avalonia.MicroCom;
namespace Avalonia.Win32.WinRT
{
class WinRTInspectable : IInspectable, IMicroComShadowContainer
{
public virtual void Dispose()
{
}
public unsafe void GetIids(ulong* iidCount, Guid** iids)
{
var interfaces = GetType().GetInterfaces().Where(typeof(IUnknown).IsAssignableFrom)
.Select(MicroComRuntime.GetGuidFor).ToArray();
var mem = (Guid*)Marshal.AllocCoTaskMem(Unsafe.SizeOf<Guid>() * interfaces.Length);
for (var c = 0; c < interfaces.Length; c++)
mem[c] = interfaces[c];
*iids = mem;
*iidCount = (ulong) interfaces.Length;
}
public IntPtr RuntimeClassName => NativeWinRTMethods.WindowsCreateString(GetType().FullName);
public TrustLevel TrustLevel => TrustLevel.BaseTrust;
public MicroComShadow Shadow { get; set; }
public virtual void OnReferencedFromNative()
{
}
public virtual void OnUnreferencedFromNative()
{
}
}
}
| mit |
sottosviluppo/elcodi | src/Elcodi/Component/Menu/Factory/MenuFactory.php | 1137 | <?php
/*
* This file is part of the Elcodi package.
*
* Copyright (c) 2014-2016 Elcodi Networks S.L.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* Feel free to edit as you please, and have fun.
*
* @author Marc Morera <yuhu@mmoreram.com>
* @author Aldo Chiecchia <zimage@tiscali.it>
* @author Elcodi Team <tech@elcodi.com>
*/
namespace Elcodi\Component\Menu\Factory;
use Doctrine\Common\Collections\ArrayCollection;
use Elcodi\Component\Core\Factory\Abstracts\AbstractFactory;
use Elcodi\Component\Menu\Entity\Menu\Menu;
/**
* Class MenuFactory.
*/
class MenuFactory extends AbstractFactory
{
/**
* Creates an instance of Menu entity.
*
* @return Menu Empty entity
*/
public function create()
{
/**
* @var Menu $menu
*/
$classNamespace = $this->getEntityNamespace();
$menu = new $classNamespace();
$menu
->setDescription('')
->setSubnodes(new ArrayCollection())
->setEnabled(false);
return $menu;
}
}
| mit |
ezgatrabajo/sf_prueba1 | vendor/lexik/jwt-authentication-bundle/Exception/MissingTokenException.php | 470 | <?php
namespace Lexik\Bundle\JWTAuthenticationBundle\Exception;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
/**
* Exception to be thrown in case of invalid token during an authentication process.
*
* @author Robin Chalas <robin.chalas@gmail.com>
*/
class MissingTokenException extends AuthenticationException
{
/**
* {@inheritdoc}
*/
public function getMessageKey()
{
return 'JWT Token not found';
}
}
| mit |
oleg-andreyev/symfony | src/Symfony/Component/Intl/Resources/data/timezones/th.php | 46438 | <?php
return [
'Names' => [
'Africa/Abidjan' => 'เวลามาตรฐานกรีนิช (อาบีจาน)',
'Africa/Accra' => 'เวลามาตรฐานกรีนิช (อักกรา)',
'Africa/Addis_Ababa' => 'เวลาแอฟริกาตะวันออก (แอดดิสอาบาบา)',
'Africa/Algiers' => 'เวลายุโรปกลาง (แอลเจียร์)',
'Africa/Asmera' => 'เวลาแอฟริกาตะวันออก (แอสมารา)',
'Africa/Bamako' => 'เวลามาตรฐานกรีนิช (บามาโก)',
'Africa/Bangui' => 'เวลาแอฟริกาตะวันตก (บังกี)',
'Africa/Banjul' => 'เวลามาตรฐานกรีนิช (บันจูล)',
'Africa/Bissau' => 'เวลามาตรฐานกรีนิช (บิสเซา)',
'Africa/Blantyre' => 'เวลาแอฟริกากลาง (แบลนไทร์)',
'Africa/Brazzaville' => 'เวลาแอฟริกาตะวันตก (บราซซาวิล)',
'Africa/Bujumbura' => 'เวลาแอฟริกากลาง (บูจุมบูรา)',
'Africa/Cairo' => 'เวลายุโรปตะวันออก (ไคโร)',
'Africa/Casablanca' => 'เวลายุโรปตะวันตก (คาสซาบลางก้า)',
'Africa/Ceuta' => 'เวลายุโรปกลาง (เซวตา)',
'Africa/Conakry' => 'เวลามาตรฐานกรีนิช (โกนากรี)',
'Africa/Dakar' => 'เวลามาตรฐานกรีนิช (ดาการ์)',
'Africa/Dar_es_Salaam' => 'เวลาแอฟริกาตะวันออก (ดาร์เอสซาลาม)',
'Africa/Djibouti' => 'เวลาแอฟริกาตะวันออก (จิบูตี)',
'Africa/Douala' => 'เวลาแอฟริกาตะวันตก (ดูอาลา)',
'Africa/El_Aaiun' => 'เวลายุโรปตะวันตก (เอลไอย์อุง)',
'Africa/Freetown' => 'เวลามาตรฐานกรีนิช (ฟรีทาวน์)',
'Africa/Gaborone' => 'เวลาแอฟริกากลาง (กาโบโรเน)',
'Africa/Harare' => 'เวลาแอฟริกากลาง (ฮาราเร)',
'Africa/Johannesburg' => 'เวลาแอฟริกาใต้ (โจฮันเนสเบอร์ก)',
'Africa/Juba' => 'เวลาแอฟริกากลาง (จูบา)',
'Africa/Kampala' => 'เวลาแอฟริกาตะวันออก (คัมพาลา)',
'Africa/Khartoum' => 'เวลาแอฟริกากลาง (คาร์ทูม)',
'Africa/Kigali' => 'เวลาแอฟริกากลาง (คิกาลี)',
'Africa/Kinshasa' => 'เวลาแอฟริกาตะวันตก (กินชาซา)',
'Africa/Lagos' => 'เวลาแอฟริกาตะวันตก (ลากอส)',
'Africa/Libreville' => 'เวลาแอฟริกาตะวันตก (ลีเบรอวิล)',
'Africa/Lome' => 'เวลามาตรฐานกรีนิช (โลเม)',
'Africa/Luanda' => 'เวลาแอฟริกาตะวันตก (ลูอันดา)',
'Africa/Lubumbashi' => 'เวลาแอฟริกากลาง (ลูบัมบาชิ)',
'Africa/Lusaka' => 'เวลาแอฟริกากลาง (ลูซากา)',
'Africa/Malabo' => 'เวลาแอฟริกาตะวันตก (มาลาโบ)',
'Africa/Maputo' => 'เวลาแอฟริกากลาง (มาปูโต)',
'Africa/Maseru' => 'เวลาแอฟริกาใต้ (มาเซรู)',
'Africa/Mbabane' => 'เวลาแอฟริกาใต้ (อัมบาบาเน)',
'Africa/Mogadishu' => 'เวลาแอฟริกาตะวันออก (โมกาดิชู)',
'Africa/Monrovia' => 'เวลามาตรฐานกรีนิช (มันโรเวีย)',
'Africa/Nairobi' => 'เวลาแอฟริกาตะวันออก (ไนโรเบีย)',
'Africa/Ndjamena' => 'เวลาแอฟริกาตะวันตก (เอ็นจาเมนา)',
'Africa/Niamey' => 'เวลาแอฟริกาตะวันตก (นีอาเมย์)',
'Africa/Nouakchott' => 'เวลามาตรฐานกรีนิช (นูแอกชอต)',
'Africa/Ouagadougou' => 'เวลามาตรฐานกรีนิช (วากาดูกู)',
'Africa/Porto-Novo' => 'เวลาแอฟริกาตะวันตก (ปอร์โต-โนโว)',
'Africa/Sao_Tome' => 'เวลามาตรฐานกรีนิช (เซาตูเม)',
'Africa/Tripoli' => 'เวลายุโรปตะวันออก (ตรีโปลี)',
'Africa/Tunis' => 'เวลายุโรปกลาง (ตูนิส)',
'Africa/Windhoek' => 'เวลาแอฟริกากลาง (วินด์ฮุก)',
'America/Adak' => 'เวลาฮาวาย-อะลูเชียน (เอดัก)',
'America/Anchorage' => 'เวลาอะแลสกา (แองเคอเรจ)',
'America/Anguilla' => 'เวลาแอตแลนติก (แองกิลลา)',
'America/Antigua' => 'เวลาแอตแลนติก (แอนติกา)',
'America/Araguaina' => 'เวลาบราซิเลีย (อารากัวนา)',
'America/Argentina/La_Rioja' => 'เวลาอาร์เจนตินา (ลาริโอจา)',
'America/Argentina/Rio_Gallegos' => 'เวลาอาร์เจนตินา (ริโอกาลเลกอส)',
'America/Argentina/Salta' => 'เวลาอาร์เจนตินา (ซัลตา)',
'America/Argentina/San_Juan' => 'เวลาอาร์เจนตินา (ซานฮวน)',
'America/Argentina/San_Luis' => 'เวลาอาร์เจนตินา (ซันลูอิส)',
'America/Argentina/Tucuman' => 'เวลาอาร์เจนตินา (ทูคูแมน)',
'America/Argentina/Ushuaia' => 'เวลาอาร์เจนตินา (อูชูเอีย)',
'America/Aruba' => 'เวลาแอตแลนติก (อารูบา)',
'America/Asuncion' => 'เวลาปารากวัย (อะซุนซิออง)',
'America/Bahia' => 'เวลาบราซิเลีย (บาเยีย)',
'America/Bahia_Banderas' => 'เวลาตอนกลางในอเมริกาเหนือ (บาเอียบันเดรัส)',
'America/Barbados' => 'เวลาแอตแลนติก (บาร์เบโดส)',
'America/Belem' => 'เวลาบราซิเลีย (เบเลง)',
'America/Belize' => 'เวลาตอนกลางในอเมริกาเหนือ (เบลีซ)',
'America/Blanc-Sablon' => 'เวลาแอตแลนติก (บลังค์-ซาบลอน)',
'America/Boa_Vista' => 'เวลาแอมะซอน (บัววีชตา)',
'America/Bogota' => 'เวลาโคลอมเบีย (โบโกตา)',
'America/Boise' => 'เวลาแถบภูเขาในอเมริกาเหนือ (บอยซี)',
'America/Buenos_Aires' => 'เวลาอาร์เจนตินา (บัวโนสไอเรส)',
'America/Cambridge_Bay' => 'เวลาแถบภูเขาในอเมริกาเหนือ (อ่าวแคมบริดจ์)',
'America/Campo_Grande' => 'เวลาแอมะซอน (กัมปูกรันดี)',
'America/Cancun' => 'เวลาทางตะวันออกในอเมริกาเหนือ (แคนคุน)',
'America/Caracas' => 'เวลาเวเนซุเอลา (คาราคัส)',
'America/Catamarca' => 'เวลาอาร์เจนตินา (กาตามาร์กา)',
'America/Cayenne' => 'เวลาเฟรนช์เกียนา (กาแยน)',
'America/Cayman' => 'เวลาทางตะวันออกในอเมริกาเหนือ (เคย์แมน)',
'America/Chicago' => 'เวลาตอนกลางในอเมริกาเหนือ (ชิคาโก)',
'America/Chihuahua' => 'เวลาแปซิฟิกเม็กซิโก (ชีวาวา)',
'America/Coral_Harbour' => 'เวลาทางตะวันออกในอเมริกาเหนือ (คอรัลฮาร์เบอร์)',
'America/Cordoba' => 'เวลาอาร์เจนตินา (คอร์โดบา)',
'America/Costa_Rica' => 'เวลาตอนกลางในอเมริกาเหนือ (คอสตาริกา)',
'America/Creston' => 'เวลาแถบภูเขาในอเมริกาเหนือ (เครสตัน)',
'America/Cuiaba' => 'เวลาแอมะซอน (กุยาบา)',
'America/Curacao' => 'เวลาแอตแลนติก (คูราเซา)',
'America/Danmarkshavn' => 'เวลามาตรฐานกรีนิช (ดานมาร์กสฮาวน์)',
'America/Dawson' => 'เวลาแถบภูเขาในอเมริกาเหนือ (ดอว์สัน)',
'America/Dawson_Creek' => 'เวลาแถบภูเขาในอเมริกาเหนือ (ดอว์สัน ครีก)',
'America/Denver' => 'เวลาแถบภูเขาในอเมริกาเหนือ (เดนเวอร์)',
'America/Detroit' => 'เวลาทางตะวันออกในอเมริกาเหนือ (ดีทรอยต์)',
'America/Dominica' => 'เวลาแอตแลนติก (โดมินิกา)',
'America/Edmonton' => 'เวลาแถบภูเขาในอเมริกาเหนือ (เอดมันตัน)',
'America/Eirunepe' => 'เวลาอาเกร (เอรูเนเป)',
'America/El_Salvador' => 'เวลาตอนกลางในอเมริกาเหนือ (เอลซัลวาดอร์)',
'America/Fort_Nelson' => 'เวลาแถบภูเขาในอเมริกาเหนือ (ฟอร์ตเนลสัน)',
'America/Fortaleza' => 'เวลาบราซิเลีย (ฟอร์ตาเลซา)',
'America/Glace_Bay' => 'เวลาแอตแลนติก (เกลซเบย์)',
'America/Godthab' => 'เวลากรีนแลนด์ตะวันตก (กอดแธบ)',
'America/Goose_Bay' => 'เวลาแอตแลนติก (กูสเบย์)',
'America/Grand_Turk' => 'เวลาทางตะวันออกในอเมริกาเหนือ (แกรนด์เติร์ก)',
'America/Grenada' => 'เวลาแอตแลนติก (เกรนาดา)',
'America/Guadeloupe' => 'เวลาแอตแลนติก (กวาเดอลูป)',
'America/Guatemala' => 'เวลาตอนกลางในอเมริกาเหนือ (กัวเตมาลา)',
'America/Guayaquil' => 'เวลาเอกวาดอร์ (กัวยากิล)',
'America/Guyana' => 'เวลากายอานา',
'America/Halifax' => 'เวลาแอตแลนติก (แฮลิแฟกซ์)',
'America/Havana' => 'เวลาคิวบา (ฮาวานา)',
'America/Hermosillo' => 'เวลาแปซิฟิกเม็กซิโก (เอร์โมซีโย)',
'America/Indiana/Knox' => 'เวลาตอนกลางในอเมริกาเหนือ (นอกซ์, อินดีแอนา)',
'America/Indiana/Marengo' => 'เวลาทางตะวันออกในอเมริกาเหนือ (มาเรงโก, อินดีแอนา)',
'America/Indiana/Petersburg' => 'เวลาทางตะวันออกในอเมริกาเหนือ (ปีเตอร์สเบิร์ก, อินดีแอนา)',
'America/Indiana/Tell_City' => 'เวลาตอนกลางในอเมริกาเหนือ (เทลล์ซิตี, อินดีแอนา)',
'America/Indiana/Vevay' => 'เวลาทางตะวันออกในอเมริกาเหนือ (วีเวย์, อินดีแอนา)',
'America/Indiana/Vincennes' => 'เวลาทางตะวันออกในอเมริกาเหนือ (วินเซนเนส, อินดีแอนา)',
'America/Indiana/Winamac' => 'เวลาทางตะวันออกในอเมริกาเหนือ (วินาแมค, อินดีแอนา)',
'America/Indianapolis' => 'เวลาทางตะวันออกในอเมริกาเหนือ (อินเดียแนโพลิส)',
'America/Inuvik' => 'เวลาแถบภูเขาในอเมริกาเหนือ (อินูวิก)',
'America/Iqaluit' => 'เวลาทางตะวันออกในอเมริกาเหนือ (อีกวาลิต)',
'America/Jamaica' => 'เวลาทางตะวันออกในอเมริกาเหนือ (จาเมกา)',
'America/Jujuy' => 'เวลาอาร์เจนตินา (จูจิว)',
'America/Juneau' => 'เวลาอะแลสกา (จูโน)',
'America/Kentucky/Monticello' => 'เวลาทางตะวันออกในอเมริกาเหนือ (มอนติเซลโล, เคนตักกี)',
'America/Kralendijk' => 'เวลาแอตแลนติก (คราเลนดิจค์)',
'America/La_Paz' => 'เวลาโบลิเวีย (ลาปาซ)',
'America/Lima' => 'เวลาเปรู (ลิมา)',
'America/Los_Angeles' => 'เวลาแปซิฟิกในอเมริกาเหนือ (ลอสแองเจลิส)',
'America/Louisville' => 'เวลาทางตะวันออกในอเมริกาเหนือ (ลูส์วิลล์)',
'America/Lower_Princes' => 'เวลาแอตแลนติก (โลเวอร์พรินซ์ ควอเตอร์)',
'America/Maceio' => 'เวลาบราซิเลีย (มาเซโอ)',
'America/Managua' => 'เวลาตอนกลางในอเมริกาเหนือ (มานากัว)',
'America/Manaus' => 'เวลาแอมะซอน (มาเนาส์)',
'America/Marigot' => 'เวลาแอตแลนติก (มาริโกต์)',
'America/Martinique' => 'เวลาแอตแลนติก (มาร์ตินีก)',
'America/Matamoros' => 'เวลาตอนกลางในอเมริกาเหนือ (มาตาโมรอส)',
'America/Mazatlan' => 'เวลาแปซิฟิกเม็กซิโก (มาซาทลาน)',
'America/Mendoza' => 'เวลาอาร์เจนตินา (เมนดูซา)',
'America/Menominee' => 'เวลาตอนกลางในอเมริกาเหนือ (เมโนมินี)',
'America/Merida' => 'เวลาตอนกลางในอเมริกาเหนือ (เมรีดา)',
'America/Metlakatla' => 'เวลาอะแลสกา (เมทลากาตละ)',
'America/Mexico_City' => 'เวลาตอนกลางในอเมริกาเหนือ (เม็กซิโกซิตี)',
'America/Miquelon' => 'เวลาแซงปีแยร์และมีเกอลง',
'America/Moncton' => 'เวลาแอตแลนติก (มองตัน)',
'America/Monterrey' => 'เวลาตอนกลางในอเมริกาเหนือ (มอนเตร์เรย์)',
'America/Montevideo' => 'เวลาอุรุกวัย (มอนเตวิเดโอ)',
'America/Montreal' => 'เวลาแคนาดา (Montreal)',
'America/Montserrat' => 'เวลาแอตแลนติก (มอนเซอร์รัต)',
'America/Nassau' => 'เวลาทางตะวันออกในอเมริกาเหนือ (แนสซอ)',
'America/New_York' => 'เวลาทางตะวันออกในอเมริกาเหนือ (นิวยอร์ก)',
'America/Nipigon' => 'เวลาทางตะวันออกในอเมริกาเหนือ (นิปิกอน)',
'America/Nome' => 'เวลาอะแลสกา (นอม)',
'America/Noronha' => 'เวลาหมู่เกาะเฟอร์นันโด (โนรอนฮา)',
'America/North_Dakota/Beulah' => 'เวลาตอนกลางในอเมริกาเหนือ (โบลาห์, นอร์ทดาโคตา)',
'America/North_Dakota/Center' => 'เวลาตอนกลางในอเมริกาเหนือ (เซนเตอร์, นอร์ทดาโคตา)',
'America/North_Dakota/New_Salem' => 'เวลาตอนกลางในอเมริกาเหนือ (นิวเซเลม, นอร์ทดาโคตา)',
'America/Ojinaga' => 'เวลาแถบภูเขาในอเมริกาเหนือ (โอจินากา)',
'America/Panama' => 'เวลาทางตะวันออกในอเมริกาเหนือ (ปานามา)',
'America/Pangnirtung' => 'เวลาทางตะวันออกในอเมริกาเหนือ (พางนีทัง)',
'America/Paramaribo' => 'เวลาซูรินาเม (ปารามาริโบ)',
'America/Phoenix' => 'เวลาแถบภูเขาในอเมริกาเหนือ (ฟินิกซ์)',
'America/Port-au-Prince' => 'เวลาทางตะวันออกในอเมริกาเหนือ (ปอร์โตแปรงซ์)',
'America/Port_of_Spain' => 'เวลาแอตแลนติก (พอร์ทออฟสเปน)',
'America/Porto_Velho' => 'เวลาแอมะซอน (ปอร์ตูเวลโย)',
'America/Puerto_Rico' => 'เวลาแอตแลนติก (เปอโตริโก)',
'America/Punta_Arenas' => 'เวลาชิลี (ปุนตาอาเรนัส)',
'America/Rainy_River' => 'เวลาตอนกลางในอเมริกาเหนือ (เรนนี่ริเวอร์)',
'America/Rankin_Inlet' => 'เวลาตอนกลางในอเมริกาเหนือ (แรงกินอินเล็ต)',
'America/Recife' => 'เวลาบราซิเลีย (เรซีเฟ)',
'America/Regina' => 'เวลาตอนกลางในอเมริกาเหนือ (ริไจนา)',
'America/Resolute' => 'เวลาตอนกลางในอเมริกาเหนือ (เรโซลูท)',
'America/Rio_Branco' => 'เวลาอาเกร (รีโอบรังโก)',
'America/Santa_Isabel' => 'เวลาเม็กซิโกตะวันตกเฉียงเหนือ (ซานตาอิซาเบล)',
'America/Santarem' => 'เวลาบราซิเลีย (ซันตาเรม)',
'America/Santiago' => 'เวลาชิลี (ซันติอาโก)',
'America/Santo_Domingo' => 'เวลาแอตแลนติก (ซานโต โดมิงโก)',
'America/Sao_Paulo' => 'เวลาบราซิเลีย (เซาเปาลู)',
'America/Scoresbysund' => 'เวลากรีนแลนด์ตะวันออก (สกอเรสไบซันด์)',
'America/Sitka' => 'เวลาอะแลสกา (ซิตกา)',
'America/St_Barthelemy' => 'เวลาแอตแลนติก (เซนต์บาร์เธเลมี)',
'America/St_Johns' => 'เวลานิวฟันด์แลนด์ (เซนต์จอนส์)',
'America/St_Kitts' => 'เวลาแอตแลนติก (เซนต์คิตส์)',
'America/St_Lucia' => 'เวลาแอตแลนติก (เซนต์ลูเซีย)',
'America/St_Thomas' => 'เวลาแอตแลนติก (เซนต์โธมัส)',
'America/St_Vincent' => 'เวลาแอตแลนติก (เซนต์วินเซนต์)',
'America/Swift_Current' => 'เวลาตอนกลางในอเมริกาเหนือ (สวิฟต์เคอร์เรนต์)',
'America/Tegucigalpa' => 'เวลาตอนกลางในอเมริกาเหนือ (เตกูซิกัลปา)',
'America/Thule' => 'เวลาแอตแลนติก (ทูเล)',
'America/Thunder_Bay' => 'เวลาทางตะวันออกในอเมริกาเหนือ (ทันเดอร์เบย์)',
'America/Tijuana' => 'เวลาแปซิฟิกในอเมริกาเหนือ (ทิฮัวนา)',
'America/Toronto' => 'เวลาทางตะวันออกในอเมริกาเหนือ (โทรอนโต)',
'America/Tortola' => 'เวลาแอตแลนติก (ตอร์โตลา)',
'America/Vancouver' => 'เวลาแปซิฟิกในอเมริกาเหนือ (แวนคูเวอร์)',
'America/Whitehorse' => 'เวลาแถบภูเขาในอเมริกาเหนือ (ไวต์ฮอร์ส)',
'America/Winnipeg' => 'เวลาตอนกลางในอเมริกาเหนือ (วินนิเพก)',
'America/Yakutat' => 'เวลาอะแลสกา (ยากูทัต)',
'America/Yellowknife' => 'เวลาแถบภูเขาในอเมริกาเหนือ (เยลโลว์ไนฟ์)',
'Antarctica/Casey' => 'เวลาเคซีย์',
'Antarctica/Davis' => 'เวลาเดวิส',
'Antarctica/DumontDUrville' => 'เวลาดูมองต์ดูร์วิลล์',
'Antarctica/Macquarie' => 'เวลาออสเตรเลียตะวันออก (แมคควอรี)',
'Antarctica/Mawson' => 'เวลามอว์สัน',
'Antarctica/McMurdo' => 'เวลานิวซีแลนด์ (แมคมัวโด)',
'Antarctica/Palmer' => 'เวลาชิลี (พาล์เมอร์)',
'Antarctica/Rothera' => 'เวลาโรธีรา',
'Antarctica/Syowa' => 'เวลาไซโยวา',
'Antarctica/Troll' => 'เวลามาตรฐานกรีนิช (โทรล)',
'Antarctica/Vostok' => 'เวลาวอสตอค',
'Arctic/Longyearbyen' => 'เวลายุโรปกลาง (ลองเยียร์เบียน)',
'Asia/Aden' => 'เวลาอาหรับ (เอเดน)',
'Asia/Almaty' => 'เวลาคาซัคสถานตะวันออก (อัลมาตี)',
'Asia/Amman' => 'เวลายุโรปตะวันออก (อัมมาน)',
'Asia/Anadyr' => 'เวลาอะนาดีร์ (อานาดีร์)',
'Asia/Aqtau' => 'เวลาคาซัคสถานตะวันตก (อัคตาอู)',
'Asia/Aqtobe' => 'เวลาคาซัคสถานตะวันตก (อัคโทบี)',
'Asia/Ashgabat' => 'เวลาเติร์กเมนิสถาน (อาชกาบัต)',
'Asia/Atyrau' => 'เวลาคาซัคสถานตะวันตก (อทีราว)',
'Asia/Baghdad' => 'เวลาอาหรับ (แบกแดด)',
'Asia/Bahrain' => 'เวลาอาหรับ (บาห์เรน)',
'Asia/Baku' => 'เวลาอาเซอร์ไบจาน (บากู)',
'Asia/Bangkok' => 'เวลาอินโดจีน (กรุงเทพ)',
'Asia/Barnaul' => 'เวลารัสเซีย (บาร์เนาว์)',
'Asia/Beirut' => 'เวลายุโรปตะวันออก (เบรุต)',
'Asia/Bishkek' => 'เวลาคีร์กีซสถาน (บิชเคก)',
'Asia/Brunei' => 'เวลาบรูไนดารุสซาลาม',
'Asia/Calcutta' => 'เวลาอินเดีย (โกลกาตา)',
'Asia/Chita' => 'เวลายาคุตสค์ (ชิตา)',
'Asia/Choibalsan' => 'เวลาอูลานบาตอร์ (ชอยบาลซาน)',
'Asia/Colombo' => 'เวลาอินเดีย (โคลัมโบ)',
'Asia/Damascus' => 'เวลายุโรปตะวันออก (ดามัสกัส)',
'Asia/Dhaka' => 'เวลาบังกลาเทศ (ดากา)',
'Asia/Dili' => 'เวลาติมอร์ตะวันออก (ดิลี)',
'Asia/Dubai' => 'เวลากัลฟ์ (ดูไบ)',
'Asia/Dushanbe' => 'เวลาทาจิกิสถาน (ดูชานเบ)',
'Asia/Famagusta' => 'เวลายุโรปตะวันออก (แฟมากุสตา)',
'Asia/Gaza' => 'เวลายุโรปตะวันออก (กาซา)',
'Asia/Hebron' => 'เวลายุโรปตะวันออก (เฮบรอน)',
'Asia/Hong_Kong' => 'เวลาฮ่องกง',
'Asia/Hovd' => 'เวลาฮอฟด์',
'Asia/Irkutsk' => 'เวลาอีร์คุตสค์',
'Asia/Jakarta' => 'เวลาอินโดนีเซียฝั่งตะวันตก (จาการ์ตา)',
'Asia/Jayapura' => 'เวลาอินโดนีเซียฝั่งตะวันออก (จายาปุระ)',
'Asia/Jerusalem' => 'เวลาอิสราเอล (เยรูซาเลม)',
'Asia/Kabul' => 'เวลาอัฟกานิสถาน (คาบูล)',
'Asia/Kamchatka' => 'เวลาคัมชัตคา (คามชัตกา)',
'Asia/Karachi' => 'เวลาปากีสถาน (การาจี)',
'Asia/Katmandu' => 'เวลาเนปาล (กาตมันดุ)',
'Asia/Khandyga' => 'เวลายาคุตสค์ (ฮันดืยกา)',
'Asia/Krasnoyarsk' => 'เวลาครัสโนยาสค์ (ครัสโนยาร์สก์)',
'Asia/Kuala_Lumpur' => 'เวลามาเลเซีย (กัวลาลัมเปอร์)',
'Asia/Kuching' => 'เวลามาเลเซีย (กูชิง)',
'Asia/Kuwait' => 'เวลาอาหรับ (คูเวต)',
'Asia/Macau' => 'เวลาจีน (มาเก๊า)',
'Asia/Magadan' => 'เวลามากาดาน',
'Asia/Makassar' => 'เวลาอินโดนีเซียตอนกลาง (มากัสซาร์)',
'Asia/Manila' => 'เวลาฟิลิปปินส์ (มะนิลา)',
'Asia/Muscat' => 'เวลากัลฟ์ (มัสกัต)',
'Asia/Nicosia' => 'เวลายุโรปตะวันออก (นิโคเซีย)',
'Asia/Novokuznetsk' => 'เวลาครัสโนยาสค์ (โนโวคุซเนตสค์)',
'Asia/Novosibirsk' => 'เวลาโนโวซีบีสค์ (โนโวซิบิร์สก์)',
'Asia/Omsk' => 'เวลาออมสค์ (โอมสก์)',
'Asia/Oral' => 'เวลาคาซัคสถานตะวันตก (ออรัล)',
'Asia/Phnom_Penh' => 'เวลาอินโดจีน (พนมเปญ)',
'Asia/Pontianak' => 'เวลาอินโดนีเซียฝั่งตะวันตก (พอนเทียนัก)',
'Asia/Pyongyang' => 'เวลาเกาหลี (เปียงยาง)',
'Asia/Qatar' => 'เวลาอาหรับ (กาตาร์)',
'Asia/Qostanay' => 'เวลาคาซัคสถานตะวันออก (คอสตาเนย์)',
'Asia/Qyzylorda' => 'เวลาคาซัคสถานตะวันตก (ไคซีลอร์ดา)',
'Asia/Rangoon' => 'เวลาพม่า (ย่างกุ้ง)',
'Asia/Riyadh' => 'เวลาอาหรับ (ริยาร์ด)',
'Asia/Saigon' => 'เวลาอินโดจีน (นครโฮจิมินห์)',
'Asia/Sakhalin' => 'เวลาซาคาลิน',
'Asia/Samarkand' => 'เวลาอุซเบกิสถาน (ซามาร์กานด์)',
'Asia/Seoul' => 'เวลาเกาหลี (โซล)',
'Asia/Shanghai' => 'เวลาจีน (เซี่ยงไฮ้)',
'Asia/Singapore' => 'เวลาสิงคโปร์',
'Asia/Srednekolymsk' => 'เวลามากาดาน (ซเรดเนคโคลิมสก์)',
'Asia/Taipei' => 'เวลาไทเป',
'Asia/Tashkent' => 'เวลาอุซเบกิสถาน (ทาชเคนต์)',
'Asia/Tbilisi' => 'เวลาจอร์เจีย (ทบิลิซิ)',
'Asia/Tehran' => 'เวลาอิหร่าน (เตหะราน)',
'Asia/Thimphu' => 'เวลาภูฏาน (ทิมพู)',
'Asia/Tokyo' => 'เวลาญี่ปุ่น (โตเกียว)',
'Asia/Tomsk' => 'เวลารัสเซีย (ตอมสค์)',
'Asia/Ulaanbaatar' => 'เวลาอูลานบาตอร์',
'Asia/Urumqi' => 'เวลาจีน (อุรุมชี)',
'Asia/Ust-Nera' => 'เวลาวลาดีวอสตอค (อุสต์เนรา)',
'Asia/Vientiane' => 'เวลาอินโดจีน (เวียงจันทน์)',
'Asia/Vladivostok' => 'เวลาวลาดีวอสตอค (วลาดิโวสต็อก)',
'Asia/Yakutsk' => 'เวลายาคุตสค์',
'Asia/Yekaterinburg' => 'เวลาเยคาเตรินบูร์ก (ยีคาเตอรินเบิร์ก)',
'Asia/Yerevan' => 'เวลาอาร์เมเนีย (เยเรวาน)',
'Atlantic/Azores' => 'เวลาอะโซร์ส (อาซอเรส)',
'Atlantic/Bermuda' => 'เวลาแอตแลนติก (เบอร์มิวดา)',
'Atlantic/Canary' => 'เวลายุโรปตะวันตก (คะเนรี)',
'Atlantic/Cape_Verde' => 'เวลาเคปเวิร์ด',
'Atlantic/Faeroe' => 'เวลายุโรปตะวันตก (แฟโร)',
'Atlantic/Madeira' => 'เวลายุโรปตะวันตก (มาเดรา)',
'Atlantic/Reykjavik' => 'เวลามาตรฐานกรีนิช (เรคยาวิก)',
'Atlantic/South_Georgia' => 'เวลาเซาท์จอร์เจีย (เซาท์ จอร์เจีย)',
'Atlantic/St_Helena' => 'เวลามาตรฐานกรีนิช (เซนต์เฮเลนา)',
'Atlantic/Stanley' => 'เวลาหมู่เกาะฟอล์กแลนด์ (สแตนลีย์)',
'Australia/Adelaide' => 'เวลาออสเตรเลียกลาง (แอดิเลด)',
'Australia/Brisbane' => 'เวลาออสเตรเลียตะวันออก (บริสเบน)',
'Australia/Broken_Hill' => 'เวลาออสเตรเลียกลาง (โบรกเคนฮิลล์)',
'Australia/Currie' => 'เวลาออสเตรเลียตะวันออก (คูร์รี)',
'Australia/Darwin' => 'เวลาออสเตรเลียกลาง (ดาร์วิน)',
'Australia/Eucla' => 'เวลาทางตะวันตกตอนกลางของออสเตรเลีย (ยูคลา)',
'Australia/Hobart' => 'เวลาออสเตรเลียตะวันออก (โฮบาร์ต)',
'Australia/Lindeman' => 'เวลาออสเตรเลียตะวันออก (ลินดีแมน)',
'Australia/Lord_Howe' => 'เวลาลอร์ดโฮว์',
'Australia/Melbourne' => 'เวลาออสเตรเลียตะวันออก (เมลเบิร์น)',
'Australia/Perth' => 'เวลาออสเตรเลียตะวันตก (เพิร์ท)',
'Australia/Sydney' => 'เวลาออสเตรเลียตะวันออก (ซิดนีย์)',
'CST6CDT' => 'เวลาตอนกลางในอเมริกาเหนือ',
'EST5EDT' => 'เวลาทางตะวันออกในอเมริกาเหนือ',
'Etc/GMT' => 'เวลามาตรฐานกรีนิช',
'Etc/UTC' => 'เวลาสากลเชิงพิกัด',
'Europe/Amsterdam' => 'เวลายุโรปกลาง (อัมสเตอดัม)',
'Europe/Andorra' => 'เวลายุโรปกลาง (อันดอร์รา)',
'Europe/Astrakhan' => 'เวลามอสโก (แอสตราคาน)',
'Europe/Athens' => 'เวลายุโรปตะวันออก (เอเธนส์)',
'Europe/Belgrade' => 'เวลายุโรปกลาง (เบลเกรด)',
'Europe/Berlin' => 'เวลายุโรปกลาง (เบอร์ลิน)',
'Europe/Bratislava' => 'เวลายุโรปกลาง (บราติสลาวา)',
'Europe/Brussels' => 'เวลายุโรปกลาง (บรัสเซลส์)',
'Europe/Bucharest' => 'เวลายุโรปตะวันออก (บูคาเรส)',
'Europe/Budapest' => 'เวลายุโรปกลาง (บูดาเปส)',
'Europe/Busingen' => 'เวลายุโรปกลาง (บุสซิงเง็น)',
'Europe/Chisinau' => 'เวลายุโรปตะวันออก (คีชีเนา)',
'Europe/Copenhagen' => 'เวลายุโรปกลาง (โคเปนเฮเกน)',
'Europe/Dublin' => 'เวลามาตรฐานกรีนิช (ดับบลิน)',
'Europe/Gibraltar' => 'เวลายุโรปกลาง (ยิบรอลตาร์)',
'Europe/Guernsey' => 'เวลามาตรฐานกรีนิช (เกิร์นซีย์)',
'Europe/Helsinki' => 'เวลายุโรปตะวันออก (เฮลซิงกิ)',
'Europe/Isle_of_Man' => 'เวลามาตรฐานกรีนิช (เกาะแมน)',
'Europe/Istanbul' => 'เวลาตุรกี (อิสตันบูล)',
'Europe/Jersey' => 'เวลามาตรฐานกรีนิช (เจอร์ซีย์)',
'Europe/Kaliningrad' => 'เวลายุโรปตะวันออก (คาลินิงกราด)',
'Europe/Kiev' => 'เวลายุโรปตะวันออก (เคียฟ)',
'Europe/Kirov' => 'เวลารัสเซีย (คิรอฟ)',
'Europe/Lisbon' => 'เวลายุโรปตะวันตก (ลิสบอน)',
'Europe/Ljubljana' => 'เวลายุโรปกลาง (ลูบลิยานา)',
'Europe/London' => 'เวลามาตรฐานกรีนิช (ลอนดอน)',
'Europe/Luxembourg' => 'เวลายุโรปกลาง (ลักเซมเบิร์ก)',
'Europe/Madrid' => 'เวลายุโรปกลาง (มาดริด)',
'Europe/Malta' => 'เวลายุโรปกลาง (มอลตา)',
'Europe/Mariehamn' => 'เวลายุโรปตะวันออก (มารีฮามน์)',
'Europe/Minsk' => 'เวลามอสโก (มินสก์)',
'Europe/Monaco' => 'เวลายุโรปกลาง (โมนาโก)',
'Europe/Moscow' => 'เวลามอสโก',
'Europe/Oslo' => 'เวลายุโรปกลาง (ออสโล)',
'Europe/Paris' => 'เวลายุโรปกลาง (ปารีส)',
'Europe/Podgorica' => 'เวลายุโรปกลาง (พอดกอรีตซา)',
'Europe/Prague' => 'เวลายุโรปกลาง (ปราก)',
'Europe/Riga' => 'เวลายุโรปตะวันออก (ริกา)',
'Europe/Rome' => 'เวลายุโรปกลาง (โรม)',
'Europe/Samara' => 'เวลาซามารา',
'Europe/San_Marino' => 'เวลายุโรปกลาง (ซานมารีโน)',
'Europe/Sarajevo' => 'เวลายุโรปกลาง (ซาราเยโว)',
'Europe/Saratov' => 'เวลามอสโก (ซาราทอฟ)',
'Europe/Simferopol' => 'เวลามอสโก (ซิมเฟอโรโปล)',
'Europe/Skopje' => 'เวลายุโรปกลาง (สโกเปีย)',
'Europe/Sofia' => 'เวลายุโรปตะวันออก (โซเฟีย)',
'Europe/Stockholm' => 'เวลายุโรปกลาง (สตอกโฮล์ม)',
'Europe/Tallinn' => 'เวลายุโรปตะวันออก (ทาลลินน์)',
'Europe/Tirane' => 'เวลายุโรปกลาง (ติรานา)',
'Europe/Ulyanovsk' => 'เวลามอสโก (อะลิยานอฟ)',
'Europe/Uzhgorod' => 'เวลายุโรปตะวันออก (อัซโกร็อด)',
'Europe/Vaduz' => 'เวลายุโรปกลาง (วาดุซ)',
'Europe/Vatican' => 'เวลายุโรปกลาง (วาติกัน)',
'Europe/Vienna' => 'เวลายุโรปกลาง (เวียนนา)',
'Europe/Vilnius' => 'เวลายุโรปตะวันออก (วิลนีอุส)',
'Europe/Volgograd' => 'เวลาวอลโกกราด',
'Europe/Warsaw' => 'เวลายุโรปกลาง (วอร์ซอ)',
'Europe/Zagreb' => 'เวลายุโรปกลาง (ซาเกร็บ)',
'Europe/Zaporozhye' => 'เวลายุโรปตะวันออก (ซาโปโรซี)',
'Europe/Zurich' => 'เวลายุโรปกลาง (ซูริค)',
'Indian/Antananarivo' => 'เวลาแอฟริกาตะวันออก (อันตานานาริโว)',
'Indian/Chagos' => 'เวลามหาสมุทรอินเดีย (ชากัส)',
'Indian/Christmas' => 'เวลาเกาะคริสต์มาส',
'Indian/Cocos' => 'เวลาหมู่เกาะโคโคส',
'Indian/Comoro' => 'เวลาแอฟริกาตะวันออก (โคโมโร)',
'Indian/Kerguelen' => 'เวลาเฟรนช์เซาเทิร์นและแอนตาร์กติก (แกร์เกอลอง)',
'Indian/Mahe' => 'เวลาเซเชลส์ (มาเอ)',
'Indian/Maldives' => 'เวลามัลดีฟส์',
'Indian/Mauritius' => 'เวลามอริเชียส',
'Indian/Mayotte' => 'เวลาแอฟริกาตะวันออก (มาโยเต)',
'Indian/Reunion' => 'เวลาเรอูนียง',
'MST7MDT' => 'เวลาแถบภูเขาในอเมริกาเหนือ',
'PST8PDT' => 'เวลาแปซิฟิกในอเมริกาเหนือ',
'Pacific/Apia' => 'เวลาอาปีอา',
'Pacific/Auckland' => 'เวลานิวซีแลนด์ (โอคแลนด์)',
'Pacific/Bougainville' => 'เวลาปาปัวนิวกินี (บูเกนวิลล์)',
'Pacific/Chatham' => 'เวลาแชทัม',
'Pacific/Easter' => 'เวลาเกาะอีสเตอร์',
'Pacific/Efate' => 'เวลาวานูอาตู (เอฟาเต)',
'Pacific/Enderbury' => 'เวลาหมู่เกาะฟินิกซ์ (เอนเดอร์เบอรี)',
'Pacific/Fakaofo' => 'เวลาโตเกเลา (ฟาเคาโฟ)',
'Pacific/Fiji' => 'เวลาฟิจิ',
'Pacific/Funafuti' => 'เวลาตูวาลู (ฟูนะฟูตี)',
'Pacific/Galapagos' => 'เวลากาลาปาโกส',
'Pacific/Gambier' => 'เวลาแกมเบียร์',
'Pacific/Guadalcanal' => 'เวลาหมู่เกาะโซโลมอน (กัวดัลคานัล)',
'Pacific/Guam' => 'เวลาชามอร์โร (กวม)',
'Pacific/Honolulu' => 'เวลาฮาวาย-อะลูเชียน (โฮโนลูลู)',
'Pacific/Johnston' => 'เวลาฮาวาย-อะลูเชียน (จอห์นสตัน)',
'Pacific/Kiritimati' => 'เวลาหมู่เกาะไลน์ (คิริทิมาตี)',
'Pacific/Kosrae' => 'เวลาคอสไร',
'Pacific/Kwajalein' => 'เวลาหมู่เกาะมาร์แชลล์ (ควาจาเลน)',
'Pacific/Majuro' => 'เวลาหมู่เกาะมาร์แชลล์ (มาจูโร)',
'Pacific/Marquesas' => 'เวลามาร์เคซัส',
'Pacific/Midway' => 'เวลาซามัว (มิดเวย์)',
'Pacific/Nauru' => 'เวลานาอูรู',
'Pacific/Niue' => 'เวลานีอูเอ',
'Pacific/Norfolk' => 'เวลาเกาะนอร์ฟอล์ก',
'Pacific/Noumea' => 'เวลานิวแคลิโดเนีย (นูเมอา)',
'Pacific/Pago_Pago' => 'เวลาซามัว (ปาโก ปาโก)',
'Pacific/Palau' => 'เวลาปาเลา',
'Pacific/Pitcairn' => 'เวลาพิตแคร์น',
'Pacific/Ponape' => 'เวลาโปนาเป',
'Pacific/Port_Moresby' => 'เวลาปาปัวนิวกินี (พอร์ตมอร์สบี)',
'Pacific/Rarotonga' => 'เวลาหมู่เกาะคุก (ราโรตองกา)',
'Pacific/Saipan' => 'เวลาชามอร์โร (ไซปัน)',
'Pacific/Tahiti' => 'เวลาตาฮีตี',
'Pacific/Tarawa' => 'เวลาหมู่เกาะกิลเบิร์ต (ตาระวา)',
'Pacific/Tongatapu' => 'เวลาตองกา (ตองกาตาปู)',
'Pacific/Truk' => 'เวลาชุก (ทรัก)',
'Pacific/Wake' => 'เวลาเกาะเวก',
'Pacific/Wallis' => 'เวลาวาลลิสและฟุตูนา',
],
'Meta' => [
],
];
| mit |
jridgewell/babel | packages/babel-parser/test/fixtures/es2015/modules/invalid-escape-export-as/input.js | 23 | export { X \u0061s Y }
| mit |
babel/babel | packages/babel-parser/test/fixtures/es2015/class/invalid-escape-static/input.js | 31 | class X { st\u0061tic y() {} }
| mit |
oxaudo/force | src/v2/Components/UserSettings/TwoFactorAuthentication/Components/BackupSecondFactor/BackupSecondFactorModalContent.tsx | 2247 | import { BorderBoxProps, Box, Flex, Sans } from "@artsy/palette"
import { SystemQueryRenderer as QueryRenderer } from "v2/Artsy/Relay/SystemQueryRenderer"
import React from "react"
import { createFragmentContainer, graphql } from "react-relay"
import { BackupSecondFactorModalContent_me } from "v2/__generated__/BackupSecondFactorModalContent_me.graphql"
import { BackupSecondFactorModalContentQuery } from "v2/__generated__/BackupSecondFactorModalContentQuery.graphql"
import { useSystemContext } from "v2/Artsy"
import { renderWithLoadProgress } from "v2/Artsy/Relay/renderWithLoadProgress"
interface BackupSecondFactorModalContentProps extends BorderBoxProps {
me: BackupSecondFactorModalContent_me
}
export const BackupSecondFactorModalContent: React.FC<BackupSecondFactorModalContentProps> = props => {
const { me } = props
return (
<Box minHeight="280px">
<Sans size="3" color="black60">
Store these two-factor recovery codes in a safe place. You can use these
one-time codes to access your account.
</Sans>
<Flex mt={3} flexDirection="row" flexWrap="wrap">
{me.backupSecondFactors.map((factor, index) => (
<Box width="50%" key={index}>
<Sans size="6" color="black60" textAlign="center" py={0.5}>
{factor.code}
</Sans>
</Box>
))}
</Flex>
</Box>
)
}
export const ModalContentFragmentContainer = createFragmentContainer(
BackupSecondFactorModalContent,
{
me: graphql`
fragment BackupSecondFactorModalContent_me on Me {
backupSecondFactors: secondFactors(kinds: [backup]) {
... on BackupSecondFactor {
code
}
}
}
`,
}
)
export const BackupSecondFactorModalContentQueryRenderer = () => {
const { relayEnvironment } = useSystemContext()
return (
<QueryRenderer<BackupSecondFactorModalContentQuery>
environment={relayEnvironment}
variables={{}}
query={graphql`
query BackupSecondFactorModalContentQuery @raw_response_type {
me {
...BackupSecondFactorModalContent_me
}
}
`}
render={renderWithLoadProgress(ModalContentFragmentContainer)}
/>
)
}
| mit |
happy5214/pywikibot-core | pywikibot/bot_choice.py | 10733 | # -*- coding: utf-8 -*-
"""Choices for input_choice."""
#
# (C) Pywikibot team, 2015-2016
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, unicode_literals
__version__ = '$Id$'
import pywikibot
class Option(object):
"""
A basic option for input_choice.
The following methods need to be implemented:
* format(default=None)
* result(value)
* test(value)
The methods C{test} and C{handled} are in such a relationship that when
C{handled} returns itself that C{test} must return True for that value. So
if C{test} returns False C{handled} may not return itself but it may return
not None.
Also C{result} only returns a sensible value when C{test} returns True for
the same value.
"""
def __init__(self, stop=True):
"""Constructor."""
super(Option, self).__init__()
self._stop = stop
@staticmethod
def formatted(text, options, default=None):
"""Create a text with the options formatted into it."""
formatted_options = []
for option in options:
formatted_options.append(option.format(default=default))
return '{0} ({1})'.format(text, ', '.join(formatted_options))
@property
def stop(self):
"""Return whether this option stops asking."""
return self._stop
def handled(self, value):
"""
Return the Option object that applies to the given value.
If this Option object doesn't know which applies it returns None.
"""
if self.test(value):
return self
else:
return None
def format(self, default=None):
"""Return a formatted string for that option."""
raise NotImplementedError()
def result(self, value):
"""Return the actual value which is associated by the given one."""
raise NotImplementedError()
def test(self, value):
"""Return True whether this option applies."""
raise NotImplementedError()
class OutputOption(Option):
"""An option that never stops and can output on each question."""
before_question = False
@property
def stop(self):
"""Never stop asking."""
return False
def result(self, value):
"""Just output the value."""
self.output()
def output(self):
"""Output a string when selected and possibily before the question."""
raise NotImplementedError()
class StandardOption(Option):
"""An option with a description and shortcut and returning the shortcut."""
def __init__(self, option, shortcut, stop=True):
"""Constructor."""
super(StandardOption, self).__init__(stop)
self.option = option
self.shortcut = shortcut.lower()
def format(self, default=None):
"""Return a formatted string for that option."""
index = self.option.lower().find(self.shortcut)
shortcut = self.shortcut
if self.shortcut == default:
shortcut = self.shortcut.upper()
if index >= 0:
return '{0}[{1}]{2}'.format(self.option[:index], shortcut,
self.option[index + len(self.shortcut):])
else:
return '{0} [{1}]'.format(self.option, shortcut)
def result(self, value):
"""Return the lowercased shortcut."""
return self.shortcut
def test(self, value):
"""Return True whether this option applies."""
return (self.shortcut.lower() == value.lower() or
self.option.lower() == value.lower())
class OutputProxyOption(OutputOption, StandardOption):
"""An option which calls output of the given output class."""
def __init__(self, option, shortcut, output):
"""Create a new option for the given sequence."""
super(OutputProxyOption, self).__init__(option, shortcut)
self._outputter = output
def output(self):
"""Output the contents."""
self._outputter.output()
class NestedOption(OutputOption, StandardOption):
"""
An option containing other options.
It will return True in test if this option applies but False if a sub
option applies while handle returns the sub option.
"""
def __init__(self, option, shortcut, description, options):
"""Constructor."""
super(NestedOption, self).__init__(option, shortcut, False)
self.description = description
self.options = options
def format(self, default=None):
"""Return a formatted string for that option."""
self._output = Option.formatted(self.description, self.options)
return super(NestedOption, self).format(default=default)
def handled(self, value):
"""Return itself if it applies or the appling sub option."""
for option in self.options:
handled = option.handled(value)
if handled is not None:
return handled
else:
return super(NestedOption, self).handled(value)
def output(self):
"""Output the suboptions."""
pywikibot.output(self._output)
class ContextOption(OutputOption, StandardOption):
"""An option to show more and more context."""
def __init__(self, option, shortcut, text, context, delta=100, start=0, end=0):
"""Constructor."""
super(ContextOption, self).__init__(option, shortcut, False)
self.text = text
self.context = context
self.delta = delta
self.start = start
self.end = end
def result(self, value):
"""Add the delta to the context and output it."""
self.context += self.delta
super(ContextOption, self).result(value)
def output(self):
"""Output the context."""
start = max(0, self.start - self.context)
end = min(len(self.text), self.end + self.context)
self.output_range(start, end)
def output_range(self, start_context, end_context):
"""Output a section from the text."""
pywikibot.output(self.text[start_context:end_context])
class IntegerOption(Option):
"""An option allowing a range of integers."""
def __init__(self, minimum=1, maximum=None, prefix=''):
"""Constructor."""
super(IntegerOption, self).__init__()
if not ((minimum is None or isinstance(minimum, int)) and
(maximum is None or isinstance(maximum, int))):
raise ValueError(
'The minimum and maximum parameters must be int or None.')
if minimum is not None and maximum is not None and minimum > maximum:
raise ValueError('The minimum must be lower than the maximum.')
self._min = minimum
self._max = maximum
self.prefix = prefix
def test(self, value):
"""Return whether the value is an int and in the specified range."""
try:
value = self.parse(value)
except ValueError:
return False
else:
return ((self.minimum is None or value >= self.minimum) and
(self.maximum is None or value <= self.maximum))
@property
def minimum(self):
"""Return the lower bound of the range of allowed values."""
return self._min
@property
def maximum(self):
"""Return the upper bound of the range of allowed values."""
return self._max
def format(self, default=None):
"""Return a formatted string showing the range."""
if default is not None and self.test(default):
value = self.parse(default)
default = '[{0}]'.format(value)
else:
value = None
default = ''
if self.minimum is not None or self.maximum is not None:
if default and value == self.minimum:
minimum = default
default = ''
else:
minimum = '' if self.minimum is None else str(self.minimum)
if default and value == self.maximum:
maximum = default
default = ''
else:
maximum = '' if self.maximum is None else str(self.maximum)
default = '-{0}-'.format(default) if default else '-'
if self.minimum == self.maximum:
rng = minimum
else:
rng = minimum + default + maximum
else:
rng = 'any' + default
return '{0}<number> [{1}]'.format(self.prefix, rng)
def parse(self, value):
"""Return integer from value with prefix removed."""
if value.lower().startswith(self.prefix.lower()):
return int(value[len(self.prefix):])
else:
raise ValueError('Value does not start with prefix')
def result(self, value):
"""Return the value converted into int."""
return (self.prefix, self.parse(value))
class ListOption(IntegerOption):
"""An option to select something from a list."""
def __init__(self, sequence, prefix=''):
"""Constructor."""
self._list = sequence
try:
super(ListOption, self).__init__(1, self.maximum, prefix)
except ValueError:
raise ValueError('The sequence is empty.')
del self._max
def format(self, default=None):
"""Return a string showing the range."""
if not self._list:
raise ValueError('The sequence is empty.')
else:
return super(ListOption, self).format(default=default)
@property
def maximum(self):
"""Return the maximum value."""
return len(self._list)
def result(self, value):
"""Return a tuple with the prefix and selected value."""
return (self.prefix, self._list[self.parse(value) - 1])
class HighlightContextOption(ContextOption):
"""Show the original region highlighted."""
def output_range(self, start, end):
"""Show normal context with a red center region."""
pywikibot.output(self.text[start:self.start] + '\03{lightred}' +
self.text[self.start:self.end] + '\03{default}' +
self.text[self.end:end])
class ChoiceException(StandardOption, Exception):
"""A choice for input_choice which result in this exception."""
def result(self, value):
"""Return itself to raise the exception."""
return self
class QuitKeyboardInterrupt(ChoiceException, KeyboardInterrupt):
"""The user has cancelled processing at a prompt."""
def __init__(self):
"""Constructor using the 'quit' ('q') in input_choice."""
super(QuitKeyboardInterrupt, self).__init__('quit', 'q')
| mit |
sottosviluppo/elcodi | src/Elcodi/Component/StateTransitionMachine/Exception/StateNotReachableException.php | 604 | <?php
/*
* This file is part of the Elcodi package.
*
* Copyright (c) 2014-2016 Elcodi Networks S.L.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* Feel free to edit as you please, and have fun.
*
* @author Marc Morera <yuhu@mmoreram.com>
* @author Aldo Chiecchia <zimage@tiscali.it>
* @author Elcodi Team <tech@elcodi.com>
*/
namespace Elcodi\Component\StateTransitionMachine\Exception;
use Exception;
/**
* Class StateNotReachableException.
*/
class StateNotReachableException extends Exception
{
}
| mit |
zrusev/SoftwareUniversity2016 | 16. Databases Advanced - Entity Framework - Feb 2019/07. Advanced Quering/BookShop/BookShop.Data/EntityConfiguration/BookConfiguration.cs | 823 | namespace BookShop.Data.EntityConfiguration
{
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Models;
internal class BookConfiguration : IEntityTypeConfiguration<Book>
{
public void Configure(EntityTypeBuilder<Book> builder)
{
builder.HasKey(e => e.BookId);
builder.Property(e => e.Title)
.IsRequired()
.HasMaxLength(50);
builder.Property(e => e.Description)
.IsRequired()
.HasMaxLength(1000);
builder.Property(e => e.ReleaseDate)
.IsRequired(false);
builder.HasOne(e => e.Author)
.WithMany(a => a.Books)
.HasForeignKey(e => e.AuthorId);
}
}
}
| mit |
unconed/three.js | src/math/Euler.js | 5245 | /**
* @author mrdoob / http://mrdoob.com/
* @author WestLangley / http://github.com/WestLangley
* @author bhouston / http://clara.io
*/
THREE.Euler = function ( x, y, z, order ) {
this._x = x || 0;
this._y = y || 0;
this._z = z || 0;
this._order = order || THREE.Euler.DefaultOrder;
};
THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
THREE.Euler.DefaultOrder = 'XYZ';
THREE.Euler.prototype = {
constructor: THREE.Euler,
get x () {
return this._x;
},
set x ( value ) {
this._x = value;
this.onChangeCallback();
},
get y () {
return this._y;
},
set y ( value ) {
this._y = value;
this.onChangeCallback();
},
get z () {
return this._z;
},
set z ( value ) {
this._z = value;
this.onChangeCallback();
},
get order () {
return this._order;
},
set order ( value ) {
this._order = value;
this.onChangeCallback();
},
set: function ( x, y, z, order ) {
this._x = x;
this._y = y;
this._z = z;
this._order = order || this._order;
this.onChangeCallback();
return this;
},
clone: function () {
return new this.constructor( this._x, this._y, this._z, this._order );
},
copy: function ( euler ) {
this._x = euler._x;
this._y = euler._y;
this._z = euler._z;
this._order = euler._order;
this.onChangeCallback();
return this;
},
setFromRotationMatrix: function ( m, order, update ) {
var clamp = THREE.Math.clamp;
// assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
var te = m.elements;
var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
order = order || this._order;
if ( order === 'XYZ' ) {
this._y = Math.asin( clamp( m13, - 1, 1 ) );
if ( Math.abs( m13 ) < 0.99999 ) {
this._x = Math.atan2( - m23, m33 );
this._z = Math.atan2( - m12, m11 );
} else {
this._x = Math.atan2( m32, m22 );
this._z = 0;
}
} else if ( order === 'YXZ' ) {
this._x = Math.asin( - clamp( m23, - 1, 1 ) );
if ( Math.abs( m23 ) < 0.99999 ) {
this._y = Math.atan2( m13, m33 );
this._z = Math.atan2( m21, m22 );
} else {
this._y = Math.atan2( - m31, m11 );
this._z = 0;
}
} else if ( order === 'ZXY' ) {
this._x = Math.asin( clamp( m32, - 1, 1 ) );
if ( Math.abs( m32 ) < 0.99999 ) {
this._y = Math.atan2( - m31, m33 );
this._z = Math.atan2( - m12, m22 );
} else {
this._y = 0;
this._z = Math.atan2( m21, m11 );
}
} else if ( order === 'ZYX' ) {
this._y = Math.asin( - clamp( m31, - 1, 1 ) );
if ( Math.abs( m31 ) < 0.99999 ) {
this._x = Math.atan2( m32, m33 );
this._z = Math.atan2( m21, m11 );
} else {
this._x = 0;
this._z = Math.atan2( - m12, m22 );
}
} else if ( order === 'YZX' ) {
this._z = Math.asin( clamp( m21, - 1, 1 ) );
if ( Math.abs( m21 ) < 0.99999 ) {
this._x = Math.atan2( - m23, m22 );
this._y = Math.atan2( - m31, m11 );
} else {
this._x = 0;
this._y = Math.atan2( m13, m33 );
}
} else if ( order === 'XZY' ) {
this._z = Math.asin( - clamp( m12, - 1, 1 ) );
if ( Math.abs( m12 ) < 0.99999 ) {
this._x = Math.atan2( m32, m22 );
this._y = Math.atan2( m13, m11 );
} else {
this._x = Math.atan2( - m23, m33 );
this._y = 0;
}
} else {
console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order );
}
this._order = order;
if ( update !== false ) this.onChangeCallback();
return this;
},
setFromQuaternion: function () {
var matrix;
return function ( q, order, update ) {
if ( matrix === undefined ) matrix = new THREE.Matrix4();
matrix.makeRotationFromQuaternion( q );
this.setFromRotationMatrix( matrix, order, update );
return this;
};
}(),
setFromVector3: function ( v, order ) {
return this.set( v.x, v.y, v.z, order || this._order );
},
reorder: function () {
// WARNING: this discards revolution information -bhouston
var q = new THREE.Quaternion();
return function ( newOrder ) {
q.setFromEuler( this );
this.setFromQuaternion( q, newOrder );
};
}(),
equals: function ( euler ) {
return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
},
fromArray: function ( array ) {
this._x = array[ 0 ];
this._y = array[ 1 ];
this._z = array[ 2 ];
if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
this.onChangeCallback();
return this;
},
toArray: function ( array, offset ) {
if ( array === undefined ) array = [];
if ( offset === undefined ) offset = 0;
array[ offset ] = this._x;
array[ offset + 1 ] = this._y;
array[ offset + 2 ] = this._z;
array[ offset + 3 ] = this._order;
return array;
},
toVector3: function ( optionalResult ) {
if ( optionalResult ) {
return optionalResult.set( this._x, this._y, this._z );
} else {
return new THREE.Vector3( this._x, this._y, this._z );
}
},
onChange: function ( callback ) {
this.onChangeCallback = callback;
return this;
},
onChangeCallback: function () {}
};
| mit |
DARKRPISSHITFIXTHISUPDATE/DarkRP | gamemode/modules/hitmenu/sh_init.lua | 3128 | local plyMeta = FindMetaTable("Player")
local hitmanTeams = {}
function plyMeta:isHitman()
return hitmanTeams[self:Team()]
end
function plyMeta:hasHit()
return self:getDarkRPVar("hasHit") or false
end
function plyMeta:getHitTarget()
return self:getDarkRPVar("hitTarget")
end
function plyMeta:getHitPrice()
return self:getDarkRPVar("hitPrice") or GAMEMODE.Config.minHitPrice
end
function DarkRP.addHitmanTeam(job)
if not job or not RPExtraTeams[job] then return end
if DarkRP.DARKRP_LOADING and DarkRP.disabledDefaults["hitmen"][RPExtraTeams[job].command] then return end
hitmanTeams[job] = true
end
DarkRP.getHitmanTeams = fp{fn.Id, hitmanTeams}
function DarkRP.hooks:canRequestHit(hitman, customer, target, price)
if not hitman:isHitman() then return false, DarkRP.getPhrase("player_not_hitman") end
if customer:GetPos():Distance(hitman:GetPos()) > GAMEMODE.Config.minHitDistance then return false, DarkRP.getPhrase("distance_too_big") end
if hitman == target then return false, DarkRP.getPhrase("hitman_no_suicide") end
if hitman == customer then return false, DarkRP.getPhrase("hitman_no_self_order") end
if not customer:canAfford(price) then return false, DarkRP.getPhrase("cant_afford", DarkRP.getPhrase("hit")) end
if price < GAMEMODE.Config.minHitPrice then return false, DarkRP.getPhrase("price_too_low") end
if hitman:hasHit() then return false, DarkRP.getPhrase("hitman_already_has_hit") end
if IsValid(target) and ((target:getDarkRPVar("lastHitTime") or -GAMEMODE.Config.hitTargetCooldown) > CurTime() - GAMEMODE.Config.hitTargetCooldown) then return false, DarkRP.getPhrase("hit_target_recently_killed_by_hit") end
if IsValid(customer) and ((customer.lastHitAccepted or -GAMEMODE.Config.hitCustomerCooldown) > CurTime() - GAMEMODE.Config.hitCustomerCooldown) then return false, DarkRP.getPhrase("customer_recently_bought_hit") end
return true
end
hook.Add("onJobRemoved", "hitmenuUpdate", function(i, job)
hitmanTeams[i] = nil
end)
/*---------------------------------------------------------------------------
DarkRPVars
---------------------------------------------------------------------------*/
DarkRP.registerDarkRPVar("hasHit", net.WriteBit, fn.Compose{tobool, net.ReadBit})
DarkRP.registerDarkRPVar("hitTarget", net.WriteEntity, net.ReadEntity)
DarkRP.registerDarkRPVar("hitPrice", fn.Curry(fn.Flip(net.WriteInt), 2)(32), fn.Partial(net.ReadInt, 32))
DarkRP.registerDarkRPVar("lastHitTime", fn.Curry(fn.Flip(net.WriteInt), 2)(32), fn.Partial(net.ReadInt, 32))
/*---------------------------------------------------------------------------
Chat commands
---------------------------------------------------------------------------*/
DarkRP.declareChatCommand{
command = "hitprice",
description = "Set the price of your hits",
condition = plyMeta.isHitman,
delay = 10
}
DarkRP.declareChatCommand{
command = "requesthit",
description = "Request a hit from the player you're looking at",
delay = 5,
condition = fn.Compose{fn.Not, fn.Null, fn.Curry(fn.Filter, 2)(plyMeta.isHitman), player.GetAll}
}
| mit |
uublive/ZenBot | node_modules/ltx/lib/sax_easysax.js | 1225 | var util = require('util');
var events = require('events');
var Easysax = require('easysax');
/**
* FIXME: This SAX parser cannot be pushed to!
*/
var SaxEasysax = module.exports = function SaxEasysax() {
events.EventEmitter.call(this);
this.parser = new Easysax();
var that = this;
this.parser.on('startNode', function(name, attr, uq, str, tagend) {
attr = attr();
for(var k in attr)
if (attr.hasOwnProperty(k)) {
attr[k] = uq(attr[k]);
}
that.emit('startElement', name, attr);
});
this.parser.on('endNode', function(name, uq, str, tagstart) {
that.emit('endElement', name);
});
this.parser.on('textNode', function(str, uq) {
that.emit('text', uq(str));
});
this.parser.on('cdata', function(str) {
that.emit('text', str);
});
this.parser.on('error', function(e) {
that.emit('error', e);
});
// TODO: other events, esp. entityDecl (billion laughs!)
};
util.inherits(SaxEasysax, events.EventEmitter);
SaxEasysax.prototype.write = function(data) {
if (typeof data !== 'string')
data = data.toString();
this.parser.parse(data);
};
SaxEasysax.prototype.end = function(data) {
if (data)
this.write(data);
};
| mit |
demenvil/starter-public-edition-4 | platform/common/language/french/rest_controller_lang.php | 805 | <?php
/*
* French language
*/
$lang['text_rest_invalid_api_key'] = 'Invalid API key %s'; // %s is the REST API key
$lang['text_rest_invalid_credentials'] = 'Invalid credentials';
$lang['text_rest_ip_denied'] = 'IP denied';
$lang['text_rest_ip_unauthorized'] = 'IP unauthorized';
$lang['text_rest_unauthorized'] = 'Unauthorized';
$lang['text_rest_ajax_only'] = 'Only AJAX requests are allowed';
$lang['text_rest_api_key_unauthorized'] = 'This API key does not have access to the requested controller';
$lang['text_rest_api_key_permissions'] = 'This API key does not have enough permissions';
$lang['text_rest_api_key_time_limit'] = 'This API key has reached the time limit for this method';
$lang['text_rest_unknown_method'] = 'Unknown method';
$lang['text_rest_unsupported'] = 'Unsupported protocol';
| mit |
raasakh/bardcoin.exe | src/rpcdump.cpp | 2962 | // Copyright (c) 2009-2012 Bitcoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "init.h" // for pwalletMain
#include "bitcoinrpc.h"
#include "ui_interface.h"
#include "base58.h"
#include <boost/lexical_cast.hpp>
#define printf OutputDebugStringF
using namespace json_spirit;
using namespace std;
class CTxDump
{
public:
CBlockIndex *pindex;
int64 nValue;
bool fSpent;
CWalletTx* ptx;
int nOut;
CTxDump(CWalletTx* ptx = NULL, int nOut = -1)
{
pindex = NULL;
nValue = 0;
fSpent = false;
this->ptx = ptx;
this->nOut = nOut;
}
};
Value importprivkey(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 3)
throw runtime_error(
"importprivkey <freicoinprivkey> [label] [rescan=true]\n"
"Adds a private key (as returned by dumpprivkey) to your wallet.");
string strSecret = params[0].get_str();
string strLabel = "";
if (params.size() > 1)
strLabel = params[1].get_str();
// Whether to perform rescan after import
bool fRescan = true;
if (params.size() > 2)
fRescan = params[2].get_bool();
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(strSecret);
if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
CKey key;
bool fCompressed;
CSecret secret = vchSecret.GetSecret(fCompressed);
key.SetSecret(secret, fCompressed);
CKeyID vchAddress = key.GetPubKey().GetID();
{
LOCK2(cs_main, pwalletMain->cs_wallet);
pwalletMain->MarkDirty();
pwalletMain->SetAddressBookName(vchAddress, strLabel);
if (!pwalletMain->AddKey(key))
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet");
if (fRescan) {
pwalletMain->ScanForWalletTransactions(pindexGenesisBlock, true);
pwalletMain->ReacceptWalletTransactions();
}
}
return Value::null;
}
Value dumpprivkey(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"dumpprivkey <freicoinaddress>\n"
"Reveals the private key corresponding to <freicoinaddress>.");
string strAddress = params[0].get_str();
CBitcoinAddress address;
if (!address.SetString(strAddress))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Freicoin address");
CKeyID keyID;
if (!address.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key");
CSecret vchSecret;
bool fCompressed;
if (!pwalletMain->GetSecret(keyID, vchSecret, fCompressed))
throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known");
return CBitcoinSecret(vchSecret, fCompressed).ToString();
}
| mit |
Langdaa/Instagram-clone | ajaxify/profile_sections/recommends.php | 1337 | <?php include '../../config/declare.php'; ?>
<!-- a universal file that has all the classes included -->
<?php include '../../config/classesGetter.php'; ?>
<!-- creating objects -->
<?php
$universal = new universal;
$tags = new tags;
$avatar = new Avatar;
$follow = new follow_system;
$general = new general;
$post = new post;
$mutual = new mutual;
$recommend = new recommend;
?>
<?php
$get_id = $universal->getIdFromGet($_GET['u']);
if (isset($_SESSION['id'])) {
$session_id = $_SESSION['id'];
}
?>
<div class="senapati pro_senapati">
<div class="m_div">
<?php
if ($universal->MeOrNot($get_id)){
$recommend->profileRecommends($get_id);
} else if ($universal->MeOrNot($get_id) == false) {
echo "<div class='home_last_mssg pro_last_mssg'><img src='". DIR ."/images/needs/large.jpg'>
<span>You should recommend yourself the most</span></div>";
}
?>
</div>
</div>
<script type="text/javascript">
LinkIndicator('profile');
$('.m_on').on('mouseover', function(e){
$(this).find('.recommend_time').show();
}).on('mouseleave', function(e){
$(this).find('.recommend_time').hide();
});
$('.follow').follow({
update: true
});
$('.unfollow').unfollow({
update: true
});
</script>
| mit |
nichesuch/AirOrche | mp4v2-2.0.0/src/atom_tx3g.cpp | 2898 | /*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is MPEG4IP.
*
* The Initial Developer of the Original Code is Cisco Systems Inc.
* Portions created by Cisco Systems Inc. are
* Copyright (C) Cisco Systems Inc. 2001. All Rights Reserved.
*/
#include "src/impl.h"
namespace mp4v2 {
namespace impl {
///////////////////////////////////////////////////////////////////////////////
MP4Tx3gAtom::MP4Tx3gAtom(MP4File &file)
: MP4Atom(file, "tx3g")
{
AddReserved(*this, "reserved1", 4); /* 0 */
AddReserved(*this, "reserved2", 2); /* 1 */
AddProperty(new MP4Integer16Property(*this, "dataReferenceIndex"));/* 2 */
AddProperty(new MP4Integer32Property(*this, "displayFlags")); /* 3 */
AddProperty(new MP4Integer8Property(*this, "horizontalJustification")); /* 4 */
AddProperty(new MP4Integer8Property(*this, "verticalJustification")); /* 5 */
AddProperty(new MP4Integer8Property(*this, "bgColorRed")); /* 6 */
AddProperty(new MP4Integer8Property(*this, "bgColorGreen")); /* 7 */
AddProperty(new MP4Integer8Property(*this, "bgColorBlue")); /* 8 */
AddProperty(new MP4Integer8Property(*this, "bgColorAlpha")); /* 9 */
AddProperty(new MP4Integer16Property(*this, "defTextBoxTop")); /* 10 */
AddProperty(new MP4Integer16Property(*this, "defTextBoxLeft")); /* 11 */
AddProperty(new MP4Integer16Property(*this, "defTextBoxBottom")); /* 12 */
AddProperty(new MP4Integer16Property(*this, "defTextBoxRight")); /* 13 */
AddProperty(new MP4Integer16Property(*this, "startChar")); /* 14 */
AddProperty(new MP4Integer16Property(*this, "endChar")); /* 15 */
AddProperty(new MP4Integer16Property(*this, "fontID")); /* 16 */
AddProperty(new MP4Integer8Property(*this, "fontFace")); /* 17 */
AddProperty(new MP4Integer8Property(*this, "fontSize")); /* 18 */
AddProperty(new MP4Integer8Property(*this, "fontColorRed")); /* 19 */
AddProperty(new MP4Integer8Property(*this, "fontColorGreen")); /* 20 */
AddProperty(new MP4Integer8Property(*this, "fontColorBlue")); /* 21 */
AddProperty(new MP4Integer8Property(*this, "fontColorAlpha")); /* 22 */
ExpectChildAtom("ftab", Optional, Many);
}
void MP4Tx3gAtom::Generate()
{
// generate children
MP4Atom::Generate();
((MP4Integer16Property*)m_pProperties[2])->SetValue(1);
}
///////////////////////////////////////////////////////////////////////////////
}
} // namespace mp4v2::impl
| mit |
su20yu1919/cwa-portal | node_modules/bytebuffer/src/types/strings/utf8string.js | 6365 | //? if (UTF8STRING && UTF8) {
// types/strings/utf8string
/**
* Metrics representing number of UTF8 characters. Evaluates to `c`.
* @type {string}
* @const
* @expose
*/
ByteBuffer.METRICS_CHARS = 'c';
/**
* Metrics representing number of bytes. Evaluates to `b`.
* @type {string}
* @const
* @expose
*/
ByteBuffer.METRICS_BYTES = 'b';
/**
* Writes an UTF8 encoded string.
* @param {string} str String to write
* @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} if omitted.
* @returns {!ByteBuffer|number} this if offset is omitted, else the actual number of bytes written.
* @expose
*/
ByteBufferPrototype.writeUTF8String = function(str, offset) {
//? RELATIVE();
if (!this.noAssert) {
//? ASSERT_OFFSET();
}
var k;
//? if (NODE) {
k = Buffer.byteLength(str, "utf8");
//? ENSURE_CAPACITY('k');
offset += this.buffer.write(str, offset, k, "utf8");
if (relative) {
this.offset = offset;
return this;
}
return k;
//? } else {
var start = offset;
k = utfx.calculateUTF16asUTF8(stringSource(str))[1];
//? ENSURE_CAPACITY('k');
utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
this.view.setUint8(offset++, b);
}.bind(this));
if (relative) {
this.offset = offset;
return this;
}
return offset - start;
//? }
};
//? if (ALIASES) {
/**
* Writes an UTF8 encoded string. This is an alias of {@link ByteBuffer#writeUTF8String}.
* @function
* @param {string} str String to write
* @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} if omitted.
* @returns {!ByteBuffer|number} this if offset is omitted, else the actual number of bytes written.
* @expose
*/
ByteBufferPrototype.writeString = ByteBufferPrototype.writeUTF8String;
//? }
/**
* Calculates the number of UTF8 characters of a string. JavaScript itself uses UTF-16, so that a string's
* `length` property does not reflect its actual UTF8 size if it contains code points larger than 0xFFFF.
* @function
* @param {string} str String to calculate
* @returns {number} Number of UTF8 characters
* @expose
*/
ByteBuffer.calculateUTF8Chars = function(str) {
return utfx.calculateUTF16asUTF8(stringSource(str))[0];
};
/**
* Calculates the number of UTF8 bytes of a string.
* @function
* @param {string} str String to calculate
* @returns {number} Number of UTF8 bytes
* @expose
*/
ByteBuffer.calculateUTF8Bytes = function(str) {
//? if (NODE) {
if (typeof str !== 'string')
throw TypeError("Illegal argument: "+(typeof str));
return Buffer.byteLength(str, "utf8");
//? } else
return utfx.calculateUTF16asUTF8(stringSource(str))[1];
};
/**
* Reads an UTF8 encoded string.
* @param {number} length Number of characters or bytes to read.
* @param {string=} metrics Metrics specifying what `length` is meant to count. Defaults to
* {@link ByteBuffer.METRICS_CHARS}.
* @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
* read if omitted.
* @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
* read and the actual number of bytes read.
* @expose
*/
ByteBufferPrototype.readUTF8String = function(length, metrics, offset) {
if (typeof metrics === 'number') {
offset = metrics;
metrics = undefined;
}
//? RELATIVE();
if (typeof metrics === 'undefined') metrics = ByteBuffer.METRICS_CHARS;
if (!this.noAssert) {
//? ASSERT_INTEGER('length');
//? ASSERT_OFFSET();
}
var i = 0,
start = offset,
//? if (NODE)
temp,
sd;
if (metrics === ByteBuffer.METRICS_CHARS) { // The same for node and the browser
sd = stringDestination();
utfx.decodeUTF8(function() {
//? if (NODE)
return i < length && offset < this.limit ? this.buffer[offset++] : null;
//? else
return i < length && offset < this.limit ? this.view.getUint8(offset++) : null;
}.bind(this), function(cp) {
++i; utfx.UTF8toUTF16(cp, sd);
}.bind(this));
if (i !== length)
throw RangeError("Illegal range: Truncated data, "+i+" == "+length);
if (relative) {
this.offset = offset;
return sd();
} else {
return {
"string": sd(),
"length": offset - start
};
}
} else if (metrics === ByteBuffer.METRICS_BYTES) {
if (!this.noAssert) {
//? ASSERT_OFFSET('length');
}
//? if (NODE) {
temp = this.buffer.toString("utf8", offset, offset+length);
if (relative) {
this.offset += length;
return temp;
} else {
return {
'string': temp,
'length': length
};
}
//? } else {
var k = offset + length;
utfx.decodeUTF8toUTF16(function() {
return offset < k ? this.view.getUint8(offset++) : null;
}.bind(this), sd = stringDestination(), this.noAssert);
if (offset !== k)
throw RangeError("Illegal range: Truncated data, "+offset+" == "+k);
if (relative) {
this.offset = offset;
return sd();
} else {
return {
'string': sd(),
'length': offset - start
};
}
//? }
} else
throw TypeError("Unsupported metrics: "+metrics);
};
//? if (ALIASES) {
/**
* Reads an UTF8 encoded string. This is an alias of {@link ByteBuffer#readUTF8String}.
* @function
* @param {number} length Number of characters or bytes to read
* @param {number=} metrics Metrics specifying what `n` is meant to count. Defaults to
* {@link ByteBuffer.METRICS_CHARS}.
* @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
* read if omitted.
* @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
* read and the actual number of bytes read.
* @expose
*/
ByteBufferPrototype.readString = ByteBufferPrototype.readUTF8String;
//? }
//? } | mit |
schmop/ng2-datepicker | e2e/app.po.ts | 221 | import { browser, element, by } from 'protractor';
export class Ng2DatepickerCliPage {
navigateTo() {
return browser.get('/');
}
getParagraphText() {
return element(by.css('app-root h1')).getText();
}
}
| mit |
empyrical/react | packages/react-dom/src/events/ReactBrowserEventEmitter.js | 6977 | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import {registrationNameDependencies} from 'events/EventPluginRegistry';
import {
TOP_BLUR,
TOP_CANCEL,
TOP_CLOSE,
TOP_FOCUS,
TOP_INVALID,
TOP_RESET,
TOP_SCROLL,
TOP_SUBMIT,
getRawEventName,
mediaEventTypes,
} from './DOMTopLevelEventTypes';
import {
setEnabled,
isEnabled,
trapBubbledEvent,
trapCapturedEvent,
} from './ReactDOMEventListener';
import isEventSupported from './isEventSupported';
/**
* Summary of `ReactBrowserEventEmitter` event handling:
*
* - Top-level delegation is used to trap most native browser events. This
* may only occur in the main thread and is the responsibility of
* ReactDOMEventListener, which is injected and can therefore support
* pluggable event sources. This is the only work that occurs in the main
* thread.
*
* - We normalize and de-duplicate events to account for browser quirks. This
* may be done in the worker thread.
*
* - Forward these native events (with the associated top-level type used to
* trap it) to `EventPluginHub`, which in turn will ask plugins if they want
* to extract any synthetic events.
*
* - The `EventPluginHub` will then process each event by annotating them with
* "dispatches", a sequence of listeners and IDs that care about that event.
*
* - The `EventPluginHub` then dispatches the events.
*
* Overview of React and the event system:
*
* +------------+ .
* | DOM | .
* +------------+ .
* | .
* v .
* +------------+ .
* | ReactEvent | .
* | Listener | .
* +------------+ . +-----------+
* | . +--------+|SimpleEvent|
* | . | |Plugin |
* +-----|------+ . v +-----------+
* | | | . +--------------+ +------------+
* | +-----------.--->|EventPluginHub| | Event |
* | | . | | +-----------+ | Propagators|
* | ReactEvent | . | | |TapEvent | |------------|
* | Emitter | . | |<---+|Plugin | |other plugin|
* | | . | | +-----------+ | utilities |
* | +-----------.--->| | +------------+
* | | | . +--------------+
* +-----|------+ . ^ +-----------+
* | . | |Enter/Leave|
* + . +-------+|Plugin |
* +-------------+ . +-----------+
* | application | .
* |-------------| .
* | | .
* | | .
* +-------------+ .
* .
* React Core . General Purpose Event Plugin System
*/
const alreadyListeningTo = {};
let reactTopListenersCounter = 0;
/**
* To ensure no conflicts with other potential React instances on the page
*/
const topListenersIDKey = '_reactListenersID' + ('' + Math.random()).slice(2);
function getListeningForDocument(mountAt: any) {
// In IE8, `mountAt` is a host object and doesn't have `hasOwnProperty`
// directly.
if (!Object.prototype.hasOwnProperty.call(mountAt, topListenersIDKey)) {
mountAt[topListenersIDKey] = reactTopListenersCounter++;
alreadyListeningTo[mountAt[topListenersIDKey]] = {};
}
return alreadyListeningTo[mountAt[topListenersIDKey]];
}
/**
* We listen for bubbled touch events on the document object.
*
* Firefox v8.01 (and possibly others) exhibited strange behavior when
* mounting `onmousemove` events at some node that was not the document
* element. The symptoms were that if your mouse is not moving over something
* contained within that mount point (for example on the background) the
* top-level listeners for `onmousemove` won't be called. However, if you
* register the `mousemove` on the document object, then it will of course
* catch all `mousemove`s. This along with iOS quirks, justifies restricting
* top-level listeners to the document object only, at least for these
* movement types of events and possibly all events.
*
* @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
*
* Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but
* they bubble to document.
*
* @param {string} registrationName Name of listener (e.g. `onClick`).
* @param {object} mountAt Container where to mount the listener
*/
export function listenTo(
registrationName: string,
mountAt: Document | Element,
) {
const isListening = getListeningForDocument(mountAt);
const dependencies = registrationNameDependencies[registrationName];
for (let i = 0; i < dependencies.length; i++) {
const dependency = dependencies[i];
if (!(isListening.hasOwnProperty(dependency) && isListening[dependency])) {
switch (dependency) {
case TOP_SCROLL:
trapCapturedEvent(TOP_SCROLL, mountAt);
break;
case TOP_FOCUS:
case TOP_BLUR:
trapCapturedEvent(TOP_FOCUS, mountAt);
trapCapturedEvent(TOP_BLUR, mountAt);
// We set the flag for a single dependency later in this function,
// but this ensures we mark both as attached rather than just one.
isListening[TOP_BLUR] = true;
isListening[TOP_FOCUS] = true;
break;
case TOP_CANCEL:
case TOP_CLOSE:
if (isEventSupported(getRawEventName(dependency))) {
trapCapturedEvent(dependency, mountAt);
}
break;
case TOP_INVALID:
case TOP_SUBMIT:
case TOP_RESET:
// We listen to them on the target DOM elements.
// Some of them bubble so we don't want them to fire twice.
break;
default:
// By default, listen on the top level to all non-media events.
// Media events don't bubble so adding the listener wouldn't do anything.
const isMediaEvent = mediaEventTypes.indexOf(dependency) !== -1;
if (!isMediaEvent) {
trapBubbledEvent(dependency, mountAt);
}
break;
}
isListening[dependency] = true;
}
}
}
export function isListeningToAllDependencies(
registrationName: string,
mountAt: Document | Element,
) {
const isListening = getListeningForDocument(mountAt);
const dependencies = registrationNameDependencies[registrationName];
for (let i = 0; i < dependencies.length; i++) {
const dependency = dependencies[i];
if (!(isListening.hasOwnProperty(dependency) && isListening[dependency])) {
return false;
}
}
return true;
}
export {setEnabled, isEnabled, trapBubbledEvent, trapCapturedEvent};
| mit |
OrchardCMS/Autofac | Core/Source/Autofac/Core/Resolving/InstanceLookupCompletionBeginningEventArgs.cs | 2305 | // This software is part of the Autofac IoC container
// Copyright © 2011 Autofac Contributors
// http://autofac.org
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
using System;
namespace Autofac.Core.Resolving
{
/// <summary>
/// Raised when the completion phase of an instance lookup operation begins.
/// </summary>
public class InstanceLookupCompletionBeginningEventArgs : EventArgs
{
readonly IInstanceLookup _instanceLookup;
/// <summary>
/// Create an instance of the <see cref="InstanceLookupCompletionBeginningEventArgs"/> class.
/// </summary>
/// <param name="instanceLookup">The instance lookup that is beginning the completion phase.</param>
public InstanceLookupCompletionBeginningEventArgs(IInstanceLookup instanceLookup)
{
if (instanceLookup == null) throw new ArgumentNullException("instanceLookup");
_instanceLookup = instanceLookup;
}
/// <summary>
/// The instance lookup operation that is beginning the completion phase.
/// </summary>
public IInstanceLookup InstanceLookup
{
get { return _instanceLookup; }
}
}
} | mit |
bmvantunes/angular-library-builder | test/fixtures/basic-html-no-css/output-expected/module.d.ts | 37 | export declare class BasicModule {
}
| mit |
JohnBrodie/visual-kanban | lib/jcommon-1.0.17/source/org/jfree/xml/parser/coretypes/RenderingHintsReadHandler.java | 4253 | /* ========================================================================
* JCommon : a free general purpose class library for the Java(tm) platform
* ========================================================================
*
* (C) Copyright 2000-2005, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jcommon/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Java is a trademark or registered trademark of Sun Microsystems, Inc.
* in the United States and other countries.]
*
* ------------------------------
* RenderingHintsReadHandler.java
* ------------------------------
* (C)opyright 2003, 2004, by Thomas Morgner and Contributors.
*
* Original Author: Thomas Morgner;
* Contributor(s): David Gilbert (for Object Refinery Limited);
*
* $Id: RenderingHintsReadHandler.java,v 1.3 2005/10/18 13:33:32 mungady Exp $
*
* Changes
* -------
* 03-Dec-2003 : Initial version
* 11-Feb-2004 : Added missing Javadocs (DG);
*
*/
package org.jfree.xml.parser.coretypes;
import java.awt.RenderingHints;
import java.util.ArrayList;
import org.jfree.xml.parser.AbstractXmlReadHandler;
import org.jfree.xml.parser.XmlReadHandler;
import org.jfree.xml.parser.XmlReaderException;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
/**
* A read handler that can parse the XML element for a {@link RenderingHints} collection.
*/
public class RenderingHintsReadHandler extends AbstractXmlReadHandler {
/** The subhandlers. */
private ArrayList handlers;
/** The rendering hints under construction. */
private RenderingHints renderingHints;
/**
* Creates a new read handler.
*/
public RenderingHintsReadHandler() {
super();
}
/**
* Starts parsing.
*
* @param attrs the attributes.
*
* @throws SAXException never.
*/
protected void startParsing(final Attributes attrs) throws SAXException {
this.handlers = new ArrayList();
}
/**
* Returns the handler for a child element.
*
* @param tagName the tag name.
* @param atts the attributes.
*
* @return the handler.
*
* @throws SAXException if there is a parsing error.
* @throws XmlReaderException if there is a reader error.
*/
protected XmlReadHandler getHandlerForChild(final String tagName, final Attributes atts)
throws XmlReaderException, SAXException {
if (!tagName.equals("entry")) {
throw new SAXException("Expected 'entry' tag.");
}
final XmlReadHandler handler = new RenderingHintValueReadHandler();
this.handlers.add(handler);
return handler;
}
/**
* Done parsing.
*
* @throws SAXException if there is a parsing error.
* @throws XmlReaderException if there is a reader error.
*/
protected void doneParsing() throws SAXException, XmlReaderException {
this.renderingHints = new RenderingHints(null);
for (int i = 0; i < this.handlers.size(); i++) {
final RenderingHintValueReadHandler rh =
(RenderingHintValueReadHandler) this.handlers.get(i);
this.renderingHints.put(rh.getKey(), rh.getValue());
}
}
/**
* Returns the object for this element.
*
* @return the object.
*
* @throws XmlReaderException if there is a parsing error.
*/
public Object getObject() throws XmlReaderException {
return this.renderingHints;
}
}
| mit |
aspose-cells/Aspose.Cells-for-Cloud | SDKs/Aspose.Cells-Cloud-SDK-for-PHP/src/Aspose/Cells/Models/Column.php | 534 | <?php
namespace Aspose\Cells\Models;
/**
* $model.description$
*
* NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
*
*/
class Column {
static $swaggerTypes = array(
'GroupLevel' => 'int',
'Index' => 'int',
'IsHidden' => 'bool',
'Width' => 'float',
'Style' => 'LinkElement',
'link' => 'Link'
);
public $GroupLevel; // int
public $Index; // int
public $IsHidden; // bool
public $Width; // float
public $Style; // LinkElement
public $link; // Link
}
| mit |
xiaomi7732/LiveSDK-for-Windows | src/WinStore/Samples/Windows/HTML/PhotoSky/PhotoSkyJavaScript/pages/settingsAccountUI/settingsFlyout.js | 2582 | <!-- --------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------ -->
/// <reference path="/LiveSDKHTML/js/wl.js" />
(function () {
"use strict";
var appView = Windows.UI.ViewManagement.ApplicationView;
var appViewState = Windows.UI.ViewManagement.ApplicationViewState;
var nav = WinJS.Navigation;
var ui = WinJS.UI;
var utils = WinJS.Utilities;
ui.Pages.define("/pages/settingsAccountUI/settingsFlyoutUi.html", {
// This function is called whenever a user navigates to this page. It
// populates the page elements with the app's data.
ready: function (element, options) {
document.getElementById("userName").innerHTML = App.username;
var signOut = document.getElementById("signOutLink");
var onlineID = new Windows.Security.Authentication.OnlineId.OnlineIdAuthenticator();
if (onlineID.canSignOut) {
signOut.onclick = signOutButtonClick;
signOut.style.visibility = "visible";
}
else {
signOut.style.visibility = "hidden";
}
},
});
function signOutButtonClick(event) {
WL.logout();
}
WinJS.Namespace.define("Accounts", {
signOutButtonClick: signOutButtonClick,
});
})();
| mit |
larryli/gitlabhq | spec/controllers/groups/milestones_controller_spec.rb | 1092 | require 'spec_helper'
describe Groups::MilestonesController do
let(:group) { create(:group) }
let(:project) { create(:project, group: group) }
let(:project2) { create(:empty_project, group: group) }
let(:user) { create(:user) }
let(:title) { '肯定不是中文的问题' }
before do
sign_in(user)
group.add_owner(user)
project.team << [user, :master]
controller.instance_variable_set(:@group, group)
end
describe "#create" do
it "should create group milestone with Chinese title" do
post :create,
group_id: group.id,
milestone: { project_ids: [project.id, project2.id], title: title }
expect(response).to redirect_to(group_milestone_path(group, title.to_slug.to_s, title: title))
expect(Milestone.where(title: title).count).to eq(2)
end
it "redirects to new when there are no project ids" do
post :create, group_id: group.id, milestone: { title: title, project_ids: [""] }
expect(response).to render_template :new
expect(assigns(:milestone).errors).not_to be_nil
end
end
end
| mit |
chrisguitarguy/symfony | src/Symfony/Component/Config/Tests/Definition/Builder/ArrayNodeDefinitionTest.php | 9703 | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Config\Tests\Definition\Builder;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
use Symfony\Component\Config\Definition\Processor;
use Symfony\Component\Config\Definition\Builder\ScalarNodeDefinition;
use Symfony\Component\Config\Definition\Exception\InvalidDefinitionException;
class ArrayNodeDefinitionTest extends TestCase
{
public function testAppendingSomeNode()
{
$parent = new ArrayNodeDefinition('root');
$child = new ScalarNodeDefinition('child');
$parent
->children()
->scalarNode('foo')->end()
->scalarNode('bar')->end()
->end()
->append($child);
$this->assertCount(3, $this->getField($parent, 'children'));
$this->assertTrue(in_array($child, $this->getField($parent, 'children')));
}
/**
* @expectedException \Symfony\Component\Config\Definition\Exception\InvalidDefinitionException
* @dataProvider providePrototypeNodeSpecificCalls
*/
public function testPrototypeNodeSpecificOption($method, $args)
{
$node = new ArrayNodeDefinition('root');
call_user_func_array(array($node, $method), $args);
$node->getNode();
}
public function providePrototypeNodeSpecificCalls()
{
return array(
array('defaultValue', array(array())),
array('addDefaultChildrenIfNoneSet', array()),
array('requiresAtLeastOneElement', array()),
array('useAttributeAsKey', array('foo')),
);
}
/**
* @expectedException \Symfony\Component\Config\Definition\Exception\InvalidDefinitionException
*/
public function testConcreteNodeSpecificOption()
{
$node = new ArrayNodeDefinition('root');
$node
->addDefaultsIfNotSet()
->prototype('array')
;
$node->getNode();
}
/**
* @expectedException \Symfony\Component\Config\Definition\Exception\InvalidDefinitionException
*/
public function testPrototypeNodesCantHaveADefaultValueWhenUsingDefaultChildren()
{
$node = new ArrayNodeDefinition('root');
$node
->defaultValue(array())
->addDefaultChildrenIfNoneSet('foo')
->prototype('array')
;
$node->getNode();
}
public function testPrototypedArrayNodeDefaultWhenUsingDefaultChildren()
{
$node = new ArrayNodeDefinition('root');
$node
->addDefaultChildrenIfNoneSet()
->prototype('array')
;
$tree = $node->getNode();
$this->assertEquals(array(array()), $tree->getDefaultValue());
}
/**
* @dataProvider providePrototypedArrayNodeDefaults
*/
public function testPrototypedArrayNodeDefault($args, $shouldThrowWhenUsingAttrAsKey, $shouldThrowWhenNotUsingAttrAsKey, $defaults)
{
$node = new ArrayNodeDefinition('root');
$node
->addDefaultChildrenIfNoneSet($args)
->prototype('array')
;
try {
$tree = $node->getNode();
$this->assertFalse($shouldThrowWhenNotUsingAttrAsKey);
$this->assertEquals($defaults, $tree->getDefaultValue());
} catch (InvalidDefinitionException $e) {
$this->assertTrue($shouldThrowWhenNotUsingAttrAsKey);
}
$node = new ArrayNodeDefinition('root');
$node
->useAttributeAsKey('attr')
->addDefaultChildrenIfNoneSet($args)
->prototype('array')
;
try {
$tree = $node->getNode();
$this->assertFalse($shouldThrowWhenUsingAttrAsKey);
$this->assertEquals($defaults, $tree->getDefaultValue());
} catch (InvalidDefinitionException $e) {
$this->assertTrue($shouldThrowWhenUsingAttrAsKey);
}
}
public function providePrototypedArrayNodeDefaults()
{
return array(
array(null, true, false, array(array())),
array(2, true, false, array(array(), array())),
array('2', false, true, array('2' => array())),
array('foo', false, true, array('foo' => array())),
array(array('foo'), false, true, array('foo' => array())),
array(array('foo', 'bar'), false, true, array('foo' => array(), 'bar' => array())),
);
}
public function testNestedPrototypedArrayNodes()
{
$node = new ArrayNodeDefinition('root');
$node
->addDefaultChildrenIfNoneSet()
->prototype('array')
->prototype('array')
;
$node->getNode();
}
public function testEnabledNodeDefaults()
{
$node = new ArrayNodeDefinition('root');
$node
->canBeEnabled()
->children()
->scalarNode('foo')->defaultValue('bar')->end()
;
$this->assertEquals(array('enabled' => false, 'foo' => 'bar'), $node->getNode()->getDefaultValue());
}
/**
* @dataProvider getEnableableNodeFixtures
*/
public function testTrueEnableEnabledNode($expected, $config, $message)
{
$processor = new Processor();
$node = new ArrayNodeDefinition('root');
$node
->canBeEnabled()
->children()
->scalarNode('foo')->defaultValue('bar')->end()
;
$this->assertEquals(
$expected,
$processor->process($node->getNode(), $config),
$message
);
}
public function testCanBeDisabled()
{
$node = new ArrayNodeDefinition('root');
$node->canBeDisabled();
$this->assertTrue($this->getField($node, 'addDefaults'));
$this->assertEquals(array('enabled' => false), $this->getField($node, 'falseEquivalent'));
$this->assertEquals(array('enabled' => true), $this->getField($node, 'trueEquivalent'));
$this->assertEquals(array('enabled' => true), $this->getField($node, 'nullEquivalent'));
$nodeChildren = $this->getField($node, 'children');
$this->assertArrayHasKey('enabled', $nodeChildren);
$enabledNode = $nodeChildren['enabled'];
$this->assertTrue($this->getField($enabledNode, 'default'));
$this->assertTrue($this->getField($enabledNode, 'defaultValue'));
}
public function testIgnoreExtraKeys()
{
$node = new ArrayNodeDefinition('root');
$this->assertFalse($this->getField($node, 'ignoreExtraKeys'));
$result = $node->ignoreExtraKeys();
$this->assertEquals($node, $result);
$this->assertTrue($this->getField($node, 'ignoreExtraKeys'));
}
public function testNormalizeKeys()
{
$node = new ArrayNodeDefinition('root');
$this->assertTrue($this->getField($node, 'normalizeKeys'));
$result = $node->normalizeKeys(false);
$this->assertEquals($node, $result);
$this->assertFalse($this->getField($node, 'normalizeKeys'));
}
public function testPrototypeVariable()
{
$node = new ArrayNodeDefinition('root');
$this->assertEquals($node->prototype('variable'), $node->variablePrototype());
}
public function testPrototypeScalar()
{
$node = new ArrayNodeDefinition('root');
$this->assertEquals($node->prototype('scalar'), $node->scalarPrototype());
}
public function testPrototypeBoolean()
{
$node = new ArrayNodeDefinition('root');
$this->assertEquals($node->prototype('boolean'), $node->booleanPrototype());
}
public function testPrototypeInteger()
{
$node = new ArrayNodeDefinition('root');
$this->assertEquals($node->prototype('integer'), $node->integerPrototype());
}
public function testPrototypeFloat()
{
$node = new ArrayNodeDefinition('root');
$this->assertEquals($node->prototype('float'), $node->floatPrototype());
}
public function testPrototypeArray()
{
$node = new ArrayNodeDefinition('root');
$this->assertEquals($node->prototype('array'), $node->arrayPrototype());
}
public function testPrototypeEnum()
{
$node = new ArrayNodeDefinition('root');
$this->assertEquals($node->prototype('enum'), $node->enumPrototype());
}
public function getEnableableNodeFixtures()
{
return array(
array(array('enabled' => true, 'foo' => 'bar'), array(true), 'true enables an enableable node'),
array(array('enabled' => true, 'foo' => 'bar'), array(null), 'null enables an enableable node'),
array(array('enabled' => true, 'foo' => 'bar'), array(array('enabled' => true)), 'An enableable node can be enabled'),
array(array('enabled' => true, 'foo' => 'baz'), array(array('foo' => 'baz')), 'any configuration enables an enableable node'),
array(array('enabled' => false, 'foo' => 'baz'), array(array('foo' => 'baz', 'enabled' => false)), 'An enableable node can be disabled'),
array(array('enabled' => false, 'foo' => 'bar'), array(false), 'false disables an enableable node'),
);
}
protected function getField($object, $field)
{
$reflection = new \ReflectionProperty($object, $field);
$reflection->setAccessible(true);
return $reflection->getValue($object);
}
}
| mit |
bayuaji13/aismardi | application/third_party/PhpWord/Writer/HTML/Style/Font.php | 2368 | <?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @link https://github.com/PHPOffice/PHPWord
* @copyright 2010-2015 PHPWord contributors
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Writer\HTML\Style;
use PhpOffice\PhpWord\Style\Font as FontStyle;
/**
* Font style HTML writer
*
* @since 0.10.0
*/
class Font extends AbstractStyle
{
/**
* Write style
*
* @return string
*/
public function write()
{
$style = $this->getStyle();
if (!$style instanceof FontStyle) {
return '';
}
$css = array();
$font = $style->getName();
$size = $style->getSize();
$color = $style->getColor();
$fgColor = $style->getFgColor();
$underline = $style->getUnderline() != FontStyle::UNDERLINE_NONE;
$lineThrough = $style->isStrikethrough() || $style->isDoubleStrikethrough();
$css['font-family'] = $this->getValueIf($font !== null, "'{$font}'");
$css['font-size'] = $this->getValueIf($size !== null, "{$size}pt");
$css['color'] = $this->getValueIf($color !== null, "#{$color}");
$css['background'] = $this->getValueIf($fgColor != '', $fgColor);
$css['font-weight'] = $this->getValueIf($style->isBold(), 'bold');
$css['font-style'] = $this->getValueIf($style->isItalic(), 'italic');
$css['vertical-align'] = $this->getValueIf($style->isSuperScript(), 'italic');
$css['vertical-align'] = $this->getValueIf($style->isSuperScript(), 'super');
$css['vertical-align'] = $this->getValueIf($style->isSubScript(), 'sub');
$css['text-decoration'] = '';
$css['text-decoration'] .= $this->getValueIf($underline, 'underline ');
$css['text-decoration'] .= $this->getValueIf($lineThrough, 'line-through ');
return $this->assembleCss($css);
}
}
| mit |
princeofdarkness76/metakit | tests/tcusto2.cpp | 9795 | // tcusto2.cpp -- Regression test program, custom view tests
// $Id$
// This is part of Metakit, the homepage is http://www.equi4.com/metakit.html
#include "regress.h"
void TestCustom2() {
B(c11, Unique operation, 0);
{
c4_IntProp p1("p1"), p2("p2");
c4_View v1, v2, v3;
v1.Add(p1[1] + p2[11]);
v1.Add(p1[1] + p2[22]);
v1.Add(p1[2] + p2[33]);
v1.Add(p1[2] + p2[33]);
v1.Add(p1[3] + p2[44]);
v1.Add(p1[4] + p2[55]);
v1.Add(p1[4] + p2[55]);
v1.Add(p1[4] + p2[55]);
v2 = v1.Unique();
A(v2.GetSize() == 5);
A(p1(v2[0]) == 1);
A(p1(v2[1]) == 1);
A(p1(v2[2]) == 2);
A(p1(v2[3]) == 3);
A(p1(v2[4]) == 4);
A(p2(v2[0]) == 11);
A(p2(v2[1]) == 22);
A(p2(v2[2]) == 33);
A(p2(v2[3]) == 44);
A(p2(v2[4]) == 55);
}
E;
B(c12, Union operation, 0) {
c4_IntProp p1("p1");
c4_View v1, v2, v3;
v1.Add(p1[1]);
v1.Add(p1[2]);
v1.Add(p1[3]);
v2.Add(p1[2]);
v2.Add(p1[3]);
v2.Add(p1[4]);
v2.Add(p1[5]);
v3 = v1.Union(v2);
A(v3.GetSize() == 5);
A(p1(v3[0]) == 1);
A(p1(v3[1]) == 2);
A(p1(v3[2]) == 3);
A(p1(v3[3]) == 4);
A(p1(v3[4]) == 5);
}
E;
B(c13, Intersect operation, 0) {
c4_IntProp p1("p1");
c4_View v1, v2, v3;
v1.Add(p1[1]);
v1.Add(p1[2]);
v1.Add(p1[3]);
v2.Add(p1[2]);
v2.Add(p1[3]);
v2.Add(p1[4]);
v2.Add(p1[5]);
v3 = v1.Intersect(v2);
A(v3.GetSize() == 2);
A(p1(v3[0]) == 2);
A(p1(v3[1]) == 3);
}
E;
B(c14, Different operation, 0) {
c4_IntProp p1("p1");
c4_View v1, v2, v3;
v1.Add(p1[1]);
v1.Add(p1[2]);
v1.Add(p1[3]);
v2.Add(p1[2]);
v2.Add(p1[3]);
v2.Add(p1[4]);
v2.Add(p1[5]);
v3 = v1.Different(v2);
A(v3.GetSize() == 3);
A(p1(v3[0]) == 1);
A(p1(v3[1]) == 4);
A(p1(v3[2]) == 5);
}
E;
B(c15, Minus operation, 0) {
c4_IntProp p1("p1");
c4_View v1, v2, v3;
v1.Add(p1[1]);
v1.Add(p1[2]);
v1.Add(p1[3]);
v2.Add(p1[2]);
v2.Add(p1[3]);
v2.Add(p1[4]);
v2.Add(p1[5]);
v3 = v1.Minus(v2);
A(v3.GetSize() == 1);
A(p1(v3[0]) == 1);
}
E;
B(c16, View comparisons, 0) {
c4_IntProp p1("p1");
c4_View v1;
v1.Add(p1[1]);
v1.Add(p1[2]);
v1.Add(p1[3]);
v1.Add(p1[4]);
v1.Add(p1[5]);
A(v1 == v1);
A(v1 == v1.Slice(0));
A(v1.Slice(0, 2) < v1.Slice(0, 3));
A(v1.Slice(0, 3) == v1.Slice(0, 3));
A(v1.Slice(0, 4) > v1.Slice(0, 3));
A(v1.Slice(0, 3) < v1.Slice(1, 3));
A(v1.Slice(0, 3) < v1.Slice(1, 4));
A(v1.Slice(1, 3) > v1.Slice(0, 3));
A(v1.Slice(1, 4) > v1.Slice(0, 3));
}
E;
B(c17, Join operation, 0) {
c4_StringProp p1("p1"), p2("p2");
c4_IntProp p3("p3");
c4_View v1, v2, v3;
v1.Add(p1[""]);
v1.Add(p1["1"] + p2["a"]);
v1.Add(p1["12"] + p2["ab"]);
v1.Add(p1["123"] + p2["abc"]);
v2.Add(p1["1"] + p3[1]);
v2.Add(p1["12"] + p3[1]);
v2.Add(p1["12"] + p3[2]);
v2.Add(p1["123"] + p3[1]);
v2.Add(p1["123"] + p3[2]);
v2.Add(p1["123"] + p3[3]);
v3 = v1.Join(p1, v2); // inner join
A(v3.GetSize() == 6);
A(p1(v3[0]) == (c4_String)"1");
A(p1(v3[1]) == (c4_String)"12");
A(p1(v3[2]) == (c4_String)"12");
A(p1(v3[3]) == (c4_String)"123");
A(p1(v3[4]) == (c4_String)"123");
A(p1(v3[5]) == (c4_String)"123");
A(p2(v3[0]) == (c4_String)"a");
A(p2(v3[1]) == (c4_String)"ab");
A(p2(v3[2]) == (c4_String)"ab");
A(p2(v3[3]) == (c4_String)"abc");
A(p2(v3[4]) == (c4_String)"abc");
A(p2(v3[5]) == (c4_String)"abc");
A(p3(v3[0]) == 1);
A(p3(v3[1]) == 1);
A(p3(v3[2]) == 2);
A(p3(v3[3]) == 1);
A(p3(v3[4]) == 2);
A(p3(v3[5]) == 3);
v3 = v1.Join(p1, v2, true); // outer join
A(v3.GetSize() == 7);
A(p1(v3[0]) == (c4_String)"");
A(p1(v3[1]) == (c4_String)"1");
A(p1(v3[2]) == (c4_String)"12");
A(p1(v3[3]) == (c4_String)"12");
A(p1(v3[4]) == (c4_String)"123");
A(p1(v3[5]) == (c4_String)"123");
A(p1(v3[6]) == (c4_String)"123");
A(p2(v3[0]) == (c4_String)"");
A(p2(v3[1]) == (c4_String)"a");
A(p2(v3[2]) == (c4_String)"ab");
A(p2(v3[3]) == (c4_String)"ab");
A(p2(v3[4]) == (c4_String)"abc");
A(p2(v3[5]) == (c4_String)"abc");
A(p2(v3[6]) == (c4_String)"abc");
A(p3(v3[0]) == 0);
A(p3(v3[1]) == 1);
A(p3(v3[2]) == 1);
A(p3(v3[3]) == 2);
A(p3(v3[4]) == 1);
A(p3(v3[5]) == 2);
A(p3(v3[6]) == 3);
}
E;
B(c18, Groupby sort fix, 0) { // fails in 1.8.4 (from P. Ritter, 14-10-1998)
c4_StringProp p1("Country");
c4_StringProp p2("City");
c4_ViewProp p3("SubList");
c4_View v1, v2, v3;
v1.Add(p1["US"] + p2["Philadelphia"]);
v1.Add(p1["France"] + p2["Bordeaux"]);
v1.Add(p1["US"] + p2["Miami"]);
v1.Add(p1["France"] + p2["Paris"]);
v1.Add(p1["US"] + p2["Boston"]);
v1.Add(p1["France"] + p2["Nice"]);
v1.Add(p1["US"] + p2["NY"]);
v1.Add(p1["US"] + p2["Miami"]);
v2 = v1.GroupBy(p1, p3);
A(v2.GetSize() == 2);
A(p1(v2[0]) == (c4_String)"France");
A(p1(v2[1]) == (c4_String)"US");
v3 = p3(v2[0]);
A(v3.GetSize() == 3);
A(p2(v3[0]) == (c4_String)"Bordeaux");
A(p2(v3[1]) == (c4_String)"Nice");
A(p2(v3[2]) == (c4_String)"Paris");
v3 = p3(v2[1]);
A(v3.GetSize() == 5);
A(p2(v3[0]) == (c4_String)"Boston");
A(p2(v3[1]) == (c4_String)"Miami");
A(p2(v3[2]) == (c4_String)"Miami");
A(p2(v3[3]) == (c4_String)"NY");
A(p2(v3[4]) == (c4_String)"Philadelphia");
}
E;
B(c19, JoinProp operation, 0) { // moved, used to also be called c15
c4_StringProp p1("p1");
c4_ViewProp p2("p2");
c4_IntProp p3("p3");
c4_View v1, v2a, v2b, v2c, v3;
v2a.Add(p3[1]);
v2a.Add(p3[2]);
v2a.Add(p3[3]);
v1.Add(p1["123"] + p2[v2a]);
v2b.Add(p3[1]);
v2b.Add(p3[2]);
v1.Add(p1["12"] + p2[v2b]);
v2c.Add(p3[1]);
v1.Add(p1["1"] + p2[v2c]);
v1.Add(p1[""]);
v3 = v1.JoinProp(p2); // inner join
A(v3.GetSize() == 6);
A(p1(v3[0]) == (c4_String)"123");
A(p1(v3[1]) == (c4_String)"123");
A(p1(v3[2]) == (c4_String)"123");
A(p1(v3[3]) == (c4_String)"12");
A(p1(v3[4]) == (c4_String)"12");
A(p1(v3[5]) == (c4_String)"1");
A(p3(v3[0]) == 1);
A(p3(v3[1]) == 2);
A(p3(v3[2]) == 3);
A(p3(v3[3]) == 1);
A(p3(v3[4]) == 2);
A(p3(v3[5]) == 1);
v3 = v1.JoinProp(p2, true); // outer join
A(v3.GetSize() == 7);
A(p1(v3[0]) == (c4_String)"123");
A(p1(v3[1]) == (c4_String)"123");
A(p1(v3[2]) == (c4_String)"123");
A(p1(v3[3]) == (c4_String)"12");
A(p1(v3[4]) == (c4_String)"12");
A(p1(v3[5]) == (c4_String)"1");
A(p1(v3[6]) == (c4_String)"");
A(p3(v3[0]) == 1);
A(p3(v3[1]) == 2);
A(p3(v3[2]) == 3);
A(p3(v3[3]) == 1);
A(p3(v3[4]) == 2);
A(p3(v3[5]) == 1);
A(p3(v3[6]) == 0);
}
E;
B(c20, Wide cartesian product, 0) {
// added 2nd prop's to do a better test - 1999-12-23
c4_IntProp p1("p1");
c4_IntProp p2("p2");
c4_IntProp p3("p3");
c4_IntProp p4("p4");
c4_View v1;
v1.Add(p1[123] + p2[321]);
v1.Add(p1[234] + p2[432]);
v1.Add(p1[345] + p2[543]);
c4_View v2;
v2.Add(p3[111] + p4[11]);
v2.Add(p3[222] + p4[22]);
c4_View v3 = v1.Product(v2);
A(v3.GetSize() == 6);
A(p1(v3[0]) == 123);
A(p2(v3[0]) == 321);
A(p3(v3[0]) == 111);
A(p4(v3[0]) == 11);
A(p1(v3[1]) == 123);
A(p2(v3[1]) == 321);
A(p3(v3[1]) == 222);
A(p4(v3[1]) == 22);
A(p1(v3[2]) == 234);
A(p2(v3[2]) == 432);
A(p3(v3[2]) == 111);
A(p4(v3[2]) == 11);
A(p1(v3[3]) == 234);
A(p2(v3[3]) == 432);
A(p3(v3[3]) == 222);
A(p4(v3[3]) == 22);
A(p1(v3[4]) == 345);
A(p2(v3[4]) == 543);
A(p3(v3[4]) == 111);
A(p4(v3[4]) == 11);
A(p1(v3[5]) == 345);
A(p2(v3[5]) == 543);
A(p3(v3[5]) == 222);
A(p4(v3[5]) == 22);
v1.Add(p1[456]);
A(v3.GetSize() == 8);
v2.Add(p2[333]);
A(v3.GetSize() == 12);
}
E;
B(c21, Join on compound key, 0) {
c4_IntProp p1("p1"), p2("p2"), p3("p3"), p4("p4");
c4_View v1, v2, v3;
v1.Add(p1[1] + p2[11] + p3[111]);
v1.Add(p1[2] + p2[22] + p3[222]);
v1.Add(p1[3] + p2[22] + p3[111]);
v2.Add(p2[11] + p3[111] + p4[1111]);
v2.Add(p2[22] + p3[222] + p4[2222]);
v2.Add(p2[22] + p3[222] + p4[3333]);
v2.Add(p2[22] + p3[333] + p4[4444]);
// this works here, but it fails in Python, i.e. Mk4py 2.4.0
v3 = v1.Join((p2, p3), v2);
A(v3.GetSize() == 3);
A(p1(v3[0]) == 1);
A(p1(v3[1]) == 2);
A(p1(v3[2]) == 2);
A(p2(v3[0]) == 11);
A(p2(v3[1]) == 22);
A(p2(v3[2]) == 22);
A(p3(v3[0]) == 111);
A(p3(v3[1]) == 222);
A(p3(v3[2]) == 222);
A(p4(v3[0]) == 1111);
A(p4(v3[1]) == 2222);
A(p4(v3[2]) == 3333);
}
E;
B(c22, Groupby with selection, 0) {
c4_Storage s1;
c4_View v1 = s1.GetAs("v1[p1:I,p2:I,p3:I]");
c4_IntProp p1("p1"), p2("p2"), p3("p3");
c4_ViewProp p4("p4");
v1.Add(p1[0] + p2[1] + p3[10]);
v1.Add(p1[1] + p2[1] + p3[20]);
v1.Add(p1[2] + p2[2] + p3[30]);
v1.Add(p1[3] + p2[3] + p3[40]);
v1.Add(p1[4] + p2[3] + p3[50]);
s1.Commit();
A(v1.GetSize() == 5);
c4_View v2 = v1.GroupBy(p2, p4);
A(v2.GetSize() == 3);
c4_View v3 = p4(v2[0]);
A(v3.GetSize() == 2);
A(p3(v3[0]) == 10);
A(p3(v3[1]) == 20);
c4_View v4 = p4(v2[1]);
A(v4.GetSize() == 1);
A(p3(v4[0]) == 30);
c4_View v5 = p4(v2[2]);
A(v5.GetSize() == 2);
A(p3(v5[0]) == 40);
A(p3(v5[1]) == 50);
c4_View v6 = v4.Sort();
A(v6.GetSize() == 1);
A(p1(v6[0]) == 2);
A(p3(v6[0]) == 30);
}
E;
}
| mit |
jacobhong/jReddit | src/main/java/com/github/jreddit/request/retrieval/submissions/SubmissionsOfSubredditRequest.java | 940 | package com.github.jreddit.request.retrieval.submissions;
import com.github.jreddit.request.retrieval.ListingRequest;
import com.github.jreddit.request.retrieval.param.SubmissionSort;
public class SubmissionsOfSubredditRequest extends ListingRequest {
private static final String ENDPOINT_FORMAT = "/r/%s/%s.json?%s";
private SubmissionSort sort;
private String subreddit;
/**
* @param subreddit Subreddit (e.g. "funny")
* @param sort Sorting method
*/
public SubmissionsOfSubredditRequest(String subreddit, SubmissionSort sort) {
this.subreddit = subreddit;
this.sort = sort;
}
public SubmissionsOfSubredditRequest setShowAll() {
this.addParameter("show", "all");
return this;
}
@Override
public String generateRedditURI() {
return String.format(ENDPOINT_FORMAT, subreddit, sort.value(), this.generateParameters());
}
}
| mit |
vbud/adventures_in_opencl | part2/main.cpp | 7603 | /*
* Adventures in OpenCL tutorial series
* Part 2
*
* author: Ian Johnson
* htt://enja.org
* code based on advisor Gordon Erlebacher's work
* NVIDIA's examples
* as well as various blogs and resources on the internet
*/
#include <stdio.h>
#include <stdlib.h>
#include <sstream>
#include <iomanip>
#include <math.h>
//OpenGL stuff
#include <GL/glew.h>
#if defined __APPLE__ || defined(MACOSX)
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
//Our OpenCL Particle Systemclass
#include "cll.h"
#define NUM_PARTICLES 20000
CL* example;
//GL related variables
int window_width = 800;
int window_height = 600;
int glutWindowHandle = 0;
float translate_z = -1.f;
// mouse controls
int mouse_old_x, mouse_old_y;
int mouse_buttons = 0;
float rotate_x = 0.0, rotate_y = 0.0;
//main app helper functions
void init_gl(int argc, char** argv);
void appRender();
void appDestroy();
void timerCB(int ms);
void appKeyboard(unsigned char key, int x, int y);
void appMouse(int button, int state, int x, int y);
void appMotion(int x, int y);
//----------------------------------------------------------------------
//quick random function to distribute our initial points
float rand_float(float mn, float mx)
{
float r = random() / (float) RAND_MAX;
return mn + (mx-mn)*r;
}
//----------------------------------------------------------------------
int main(int argc, char** argv)
{
printf("Hello, OpenCL\n");
//Setup our GLUT window and OpenGL related things
//glut callback functions are setup here too
init_gl(argc, argv);
//initialize our CL object, this sets up the context
example = new CL();
//load and build our CL program from the file
#include "part2.cl" //std::string kernel_source is defined in this file
example->loadProgram(kernel_source);
//initialize our particle system with positions, velocities and color
int num = NUM_PARTICLES;
std::vector<Vec4> pos(num);
std::vector<Vec4> vel(num);
std::vector<Vec4> color(num);
//fill our vectors with initial data
for(int i = 0; i < num; i++)
{
//distribute the particles in a random circle around z axis
float rad = rand_float(.2, .5);
float x = rad*sin(2*3.14 * i/num);
float z = 0.0f;// -.1 + .2f * i/num;
float y = rad*cos(2*3.14 * i/num);
pos[i] = Vec4(x, y, z, 1.0f);
//give some initial velocity
//float xr = rand_float(-.1, .1);
//float yr = rand_float(1.f, 3.f);
//the life is the lifetime of the particle: 1 = alive 0 = dead
//as you will see in part2.cl we reset the particle when it dies
float life_r = rand_float(0.f, 1.f);
vel[i] = Vec4(0.0, 0.0, 3.0f, life_r);
//just make them red and full alpha
color[i] = Vec4(1.0f, 0.0f,0.0f, 1.0f);
}
//our load data function sends our initial values to the GPU
example->loadData(pos, vel, color);
//initialize the kernel
example->popCorn();
//this starts the GLUT program, from here on out everything we want
//to do needs to be done in glut callback functions
glutMainLoop();
}
//----------------------------------------------------------------------
void appRender()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//this updates the particle system by calling the kernel
example->runKernel();
//render the particles from VBOs
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_POINT_SMOOTH);
glPointSize(5.);
//printf("color buffer\n");
glBindBuffer(GL_ARRAY_BUFFER, example->c_vbo);
glColorPointer(4, GL_FLOAT, 0, 0);
//printf("vertex buffer\n");
glBindBuffer(GL_ARRAY_BUFFER, example->p_vbo);
glVertexPointer(4, GL_FLOAT, 0, 0);
//printf("enable client state\n");
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
//Need to disable these for blender
glDisableClientState(GL_NORMAL_ARRAY);
//printf("draw arrays\n");
glDrawArrays(GL_POINTS, 0, example->num);
//printf("disable stuff\n");
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
glutSwapBuffers();
}
//----------------------------------------------------------------------
void init_gl(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowSize(window_width, window_height);
glutInitWindowPosition (glutGet(GLUT_SCREEN_WIDTH)/2 - window_width/2,
glutGet(GLUT_SCREEN_HEIGHT)/2 - window_height/2);
std::stringstream ss;
ss << "Adventures in OpenCL: Part 2, " << NUM_PARTICLES << " particles" << std::ends;
glutWindowHandle = glutCreateWindow(ss.str().c_str());
glutDisplayFunc(appRender); //main rendering function
glutTimerFunc(30, timerCB, 30); //determin a minimum time between frames
glutKeyboardFunc(appKeyboard);
glutMouseFunc(appMouse);
glutMotionFunc(appMotion);
glewInit();
glClearColor(0.0, 0.0, 0.0, 1.0);
glDisable(GL_DEPTH_TEST);
// viewport
glViewport(0, 0, window_width, window_height);
// projection
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(90.0, (GLfloat)window_width / (GLfloat) window_height, 0.1, 1000.0);
// set view matrix
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.0, 0.0, translate_z);
}
//----------------------------------------------------------------------
void appDestroy()
{
//this makes sure we properly cleanup our OpenCL context
delete example;
if(glutWindowHandle)glutDestroyWindow(glutWindowHandle);
printf("about to exit!\n");
exit(0);
}
//----------------------------------------------------------------------
void timerCB(int ms)
{
//this makes sure the appRender function is called every ms miliseconds
glutTimerFunc(ms, timerCB, ms);
glutPostRedisplay();
}
//----------------------------------------------------------------------
void appKeyboard(unsigned char key, int x, int y)
{
//this way we can exit the program cleanly
switch(key)
{
case '\033': // escape quits
case '\015': // Enter quits
case 'Q': // Q quits
case 'q': // q (or escape) quits
// Cleanup up and quit
appDestroy();
break;
}
}
//----------------------------------------------------------------------
void appMouse(int button, int state, int x, int y)
{
//handle mouse interaction for rotating/zooming the view
if (state == GLUT_DOWN) {
mouse_buttons |= 1<<button;
} else if (state == GLUT_UP) {
mouse_buttons = 0;
}
mouse_old_x = x;
mouse_old_y = y;
}
//----------------------------------------------------------------------
void appMotion(int x, int y)
{
//hanlde the mouse motion for zooming and rotating the view
float dx, dy;
dx = x - mouse_old_x;
dy = y - mouse_old_y;
if (mouse_buttons & 1) {
rotate_x += dy * 0.2;
rotate_y += dx * 0.2;
} else if (mouse_buttons & 4) {
translate_z += dy * 0.1;
}
mouse_old_x = x;
mouse_old_y = y;
// set view matrix
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.0, 0.0, translate_z);
glRotatef(rotate_x, 1.0, 0.0, 0.0);
glRotatef(rotate_y, 0.0, 1.0, 0.0);
}
| mit |
hyonholee/azure-sdk-for-net | sdk/automation/Microsoft.Azure.Management.Automation/src/Generated/AutomationClient.cs | 23952 | // <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.Automation
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Serialization;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
/// <summary>
/// Automation Client
/// </summary>
public partial class AutomationClient : ServiceClient<AutomationClient>, IAutomationClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft Azure
/// subscription. The subscription ID forms part of the URI for every service
/// call.
/// </summary>
public string SubscriptionId { get; set; }
/// <summary>
/// The preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// The retry timeout in seconds for Long Running Operations. Default value is
/// 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// Whether a unique x-ms-client-request-id should be generated. When set to
/// true a unique x-ms-client-request-id value is generated and included in
/// each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IAutomationAccountOperations.
/// </summary>
public virtual IAutomationAccountOperations AutomationAccount { get; private set; }
/// <summary>
/// Gets the IOperations.
/// </summary>
public virtual IOperations Operations { get; private set; }
/// <summary>
/// Gets the IStatisticsOperations.
/// </summary>
public virtual IStatisticsOperations Statistics { get; private set; }
/// <summary>
/// Gets the IUsagesOperations.
/// </summary>
public virtual IUsagesOperations Usages { get; private set; }
/// <summary>
/// Gets the IKeysOperations.
/// </summary>
public virtual IKeysOperations Keys { get; private set; }
/// <summary>
/// Gets the ICertificateOperations.
/// </summary>
public virtual ICertificateOperations Certificate { get; private set; }
/// <summary>
/// Gets the IConnectionOperations.
/// </summary>
public virtual IConnectionOperations Connection { get; private set; }
/// <summary>
/// Gets the IConnectionTypeOperations.
/// </summary>
public virtual IConnectionTypeOperations ConnectionType { get; private set; }
/// <summary>
/// Gets the ICredentialOperations.
/// </summary>
public virtual ICredentialOperations Credential { get; private set; }
/// <summary>
/// Gets the IDscConfigurationOperations.
/// </summary>
public virtual IDscConfigurationOperations DscConfiguration { get; private set; }
/// <summary>
/// Gets the IHybridRunbookWorkerGroupOperations.
/// </summary>
public virtual IHybridRunbookWorkerGroupOperations HybridRunbookWorkerGroup { get; private set; }
/// <summary>
/// Gets the IJobScheduleOperations.
/// </summary>
public virtual IJobScheduleOperations JobSchedule { get; private set; }
/// <summary>
/// Gets the ILinkedWorkspaceOperations.
/// </summary>
public virtual ILinkedWorkspaceOperations LinkedWorkspace { get; private set; }
/// <summary>
/// Gets the IActivityOperations.
/// </summary>
public virtual IActivityOperations Activity { get; private set; }
/// <summary>
/// Gets the IModuleOperations.
/// </summary>
public virtual IModuleOperations Module { get; private set; }
/// <summary>
/// Gets the IObjectDataTypesOperations.
/// </summary>
public virtual IObjectDataTypesOperations ObjectDataTypes { get; private set; }
/// <summary>
/// Gets the IFieldsOperations.
/// </summary>
public virtual IFieldsOperations Fields { get; private set; }
/// <summary>
/// Gets the IScheduleOperations.
/// </summary>
public virtual IScheduleOperations Schedule { get; private set; }
/// <summary>
/// Gets the IVariableOperations.
/// </summary>
public virtual IVariableOperations Variable { get; private set; }
/// <summary>
/// Gets the IWebhookOperations.
/// </summary>
public virtual IWebhookOperations Webhook { get; private set; }
/// <summary>
/// Gets the IWatcherOperations.
/// </summary>
public virtual IWatcherOperations Watcher { get; private set; }
/// <summary>
/// Gets the ISoftwareUpdateConfigurationsOperations.
/// </summary>
public virtual ISoftwareUpdateConfigurationsOperations SoftwareUpdateConfigurations { get; private set; }
/// <summary>
/// Gets the ISoftwareUpdateConfigurationRunsOperations.
/// </summary>
public virtual ISoftwareUpdateConfigurationRunsOperations SoftwareUpdateConfigurationRuns { get; private set; }
/// <summary>
/// Gets the ISoftwareUpdateConfigurationMachineRunsOperations.
/// </summary>
public virtual ISoftwareUpdateConfigurationMachineRunsOperations SoftwareUpdateConfigurationMachineRuns { get; private set; }
/// <summary>
/// Gets the ISourceControlOperations.
/// </summary>
public virtual ISourceControlOperations SourceControl { get; private set; }
/// <summary>
/// Gets the ISourceControlSyncJobOperations.
/// </summary>
public virtual ISourceControlSyncJobOperations SourceControlSyncJob { get; private set; }
/// <summary>
/// Gets the ISourceControlSyncJobStreamsOperations.
/// </summary>
public virtual ISourceControlSyncJobStreamsOperations SourceControlSyncJobStreams { get; private set; }
/// <summary>
/// Gets the IJobOperations.
/// </summary>
public virtual IJobOperations Job { get; private set; }
/// <summary>
/// Gets the IJobStreamOperations.
/// </summary>
public virtual IJobStreamOperations JobStream { get; private set; }
/// <summary>
/// Gets the IAgentRegistrationInformationOperations.
/// </summary>
public virtual IAgentRegistrationInformationOperations AgentRegistrationInformation { get; private set; }
/// <summary>
/// Gets the IDscNodeOperations.
/// </summary>
public virtual IDscNodeOperations DscNode { get; private set; }
/// <summary>
/// Gets the INodeReportsOperations.
/// </summary>
public virtual INodeReportsOperations NodeReports { get; private set; }
/// <summary>
/// Gets the IDscCompilationJobOperations.
/// </summary>
public virtual IDscCompilationJobOperations DscCompilationJob { get; private set; }
/// <summary>
/// Gets the IDscCompilationJobStreamOperations.
/// </summary>
public virtual IDscCompilationJobStreamOperations DscCompilationJobStream { get; private set; }
/// <summary>
/// Gets the IDscNodeConfigurationOperations.
/// </summary>
public virtual IDscNodeConfigurationOperations DscNodeConfiguration { get; private set; }
/// <summary>
/// Gets the INodeCountInformationOperations.
/// </summary>
public virtual INodeCountInformationOperations NodeCountInformation { get; private set; }
/// <summary>
/// Gets the IRunbookDraftOperations.
/// </summary>
public virtual IRunbookDraftOperations RunbookDraft { get; private set; }
/// <summary>
/// Gets the IRunbookOperations.
/// </summary>
public virtual IRunbookOperations Runbook { get; private set; }
/// <summary>
/// Gets the ITestJobStreamsOperations.
/// </summary>
public virtual ITestJobStreamsOperations TestJobStreams { get; private set; }
/// <summary>
/// Gets the ITestJobOperations.
/// </summary>
public virtual ITestJobOperations TestJob { get; private set; }
/// <summary>
/// Gets the IPython2PackageOperations.
/// </summary>
public virtual IPython2PackageOperations Python2Package { get; private set; }
/// <summary>
/// Initializes a new instance of the AutomationClient class.
/// </summary>
/// <param name='httpClient'>
/// HttpClient to be used
/// </param>
/// <param name='disposeHttpClient'>
/// True: will dispose the provided httpClient on calling AutomationClient.Dispose(). False: will not dispose provided httpClient</param>
protected AutomationClient(HttpClient httpClient, bool disposeHttpClient) : base(httpClient, disposeHttpClient)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the AutomationClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AutomationClient(params DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the AutomationClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AutomationClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the AutomationClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected AutomationClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AutomationClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected AutomationClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AutomationClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutomationClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutomationClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='httpClient'>
/// HttpClient to be used
/// </param>
/// <param name='disposeHttpClient'>
/// True: will dispose the provided httpClient on calling AutomationClient.Dispose(). False: will not dispose provided httpClient</param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutomationClient(ServiceClientCredentials credentials, HttpClient httpClient, bool disposeHttpClient) : this(httpClient, disposeHttpClient)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutomationClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutomationClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutomationClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutomationClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutomationClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutomationClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
AutomationAccount = new AutomationAccountOperations(this);
Operations = new Operations(this);
Statistics = new StatisticsOperations(this);
Usages = new UsagesOperations(this);
Keys = new KeysOperations(this);
Certificate = new CertificateOperations(this);
Connection = new ConnectionOperations(this);
ConnectionType = new ConnectionTypeOperations(this);
Credential = new CredentialOperations(this);
DscConfiguration = new DscConfigurationOperations(this);
HybridRunbookWorkerGroup = new HybridRunbookWorkerGroupOperations(this);
JobSchedule = new JobScheduleOperations(this);
LinkedWorkspace = new LinkedWorkspaceOperations(this);
Activity = new ActivityOperations(this);
Module = new ModuleOperations(this);
ObjectDataTypes = new ObjectDataTypesOperations(this);
Fields = new FieldsOperations(this);
Schedule = new ScheduleOperations(this);
Variable = new VariableOperations(this);
Webhook = new WebhookOperations(this);
Watcher = new WatcherOperations(this);
SoftwareUpdateConfigurations = new SoftwareUpdateConfigurationsOperations(this);
SoftwareUpdateConfigurationRuns = new SoftwareUpdateConfigurationRunsOperations(this);
SoftwareUpdateConfigurationMachineRuns = new SoftwareUpdateConfigurationMachineRunsOperations(this);
SourceControl = new SourceControlOperations(this);
SourceControlSyncJob = new SourceControlSyncJobOperations(this);
SourceControlSyncJobStreams = new SourceControlSyncJobStreamsOperations(this);
Job = new JobOperations(this);
JobStream = new JobStreamOperations(this);
AgentRegistrationInformation = new AgentRegistrationInformationOperations(this);
DscNode = new DscNodeOperations(this);
NodeReports = new NodeReportsOperations(this);
DscCompilationJob = new DscCompilationJobOperations(this);
DscCompilationJobStream = new DscCompilationJobStreamOperations(this);
DscNodeConfiguration = new DscNodeConfigurationOperations(this);
NodeCountInformation = new NodeCountInformationOperations(this);
RunbookDraft = new RunbookDraftOperations(this);
Runbook = new RunbookOperations(this);
TestJobStreams = new TestJobStreamsOperations(this);
TestJob = new TestJobOperations(this);
Python2Package = new Python2PackageOperations(this);
BaseUri = new System.Uri("https://management.azure.com");
AcceptLanguage = "en-US";
LongRunningOperationRetryTimeout = 30;
GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| mit |
rschiefer/templating | src/Microsoft.TemplateEngine.Abstractions/ILocalizationModel.cs | 711 | using System;
using System.Collections.Generic;
namespace Microsoft.TemplateEngine.Abstractions
{
public interface ILocalizationModel
{
string Author { get; }
string Name { get; }
string Description { get; }
// Identifies the langpack association with an actual template. They'll both have the same identity.
// This is not localized info, more like a key
string Identity { get; }
IReadOnlyDictionary<string, IParameterSymbolLocalizationModel> ParameterSymbols { get; }
IReadOnlyDictionary<Guid, IPostActionLocalizationModel> PostActions { get; }
IReadOnlyList<IFileLocalizationModel> FileLocalizations { get; }
}
}
| mit |
wangjun/OP | client/scripts/services/exchangeSceneService.js | 2894 | (function() {
var ExchangeSceneService;
ExchangeSceneService = (function() {
ExchangeSceneService.headers = {
'Accept': 'application/json',
'Content-Type': 'application/json'
};
ExchangeSceneService.defaultConfig = {
headers: ExchangeSceneService.headers
};
function ExchangeSceneService($log, $http, $q) {
this.$log = $log;
this.$http = $http;
this.$q = $q;
this.$log.debug("constructing ExchangeRuleService");
}
ExchangeSceneService.prototype.findExchangeScenes = function(pager) {
var deferred;
this.$log.debug("findExchangeScenes()");
deferred = this.$q.defer();
this.$http.get(baseUrl + "/exchangescene", {
headers: {
'params': encodeURIComponent(angular.toJson(pager))
}
}).success((function(_this) {
return function(data, status, headers) {
_this.$log.info("Successfully find exchangescene - status " + status);
return deferred.resolve(data);
};
})(this)).error((function(_this) {
return function(data, status, headers) {
_this.$log.error("Failed to find exchangescene - status " + status);
return deferred.reject(data);
};
})(this));
return deferred.promise;
};
ExchangeSceneService.prototype.saveScene = function(scene) {
var deferred;
this.$log.debug("saveRule " + (angular.toJson(scene, true)));
deferred = this.$q.defer();
this.$http.post(baseUrl + "/exchangescene", scene).success((function(_this) {
return function(data, status, headers) {
_this.$log.info("Successfully save scene - status " + status);
return deferred.resolve(data);
};
})(this)).error((function(_this) {
return function(data, status, headers) {
_this.$log.error("Failed to save scene - status " + status);
return deferred.reject(data);
};
})(this));
return deferred.promise;
};
ExchangeSceneService.prototype.deleteScene = function(scene) {
var deferred;
this.$log.debug("deleteRule " + (angular.toJson(scene, true)));
deferred = this.$q.defer();
this.$http.delete(baseUrl + '/exchangescene/' + scene.id).success((function(_this) {
return function(data, status, headers) {
_this.$log.info("Successfully delete scene - status " + status);
return deferred.resolve(data);
};
})(this)).error((function(_this) {
return function(data, status, headers) {
_this.$log.error("Failed to delete scene - status " + status);
return deferred.reject(data);
};
})(this));
return deferred.promise;
};
return ExchangeSceneService;
})();
angular.module('sbAdminApp').service('ExchangeSceneService', ExchangeSceneService);
}).call(this);
| mit |
anaqreon/hubzilla | Zotlabs/Lib/Verify.php | 1386 | <?php
namespace Zotlabs\Lib;
class Verify {
function create($type,$channel_id,$token,$meta) {
return q("insert into verify ( vtype, channel, token, meta, created ) values ( '%s', %d, '%s', '%s', '%s' )",
dbesc($type),
intval($channel_id),
dbesc($token),
dbesc($meta),
dbesc(datetime_convert())
);
}
function match($type,$channel_id,$token,$meta) {
$r = q("select id from verify where vtype = '%s' and channel = %d and token = '%s' and meta = '%s' limit 1",
dbesc($type),
intval($channel_id),
dbesc($token),
dbesc($meta)
);
if($r) {
q("delete from verify where id = %d",
intval($r[0]['id'])
);
return true;
}
return false;
}
function get_meta($type,$channel_id,$token) {
$r = q("select id, meta from verify where vtype = '%s' and channel = %d and token = '%s' limit 1",
dbesc($type),
intval($channel_id),
dbesc($token)
);
if($r) {
q("delete from verify where id = %d",
intval($r[0]['id'])
);
return $r[0]['meta'];
}
return false;
}
/**
* @brief Purge entries of a verify-type older than interval.
*
* @param string $type Verify type
* @param string $interval SQL compatible time interval
*/
function purge($type, $interval) {
q("delete from verify where vtype = '%s' and created < %s - INTERVAL %s",
dbesc($type),
db_utcnow(),
db_quoteinterval($interval)
);
}
} | mit |
gokudomatic/godot | tools/editor/groups_editor.cpp | 5064 | /*************************************************************************/
/* groups_editor.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* http://www.godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "groups_editor.h"
#include "scene/gui/box_container.h"
#include "scene/gui/label.h"
#include "print_string.h"
void GroupsEditor::_notification(int p_what) {
if (p_what==NOTIFICATION_ENTER_TREE) {
connect("confirmed", this,"_close");
}
}
void GroupsEditor::_close() {
hide();
}
void GroupsEditor::_add() {
if (!node)
return;
undo_redo->create_action("Add To Group");
undo_redo->add_do_method(node,"add_to_group",group_name->get_text(),true);
undo_redo->add_undo_method(node,"remove_from_group",group_name->get_text());
undo_redo->add_do_method(this,"update_tree");
undo_redo->add_undo_method(this,"update_tree");
undo_redo->commit_action();
}
void GroupsEditor::_remove() {
if (!tree->get_selected())
return;
if (!node)
return;
TreeItem *sel = tree->get_selected();
if (!sel)
return;
node->remove_from_group( sel->get_text(0) );
update_tree();
}
void GroupsEditor::update_tree() {
tree->clear();
if (!node)
return;
List<GroupInfo> groups;
node->get_groups(&groups);
TreeItem *root=tree->create_item();
for(List<GroupInfo>::Element *E=groups.front();E;E=E->next()) {
if (!E->get().persistent)
continue;
TreeItem *item=tree->create_item(root);
item->set_text(0, E->get().name);
}
}
void GroupsEditor::set_current(Node* p_node) {
node=p_node;
update_tree();
}
void GroupsEditor::_bind_methods() {
ObjectTypeDB::bind_method("_add",&GroupsEditor::_add);
ObjectTypeDB::bind_method("_close",&GroupsEditor::_close);
ObjectTypeDB::bind_method("_remove",&GroupsEditor::_remove);
ObjectTypeDB::bind_method("update_tree",&GroupsEditor::update_tree);
}
GroupsEditor::GroupsEditor() {
set_title("Group Editor");
Label * label = memnew( Label );
label->set_pos( Point2( 8,11) );
label->set_text("Groups:");
add_child(label);
group_name = memnew(LineEdit);
group_name->set_anchor( MARGIN_RIGHT, ANCHOR_END );
group_name->set_begin( Point2( 15,28) );
group_name->set_end( Point2( 94,48 ) );
add_child(group_name);
tree = memnew( Tree );
tree->set_anchor( MARGIN_RIGHT, ANCHOR_END );
tree->set_anchor( MARGIN_BOTTOM, ANCHOR_END );
tree->set_begin( Point2( 15,52) );
tree->set_end( Point2( 94,42 ) );
tree->set_hide_root(true);
add_child(tree);
add = memnew( Button );
add->set_anchor( MARGIN_LEFT, ANCHOR_END );
add->set_anchor( MARGIN_RIGHT, ANCHOR_END );
add->set_begin( Point2( 90, 28 ) );
add->set_end( Point2( 15, 48 ) );
add->set_text("Add");
add_child(add);
remove = memnew( Button );
remove->set_anchor( MARGIN_LEFT, ANCHOR_END );
remove->set_anchor( MARGIN_RIGHT, ANCHOR_END );
remove->set_begin( Point2( 90, 52 ) );
remove->set_end( Point2( 15, 72 ) );
remove->set_text("Remove");
add_child(remove);
get_ok()->set_text("Close");
add->connect("pressed", this,"_add");
remove->connect("pressed", this,"_remove");
node=NULL;
}
GroupsEditor::~GroupsEditor()
{
}
| mit |
SpacePossum/PHP-CS-Fixer | tests/Fixer/LanguageConstruct/CombineConsecutiveIssetsFixerTest.php | 5889 | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Tests\Fixer\LanguageConstruct;
use PhpCsFixer\Tests\Test\AbstractFixerTestCase;
/**
* @internal
*
* @covers \PhpCsFixer\Fixer\LanguageConstruct\CombineConsecutiveIssetsFixer
*/
final class CombineConsecutiveIssetsFixerTest extends AbstractFixerTestCase
{
/**
* @dataProvider provideFixCases
*/
public function testFix(string $expected, ?string $input = null): void
{
$this->doTest($expected, $input);
}
public function provideFixCases(): array
{
return [
[
'<?php $a = isset($a, $b) ;',
'<?php $a = isset($a) && isset($b);',
],
[
'<?php $a = isset($a, $b,$c) ;',
'<?php $a = isset($a) && isset($b,$c);',
],
[
'<?php $a = isset($a,$c, $b,$c) ;',
'<?php $a = isset($a,$c) && isset($b,$c);',
],
[
'<?php $a = isset($a,$c, $b) ;',
'<?php $a = isset($a,$c) && isset($b);',
],
[
'<?php $a = isset($a, $b) || isset($c, $e) ?>',
'<?php $a = isset($a) && isset($b) || isset($c) && isset($e)?>',
],
[
'<?php $a = isset($a[a() ? b() : $d], $b) ;',
'<?php $a = isset($a[a() ? b() : $d]) && isset($b);',
],
[
'<?php $a = isset($a[$b], $b/**/) ;',
'<?php $a = isset($a[$b]/**/) && isset($b);',
],
[
'<?php $a = isset ( $a, $c, $d /*1*/ ) ;',
'<?php $a = isset ( $a /*1*/ ) && isset ( $c ) && isset( $d );',
],
'minimal fix case' => [
'<?php {{isset($a, $b);}}',
'<?php {{isset($a)&&isset($b);}}',
],
[
'<?php foo(isset($a, $b, $c) );',
'<?php foo(isset($a) && isset($b) && isset($c));',
],
[
'<?php isset($a, $b) && !isset($c) ?>',
'<?php isset($a) && isset($b) && !isset($c) ?>',
],
[
'<?php $a = isset($a,$c, $b,$c, $b,$c,$d,$f, $b) ;',
'<?php $a = isset($a,$c) && isset($b,$c) && isset($b,$c,$d,$f) && isset($b);',
],
'comments' => [
'<?php
$a =#0
isset#1
(#2
$a, $b,$c, $d#3
)#4
#5
#6
#7
#8
#9
/*10*/ /**11
*/
'.'
;',
'<?php
$a =#0
isset#1
(#2
$a#3
)#4
&
isset
#6
#7
( #8
$b #9
/*10*/, $c/**11
*/
)&& isset($d)
;',
],
[
'<?php
$a = isset($a, $b, $c, $d, $e, $f) ;
echo 1; echo 1; echo 1; echo 1; echo 1; echo 1; echo 1;
echo 1; echo 1; echo 1; echo 1; echo 1; echo 1; echo 1;
echo 1; echo 1; echo 1; echo 1; echo 1; echo 1; echo 1;
echo 1; echo 1; echo 1; echo 1; echo 1; echo 1; echo 1;
$a = isset($a, $b) ;
',
'<?php
$a = isset($a) && isset($b) && isset($c) && isset($d) && isset($e) && isset($f);
echo 1; echo 1; echo 1; echo 1; echo 1; echo 1; echo 1;
echo 1; echo 1; echo 1; echo 1; echo 1; echo 1; echo 1;
echo 1; echo 1; echo 1; echo 1; echo 1; echo 1; echo 1;
echo 1; echo 1; echo 1; echo 1; echo 1; echo 1; echo 1;
$a = isset($a) && isset($b);
',
],
[
'<?php $d = isset($z[1], $z[2], $z[3]) || false;',
'<?php $d = isset($z[1]) && isset($z[2]) && isset($z[3]) || false;',
],
[
'<?php
$a = isset($a, $b) && isset($c) === false;
$a = isset($a, $b) && isset($c) | false;
$a = isset($a, $b) && isset($c) ^ false;
',
'<?php
$a = isset($a) && isset($b) && isset($c) === false;
$a = isset($a) && isset($b) && isset($c) | false;
$a = isset($a) && isset($b) && isset($c) ^ false;
',
],
// don't fix cases
[
'<?php $a = isset($a) && $a->isset(); $b=isset($d);',
],
[
'<?php
$a = !isset($a) && isset($b);
$a = !isset($a) && !isset($b);
$a = isset($a) && !isset($b);
//
$a = isset($b) && isset($c) === false;
$a = isset($b) && isset($c) | false;
$a = isset($b) && isset($c) ^ false;
//
$a = false === isset($b) && isset($c);
$a = false | isset($b) && isset($c);
$a = false ^ isset($b) && isset($c);
',
],
[
'<?php $a = !isset($container[$a]) && isset($container[$b]) && !isset($container[$c]) && isset($container[$d]);',
],
];
}
public function testAnonymousClass(): void
{
$this->doTest(
'<?php
class A {function isset(){}} // isset($b) && isset($c)
$a = new A(); /** isset($b) && isset($c) */
if (isset($b) && $a->isset()) {}
'
);
}
}
| mit |
enclose-io/compiler | lts/test/node-api/test_exception/test.js | 578 | 'use strict';
// Flags: --expose-gc
const common = require('../../common');
const assert = require('assert');
const test_exception = require(`./build/${common.buildType}/test_exception`);
// Make sure that exceptions that occur during finalization are propagated.
function testFinalize(binding) {
let x = test_exception[binding]();
x = null;
global.gc();
process.on('uncaughtException', (err) => {
assert.strictEqual(err.message, 'Error during Finalize');
});
// To assuage the linter's concerns.
(function() {})(x);
}
testFinalize('createExternalBuffer');
| mit |
sgarciac/spec | library/fiber/transfer_spec.rb | 1690 | require File.expand_path('../../../spec_helper', __FILE__)
require File.expand_path('../../../shared/fiber/resume', __FILE__)
with_feature :fiber_library do
require 'fiber'
describe "Fiber#transfer" do
it_behaves_like :fiber_resume, :transfer
end
describe "Fiber#transfer" do
it "transfers control from one Fiber to another when called from a Fiber" do
fiber1 = Fiber.new { :fiber1 }
fiber2 = Fiber.new { fiber1.transfer; :fiber2 }
fiber2.resume.should == :fiber1
end
it "returns to the root Fiber when finished" do
f1 = Fiber.new { :fiber_1 }
f2 = Fiber.new { f1.transfer; :fiber_2 }
f2.transfer.should == :fiber_1
f2.transfer.should == :fiber_2
end
it "can be invoked from the same Fiber it transfers control to" do
states = []
fiber = Fiber.new { states << :start; fiber.transfer; states << :end }
fiber.transfer
states.should == [:start, :end]
states = []
fiber = Fiber.new { states << :start; fiber.transfer; states << :end }
fiber.resume
states.should == [:start, :end]
end
it "can transfer control to a Fiber that has transfered to another Fiber" do
states = []
fiber1 = Fiber.new { states << :fiber1 }
fiber2 = Fiber.new { states << :fiber2_start; fiber1.transfer; states << :fiber2_end}
fiber2.resume.should == [:fiber2_start, :fiber1]
fiber2.transfer.should == [:fiber2_start, :fiber1, :fiber2_end]
end
it "raises a FiberError when transferring to a Fiber which resumes itself" do
fiber = Fiber.new { fiber.resume }
lambda { fiber.transfer }.should raise_error(FiberError)
end
end
end
| mit |
enhavo/EnhavoNewsletterBundle | Model/Subscriber.php | 1683 | <?php
/**
* Subscriber.php
*
* @since $date
* @author $username-media
*/
namespace Enhavo\Bundle\NewsletterBundle\Model;
class Subscriber implements SubscriberInterface
{
/**
* @var string
*/
private $email;
/**
* @var \DateTime
*/
private $createdAt;
/**
* @var string
*/
private $subscription;
/**
* @var string|null
*/
private $confirmationToken;
/**
* @param string|null $email
*/
public function setEmail(?string $email): void
{
$this->email = $email;
}
/**
* @return string|null
*/
public function getEmail(): ?string
{
return $this->email;
}
/**
* @return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* @param \DateTime $createdAt
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
}
/**
* @return string|null
*/
public function getSubscription(): ?string
{
return $this->subscription;
}
/**
* @param string|null $subscription
*/
public function setSubscription(?string $subscription): void
{
$this->subscription = $subscription;
}
/**
* @return string|null
*/
public function getConfirmationToken(): ?string
{
return $this->confirmationToken;
}
/**
* @param string|null $token
*/
public function setConfirmationToken(?string $token): void
{
$this->confirmationToken = $token;
}
public function __toString()
{
return $this->email;
}
}
| mit |
okmttdhr/flux-challenge | submissions/jas-chen/src/constants.js | 69 | export const TOTAL_SLOT_COUNT = 5;
export const MOVE_SLOT_COUNT = 2;
| mit |
TelerikAcademy/JavaScript-OOP | Topics/01. Functions-and-Function-Expressions/demos/04. function-expressions/function-expressions.js | 438 | /* globals console */
var print = function(message) {
let doc = this.document;
if (doc && doc.body) {
doc.body.innerHTML +=
`<div class='message'>${message}</div>`;
} else {
console.log(message);
}
};
print(123);
let f3 = function() {
print("This is f3");
};
let f2 = function() {
f3();
print("This is f2");
};
let f1 = function() {
f2();
print("This is f1");
};
f1(); | mit |
Alex1990/grunt-seajs-fresh | test/origin/basic/src/foo.js | 226 | define(function(require, exports, module) {
var $ = require('jQuery');
var alert = require('alert');
var out = {
alert: function(o) {
$.alert(o);
}
};
module.exports = out;
}); | mit |
mattgray/SevenDigital.Api.Wrapper | src/SevenDigital.Api.Wrapper.Unit.Tests/Exceptions/InvalidResourceExceptionTests.cs | 1304 | using System.Collections.Generic;
using System.Net;
using NUnit.Framework;
using SevenDigital.Api.Schema;
using SevenDigital.Api.Wrapper.Exceptions;
using SevenDigital.Api.Wrapper.Http;
namespace SevenDigital.Api.Wrapper.Unit.Tests.Exceptions
{
[TestFixture]
public class InvalidResourceExceptionTests
{
[Test]
public void Should_round_trip_serialise_and_deserialise_exception()
{
var headers = new Dictionary<string, string>
{
{"Header1", "Header1Value"},
{"Header2", "Header2Value"}
};
var response = new Response(HttpStatusCode.Conflict, headers, "responseBody");
var inputException = new InvalidResourceException("The resource was not found", response, ErrorCode.ResourceNotFound);
var roundTripSerialiser = new RoundTripSerialiser();
var outputException = roundTripSerialiser.RoundTrip(inputException);
Assert.That(outputException.ErrorCode, Is.EqualTo(inputException.ErrorCode));
Assert.That(outputException.Headers, Is.EqualTo(inputException.Headers));
Assert.That(outputException.ResponseBody, Is.EqualTo(inputException.ResponseBody));
Assert.That(outputException.StatusCode, Is.EqualTo(inputException.StatusCode));
Assert.That(outputException.Message, Is.EqualTo(inputException.Message));
}
}
}
| mit |
jkroepke/2Moons | includes/pages/game/ShowOfficierPage.class.php | 5028 | <?php
/**
* 2Moons
* by Jan-Otto Kröpke 2009-2016
*
* For the full copyright and license information, please view the LICENSE
*
* @package 2Moons
* @author Jan-Otto Kröpke <slaver7@gmail.com>
* @copyright 2009 Lucky
* @copyright 2016 Jan-Otto Kröpke <slaver7@gmail.com>
* @licence MIT
* @version 1.8.0
* @link https://github.com/jkroepke/2Moons
*/
class ShowOfficierPage extends AbstractGamePage
{
public static $requireModule = 0;
function __construct()
{
parent::__construct();
}
public function UpdateExtra($Element)
{
global $PLANET, $USER, $resource, $pricelist;
$costResources = BuildFunctions::getElementPrice($USER, $PLANET, $Element);
if (!BuildFunctions::isElementBuyable($USER, $PLANET, $Element, $costResources)) {
return;
}
$USER[$resource[$Element]] = max($USER[$resource[$Element]], TIMESTAMP) + $pricelist[$Element]['time'];
if(isset($costResources[901])) { $PLANET[$resource[901]] -= $costResources[901]; }
if(isset($costResources[902])) { $PLANET[$resource[902]] -= $costResources[902]; }
if(isset($costResources[903])) { $PLANET[$resource[903]] -= $costResources[903]; }
if(isset($costResources[921])) { $USER[$resource[921]] -= $costResources[921]; }
$sql = 'UPDATE %%USERS%% SET
'.$resource[$Element].' = :newTime
WHERE
id = :userId;';
Database::get()->update($sql, array(
':newTime' => $USER[$resource[$Element]],
':userId' => $USER['id']
));
}
public function UpdateOfficier($Element)
{
global $USER, $PLANET, $resource, $pricelist;
$costResources = BuildFunctions::getElementPrice($USER, $PLANET, $Element);
if (!BuildFunctions::isTechnologieAccessible($USER, $PLANET, $Element)
|| !BuildFunctions::isElementBuyable($USER, $PLANET, $Element, $costResources)
|| $pricelist[$Element]['max'] <= $USER[$resource[$Element]]) {
return;
}
$USER[$resource[$Element]] += 1;
if(isset($costResources[901])) { $PLANET[$resource[901]] -= $costResources[901]; }
if(isset($costResources[902])) { $PLANET[$resource[902]] -= $costResources[902]; }
if(isset($costResources[903])) { $PLANET[$resource[903]] -= $costResources[903]; }
if(isset($costResources[921])) { $USER[$resource[921]] -= $costResources[921]; }
$sql = 'UPDATE %%USERS%% SET
'.$resource[$Element].' = :newTime
WHERE
id = :userId;';
Database::get()->update($sql, array(
':newTime' => $USER[$resource[$Element]],
':userId' => $USER['id']
));
}
public function show()
{
global $USER, $PLANET, $resource, $reslist, $LNG, $pricelist;
$updateID = HTTP::_GP('id', 0);
if (!empty($updateID) && $_SERVER['REQUEST_METHOD'] === 'POST' && $USER['urlaubs_modus'] == 0)
{
if(isModuleAvailable(MODULE_OFFICIER) && in_array($updateID, $reslist['officier'])) {
$this->UpdateOfficier($updateID);
} elseif(isModuleAvailable(MODULE_DMEXTRAS) && in_array($updateID, $reslist['dmfunc'])) {
$this->UpdateExtra($updateID);
}
}
$darkmatterList = array();
$officierList = array();
if(isModuleAvailable(MODULE_DMEXTRAS))
{
foreach($reslist['dmfunc'] as $Element)
{
if($USER[$resource[$Element]] > TIMESTAMP) {
$this->tplObj->execscript("GetOfficerTime(".$Element.", ".($USER[$resource[$Element]] - TIMESTAMP).");");
}
$costResources = BuildFunctions::getElementPrice($USER, $PLANET, $Element);
$buyable = BuildFunctions::isElementBuyable($USER, $PLANET, $Element, $costResources);
$costOverflow = BuildFunctions::getRestPrice($USER, $PLANET, $Element, $costResources);
$elementBonus = BuildFunctions::getAvalibleBonus($Element);
$darkmatterList[$Element] = array(
'timeLeft' => max($USER[$resource[$Element]] - TIMESTAMP, 0),
'costResources' => $costResources,
'buyable' => $buyable,
'time' => $pricelist[$Element]['time'],
'costOverflow' => $costOverflow,
'elementBonus' => $elementBonus,
);
}
}
if(isModuleAvailable(MODULE_OFFICIER))
{
foreach($reslist['officier'] as $Element)
{
if (!BuildFunctions::isTechnologieAccessible($USER, $PLANET, $Element))
continue;
$costResources = BuildFunctions::getElementPrice($USER, $PLANET, $Element);
$buyable = BuildFunctions::isElementBuyable($USER, $PLANET, $Element, $costResources);
$costOverflow = BuildFunctions::getRestPrice($USER, $PLANET, $Element, $costResources);
$elementBonus = BuildFunctions::getAvalibleBonus($Element);
$officierList[$Element] = array(
'level' => $USER[$resource[$Element]],
'maxLevel' => $pricelist[$Element]['max'],
'costResources' => $costResources,
'buyable' => $buyable,
'costOverflow' => $costOverflow,
'elementBonus' => $elementBonus,
);
}
}
$this->assign(array(
'officierList' => $officierList,
'darkmatterList' => $darkmatterList,
'of_dm_trade' => sprintf($LNG['of_dm_trade'], $LNG['tech'][921]),
));
$this->display('page.officier.default.tpl');
}
} | mit |
newky2k/DHDialogs | src/XamDialogs/Properties/AssemblyInfo.cs | 987 | using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle ("XamDialogs")]
[assembly: AssemblyDescription ("")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("")]
[assembly: AssemblyProduct ("")]
[assembly: AssemblyCopyright ("davidhum")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly:AssemblyVersion("1.1")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| mit |
CPFL/gdev | compiler/as/ptx2sass/ocelot/executive/test/TestEmulator.cpp | 11362 | /*!
\file TestEmulator.cpp
\author Andrew Kerr <arkerr@gatech.edu>
\brief tests the emulation layer
*/
#include <sstream>
#include <fstream>
#include <hydrazine/interface/Test.h>
#include <hydrazine/interface/Exception.h>
#include <hydrazine/interface/ArgumentParser.h>
#include <hydrazine/interface/macros.h>
#include <hydrazine/interface/debug.h>
#include <ocelot/ir/interface/Module.h>
#include <ocelot/executive/interface/EmulatedKernel.h>
#include <ocelot/executive/interface/RuntimeException.h>
#include <ocelot/executive/interface/CooperativeThreadArray.h>
#include <cmath>
namespace test {
class TestEmulator: public Test {
public:
ir::Module module;
ir::IRKernel* rawKernel;
public:
TestEmulator() {
name = "TestEmulator";
rawKernel = 0;
status << "Test output:\n";
}
/*!
Tests initialization of executive, load of kernel, and translation to
EmulatedKernel
*/
bool testKernelLoading() {
using namespace std;
using namespace ir;
using namespace executive;
bool result = true;
string path = "ocelot/executive/test/sequence.ptx";
bool loaded = false;
try {
loaded = module.load(path);
}
catch(const hydrazine::Exception& e) {
status << " error - " << e.what() << "\n";
}
if(!loaded) {
status << "failed to load module '" << path << "'\n";
return (result = false);
}
rawKernel = module.getKernel("_Z17k_simple_sequencePi");
if (!rawKernel) {
status << "failed to get kernel\n";
return (result = false);
}
return result;
}
/*!
Tests register getters and setters:
Construct a Module,
*/
bool testRegisterAccessors() {
using namespace std;
using namespace ir;
using namespace executive;
bool result = true;
EmulatedKernel *kernel = 0;
if (!rawKernel) {
status << "failed to get kernel\n";
return (result = false);
}
EmulatedKernel k(rawKernel, 0);
kernel = &k;
// construct a CooperativeThreadArray from kernel
const int Threads = 8;
kernel->setKernelShape(Threads,1,1);
status << kernel->registerCount() << " registers\n";
CooperativeThreadArray cta(kernel, ir::Dim3(), false);
for (int j = 0; j < (int)kernel->registerCount(); j++) {
for (int i = 0; i < Threads; i++) {
cta.setRegAsU32(i, j, i*(j+1));
}
}
for (int j = 0; result && j < (int)kernel->registerCount(); j++) {
for (int i = 0; result && i < Threads; i++) {
if (cta.getRegAsU32(i, j) != (ir::PTXU32)(i*(j+1))) {
result = false;
status << "set/getRegAsU32 test failed\n";
}
}
}
for (int i = 0; result && i < Threads; i ++) {
// set as float, get as float
if (result) {
cta.setRegAsF32(i, 1, 12.5f);
if (std::fabs(cta.getRegAsF32(i, 1) - 12.5f) > 0.01f) {
result = false;
status << "set/getRegAsF32 failed\n";
}
}
// handling types of mixed sizes
if (result) {
PTXU64 value = 0xffffffffffffffffULL;
PTXU64 outval = 0xffffffffffff0000ULL;
PTXU64 encountered;
cta.setRegAsU64(i, 3, value);
cta.setRegAsU16(i, 3, 0);
encountered = cta.getRegAsU64(i, 3);
if (encountered != outval) {
result = false;
status << "setAsU64, setAsU16 failed: getAsU64 returned 0x"
<< std::hex;
status << encountered << ", expected: 0x" << outval
<< std::dec << " for thread " << i << "\n";
status << "read the register one more time: 0x"
<< std::hex << cta.getRegAsU64(i, 3) << dec << "\n";
}
}
// set as float, get as uint
if (result) {
cta.setRegAsF32(i, 2, 1.0f);
if (cta.getRegAsU32(i, 2) != 0x3F800000) {
result = false;
status << "setRegAsF32, getRegAsU32 failed: 0x"
<< std::hex << cta.getRegAsU32(i, 2) << std::dec
<< "\n";
}
}
}
if (result) {
status << "Register test passed\n";
}
return result;
}
/*!
Tests load instructions
*/
bool testLd() {
using namespace std;
using namespace ir;
using namespace executive;
bool result = true;
EmulatedKernel *kernel = 0;
if (!rawKernel) {
status << "failed to get kernel\n";
return (result = false);
}
EmulatedKernel k(rawKernel, 0);
kernel = &k;
int Threads = 1;
kernel->setKernelShape(Threads, 1, 1);
CooperativeThreadArray cta(kernel, ir::Dim3(), false);
// load and store to global memory
PTXU32 block[64];
PTXInstruction ld;
ld.opcode = PTXInstruction::Ld;
ld.addressSpace = PTXInstruction::Global;
ld.d.reg = 0;
ld.d.type = PTXOperand::u32;
ld.d.addressMode = PTXOperand::Register;
ld.a.type = PTXOperand::u32;
ld.a.offset = 0;
ld.a.reg = 1;
ld.a.addressMode = PTXOperand::Indirect;
ld.volatility = PTXInstruction::Nonvolatile;
if (ld.valid() != "") {
status << "ld.global instruction invalid: " << ld.valid() << "\n";
return (result = false);
}
block[0] = 0xa5a500a3;
cta.setRegAsU32(0, 0, 0);
cta.setRegAsU64(0, 1, (PTXU64)block);
try {
cta.eval_Ld(cta.getActiveContext(), ld);
if (cta.getRegAsU32(0, 0) != 0xa5a500a3) {
// load failed
result = false;
status << "ld.global failed. Got: 0x" << hex
<< cta.getRegAsU32(0,0) << "\n";
}
}
catch (RuntimeException &exp) {
status << "load test 1 failed\n";
status << "runtime exception on instruction "
<< exp.instruction.toString() << ":\n";
status << " " << exp.message << "\n";
result = false;
}
block[1] = 0x3F800000;
ld.a.offset = 4;
try {
cta.eval_Ld(cta.getActiveContext(), ld);
if (std::fabs(cta.getRegAsF32(0, 0) - 1.0f) > 0.1f) {
// load failed
result = false;
status << "ld.global failed. Got: " << cta.getRegAsF32(0,0)
<< "\n";
}
}
catch (RuntimeException &exp) {
status << "load test 2 failed\n";
status << "runtime exception on instruction "
<< exp.instruction.toString() << ":\n";
status << " " << exp.message << "\n";
result = false;
}
ld.type = PTXOperand::f32;
ld.d.addressMode = PTXOperand::Register;
ld.d.reg = 0;
ld.d.type = PTXOperand::f32;
ld.a.reg = 1;
ld.a.type = PTXOperand::u64;
ld.a.addressMode = PTXOperand::Indirect;
ld.a.offset = 8;
ld.addressSpace = PTXInstruction::Global;
if (ld.valid() != "") {
result = false;
status << "ld.global instruction invalid: " << ld.valid() << "\n";
}
cta.setRegAsU64(0, 1, (PTXU64)block);
cta.setRegAsF32(0, 0, -1.0f);
block[2] = 0xC0490E56; // -3.14159f
try {
cta.eval_Ld(cta.getActiveContext(), ld);
if (std::fabs(cta.getRegAsF32(0, 0) + 3.14159f) > 0.1f) {
result = false;
status << "ld.global failed: got "
<< cta.getRegAsF32(0,0) << "\n";
}
}
catch (RuntimeException &exp) {
status << "load test 3 failed\n";
status << "runtime exception on instruction "
<< exp.instruction.toString() << ":\n";
status << " " << exp.message << "\n";
result = false;
}
if (result) {
status << "Load test passed\n";
}
return result;
}
/*!
Tests store instructions
*/
bool testSt() {
using namespace std;
using namespace ir;
using namespace executive;
bool result = true;
EmulatedKernel *kernel = 0;
if (!rawKernel) {
status << "failed to get kernel\n";
return (result = false);
}
int Threads = 1;
EmulatedKernel k(rawKernel, 0);
kernel = &k;
kernel->setKernelShape(Threads, 1, 1);
CooperativeThreadArray cta(kernel, ir::Dim3(), false);
// load and store to global memory
PTXU32 u_block[4];
PTXF32 f_block[2];
PTXInstruction st;
st.opcode = PTXInstruction::St;
st.addressSpace = PTXInstruction::Global;
st.a.reg = 0;
st.a.type = PTXOperand::u32;
st.a.addressMode = PTXOperand::Register;
st.a.identifier = "source";
st.d.type = PTXOperand::u64;
st.d.offset = 0;
st.d.reg = 1;
st.d.addressMode = PTXOperand::Indirect;
st.d.identifier = "dest";
if (st.valid() != "") {
status << "st.global instruction invalid: " << st.valid() << "\n";
return (result = false);
}
cta.setRegAsU64(0, 1, (PTXU64)u_block);
cta.setRegAsU32(0, 0, 74);
try {
cta.eval_St(cta.getActiveContext(), st);
if (u_block[0] != 74) {
result = false;
status << "st.global failed - got " << hex
<< u_block[0] << ", expected: " << cta.getRegAsU32(0, 0)
<< "\n";
}
}
catch (RuntimeException &exp) {
status << "store test 1 failed\n";
status << "runtime exception on instruction "
<< exp.instruction.toString() << ":\n";
status << " " << exp.message << "\n";
result = false;
}
cta.setRegAsU64(0, 1, (PTXU64)f_block);
cta.setRegAsF32(0, 0, 24.3f);
st.type = PTXOperand::f32;
st.a.type = PTXOperand::f32;
try {
cta.eval_St(cta.getActiveContext(), st);
if (std::fabs(f_block[0] - 24.3f) > 0.1f) {
result = false;
status << "st.global failed - got " << f_block[0]
<< ", expected: " << cta.getRegAsF32(0, 0) << "\n";
}
}
catch (RuntimeException &exp) {
status << "store test 2 failed\n";
status << "runtime exception on instruction "
<< exp.instruction.toString() << ":\n";
status << " " << exp.message << "\n";
result = false;
}
if (result) {
status << "Store test passed\n";
}
return result;
}
/*!
Loads a kernel, configures parameters, executes kernel,
and tests for accurate results
*/
bool testFullKernel() {
using namespace std;
using namespace ir;
using namespace executive;
bool result = true;
EmulatedKernel *kernel = 0;
if (!rawKernel) {
status << "failed to get kernel\n";
return (result = false);
}
EmulatedKernel k(rawKernel, 0);
kernel = &k;
const int N = 32;
int *inputSequence = new int[N];
// configure parameters
Parameter ¶m_A = *kernel->getParameter(
"__cudaparm__Z17k_simple_sequencePi_A");
// set parameter values
param_A.arrayValues.resize(1);
param_A.arrayValues[0].val_u64 = (PTXU64)inputSequence;
kernel->updateArgumentMemory();
// launch the kernel
try {
kernel->setKernelShape(N,1,1);
kernel->launchGrid(1,1,1);
// context.synchronize();
}
catch (RuntimeException &exp) {
status << "Full kernel test failed\n";
status << "Runtime exception on instruction [ "
<< exp.instruction.toString() << " ]:\n"
<< exp.message << "\n";
}
int errors = 0;
for (int i = 0; !errors && i < N; i++) {
if (inputSequence[i] != 2*i + 1) {
++ errors;
status << "error on status[" << i << "]: "
<< inputSequence[i] << "\n";
}
}
if (errors) {
status << "there were errors\n";
result = false;
}
else {
status << "no errors\n";
result = true;
}
delete[] inputSequence;
if (result) {
status << "Full kernel test passed\n";
}
return result;
}
/*!
Test driver
*/
bool doTest( ) {
bool result = testKernelLoading();
result = result && testRegisterAccessors() && testLd();
result = (result && testSt());
result = (result && testFullKernel());
return result;
}
private:
};
}
int main(int argc, char **argv) {
using namespace std;
using namespace ir;
using namespace test;
hydrazine::ArgumentParser parser( argc, argv );
test::TestEmulator test;
parser.description( test.testDescription() );
parser.parse( "-s", test.seed, 0,
"Set the random seed, 0 implies seed with time." );
parser.parse( "-v", test.verbose, false, "Print out info after the test." );
parser.parse();
test.test();
return test.passed();
}
| mit |
JoshuaEstes/apostrophePlugin | lib/form/aMediaEditForm.class.php | 264 | <?php
/**
* @package apostrophePlugin
* @subpackage form
* @author P'unk Avenue <apostrophe@punkave.com>
*/
class aMediaEditForm extends BaseaMediaEditForm
{
// You can override me with a project-level version that also extends BaseaMediaEditForm
} | mit |
g3aishih/csc309ip | node_modules/node-restful/examples/notes.js | 2690 | var express = require('express'),
mongoose = require('mongoose'),
restful = require('../');
// Make a new Express app
var app = module.exports = express();
// Connect to mongodb
mongoose.connect("mongodb://localhost/restful");
// Use middleware to parse POST data and use custom HTTP methods
app.use(express.bodyParser());
app.use(express.methodOverride());
var hashPassword = function(req, res, next) {
if (!req.body.password)
return next({ status: 400, err: "No password!" }); // We can also throw an error from a before route
req.body.password = bcrypt.hashSync(req.body.password, 10); // Using bcrypt
return next(); // Call the handler
}
var sendEmail = function(req, res, next) {
// We can get the user from res.bundle and status code from res.status and
// trigger an error by calling next(err) or populate information that would otherwise be miggins
next(); // I'll just pass though
}
var User = restful.model( "users", mongoose.Schema({
username: 'string',
password_hash: 'string',
}))
.methods(['get', 'put', 'delete', {
method: 'post',
before: hashPassword, // Before we make run the default POST to create a user, we want to hash the password (implementation omitted)
after: sendEmail, // After we register them, we will send them a confirmation email
}]);
User.register(app, '/user'); // Register the user model at the localhost:3000/user
var validateUser = function(req, res, next) {
if (!req.body.creator) {
return next({ status: 400, err: "Notes need a creator" });
}
User.Model.findById(req.body.creator, function(err, model) {
if (!model) return next(restful.objectNotFound());
return next();
});
}
var Note = restful.model("note", mongoose.Schema({
title: { type: 'string', required: true},
body: { type: 'string', required: true},
creator: { type: 'ObjectId', ref: 'user', require: true},
}))
.methods(['get', 'delete', { method: 'post', before: validateUser }, { method: 'put', before: validateUser }]);
Note.register(app, '/note');
User.route("notes", {
handler: function(req, res, next, err, model) { // we get err and model parameters on detail routes (model being the one model that was found)
Note.Model.find({ creator: model._id }, function(err, list) {
if (err) return next({ status: 500, err: "Something went wrong" });
//res.status is the status code
res.status = 200;
// res.bundle is what is returned, serialized to JSON
res.bundle = list;
return next();
});
},
detail: true, // detail routes operate on a single instance, i.e. /user/:id
methods: ['get'], // only respond to GET requests
});
app.listen(3000);
| mit |
dotnet/roslyn | src/Features/Core/Portable/ExtractMethod/MethodExtractor.CodeGenerator.cs | 19521 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExtractMethod
{
internal abstract partial class MethodExtractor
{
protected abstract partial class CodeGenerator<TStatement, TExpression, TNodeUnderContainer>
where TStatement : SyntaxNode
where TExpression : SyntaxNode
where TNodeUnderContainer : SyntaxNode
{
protected readonly SyntaxAnnotation MethodNameAnnotation;
protected readonly SyntaxAnnotation MethodDefinitionAnnotation;
protected readonly SyntaxAnnotation CallSiteAnnotation;
protected readonly InsertionPoint InsertionPoint;
protected readonly SemanticDocument SemanticDocument;
protected readonly SelectionResult SelectionResult;
protected readonly AnalyzerResult AnalyzerResult;
protected readonly OptionSet Options;
protected readonly bool LocalFunction;
protected CodeGenerator(InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult, OptionSet options = null, bool localFunction = false)
{
Contract.ThrowIfFalse(insertionPoint.SemanticDocument == analyzerResult.SemanticDocument);
InsertionPoint = insertionPoint;
SemanticDocument = insertionPoint.SemanticDocument;
SelectionResult = selectionResult;
AnalyzerResult = analyzerResult;
Options = options;
LocalFunction = localFunction;
MethodNameAnnotation = new SyntaxAnnotation();
CallSiteAnnotation = new SyntaxAnnotation();
MethodDefinitionAnnotation = new SyntaxAnnotation();
}
#region method to be implemented in sub classes
protected abstract SyntaxNode GetOutermostCallSiteContainerToProcess(CancellationToken cancellationToken);
protected abstract Task<SyntaxNode> GenerateBodyForCallSiteContainerAsync(CancellationToken cancellationToken);
protected abstract SyntaxNode GetPreviousMember(SemanticDocument document);
protected abstract OperationStatus<IMethodSymbol> GenerateMethodDefinition(bool localFunction, CancellationToken cancellationToken);
protected abstract bool ShouldLocalFunctionCaptureParameter(SyntaxNode node);
protected abstract SyntaxToken CreateIdentifier(string name);
protected abstract SyntaxToken CreateMethodName();
protected abstract bool LastStatementOrHasReturnStatementInReturnableConstruct();
protected abstract TNodeUnderContainer GetFirstStatementOrInitializerSelectedAtCallSite();
protected abstract TNodeUnderContainer GetLastStatementOrInitializerSelectedAtCallSite();
protected abstract Task<TNodeUnderContainer> GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(CancellationToken cancellationToken);
protected abstract TExpression CreateCallSignature();
protected abstract TStatement CreateDeclarationStatement(VariableInfo variable, TExpression initialValue, CancellationToken cancellationToken);
protected abstract TStatement CreateAssignmentExpressionStatement(SyntaxToken identifier, TExpression rvalue);
protected abstract TStatement CreateReturnStatement(string identifierName = null);
protected abstract ImmutableArray<TStatement> GetInitialStatementsForMethodDefinitions();
#endregion
public async Task<GeneratedCode> GenerateAsync(CancellationToken cancellationToken)
{
var root = SemanticDocument.Root;
// should I check venus hidden position check here as well?
root = root.ReplaceNode(GetOutermostCallSiteContainerToProcess(cancellationToken), await GenerateBodyForCallSiteContainerAsync(cancellationToken).ConfigureAwait(false));
var callSiteDocument = await SemanticDocument.WithSyntaxRootAsync(root, cancellationToken).ConfigureAwait(false);
var newCallSiteRoot = callSiteDocument.Root;
var codeGenerationService = SemanticDocument.Document.GetLanguageService<ICodeGenerationService>();
var result = GenerateMethodDefinition(LocalFunction, cancellationToken);
SyntaxNode destination, newContainer;
if (LocalFunction)
{
destination = InsertionPoint.With(callSiteDocument).GetContext();
// No valid location to insert the new method call.
if (destination == null)
{
return await CreateGeneratedCodeAsync(
OperationStatus.NoValidLocationToInsertMethodCall, callSiteDocument, cancellationToken).ConfigureAwait(false);
}
var options = codeGenerationService.GetOptions(
destination.SyntaxTree.Options,
Options,
new CodeGenerationContext(
generateDefaultAccessibility: false,
generateMethodBodies: true));
var localMethod = codeGenerationService.CreateMethodDeclaration(result.Data, CodeGenerationDestination.Unspecified, options, cancellationToken);
newContainer = codeGenerationService.AddStatements(destination, new[] { localMethod }, options, cancellationToken);
}
else
{
var previousMemberNode = GetPreviousMember(callSiteDocument);
// it is possible in a script file case where there is no previous member. in that case, insert new text into top level script
destination = previousMemberNode.Parent ?? previousMemberNode;
var options = codeGenerationService.GetOptions(
destination.SyntaxTree.Options,
Options,
new CodeGenerationContext(
afterThisLocation: previousMemberNode.GetLocation(),
generateDefaultAccessibility: true,
generateMethodBodies: true));
newContainer = codeGenerationService.AddMethod(destination, result.Data, options, cancellationToken);
}
var newSyntaxRoot = newCallSiteRoot.ReplaceNode(destination, newContainer);
var newDocument = callSiteDocument.Document.WithSyntaxRoot(newSyntaxRoot);
var generatedDocument = await SemanticDocument.CreateAsync(newDocument, cancellationToken).ConfigureAwait(false);
// For nullable reference types, we can provide a better experience by reducing use
// of nullable reference types after a method is done being generated. If we can
// determine that the method never returns null, for example, then we can
// make the signature into a non-null reference type even though
// the original type was nullable. This allows our code generation to
// follow our recommendation of only using nullable when necessary.
// This is done after method generation instead of at analyzer time because it's purely
// based on the resulting code, which the generator can modify as needed. If return statements
// are added, the flow analysis could change to indicate something different. It's cleaner to rely
// on flow analysis of the final resulting code than to try and predict from the analyzer what
// will happen in the generator.
var finalDocument = await UpdateMethodAfterGenerationAsync(generatedDocument, result, cancellationToken).ConfigureAwait(false);
var finalRoot = finalDocument.Root;
var methodDefinition = finalRoot.GetAnnotatedNodesAndTokens(MethodDefinitionAnnotation).FirstOrDefault();
if (!methodDefinition.IsNode || methodDefinition.AsNode() == null)
{
return await CreateGeneratedCodeAsync(
result.Status.With(OperationStatus.FailedWithUnknownReason), finalDocument, cancellationToken).ConfigureAwait(false);
}
if (methodDefinition.SyntaxTree.IsHiddenPosition(methodDefinition.AsNode().SpanStart, cancellationToken) ||
methodDefinition.SyntaxTree.IsHiddenPosition(methodDefinition.AsNode().Span.End, cancellationToken))
{
return await CreateGeneratedCodeAsync(
result.Status.With(OperationStatus.OverlapsHiddenPosition), finalDocument, cancellationToken).ConfigureAwait(false);
}
return await CreateGeneratedCodeAsync(result.Status, finalDocument, cancellationToken).ConfigureAwait(false);
}
protected virtual Task<SemanticDocument> UpdateMethodAfterGenerationAsync(
SemanticDocument originalDocument,
OperationStatus<IMethodSymbol> methodSymbolResult,
CancellationToken cancellationToken)
=> Task.FromResult(originalDocument);
protected virtual Task<GeneratedCode> CreateGeneratedCodeAsync(OperationStatus status, SemanticDocument newDocument, CancellationToken cancellationToken)
{
return Task.FromResult(new GeneratedCode(
status,
newDocument,
MethodNameAnnotation,
CallSiteAnnotation,
MethodDefinitionAnnotation));
}
protected VariableInfo GetOutermostVariableToMoveIntoMethodDefinition(CancellationToken cancellationToken)
{
using var _ = ArrayBuilder<VariableInfo>.GetInstance(out var variables);
variables.AddRange(AnalyzerResult.GetVariablesToMoveIntoMethodDefinition(cancellationToken));
if (variables.Count <= 0)
return null;
VariableInfo.SortVariables(SemanticDocument.SemanticModel.Compilation, variables);
return variables[0];
}
protected ImmutableArray<TStatement> AddReturnIfUnreachable(ImmutableArray<TStatement> statements)
{
if (AnalyzerResult.EndOfSelectionReachable)
{
return statements;
}
var type = SelectionResult.GetContainingScopeType();
if (type != null && type.SpecialType != SpecialType.System_Void)
{
return statements;
}
// no return type + end of selection not reachable
if (LastStatementOrHasReturnStatementInReturnableConstruct())
{
return statements;
}
return statements.Concat(CreateReturnStatement());
}
protected async Task<ImmutableArray<TStatement>> AddInvocationAtCallSiteAsync(
ImmutableArray<TStatement> statements, CancellationToken cancellationToken)
{
if (AnalyzerResult.HasVariableToUseAsReturnValue)
{
return statements;
}
Contract.ThrowIfTrue(AnalyzerResult.GetVariablesToSplitOrMoveOutToCallSite(cancellationToken).Any(v => v.UseAsReturnValue));
// add invocation expression
return statements.Concat(
(TStatement)(SyntaxNode)await GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(cancellationToken).ConfigureAwait(false));
}
protected ImmutableArray<TStatement> AddAssignmentStatementToCallSite(
ImmutableArray<TStatement> statements,
CancellationToken cancellationToken)
{
if (!AnalyzerResult.HasVariableToUseAsReturnValue)
{
return statements;
}
var variable = AnalyzerResult.VariableToUseAsReturnValue;
if (variable.ReturnBehavior == ReturnBehavior.Initialization)
{
// there must be one decl behavior when there is "return value and initialize" variable
Contract.ThrowIfFalse(AnalyzerResult.GetVariablesToSplitOrMoveOutToCallSite(cancellationToken).Single(v => v.ReturnBehavior == ReturnBehavior.Initialization) != null);
var declarationStatement = CreateDeclarationStatement(
variable, CreateCallSignature(), cancellationToken);
declarationStatement = declarationStatement.WithAdditionalAnnotations(CallSiteAnnotation);
return statements.Concat(declarationStatement);
}
Contract.ThrowIfFalse(variable.ReturnBehavior == ReturnBehavior.Assignment);
return statements.Concat(
CreateAssignmentExpressionStatement(CreateIdentifier(variable.Name), CreateCallSignature()).WithAdditionalAnnotations(CallSiteAnnotation));
}
protected ImmutableArray<TStatement> CreateDeclarationStatements(
ImmutableArray<VariableInfo> variables, CancellationToken cancellationToken)
{
return variables.SelectAsArray(v => CreateDeclarationStatement(v, initialValue: null, cancellationToken));
}
protected ImmutableArray<TStatement> AddSplitOrMoveDeclarationOutStatementsToCallSite(
CancellationToken cancellationToken)
{
using var _ = ArrayBuilder<TStatement>.GetInstance(out var list);
foreach (var variable in AnalyzerResult.GetVariablesToSplitOrMoveOutToCallSite(cancellationToken))
{
if (variable.UseAsReturnValue)
continue;
var declaration = CreateDeclarationStatement(
variable, initialValue: null, cancellationToken: cancellationToken);
list.Add(declaration);
}
return list.ToImmutable();
}
protected ImmutableArray<TStatement> AppendReturnStatementIfNeeded(ImmutableArray<TStatement> statements)
{
if (!AnalyzerResult.HasVariableToUseAsReturnValue)
{
return statements;
}
var variableToUseAsReturnValue = AnalyzerResult.VariableToUseAsReturnValue;
Contract.ThrowIfFalse(variableToUseAsReturnValue.ReturnBehavior is ReturnBehavior.Assignment or
ReturnBehavior.Initialization);
return statements.Concat(CreateReturnStatement(AnalyzerResult.VariableToUseAsReturnValue.Name));
}
protected static HashSet<SyntaxAnnotation> CreateVariableDeclarationToRemoveMap(
IEnumerable<VariableInfo> variables, CancellationToken cancellationToken)
{
var annotations = new List<Tuple<SyntaxToken, SyntaxAnnotation>>();
foreach (var variable in variables)
{
Contract.ThrowIfFalse(variable.GetDeclarationBehavior(cancellationToken) is DeclarationBehavior.MoveOut or
DeclarationBehavior.MoveIn or
DeclarationBehavior.Delete);
variable.AddIdentifierTokenAnnotationPair(annotations, cancellationToken);
}
return new HashSet<SyntaxAnnotation>(annotations.Select(t => t.Item2));
}
protected ImmutableArray<ITypeParameterSymbol> CreateMethodTypeParameters()
{
if (AnalyzerResult.MethodTypeParametersInDeclaration.Count == 0)
{
return ImmutableArray<ITypeParameterSymbol>.Empty;
}
var set = new HashSet<ITypeParameterSymbol>(AnalyzerResult.MethodTypeParametersInConstraintList);
var typeParameters = ArrayBuilder<ITypeParameterSymbol>.GetInstance();
foreach (var parameter in AnalyzerResult.MethodTypeParametersInDeclaration)
{
if (parameter != null && set.Contains(parameter))
{
typeParameters.Add(parameter);
continue;
}
typeParameters.Add(CodeGenerationSymbolFactory.CreateTypeParameter(
parameter.GetAttributes(), parameter.Variance, parameter.Name, ImmutableArray.Create<ITypeSymbol>(), parameter.NullableAnnotation,
parameter.HasConstructorConstraint, parameter.HasReferenceTypeConstraint, parameter.HasUnmanagedTypeConstraint,
parameter.HasValueTypeConstraint, parameter.HasNotNullConstraint, parameter.Ordinal));
}
return typeParameters.ToImmutableAndFree();
}
protected ImmutableArray<IParameterSymbol> CreateMethodParameters()
{
var parameters = ArrayBuilder<IParameterSymbol>.GetInstance();
var isLocalFunction = LocalFunction && ShouldLocalFunctionCaptureParameter(SemanticDocument.Root);
foreach (var parameter in AnalyzerResult.MethodParameters)
{
if (!isLocalFunction || !parameter.CanBeCapturedByLocalFunction)
{
var refKind = GetRefKind(parameter.ParameterModifier);
var type = parameter.GetVariableType(SemanticDocument);
parameters.Add(
CodeGenerationSymbolFactory.CreateParameterSymbol(
attributes: ImmutableArray<AttributeData>.Empty,
refKind: refKind,
isParams: false,
type: type,
name: parameter.Name));
}
}
return parameters.ToImmutableAndFree();
}
private static RefKind GetRefKind(ParameterBehavior parameterBehavior)
{
return parameterBehavior == ParameterBehavior.Ref ? RefKind.Ref :
parameterBehavior == ParameterBehavior.Out ? RefKind.Out : RefKind.None;
}
}
}
}
| mit |
zBMNForks/high_voltage | spec/controllers/pages_controller_spec.rb | 3434 | # encoding: utf-8
require "spec_helper"
describe HighVoltage::PagesController do
render_views
context "using default configuration" do
describe "on GET to /pages/exists" do
before { get :show, id: "exists" }
it "responds with success and render template" do
expect(response).to be_success
expect(response).to render_template("exists")
end
it "uses the default layout used by ApplicationController" do
expect(response).to render_template("layouts/application")
end
end
describe "on GET to /pages/dir/nested" do
before { get :show, id: "dir/nested" }
it "responds with success and render template" do
expect(response).to be_success
expect(response).to render_template("pages/dir/nested")
end
end
it "raises a routing error for an invalid page" do
expect { get :show, id: "invalid" }.
to raise_error(ActionController::RoutingError)
end
it "raises a routing error for a page in another directory" do
expect { get :show, id: "../other/wrong" }.
to raise_error(ActionController::RoutingError)
end
it "raises a missing template error for valid page with invalid partial" do
expect { get :show, id: "exists_but_references_nonexistent_partial" }.
to raise_error(ActionView::MissingTemplate)
end
end
context "using custom layout" do
before(:each) do
HighVoltage.layout = "alternate"
end
describe "on GET to /pages/exists" do
before { get :show, id: "exists" }
it "uses the custom configured layout" do
expect(response).not_to render_template("layouts/application")
expect(response).to render_template("layouts/alternate")
end
end
end
context "using custom content path" do
before(:each) do
HighVoltage.content_path = "other_pages/"
Rails.application.reload_routes!
end
describe "on GET to /other_pages/also_exists" do
before { get :show, id: "also_exists" }
it "responds with success and render template" do
expect(response).to be_success
expect(response).to render_template("other_pages/also_exists")
end
end
describe "on GET to /other_pages/also_dir/nested" do
before { get :show, id: "also_dir/also_nested" }
it "responds with success and render template" do
expect(response).to be_success
expect(response).to render_template("other_pages/also_dir/also_nested")
end
end
it "raises a routing error for an invalid page" do
expect { get :show, id: "also_invalid" }.
to raise_error(ActionController::RoutingError)
expect { get :show, id: "√®ø" }.
to raise_error(ActionController::RoutingError)
end
context "page in another directory" do
it "raises a routing error" do
expect { get :show, id: "../other_wrong" }.
to raise_error(ActionController::RoutingError)
end
it "raises a routing error when using a Unicode exploit" do
expect { get :show, id: "/\\../other/wrong" }.
to raise_error(ActionController::RoutingError)
end
end
it "raises a missing template error for valid page with invalid partial" do
id = "also_exists_but_references_nonexistent_partial"
expect { get :show, id: id }.
to raise_error(ActionView::MissingTemplate)
end
end
end
| mit |