repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
MavenRain/roslyn | src/Compilers/Core/Portable/Symbols/Attributes/AttributeUsageInfo.cs | 8585 | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Diagnostics;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
internal struct AttributeUsageInfo : IEquatable<AttributeUsageInfo>
{
[Flags()]
private enum PackedAttributeUsage
{
None = 0,
Assembly = AttributeTargets.Assembly,
Module = AttributeTargets.Module,
Class = AttributeTargets.Class,
Struct = AttributeTargets.Struct,
Enum = AttributeTargets.Enum,
Constructor = AttributeTargets.Constructor,
Method = AttributeTargets.Method,
Property = AttributeTargets.Property,
Field = AttributeTargets.Field,
Event = AttributeTargets.Event,
Interface = AttributeTargets.Interface,
Parameter = AttributeTargets.Parameter,
Delegate = AttributeTargets.Delegate,
ReturnValue = AttributeTargets.ReturnValue,
GenericParameter = AttributeTargets.GenericParameter,
All = AttributeTargets.All,
// NOTE: VB allows AttributeUsageAttribute with no valid target, i.e. <AttributeUsageAttribute(0)>, and doesn't generate any diagnostics.
// We use use PackedAttributeUsage.Initialized field to differentiate between uninitialized AttributeUsageInfo and initialized AttributeUsageInfo with no valid target.
Initialized = GenericParameter << 1,
AllowMultiple = Initialized << 1,
Inherited = AllowMultiple << 1
}
private readonly PackedAttributeUsage _flags;
/// <summary>
/// Default attribute usage for attribute types:
/// (a) Valid targets: AttributeTargets.All
/// (b) AllowMultiple: false
/// (c) Inherited: true
/// </summary>
static internal readonly AttributeUsageInfo Default = new AttributeUsageInfo(validTargets: AttributeTargets.All, allowMultiple: false, inherited: true);
static internal readonly AttributeUsageInfo Null = default(AttributeUsageInfo);
internal AttributeUsageInfo(AttributeTargets validTargets, bool allowMultiple, bool inherited)
{
// NOTE: VB allows AttributeUsageAttribute with no valid target, i.e. <AttributeUsageAttribute(0)>, and doesn't generate any diagnostics.
// We use use PackedAttributeUsage.Initialized field to differentiate between uninitialized AttributeUsageInfo and initialized AttributeUsageInfo with no valid targets.
_flags = (PackedAttributeUsage)validTargets | PackedAttributeUsage.Initialized;
if (allowMultiple)
{
_flags |= PackedAttributeUsage.AllowMultiple;
}
if (inherited)
{
_flags |= PackedAttributeUsage.Inherited;
}
}
public bool IsNull
{
get
{
return (_flags & PackedAttributeUsage.Initialized) == 0;
}
}
internal AttributeTargets ValidTargets
{
get
{
return (AttributeTargets)(_flags & PackedAttributeUsage.All);
}
}
internal bool AllowMultiple
{
get
{
return (_flags & PackedAttributeUsage.AllowMultiple) != 0;
}
}
internal bool Inherited
{
get
{
return (_flags & PackedAttributeUsage.Inherited) != 0;
}
}
public static bool operator ==(AttributeUsageInfo left, AttributeUsageInfo right)
{
return left._flags == right._flags;
}
public static bool operator !=(AttributeUsageInfo left, AttributeUsageInfo right)
{
return left._flags != right._flags;
}
public override bool Equals(object obj)
{
if (obj is AttributeUsageInfo)
{
return this.Equals((AttributeUsageInfo)obj);
}
return false;
}
public bool Equals(AttributeUsageInfo other)
{
return this == other;
}
public override int GetHashCode()
{
return _flags.GetHashCode();
}
internal bool HasValidAttributeTargets
{
get
{
var value = (int)ValidTargets;
return value != 0 && (value & (int)~AttributeTargets.All) == 0;
}
}
internal object GetValidTargetsErrorArgument()
{
var validTargetsInt = (int)ValidTargets;
if (!HasValidAttributeTargets)
{
return string.Empty;
}
var builder = ArrayBuilder<string>.GetInstance();
int flag = 0;
while (validTargetsInt > 0)
{
if ((validTargetsInt & 1) != 0)
{
builder.Add(GetErrorDisplayNameResourceId((AttributeTargets)(1 << flag)));
}
validTargetsInt >>= 1;
flag++;
}
return new ValidTargetsStringLocalizableErrorArgument(builder.ToArrayAndFree());
}
private struct ValidTargetsStringLocalizableErrorArgument : IFormattable, IMessageSerializable
{
private readonly string[] _targetResourceIds;
internal ValidTargetsStringLocalizableErrorArgument(string[] targetResourceIds)
{
Debug.Assert(targetResourceIds != null);
_targetResourceIds = targetResourceIds;
}
public override string ToString()
{
return ToString(null, null);
}
public string ToString(string format, IFormatProvider formatProvider)
{
var builder = PooledStringBuilder.GetInstance();
var culture = formatProvider as System.Globalization.CultureInfo;
if (_targetResourceIds != null)
{
foreach (string id in _targetResourceIds)
{
if (builder.Builder.Length > 0)
{
builder.Builder.Append(", ");
}
builder.Builder.Append(CodeAnalysisResources.ResourceManager.GetString(id, culture));
}
}
var message = builder.Builder.ToString();
builder.Free();
return message;
}
}
private static string GetErrorDisplayNameResourceId(AttributeTargets target)
{
switch (target)
{
case AttributeTargets.Assembly: return nameof(CodeAnalysisResources.Assembly);
case AttributeTargets.Class: return nameof(CodeAnalysisResources.Class1);
case AttributeTargets.Constructor: return nameof(CodeAnalysisResources.Constructor);
case AttributeTargets.Delegate: return nameof(CodeAnalysisResources.Delegate1);
case AttributeTargets.Enum: return nameof(CodeAnalysisResources.Enum1);
case AttributeTargets.Event: return nameof(CodeAnalysisResources.Event1);
case AttributeTargets.Field: return nameof(CodeAnalysisResources.Field);
case AttributeTargets.GenericParameter: return nameof(CodeAnalysisResources.TypeParameter);
case AttributeTargets.Interface: return nameof(CodeAnalysisResources.Interface1);
case AttributeTargets.Method: return nameof(CodeAnalysisResources.Method);
case AttributeTargets.Module: return nameof(CodeAnalysisResources.Module);
case AttributeTargets.Parameter: return nameof(CodeAnalysisResources.Parameter);
case AttributeTargets.Property: return nameof(CodeAnalysisResources.Property);
case AttributeTargets.ReturnValue: return nameof(CodeAnalysisResources.Return1);
case AttributeTargets.Struct: return nameof(CodeAnalysisResources.Struct1);
default:
throw ExceptionUtilities.UnexpectedValue(target);
}
}
}
}
| apache-2.0 |
uschindler/elasticsearch | server/src/main/java/org/elasticsearch/action/admin/cluster/state/ClusterStateAction.java | 1201 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.action.admin.cluster.state;
import org.elasticsearch.action.ActionType;
public class ClusterStateAction extends ActionType<ClusterStateResponse> {
public static final ClusterStateAction INSTANCE = new ClusterStateAction();
public static final String NAME = "cluster:monitor/state";
private ClusterStateAction() {
super(NAME, ClusterStateResponse::new);
}
}
| apache-2.0 |
minestarks/TypeScript | tests/cases/fourslash/signatureHelpInParenthetical.ts | 265 | /// <reference path='fourslash.ts' />
//// class base { constructor (public n: number, public y: string) { } }
//// (new base(/**/
verify.signatureHelp({ marker: "", parameterName: "n" });
edit.insert('0, ');
verify.signatureHelp({ parameterName: "y" });
| apache-2.0 |
rawlingsj/gofabric8 | vendor/github.com/openshift/origin/pkg/project/auth/cache_test.go | 7438 | package auth
import (
"fmt"
"strconv"
"testing"
kapi "k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/auth/user"
"k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake"
"k8s.io/kubernetes/pkg/util/sets"
authorizationapi "github.com/openshift/origin/pkg/authorization/api"
"github.com/openshift/origin/pkg/client"
)
// MockPolicyClient implements the PolicyCache interface for testing
type MockPolicyClient struct{}
// Following methods enable the MockPolicyClient to implement the PolicyCache interface
// Policies gives access to a read-only policy interface
func (this *MockPolicyClient) Policies(namespace string) client.PolicyLister {
return MockPolicyGetter{}
}
type MockPolicyGetter struct{}
func (this MockPolicyGetter) List(options kapi.ListOptions) (*authorizationapi.PolicyList, error) {
return &authorizationapi.PolicyList{}, nil
}
func (this MockPolicyGetter) Get(name string) (*authorizationapi.Policy, error) {
return &authorizationapi.Policy{}, nil
}
// ClusterPolicies gives access to a read-only cluster policy interface
func (this *MockPolicyClient) ClusterPolicies() client.ClusterPolicyLister {
return MockClusterPolicyGetter{}
}
type MockClusterPolicyGetter struct{}
func (this MockClusterPolicyGetter) List(options kapi.ListOptions) (*authorizationapi.ClusterPolicyList, error) {
return &authorizationapi.ClusterPolicyList{}, nil
}
func (this MockClusterPolicyGetter) Get(name string) (*authorizationapi.ClusterPolicy, error) {
return &authorizationapi.ClusterPolicy{}, nil
}
// PolicyBindings gives access to a read-only policy binding interface
func (this *MockPolicyClient) PolicyBindings(namespace string) client.PolicyBindingLister {
return MockPolicyBindingGetter{}
}
type MockPolicyBindingGetter struct{}
func (this MockPolicyBindingGetter) List(options kapi.ListOptions) (*authorizationapi.PolicyBindingList, error) {
return &authorizationapi.PolicyBindingList{}, nil
}
func (this MockPolicyBindingGetter) Get(name string) (*authorizationapi.PolicyBinding, error) {
return &authorizationapi.PolicyBinding{}, nil
}
// ClusterPolicyBindings gives access to a read-only cluster policy binding interface
func (this *MockPolicyClient) ClusterPolicyBindings() client.ClusterPolicyBindingLister {
return MockClusterPolicyBindingGetter{}
}
type MockClusterPolicyBindingGetter struct{}
func (this MockClusterPolicyBindingGetter) List(options kapi.ListOptions) (*authorizationapi.ClusterPolicyBindingList, error) {
return &authorizationapi.ClusterPolicyBindingList{}, nil
}
func (this MockClusterPolicyBindingGetter) Get(name string) (*authorizationapi.ClusterPolicyBinding, error) {
return &authorizationapi.ClusterPolicyBinding{}, nil
}
// LastSyncResourceVersion returns the resource version for the last sync performed
func (this *MockPolicyClient) LastSyncResourceVersion() string {
return ""
}
// mockReview implements the Review interface for test cases
type mockReview struct {
users []string
groups []string
err string
}
// Users returns the users that can access a resource
func (r *mockReview) Users() []string {
return r.users
}
// Groups returns the groups that can access a resource
func (r *mockReview) Groups() []string {
return r.groups
}
func (r *mockReview) EvaluationError() string {
return r.err
}
// common test users
var (
alice = &user.DefaultInfo{
Name: "Alice",
UID: "alice-uid",
Groups: []string{},
}
bob = &user.DefaultInfo{
Name: "Bob",
UID: "bob-uid",
Groups: []string{"employee"},
}
eve = &user.DefaultInfo{
Name: "Eve",
UID: "eve-uid",
Groups: []string{"employee"},
}
frank = &user.DefaultInfo{
Name: "Frank",
UID: "frank-uid",
Groups: []string{},
}
)
// mockReviewer returns the specified values for each supplied resource
type mockReviewer struct {
expectedResults map[string]*mockReview
}
// Review returns the mapped review from the mock object, or an error if none exists
func (mr *mockReviewer) Review(name string) (Review, error) {
review := mr.expectedResults[name]
if review == nil {
return nil, fmt.Errorf("Item %s does not exist", name)
}
return review, nil
}
func validateList(t *testing.T, lister Lister, user user.Info, expectedSet sets.String) {
namespaceList, err := lister.List(user)
if err != nil {
t.Errorf("Unexpected error %v", err)
}
results := sets.String{}
for _, namespace := range namespaceList.Items {
results.Insert(namespace.Name)
}
if results.Len() != expectedSet.Len() || !results.HasAll(expectedSet.List()...) {
t.Errorf("User %v, Expected: %v, Actual: %v", user.GetName(), expectedSet, results)
}
}
func TestSyncNamespace(t *testing.T) {
namespaceList := kapi.NamespaceList{
Items: []kapi.Namespace{
{
ObjectMeta: kapi.ObjectMeta{Name: "foo", ResourceVersion: "1"},
},
{
ObjectMeta: kapi.ObjectMeta{Name: "bar", ResourceVersion: "2"},
},
{
ObjectMeta: kapi.ObjectMeta{Name: "car", ResourceVersion: "3"},
},
},
}
mockKubeClient := fake.NewSimpleClientset(&namespaceList)
reviewer := &mockReviewer{
expectedResults: map[string]*mockReview{
"foo": {
users: []string{alice.GetName(), bob.GetName()},
groups: eve.GetGroups(),
},
"bar": {
users: []string{frank.GetName(), eve.GetName()},
groups: []string{"random"},
},
"car": {
users: []string{},
groups: []string{},
},
},
}
mockPolicyCache := &MockPolicyClient{}
authorizationCache := NewAuthorizationCache(reviewer, mockKubeClient.Core().Namespaces(), mockPolicyCache, mockPolicyCache, mockPolicyCache, mockPolicyCache)
// we prime the data we need here since we are not running reflectors
for i := range namespaceList.Items {
authorizationCache.namespaceStore.Add(&namespaceList.Items[i])
}
// synchronize the cache
authorizationCache.synchronize()
validateList(t, authorizationCache, alice, sets.NewString("foo"))
validateList(t, authorizationCache, bob, sets.NewString("foo"))
validateList(t, authorizationCache, eve, sets.NewString("foo", "bar"))
validateList(t, authorizationCache, frank, sets.NewString("bar"))
// modify access rules
reviewer.expectedResults["foo"].users = []string{bob.GetName()}
reviewer.expectedResults["foo"].groups = []string{"random"}
reviewer.expectedResults["bar"].users = []string{alice.GetName(), eve.GetName()}
reviewer.expectedResults["bar"].groups = []string{"employee"}
reviewer.expectedResults["car"].users = []string{bob.GetName(), eve.GetName()}
reviewer.expectedResults["car"].groups = []string{"employee"}
// modify resource version on each namespace to simulate a change had occurred to force cache refresh
for i := range namespaceList.Items {
namespace := namespaceList.Items[i]
oldVersion, err := strconv.Atoi(namespace.ResourceVersion)
if err != nil {
t.Errorf("Bad test setup, resource versions should be numbered, %v", err)
}
newVersion := strconv.Itoa(oldVersion + 1)
namespace.ResourceVersion = newVersion
authorizationCache.namespaceStore.Add(&namespace)
}
// now refresh the cache (which is resource version aware)
authorizationCache.synchronize()
// make sure new rights hold
validateList(t, authorizationCache, alice, sets.NewString("bar"))
validateList(t, authorizationCache, bob, sets.NewString("foo", "bar", "car"))
validateList(t, authorizationCache, eve, sets.NewString("bar", "car"))
validateList(t, authorizationCache, frank, sets.NewString())
}
| apache-2.0 |
asashour/framework | uitest/src/main/java/com/vaadin/tests/components/combobox/ComboBoxSuggestionPopupClose.java | 827 | package com.vaadin.tests.components.combobox;
import com.vaadin.server.VaadinRequest;
import com.vaadin.tests.components.AbstractReindeerTestUI;
import com.vaadin.ui.ComboBox;
public class ComboBoxSuggestionPopupClose extends AbstractReindeerTestUI {
@Override
protected void setup(VaadinRequest request) {
final ComboBox<String> select = new ComboBox<>("ComboBox");
select.setItems("one", "two", "three");
addComponent(select);
}
@Override
protected String getTestDescription() {
return "Closing the suggestion popup using Enter key is "
+ "broken in combobox when opening popup using Enter "
+ "key and not changin the selection using arrows";
}
@Override
protected Integer getTicketNumber() {
return 14379;
}
}
| apache-2.0 |
youdonghai/intellij-community | platform/lang-impl/src/com/intellij/psi/impl/source/codeStyle/CodeStyleFacadeImpl.java | 3814 | /*
* 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.
*/
/*
* @author max
*/
package com.intellij.psi.impl.source.codeStyle;
import com.intellij.codeStyle.CodeStyleFacade;
import com.intellij.lang.Language;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
import com.intellij.psi.codeStyle.lineIndent.LineIndentProvider;
import com.intellij.psi.codeStyle.lineIndent.LineIndentProviderEP;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class CodeStyleFacadeImpl extends CodeStyleFacade {
private final Project myProject;
public CodeStyleFacadeImpl() {
this(null);
}
public CodeStyleFacadeImpl(final Project project) {
myProject = project;
}
@Override
public int getIndentSize(final FileType fileType) {
return CodeStyleSettingsManager.getSettings(myProject).getIndentSize(fileType);
}
@Override
@Nullable
@Deprecated
public String getLineIndent(@NotNull final Document document, int offset) {
if (myProject == null) return null;
PsiDocumentManager.getInstance(myProject).commitDocument(document);
return CodeStyleManager.getInstance(myProject).getLineIndent(document, offset);
}
@Override
public String getLineIndent(@NotNull Editor editor, @Nullable Language language, int offset) {
if (myProject == null) return null;
LineIndentProvider lineIndentProvider = LineIndentProviderEP.findLineIndentProvider(language);
return lineIndentProvider != null ? lineIndentProvider.getLineIndent(myProject, editor, language, offset) : null;
}
@Override
public String getLineSeparator() {
return CodeStyleSettingsManager.getSettings(myProject).getLineSeparator();
}
@Override
public boolean projectUsesOwnSettings() {
return myProject != null && CodeStyleSettingsManager.getInstance(myProject).USE_PER_PROJECT_SETTINGS;
}
@Override
public boolean isUnsuitableCodeStyleConfigurable(final Configurable c) {
return false;
}
@Override
public int getRightMargin(Language language) {
return CodeStyleSettingsManager.getSettings(myProject).getRightMargin(language);
}
@Override
@Deprecated
public boolean isWrapWhenTypingReachesRightMargin() {
return CodeStyleSettingsManager.getSettings(myProject).WRAP_WHEN_TYPING_REACHES_RIGHT_MARGIN;
}
@Override
public boolean isWrapOnTyping(@Nullable Language language) {
return CodeStyleSettingsManager.getSettings(myProject).isWrapOnTyping(language);
}
@Override
public int getTabSize(final FileType fileType) {
return CodeStyleSettingsManager.getSettings(myProject).getTabSize(fileType);
}
@Override
public boolean isSmartTabs(final FileType fileType) {
return CodeStyleSettingsManager.getSettings(myProject).isSmartTabs(fileType);
}
@Override
public boolean useTabCharacter(final FileType fileType) {
return CodeStyleSettingsManager.getSettings(myProject).useTabCharacter(fileType);
}
} | apache-2.0 |
selckin/wicket | wicket-core/src/main/java/org/apache/wicket/UrlResourceReferenceMapper.java | 2673 | /*
* 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.wicket;
import org.apache.wicket.request.IRequestHandler;
import org.apache.wicket.request.IRequestMapper;
import org.apache.wicket.request.Request;
import org.apache.wicket.request.Url;
import org.apache.wicket.request.handler.resource.ResourceReferenceRequestHandler;
import org.apache.wicket.request.resource.ResourceReference;
import org.apache.wicket.request.resource.UrlResourceReference;
import org.apache.wicket.resource.bundles.ResourceBundleReference;
/**
* A request mapper that is used to create Url out of UrlResourceReference.
* UrlResourceReference works with {@link org.apache.wicket.request.resource.UrlResourceReference.CalculatedUrl} and
* thus this mapper should not use {@link org.apache.wicket.SystemMapper.ParentFolderPlaceholderProvider}
*/
public class UrlResourceReferenceMapper implements IRequestMapper
{
@Override
public Url mapHandler(IRequestHandler requestHandler)
{
Url url = null;
if (requestHandler instanceof ResourceReferenceRequestHandler)
{
ResourceReferenceRequestHandler resourceReferenceRequestHandler = (ResourceReferenceRequestHandler) requestHandler;
ResourceReference resourceReference = resourceReferenceRequestHandler.getResourceReference();
while (resourceReference instanceof ResourceBundleReference)
{
// unwrap the bundle to render the url for the actual reference
resourceReference = ((ResourceBundleReference)resourceReference).getBundleReference();
}
if (resourceReference instanceof UrlResourceReference)
{
UrlResourceReference urlResourceReference = (UrlResourceReference) resourceReference;
url = urlResourceReference.getUrl();
}
}
return url;
}
@Override
public IRequestHandler mapRequest(Request request)
{
return null;
}
@Override
public int getCompatibilityScore(Request request)
{
return Integer.MIN_VALUE;
}
}
| apache-2.0 |
smennetrier/closure-stylesheets | src/com/google/common/css/compiler/gssfunctions/ColorUtil.java | 4612 | /*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.css.compiler.gssfunctions;
import java.awt.Color;
/**
* Utility functions to deal with colors.
*
* @author [email protected] (Damian Gajda)
*/
class ColorUtil {
public static final int H = 0;
public static final int S = 1;
public static final int B = 2;
public static float[] toHsb(Color color) {
return Color.RGBtoHSB(
color.getRed(), color.getGreen(), color.getBlue(), null);
}
public static String formatColor(Color color) {
return String.format("#%02X%02X%02X",
color.getRed(), color.getGreen(), color.getBlue());
}
public static Color hsbToColor(float[] inputHsb) {
return Color.getHSBColor(inputHsb[H], inputHsb[S], inputHsb[B]);
}
/**
* Tests whether the given colors are contrasting colors, according to the
* test described in the W3C accessibility evaluation working draft
* {@link "http://www.w3.org/TR/AERT#color-contrast"}. This is a lenient
* version of the test which allows the user to pass in the accepted leniency
* margin.
*
* <p>The value of the leniency margin is in the range 0 to 1.0. 0 means
* that the test is not lenient at all, 1.0 means that the test will pass for
* all colors that are different. It is recommended not to use values of more
* than 0.01.
*
* @param color1 the first of the two checked colors
* @param color2 the second of the two checked colors
* @param margin the test leniency margin
* @return whether the given colors are considered contrasting, taking the
* leniency margin into account
*/
public static boolean testContrast(Color color1, Color color2, float margin) {
float differenceFraction = 1f - margin;
return luminanceDiff(color1, color2) > 125 * differenceFraction
&& colorDiff(color1, color2) > 500 * differenceFraction;
}
/**
* Tests whether the given colors are contrasting colors, according to the
* test described in the W3C accessibility evaluation working draft
* {@link "http://www.w3.org/TR/AERT#color-contrast"}.
*
* @param color1 the first of the two checked colors
* @param color2 the second of the two checked colors
* @return whether the given colors are considered contrasting
*/
public static boolean testContrast(Color color1, Color color2) {
return luminanceDiff(color1, color2) > 125
&& colorDiff(color1, color2) > 500;
}
/**
* Computes the luminance difference of two colors (a value in range 0-255).
* It is the luminance value equal to the Y component of the YIQ or the YUV
* color space models.
*/
public static int luminanceDiff(Color c1, Color c2) {
return Math.abs(luminance(c1) - luminance(c2));
}
/**
* Computes the luminance value of a color (a value in range 0-255).
* It is the luminance value equal to the Y component of the YIQ or the YUV
* color space models.
*/
public static int luminance(Color color) {
return luminance(color.getRed(), color.getGreen(), color.getBlue());
}
/**
* Computes the luminance value of a color (a value in range 0-255).
* It is the luminance value equal to the Y component of the YIQ or the YUV
* color space models.
*/
public static int luminance(int red, int green, int blue) {
return (red * 299 + green * 587 + blue * 114) / 1000;
}
/**
* Calculates the Manhattan distance of two colors in the RGB color space
* (a value in range 0-(255*3)).
*/
public static int colorDiff(Color color1, Color color2) {
return colorDiff(
color1.getRed(), color1.getGreen(), color1.getBlue(),
color2.getRed(), color2.getGreen(), color2.getBlue());
}
/**
* Calculates the Manhattan distance of two colors in the RGB color space
* (a value in range 0-(255*3)).
*/
public static int colorDiff(int r1, int g1, int b1, int r2, int g2, int b2) {
return Math.abs(r1 - r2) + Math.abs(g1 - g2) + Math.abs(b1 - b2);
}
// Utility class, static methods only.
private ColorUtil() {
}
}
| apache-2.0 |
kaffeel/oppia | core/jobs_test.py | 34275 | # coding: utf-8
#
# Copyright 2014 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for long running jobs and continuous computations."""
__author__ = 'Sean Lip'
import ast
from core import jobs
from core import jobs_registry
from core.domain import event_services
from core.domain import exp_domain
from core.domain import exp_services
from core.platform import models
(base_models, exp_models, stats_models) = models.Registry.import_models([
models.NAMES.base_model, models.NAMES.exploration, models.NAMES.statistics])
taskqueue_services = models.Registry.import_taskqueue_services()
transaction_services = models.Registry.import_transaction_services()
from core.tests import test_utils
import feconf
from google.appengine.ext import ndb
JOB_FAILED_MESSAGE = 'failed (as expected)'
class DummyJobManager(jobs.BaseDeferredJobManager):
@classmethod
def _run(cls, additional_job_params):
return 'output'
class AnotherDummyJobManager(jobs.BaseDeferredJobManager):
@classmethod
def _run(cls, additional_job_params):
return 'output'
class DummyJobManagerWithParams(jobs.BaseDeferredJobManager):
@classmethod
def _run(cls, additional_job_params):
return additional_job_params['correct']
class DummyFailingJobManager(jobs.BaseDeferredJobManager):
@classmethod
def _run(cls, additional_job_params):
raise Exception(JOB_FAILED_MESSAGE)
class JobWithNoRunMethodManager(jobs.BaseDeferredJobManager):
pass
class JobManagerUnitTests(test_utils.GenericTestBase):
"""Test basic job manager operations."""
def test_create_new(self):
"""Test the creation of a new job."""
job_id = DummyJobManager.create_new()
self.assertTrue(job_id.startswith('DummyJob'))
self.assertEqual(
DummyJobManager.get_status_code(job_id), jobs.STATUS_CODE_NEW)
self.assertIsNone(DummyJobManager.get_time_queued_msec(job_id))
self.assertIsNone(DummyJobManager.get_time_started_msec(job_id))
self.assertIsNone(DummyJobManager.get_time_finished_msec(job_id))
self.assertIsNone(DummyJobManager.get_metadata(job_id))
self.assertIsNone(DummyJobManager.get_output(job_id))
self.assertIsNone(DummyJobManager.get_error(job_id))
self.assertFalse(DummyJobManager.is_active(job_id))
self.assertFalse(DummyJobManager.has_finished(job_id))
def test_enqueue_job(self):
"""Test the enqueueing of a job."""
job_id = DummyJobManager.create_new()
DummyJobManager.enqueue(job_id)
self.assertEqual(self.count_jobs_in_taskqueue(), 1)
self.assertEqual(
DummyJobManager.get_status_code(job_id), jobs.STATUS_CODE_QUEUED)
self.assertIsNotNone(DummyJobManager.get_time_queued_msec(job_id))
self.assertIsNone(DummyJobManager.get_output(job_id))
def test_failure_for_job_enqueued_using_wrong_manager(self):
job_id = DummyJobManager.create_new()
with self.assertRaisesRegexp(Exception, 'Invalid job type'):
AnotherDummyJobManager.enqueue(job_id)
def test_failure_for_job_with_no_run_method(self):
job_id = JobWithNoRunMethodManager.create_new()
JobWithNoRunMethodManager.enqueue(job_id)
self.assertEqual(self.count_jobs_in_taskqueue(), 1)
with self.assertRaisesRegexp(Exception, 'NotImplementedError'):
self.process_and_flush_pending_tasks()
def test_complete_job(self):
job_id = DummyJobManager.create_new()
DummyJobManager.enqueue(job_id)
self.assertEqual(self.count_jobs_in_taskqueue(), 1)
self.process_and_flush_pending_tasks()
self.assertEqual(
DummyJobManager.get_status_code(job_id),
jobs.STATUS_CODE_COMPLETED)
time_queued_msec = DummyJobManager.get_time_queued_msec(job_id)
time_started_msec = DummyJobManager.get_time_started_msec(job_id)
time_finished_msec = DummyJobManager.get_time_finished_msec(job_id)
self.assertIsNotNone(time_queued_msec)
self.assertIsNotNone(time_started_msec)
self.assertIsNotNone(time_finished_msec)
self.assertLess(time_queued_msec, time_started_msec)
self.assertLess(time_started_msec, time_finished_msec)
metadata = DummyJobManager.get_metadata(job_id)
output = DummyJobManager.get_output(job_id)
error = DummyJobManager.get_error(job_id)
self.assertIsNone(metadata)
self.assertEqual(output, 'output')
self.assertIsNone(error)
self.assertFalse(DummyJobManager.is_active(job_id))
self.assertTrue(DummyJobManager.has_finished(job_id))
def test_deferred_job_with_additional_params(self):
"""Test the enqueueing of a job with additional parameters."""
ADDITIONAL_PARAMS_1 = {'random': 3, 'correct': 60}
ADDITIONAL_PARAMS_2 = {'random': 20, 'correct': 25}
job_id_1 = DummyJobManagerWithParams.create_new()
DummyJobManagerWithParams.enqueue(
job_id_1, additional_job_params=ADDITIONAL_PARAMS_1)
job_id_2 = DummyJobManagerWithParams.create_new()
DummyJobManagerWithParams.enqueue(
job_id_2, additional_job_params=ADDITIONAL_PARAMS_2)
self.assertEqual(self.count_jobs_in_taskqueue(), 2)
self.process_and_flush_pending_tasks()
self.assertTrue(DummyJobManagerWithParams.has_finished(job_id_1))
self.assertEqual(DummyJobManagerWithParams.get_output(job_id_1), 60)
self.assertTrue(DummyJobManagerWithParams.has_finished(job_id_2))
self.assertEqual(DummyJobManagerWithParams.get_output(job_id_2), 25)
def test_job_failure(self):
job_id = DummyFailingJobManager.create_new()
DummyFailingJobManager.enqueue(job_id)
self.assertEqual(self.count_jobs_in_taskqueue(), 1)
with self.assertRaisesRegexp(Exception, 'Task failed'):
self.process_and_flush_pending_tasks()
self.assertEqual(
DummyFailingJobManager.get_status_code(job_id),
jobs.STATUS_CODE_FAILED)
time_queued_msec = DummyFailingJobManager.get_time_queued_msec(job_id)
time_started_msec = DummyFailingJobManager.get_time_started_msec(
job_id)
time_finished_msec = DummyFailingJobManager.get_time_finished_msec(
job_id)
self.assertIsNotNone(time_queued_msec)
self.assertIsNotNone(time_started_msec)
self.assertIsNotNone(time_finished_msec)
self.assertLess(time_queued_msec, time_started_msec)
self.assertLess(time_started_msec, time_finished_msec)
metadata = DummyFailingJobManager.get_metadata(job_id)
output = DummyFailingJobManager.get_output(job_id)
error = DummyFailingJobManager.get_error(job_id)
self.assertIsNone(metadata)
self.assertIsNone(output)
self.assertIn(JOB_FAILED_MESSAGE, error)
self.assertFalse(DummyFailingJobManager.is_active(job_id))
self.assertTrue(DummyFailingJobManager.has_finished(job_id))
def test_status_code_transitions(self):
"""Test that invalid status code transitions are caught."""
job_id = DummyJobManager.create_new()
DummyJobManager.enqueue(job_id)
DummyJobManager.register_start(job_id)
DummyJobManager.register_completion(job_id, 'output')
with self.assertRaisesRegexp(Exception, 'Invalid status code change'):
DummyJobManager.enqueue(job_id)
with self.assertRaisesRegexp(Exception, 'Invalid status code change'):
DummyJobManager.register_completion(job_id, 'output')
with self.assertRaisesRegexp(Exception, 'Invalid status code change'):
DummyJobManager.register_failure(job_id, 'error')
def test_different_jobs_are_independent(self):
job_id = DummyJobManager.create_new()
another_job_id = AnotherDummyJobManager.create_new()
DummyJobManager.enqueue(job_id)
DummyJobManager.register_start(job_id)
AnotherDummyJobManager.enqueue(another_job_id)
self.assertEqual(
DummyJobManager.get_status_code(job_id), jobs.STATUS_CODE_STARTED)
self.assertEqual(
AnotherDummyJobManager.get_status_code(another_job_id),
jobs.STATUS_CODE_QUEUED)
def test_cannot_instantiate_jobs_from_abstract_base_classes(self):
with self.assertRaisesRegexp(
Exception, 'directly create a job using the abstract base'):
jobs.BaseJobManager.create_new()
def test_cannot_enqueue_same_job_twice(self):
job_id = DummyJobManager.create_new()
DummyJobManager.enqueue(job_id)
with self.assertRaisesRegexp(Exception, 'Invalid status code change'):
DummyJobManager.enqueue(job_id)
def test_can_enqueue_two_instances_of_the_same_job(self):
job_id = DummyJobManager.create_new()
DummyJobManager.enqueue(job_id)
job_id_2 = DummyJobManager.create_new()
DummyJobManager.enqueue(job_id_2)
def test_cancel_kills_queued_job(self):
job_id = DummyJobManager.create_new()
DummyJobManager.enqueue(job_id)
self.assertTrue(DummyJobManager.is_active(job_id))
DummyJobManager.cancel(job_id, 'admin_user_id')
self.assertFalse(DummyJobManager.is_active(job_id))
self.assertEquals(
DummyJobManager.get_status_code(job_id), jobs.STATUS_CODE_CANCELED)
self.assertIsNone(DummyJobManager.get_output(job_id))
self.assertEquals(
DummyJobManager.get_error(job_id), 'Canceled by admin_user_id')
def test_cancel_kills_started_job(self):
job_id = DummyJobManager.create_new()
DummyJobManager.enqueue(job_id)
self.assertTrue(DummyJobManager.is_active(job_id))
DummyJobManager.register_start(job_id)
# Cancel the job immediately after it has started.
DummyJobManager.cancel(job_id, 'admin_user_id')
# The job then finishes.
with self.assertRaisesRegexp(Exception, 'Invalid status code change'):
DummyJobManager.register_completion(job_id, 'job_output')
self.assertFalse(DummyJobManager.is_active(job_id))
self.assertEquals(
DummyJobManager.get_status_code(job_id), jobs.STATUS_CODE_CANCELED)
# Note that no results are recorded for this job.
self.assertIsNone(DummyJobManager.get_output(job_id))
self.assertEquals(
DummyJobManager.get_error(job_id), 'Canceled by admin_user_id')
def test_cancel_does_not_kill_completed_job(self):
job_id = DummyJobManager.create_new()
DummyJobManager.enqueue(job_id)
self.assertTrue(DummyJobManager.is_active(job_id))
# Complete the job.
self.process_and_flush_pending_tasks()
self.assertFalse(DummyJobManager.is_active(job_id))
self.assertEquals(
DummyJobManager.get_status_code(job_id),
jobs.STATUS_CODE_COMPLETED)
# Cancel the job after it has finished.
with self.assertRaisesRegexp(Exception, 'Invalid status code change'):
DummyJobManager.cancel(job_id, 'admin_user_id')
# The job should still have 'completed' status.
self.assertFalse(DummyJobManager.is_active(job_id))
self.assertEquals(
DummyJobManager.get_status_code(job_id),
jobs.STATUS_CODE_COMPLETED)
self.assertEquals(DummyJobManager.get_output(job_id), 'output')
self.assertIsNone(DummyJobManager.get_error(job_id))
def test_cancel_does_not_kill_failed_job(self):
job_id = DummyFailingJobManager.create_new()
DummyFailingJobManager.enqueue(job_id)
self.assertTrue(DummyFailingJobManager.is_active(job_id))
with self.assertRaisesRegexp(Exception, 'Task failed'):
self.process_and_flush_pending_tasks()
self.assertFalse(DummyFailingJobManager.is_active(job_id))
self.assertEquals(
DummyFailingJobManager.get_status_code(job_id),
jobs.STATUS_CODE_FAILED)
# Cancel the job after it has finished.
with self.assertRaisesRegexp(Exception, 'Invalid status code change'):
DummyFailingJobManager.cancel(job_id, 'admin_user_id')
# The job should still have 'failed' status.
self.assertFalse(DummyFailingJobManager.is_active(job_id))
self.assertEquals(
DummyFailingJobManager.get_status_code(job_id),
jobs.STATUS_CODE_FAILED)
self.assertIsNone(DummyFailingJobManager.get_output(job_id))
self.assertIn(
'raise Exception', DummyFailingJobManager.get_error(job_id))
def test_cancelling_multiple_unfinished_jobs(self):
job1_id = DummyJobManager.create_new()
DummyJobManager.enqueue(job1_id)
job2_id = DummyJobManager.create_new()
DummyJobManager.enqueue(job2_id)
DummyJobManager.register_start(job1_id)
DummyJobManager.register_start(job2_id)
DummyJobManager.cancel_all_unfinished_jobs('admin_user_id')
self.assertFalse(DummyJobManager.is_active(job1_id))
self.assertFalse(DummyJobManager.is_active(job2_id))
self.assertEquals(
DummyJobManager.get_status_code(job1_id),
jobs.STATUS_CODE_CANCELED)
self.assertEquals(
DummyJobManager.get_status_code(job2_id),
jobs.STATUS_CODE_CANCELED)
self.assertIsNone(DummyJobManager.get_output(job1_id))
self.assertIsNone(DummyJobManager.get_output(job2_id))
self.assertEquals(
'Canceled by admin_user_id', DummyJobManager.get_error(job1_id))
self.assertEquals(
'Canceled by admin_user_id', DummyJobManager.get_error(job2_id))
def test_cancelling_one_unfinished_job(self):
job1_id = DummyJobManager.create_new()
DummyJobManager.enqueue(job1_id)
job2_id = DummyJobManager.create_new()
DummyJobManager.enqueue(job2_id)
DummyJobManager.register_start(job1_id)
DummyJobManager.register_start(job2_id)
DummyJobManager.cancel(job1_id, 'admin_user_id')
with self.assertRaisesRegexp(Exception, 'Invalid status code change'):
self.process_and_flush_pending_tasks()
DummyJobManager.register_completion(job2_id, 'output')
self.assertFalse(DummyJobManager.is_active(job1_id))
self.assertFalse(DummyJobManager.is_active(job2_id))
self.assertEquals(
DummyJobManager.get_status_code(job1_id),
jobs.STATUS_CODE_CANCELED)
self.assertEquals(
DummyJobManager.get_status_code(job2_id),
jobs.STATUS_CODE_COMPLETED)
self.assertIsNone(DummyJobManager.get_output(job1_id))
self.assertEquals(DummyJobManager.get_output(job2_id), 'output')
self.assertEquals(
'Canceled by admin_user_id', DummyJobManager.get_error(job1_id))
self.assertIsNone(DummyJobManager.get_error(job2_id))
SUM_MODEL_ID = 'all_data_id'
class NumbersModel(ndb.Model):
number = ndb.IntegerProperty()
class SumModel(ndb.Model):
total = ndb.IntegerProperty(default=0)
failed = ndb.BooleanProperty(default=False)
class TestDeferredJobManager(jobs.BaseDeferredJobManager):
"""Base class for testing deferred jobs."""
pass
class TestAdditionJobManager(TestDeferredJobManager):
"""Test job that sums all NumbersModel data.
The result is stored in a SumModel entity with id SUM_MODEL_ID.
"""
@classmethod
def _run(cls, additional_job_params):
total = sum([
numbers_model.number for numbers_model in NumbersModel.query()])
SumModel(id=SUM_MODEL_ID, total=total).put()
class FailingAdditionJobManager(TestDeferredJobManager):
"""Test job that stores stuff in SumModel and then fails."""
@classmethod
def _run(cls, additional_job_params):
total = sum([
numbers_model.number for numbers_model in NumbersModel.query()])
SumModel(id=SUM_MODEL_ID, total=total).put()
raise Exception('Oops, I failed.')
@classmethod
def _post_failure_hook(cls, job_id):
model = SumModel.get_by_id(SUM_MODEL_ID)
model.failed = True
model.put()
class DatastoreJobIntegrationTests(test_utils.GenericTestBase):
"""Tests the behavior of a job that affects data in the datastore.
This job gets all NumbersModel instances and sums their values, and puts
the summed values in a SumModel instance with id SUM_MODEL_ID. The
computation is redone from scratch each time the job is run.
"""
def _get_stored_total(self):
sum_model = SumModel.get_by_id(SUM_MODEL_ID)
return sum_model.total if sum_model else 0
def _populate_data(self):
"""Populate the datastore with four NumbersModel instances."""
NumbersModel(number=1).put()
NumbersModel(number=2).put()
NumbersModel(number=1).put()
NumbersModel(number=2).put()
def test_sequential_jobs(self):
self._populate_data()
self.assertEqual(self._get_stored_total(), 0)
TestAdditionJobManager.enqueue(
TestAdditionJobManager.create_new())
self.assertEqual(self.count_jobs_in_taskqueue(), 1)
self.process_and_flush_pending_tasks()
self.assertEqual(self._get_stored_total(), 6)
NumbersModel(number=3).put()
TestAdditionJobManager.enqueue(
TestAdditionJobManager.create_new())
self.assertEqual(self.count_jobs_in_taskqueue(), 1)
self.process_and_flush_pending_tasks()
self.assertEqual(self._get_stored_total(), 9)
def test_multiple_enqueued_jobs(self):
self._populate_data()
TestAdditionJobManager.enqueue(
TestAdditionJobManager.create_new())
NumbersModel(number=3).put()
TestAdditionJobManager.enqueue(
TestAdditionJobManager.create_new())
self.assertEqual(self.count_jobs_in_taskqueue(), 2)
self.process_and_flush_pending_tasks()
self.assertEqual(self._get_stored_total(), 9)
def test_failing_job(self):
self._populate_data()
job_id = FailingAdditionJobManager.create_new()
FailingAdditionJobManager.enqueue(job_id)
self.assertEqual(self.count_jobs_in_taskqueue(), 1)
with self.assertRaisesRegexp(
taskqueue_services.PermanentTaskFailure, 'Oops, I failed'):
self.process_and_flush_pending_tasks()
# The work that the failing job did before it failed is still done.
self.assertEqual(self._get_stored_total(), 6)
# The post-failure hook should have run.
self.assertTrue(SumModel.get_by_id(SUM_MODEL_ID).failed)
self.assertTrue(
FailingAdditionJobManager.get_status_code(job_id),
jobs.STATUS_CODE_FAILED)
class SampleMapReduceJobManager(jobs.BaseMapReduceJobManager):
"""Test job that counts the total number of explorations."""
@classmethod
def entity_classes_to_map_over(cls):
return [exp_models.ExplorationModel]
@staticmethod
def map(item):
yield ('sum', 1)
@staticmethod
def reduce(key, values):
yield (key, sum([int(value) for value in values]))
class MapReduceJobIntegrationTests(test_utils.GenericTestBase):
"""Tests MapReduce jobs end-to-end."""
def setUp(self):
"""Create an exploration so that there is something to count."""
super(MapReduceJobIntegrationTests, self).setUp()
exploration = exp_domain.Exploration.create_default_exploration(
'exp_id', 'title', 'A category')
exp_services.save_new_exploration('owner_id', exploration)
self.process_and_flush_pending_tasks()
def test_count_all_explorations(self):
job_id = SampleMapReduceJobManager.create_new()
SampleMapReduceJobManager.enqueue(job_id)
self.assertEqual(self.count_jobs_in_taskqueue(), 1)
self.process_and_flush_pending_tasks()
self.assertEqual(
SampleMapReduceJobManager.get_output(job_id), [['sum', 1]])
self.assertEqual(
SampleMapReduceJobManager.get_status_code(job_id),
jobs.STATUS_CODE_COMPLETED)
class JobRegistryTests(test_utils.GenericTestBase):
"""Tests job registry."""
def test_each_one_off_class_is_subclass_of_BaseJobManager(self):
for klass in jobs_registry.ONE_OFF_JOB_MANAGERS:
self.assertTrue(issubclass(klass, jobs.BaseJobManager))
def test_each_one_off_class_is_not_abstract(self):
for klass in jobs_registry.ONE_OFF_JOB_MANAGERS:
self.assertFalse(klass._is_abstract())
def test_validity_of_each_continuous_computation_class(self):
for klass in jobs_registry.ALL_CONTINUOUS_COMPUTATION_MANAGERS:
self.assertTrue(
issubclass(klass, jobs.BaseContinuousComputationManager))
event_types_listened_to = klass.get_event_types_listened_to()
self.assertTrue(isinstance(event_types_listened_to, list))
for event_type in event_types_listened_to:
self.assertTrue(isinstance(event_type, basestring))
self.assertTrue(issubclass(
event_services.Registry.get_event_class_by_type(
event_type),
event_services.BaseEventHandler))
rdc = klass._get_realtime_datastore_class()
self.assertTrue(issubclass(
rdc, jobs.BaseRealtimeDatastoreClassForContinuousComputations))
# The list of allowed base classes. This can be extended as the
# need arises, though we may also want to implement
# _get_continuous_computation_class() and
# _entity_created_before_job_queued() for other base classes
# that are added to this list.
ALLOWED_BASE_BATCH_JOB_CLASSES = [
jobs.BaseMapReduceJobManagerForContinuousComputations]
self.assertTrue(any([
issubclass(klass._get_batch_job_manager_class(), superclass)
for superclass in ALLOWED_BASE_BATCH_JOB_CLASSES]))
class JobQueriesTests(test_utils.GenericTestBase):
"""Tests queries for jobs."""
def test_get_data_for_recent_jobs(self):
self.assertEqual(jobs.get_data_for_recent_jobs(), [])
job_id = DummyJobManager.create_new()
DummyJobManager.enqueue(job_id)
recent_jobs = jobs.get_data_for_recent_jobs()
self.assertEqual(len(recent_jobs), 1)
self.assertDictContainsSubset({
'id': job_id,
'status_code': jobs.STATUS_CODE_QUEUED,
'job_type': 'DummyJobManager',
'is_cancelable': True,
'error': None
}, recent_jobs[0])
class TwoClassesMapReduceJobManager(jobs.BaseMapReduceJobManager):
"""A test job handler that counts entities in two datastore classes."""
@classmethod
def entity_classes_to_map_over(cls):
return [exp_models.ExplorationModel, exp_models.ExplorationRightsModel]
@staticmethod
def map(item):
yield ('sum', 1)
@staticmethod
def reduce(key, values):
yield [key, sum([int(value) for value in values])]
class TwoClassesMapReduceJobIntegrationTests(test_utils.GenericTestBase):
"""Tests MapReduce jobs using two classes end-to-end."""
def setUp(self):
"""Create an exploration so that there is something to count."""
super(TwoClassesMapReduceJobIntegrationTests, self).setUp()
exploration = exp_domain.Exploration.create_default_exploration(
'exp_id', 'title', 'A category')
# Note that this ends up creating an entry in the
# ExplorationRightsModel as well.
exp_services.save_new_exploration('owner_id', exploration)
self.process_and_flush_pending_tasks()
def test_count_entities(self):
self.assertEqual(exp_models.ExplorationModel.query().count(), 1)
self.assertEqual(exp_models.ExplorationRightsModel.query().count(), 1)
job_id = TwoClassesMapReduceJobManager.create_new()
TwoClassesMapReduceJobManager.enqueue(job_id)
self.assertEqual(self.count_jobs_in_taskqueue(), 1)
self.process_and_flush_pending_tasks()
self.assertEqual(
TwoClassesMapReduceJobManager.get_output(job_id), [['sum', 2]])
self.assertEqual(
TwoClassesMapReduceJobManager.get_status_code(job_id),
jobs.STATUS_CODE_COMPLETED)
class StartExplorationRealtimeModel(
jobs.BaseRealtimeDatastoreClassForContinuousComputations):
count = ndb.IntegerProperty(default=0)
class StartExplorationMRJobManager(
jobs.BaseMapReduceJobManagerForContinuousComputations):
@classmethod
def _get_continuous_computation_class(cls):
return StartExplorationEventCounter
@classmethod
def entity_classes_to_map_over(cls):
return [stats_models.StartExplorationEventLogEntryModel]
@staticmethod
def map(item):
current_class = StartExplorationMRJobManager
if current_class._entity_created_before_job_queued(item):
yield (item.exploration_id, {
'event_type': item.event_type,
})
@staticmethod
def reduce(key, stringified_values):
started_count = 0
for value_str in stringified_values:
value = ast.literal_eval(value_str)
if value['event_type'] == feconf.EVENT_TYPE_START_EXPLORATION:
started_count += 1
stats_models.ExplorationAnnotationsModel(
id=key, num_starts=started_count).put()
class StartExplorationEventCounter(jobs.BaseContinuousComputationManager):
"""A continuous-computation job that counts 'start exploration' events.
This class should only be used in tests.
"""
@classmethod
def get_event_types_listened_to(cls):
return [feconf.EVENT_TYPE_START_EXPLORATION]
@classmethod
def _get_realtime_datastore_class(cls):
return StartExplorationRealtimeModel
@classmethod
def _get_batch_job_manager_class(cls):
return StartExplorationMRJobManager
@classmethod
def _kickoff_batch_job_after_previous_one_ends(cls):
"""Override this method so that it does not immediately start a
new MapReduce job. Non-test subclasses should not do this."""
pass
@classmethod
def _handle_incoming_event(
cls, active_realtime_layer, event_type, exp_id, exp_version,
state_name, session_id, params, play_type):
def _increment_counter():
realtime_class = cls._get_realtime_datastore_class()
realtime_model_id = realtime_class.get_realtime_id(
active_realtime_layer, exp_id)
realtime_model = realtime_class.get(
realtime_model_id, strict=False)
if realtime_model is None:
realtime_class(
id=realtime_model_id, count=1,
realtime_layer=active_realtime_layer).put()
else:
realtime_model.count += 1
realtime_model.put()
transaction_services.run_in_transaction(_increment_counter)
# Public query method.
@classmethod
def get_count(cls, exploration_id):
"""Return the number of 'start exploration' events received.
Answers the query by combining the existing MR job output and the
active realtime_datastore_class.
"""
mr_model = stats_models.ExplorationAnnotationsModel.get(
exploration_id, strict=False)
realtime_model = cls._get_realtime_datastore_class().get(
cls.get_active_realtime_layer_id(exploration_id), strict=False)
answer = 0
if mr_model is not None:
answer += mr_model.num_starts
if realtime_model is not None:
answer += realtime_model.count
return answer
class ContinuousComputationTests(test_utils.GenericTestBase):
"""Tests continuous computations for 'start exploration' events."""
EXP_ID = 'exp_id'
ALL_CONTINUOUS_COMPUTATION_MANAGERS_FOR_TESTS = [
StartExplorationEventCounter]
def setUp(self):
"""Create an exploration and register the event listener manually."""
super(ContinuousComputationTests, self).setUp()
exploration = exp_domain.Exploration.create_default_exploration(
self.EXP_ID, 'title', 'A category')
exp_services.save_new_exploration('owner_id', exploration)
self.process_and_flush_pending_tasks()
def test_continuous_computation_workflow(self):
"""An integration test for continuous computations."""
with self.swap(
jobs_registry, 'ALL_CONTINUOUS_COMPUTATION_MANAGERS',
self.ALL_CONTINUOUS_COMPUTATION_MANAGERS_FOR_TESTS):
self.assertEqual(
StartExplorationEventCounter.get_count(self.EXP_ID), 0)
# Record an event. This will put the event in the task queue.
event_services.StartExplorationEventHandler.record(
self.EXP_ID, 1, feconf.DEFAULT_INIT_STATE_NAME, 'session_id', {},
feconf.PLAY_TYPE_NORMAL)
self.assertEqual(
StartExplorationEventCounter.get_count(self.EXP_ID), 0)
self.assertEqual(self.count_jobs_in_taskqueue(), 1)
# When the task queue is flushed, the data is recorded in the two
# realtime layers.
self.process_and_flush_pending_tasks()
self.assertEqual(self.count_jobs_in_taskqueue(), 0)
self.assertEqual(
StartExplorationEventCounter.get_count(self.EXP_ID), 1)
self.assertEqual(StartExplorationRealtimeModel.get(
'0:%s' % self.EXP_ID).count, 1)
self.assertEqual(StartExplorationRealtimeModel.get(
'1:%s' % self.EXP_ID).count, 1)
# The batch job has not run yet, so no entity for self.EXP_ID will
# have been created in the batch model yet.
with self.assertRaises(base_models.BaseModel.EntityNotFoundError):
stats_models.ExplorationAnnotationsModel.get(self.EXP_ID)
# Launch the batch computation.
StartExplorationEventCounter.start_computation()
# Data in realtime layer 0 is still there.
self.assertEqual(StartExplorationRealtimeModel.get(
'0:%s' % self.EXP_ID).count, 1)
# Data in realtime layer 1 has been deleted.
self.assertIsNone(StartExplorationRealtimeModel.get(
'1:%s' % self.EXP_ID, strict=False))
self.assertEqual(self.count_jobs_in_taskqueue(), 1)
self.process_and_flush_pending_tasks()
self.assertEqual(
stats_models.ExplorationAnnotationsModel.get(
self.EXP_ID).num_starts, 1)
# The overall count is still 1.
self.assertEqual(
StartExplorationEventCounter.get_count(self.EXP_ID), 1)
# Data in realtime layer 0 has been deleted.
self.assertIsNone(StartExplorationRealtimeModel.get(
'0:%s' % self.EXP_ID, strict=False))
# Data in realtime layer 1 has been deleted.
self.assertIsNone(StartExplorationRealtimeModel.get(
'1:%s' % self.EXP_ID, strict=False))
def test_events_coming_in_while_batch_job_is_running(self):
with self.swap(
jobs_registry, 'ALL_CONTINUOUS_COMPUTATION_MANAGERS',
self.ALL_CONTINUOUS_COMPUTATION_MANAGERS_FOR_TESTS):
# Currently no events have been recorded.
self.assertEqual(
StartExplorationEventCounter.get_count(self.EXP_ID), 0)
# Enqueue the batch computation. (It is running on 0 events.)
StartExplorationEventCounter._kickoff_batch_job()
# Record an event while this job is in the queue. Simulate
# this by directly calling on_incoming_event(), because using
# StartExplorationEventHandler.record() would just put the event
# in the task queue, which we don't want to flush yet.
event_services.StartExplorationEventHandler._handle_event(
self.EXP_ID, 1, feconf.DEFAULT_INIT_STATE_NAME, 'session_id', {},
feconf.PLAY_TYPE_NORMAL)
StartExplorationEventCounter.on_incoming_event(
event_services.StartExplorationEventHandler.EVENT_TYPE,
self.EXP_ID, 1, feconf.DEFAULT_INIT_STATE_NAME, 'session_id', {},
feconf.PLAY_TYPE_NORMAL)
# The overall count is now 1.
self.assertEqual(
StartExplorationEventCounter.get_count(self.EXP_ID), 1)
# Finish the job.
self.process_and_flush_pending_tasks()
# When the batch job completes, the overall count is still 1.
self.assertEqual(
StartExplorationEventCounter.get_count(self.EXP_ID), 1)
# The batch job result should still be 0, since the event arrived
# after the batch job started.
with self.assertRaises(base_models.BaseModel.EntityNotFoundError):
stats_models.ExplorationAnnotationsModel.get(self.EXP_ID)
# TODO(sll): When we have some concrete ContinuousComputations running in
# production, add an integration test to ensure that the registration of event
# handlers in the main codebase is happening correctly.
| apache-2.0 |
NSAmelchev/ignite | modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/replicated/GridCacheReplicatedLockSelfTest.java | 1312 | /*
* 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.ignite.internal.processors.cache.distributed.replicated;
import org.apache.ignite.cache.CacheMode;
import org.apache.ignite.internal.processors.cache.distributed.GridCacheLockAbstractTest;
import static org.apache.ignite.cache.CacheMode.REPLICATED;
/**
* Test cases for multi-threaded tests.
*/
public class GridCacheReplicatedLockSelfTest extends GridCacheLockAbstractTest {
/** {@inheritDoc} */
@Override protected CacheMode cacheMode() {
return REPLICATED;
}
}
| apache-2.0 |
ericschultz/outercurve-orchard | src/Orchard.Web/Core/Containers/Extensions/ContentQueryExtensions.cs | 8590 | using System;
using System.Collections.Generic;
using Orchard.ContentManagement;
using Orchard.Core.Common.Models;
using Orchard.Core.Containers.Models;
using Orchard.Core.Title.Models;
namespace Orchard.Core.Containers.Extensions {
public static class ContentQueryExtensions {
public static IContentQuery<T> OrderBy<T>(this IContentQuery<T> query, string partAndProperty, bool descendingOrder) where T : IContent {
//todo: (heskew) order by custom part properties
switch (partAndProperty) {
case "ContainablePart.Weight":
query = descendingOrder
? query.OrderByDescending<ContainablePartRecord>(record => record.Weight)
: query.OrderBy<ContainablePartRecord>(record => record.Weight);
break;
case "TitlePart.Title":
query = descendingOrder
? query.OrderByDescending<TitlePartRecord>(record => record.Title)
: query.OrderBy<TitlePartRecord>(record => record.Title);
break;
case "CustomPropertiesPart.CustomOne":
query = descendingOrder
? query.OrderByDescending<CustomPropertiesPartRecord>(record => record.CustomOne)
: query.OrderBy<CustomPropertiesPartRecord>(record => record.CustomOne);
break;
case "CustomPropertiesPart.CustomTwo":
query = descendingOrder
? query.OrderByDescending<CustomPropertiesPartRecord>(record => record.CustomTwo)
: query.OrderBy<CustomPropertiesPartRecord>(record => record.CustomTwo);
break;
case "CustomPropertiesPart.CustomThree":
query = descendingOrder
? query.OrderByDescending<CustomPropertiesPartRecord>(record => record.CustomThree)
: query.OrderBy<CustomPropertiesPartRecord>(record => record.CustomThree);
break;
case "CommonPart.CreatedUtc":
query = descendingOrder
? query.OrderByDescending<CommonPartRecord>(record => record.CreatedUtc)
: query.OrderBy<CommonPartRecord>(record => record.CreatedUtc);
break;
default: // "CommonPart.PublishedUtc"
query = descendingOrder
? query.OrderByDescending<CommonPartRecord>(record => record.PublishedUtc)
: query.OrderBy<CommonPartRecord>(record => record.PublishedUtc);
break;
}
return query;
}
public static IContentQuery<ContentItem> Where(this IContentQuery<ContentItem> query, string partAndProperty, string comparisonOperator, string comparisonValue) {
var filterKey = string.Format("{0}|{1}", partAndProperty, comparisonOperator);
if (!_filters.ContainsKey(filterKey))
return query;
return _filters[filterKey](query, comparisonValue);
}
// convoluted: yes; quick and works for now: yes; technical debt: not much
private static readonly Dictionary<string, Func<IContentQuery<ContentItem>, string, IContentQuery<ContentItem>>> _filters = new Dictionary<string, Func<IContentQuery<ContentItem>, string, IContentQuery<ContentItem>>> {
{"TitlePart.Title|<", new Func<IContentQuery<ContentItem>, string, IContentQuery<ContentItem>>((q, s) => q.Where<TitlePartRecord>(r => true /* CompareTo is not implemented - r.Title.CompareTo(s) == -1*/))},
{"TitlePart.Title|>", new Func<IContentQuery<ContentItem>, string, IContentQuery<ContentItem>>((q, s) => q.Where<TitlePartRecord>(r => true /* CompareTo is not implemented - r.Title.CompareTo(s) == 1*/))},
{"TitlePart.Title|=", new Func<IContentQuery<ContentItem>, string, IContentQuery<ContentItem>>((q, s) => q.Where<TitlePartRecord>(r => r.Title.Equals(s, StringComparison.OrdinalIgnoreCase)))},
{"TitlePart.Title|^=", new Func<IContentQuery<ContentItem>, string, IContentQuery<ContentItem>>((q, s) => q.Where<TitlePartRecord>(r => r.Title.StartsWith(s, StringComparison.OrdinalIgnoreCase)))},
{"CommonPart.PublishedUtc|<", new Func<IContentQuery<ContentItem>, string, IContentQuery<ContentItem>>((q, s) => q.Where<CommonPartRecord>(r => r.PublishedUtc < DateTime.Parse(s)))},
{"CommonPart.PublishedUtc|>", new Func<IContentQuery<ContentItem>, string, IContentQuery<ContentItem>>((q, s) => q.Where<CommonPartRecord>(r => r.PublishedUtc > DateTime.Parse(s)))},
{"CommonPart.PublishedUtc|=", new Func<IContentQuery<ContentItem>, string, IContentQuery<ContentItem>>((q, s) => q.Where<CommonPartRecord>(r => r.PublishedUtc == DateTime.Parse(s)))}, // todo: (heskew) not practical as is. needs some sense of precision....
{"CommonPart.PublishedUtc|^=", new Func<IContentQuery<ContentItem>, string, IContentQuery<ContentItem>>((q, s) => q.Where<CommonPartRecord>(r => true /* can't modified PublishedUtc for partial comparisons */))},
// todo: (hesekw) this could benefit from a better filter implementation as this is currently very limited in functionality and I have no idea how the custom parts will be used by folks
{"CustomPropertiesPart.CustomOne|<", new Func<IContentQuery<ContentItem>, string, IContentQuery<ContentItem>>((q, s) => q.Where<CustomPropertiesPartRecord>(r => true /* CompareTo is not implemented - r.CustomOne.CompareTo(s) == -1*/))},
{"CustomPropertiesPart.CustomOne|>", new Func<IContentQuery<ContentItem>, string, IContentQuery<ContentItem>>((q, s) => q.Where<CustomPropertiesPartRecord>(r => true /* CompareTo is not implemented - r.CustomOne.CompareTo(s) == 1*/))},
{"CustomPropertiesPart.CustomOne|=", new Func<IContentQuery<ContentItem>, string, IContentQuery<ContentItem>>((q, s) => q.Where<CustomPropertiesPartRecord>(r => r.CustomOne.Equals(s, StringComparison.OrdinalIgnoreCase)))},
{"CustomPropertiesPart.CustomOne|^=", new Func<IContentQuery<ContentItem>, string, IContentQuery<ContentItem>>((q, s) => q.Where<CustomPropertiesPartRecord>(r => r.CustomOne.StartsWith(s, StringComparison.OrdinalIgnoreCase)))},
{"CustomPropertiesPart.CustomTwo|<", new Func<IContentQuery<ContentItem>, string, IContentQuery<ContentItem>>((q, s) => q.Where<CustomPropertiesPartRecord>(r => true /* CompareTo is not implemented - r.CustomTwo.CompareTo(s) == -1*/))},
{"CustomPropertiesPart.CustomTwo|>", new Func<IContentQuery<ContentItem>, string, IContentQuery<ContentItem>>((q, s) => q.Where<CustomPropertiesPartRecord>(r => true /* CompareTo is not implemented - r.CustomTwo.CompareTo(s) == 1*/))},
{"CustomPropertiesPart.CustomTwo|=", new Func<IContentQuery<ContentItem>, string, IContentQuery<ContentItem>>((q, s) => q.Where<CustomPropertiesPartRecord>(r => r.CustomTwo.Equals(s, StringComparison.OrdinalIgnoreCase)))},
{"CustomPropertiesPart.CustomTwo|^=", new Func<IContentQuery<ContentItem>, string, IContentQuery<ContentItem>>((q, s) => q.Where<CustomPropertiesPartRecord>(r => r.CustomTwo.StartsWith(s, StringComparison.OrdinalIgnoreCase)))},
{"CustomPropertiesPart.CustomThree|<", new Func<IContentQuery<ContentItem>, string, IContentQuery<ContentItem>>((q, s) => q.Where<CustomPropertiesPartRecord>(r => true /* CompareTo is not implemented - r.CustomThree.CompareTo(s) == -1*/))},
{"CustomPropertiesPart.CustomThree|>", new Func<IContentQuery<ContentItem>, string, IContentQuery<ContentItem>>((q, s) => q.Where<CustomPropertiesPartRecord>(r => true /* CompareTo is not implemented - r.CustomThree.CompareTo(s) == 1*/))},
{"CustomPropertiesPart.CustomThree|=", new Func<IContentQuery<ContentItem>, string, IContentQuery<ContentItem>>((q, s) => q.Where<CustomPropertiesPartRecord>(r => r.CustomThree.Equals(s, StringComparison.OrdinalIgnoreCase)))},
{"CustomPropertiesPart.CustomThree|^=", new Func<IContentQuery<ContentItem>, string, IContentQuery<ContentItem>>((q, s) => q.Where<CustomPropertiesPartRecord>(r => r.CustomThree.StartsWith(s, StringComparison.OrdinalIgnoreCase)))},
};
}
} | apache-2.0 |
Addepar/buck | test/com/facebook/buck/features/python/testdata/python_binary/external_sources/wheel_package/wheel_package/my_wheel.py | 68 | from __future__ import print_function
def f():
print("wheel")
| apache-2.0 |
holmes/intellij-community | python/src/com/jetbrains/python/psi/impl/references/PyImportReference.java | 12997 | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.psi.impl.references;
import com.intellij.codeInsight.completion.CompletionUtil;
import com.intellij.codeInsight.completion.InsertHandler;
import com.intellij.codeInsight.completion.InsertionContext;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.psi.*;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.ArrayUtil;
import com.intellij.util.ProcessingContext;
import com.jetbrains.python.PyNames;
import com.jetbrains.python.PyTokenTypes;
import com.jetbrains.python.psi.*;
import com.intellij.psi.util.QualifiedName;
import com.jetbrains.python.psi.impl.PyReferenceExpressionImpl;
import com.jetbrains.python.psi.resolve.*;
import com.jetbrains.python.psi.types.PyModuleType;
import com.jetbrains.python.psi.types.PyType;
import com.jetbrains.python.psi.types.TypeEvalContext;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
/**
* Reference in an import statement:<br/>
* <code>import <u>foo.name</u></code>
*
* @author yole
*/
public class PyImportReference extends PyReferenceImpl {
protected final PyReferenceExpressionImpl myElement;
public PyImportReference(PyReferenceExpressionImpl element, PyResolveContext context) {
super(element, context);
myElement = element;
}
public static PyImportReference forElement(PyReferenceExpressionImpl expression, PsiElement importParent, PyResolveContext context) {
if (importParent instanceof PyImportElement) {
final PyImportStatementBase importStatement = PsiTreeUtil.getParentOfType(importParent, PyImportStatementBase.class);
if (importStatement instanceof PyFromImportStatement) {
return new PyFromImportNameReference(expression, context);
}
return new PyImportReference(expression, context);
}
return new PyFromImportSourceReference(expression, context);
}
@Override
public String getUnresolvedDescription() {
final PyImportStatement importStatement = PsiTreeUtil.getParentOfType(myElement, PyImportStatement.class);
if (importStatement != null) {
return "No module named " + myElement.getReferencedName();
}
return super.getUnresolvedDescription();
}
@NotNull
@Override
protected List<RatedResolveResult> resolveInner() {
final PyImportElement parent = PsiTreeUtil.getParentOfType(myElement, PyImportElement.class); //importRef.getParent();
final QualifiedName qname = myElement.asQualifiedName();
return qname == null ? Collections.<RatedResolveResult>emptyList() : ResolveImportUtil.resolveNameInImportStatement(parent, qname);
}
@NotNull
@Override
public Object[] getVariants() {
// no completion in invalid import statements
PyImportElement importElement = PsiTreeUtil.getParentOfType(myElement, PyImportElement.class);
if (importElement != null) {
PsiErrorElement prevError = PsiTreeUtil.getPrevSiblingOfType(importElement, PsiErrorElement.class);
if (prevError != null) {
return ArrayUtil.EMPTY_OBJECT_ARRAY;
}
}
PyExpression qualifier = myElement.getQualifier();
final TypeEvalContext context = TypeEvalContext.codeCompletion(myElement.getProject(),
CompletionUtil.getOriginalOrSelf(myElement).getContainingFile());
if (qualifier != null) {
// qualifier's type must be module, it should know how to complete
PyType type = context.getType(qualifier);
if (type != null) {
Object[] variants = getTypeCompletionVariants(myElement, type);
if (!alreadyHasImportKeyword()) {
replaceInsertHandler(variants, ImportKeywordHandler.INSTANCE);
}
return variants;
}
else {
return ArrayUtil.EMPTY_OBJECT_ARRAY;
}
}
else {
// complete to possible modules
return new ImportVariantCollector(context).execute();
}
}
private static void replaceInsertHandler(Object[] variants, final InsertHandler<LookupElement> insertHandler) {
for (int i=0; i < variants.length; i+=1) {
Object item = variants[i];
if (hasChildPackages(item)) continue;
if (item instanceof LookupElementBuilder) {
variants[i] = ((LookupElementBuilder)item).withInsertHandler(insertHandler);
}
else if (item instanceof PsiNamedElement) {
final PsiNamedElement element = (PsiNamedElement)item;
final String name = element.getName();
assert name != null; // it can't really have null name
variants[i] = LookupElementBuilder
.create(name)
.withIcon(element.getIcon(0))
.withInsertHandler(insertHandler);
}
}
}
private static boolean hasChildPackages(Object item) {
PsiElement itemElement = null;
if (item instanceof PsiElement) {
itemElement = (PsiElement) item;
}
else if (item instanceof LookupElement) {
LookupElement lookupElement = (LookupElement) item;
if (lookupElement.getObject() instanceof PsiElement) {
itemElement = (PsiElement) lookupElement.getObject();
}
}
return !(itemElement instanceof PsiFile); // TODO deeper check?
}
private boolean alreadyHasImportKeyword() {
if (PsiTreeUtil.getParentOfType(myElement, PyImportStatement.class) != null) {
return true;
}
ASTNode node = myElement.getNode();
while (node != null) {
final IElementType nodeType = node.getElementType();
if (nodeType == PyTokenTypes.IMPORT_KEYWORD) {
return true;
}
node = node.getTreeNext();
}
return false;
}
class ImportVariantCollector {
private final PsiFile myCurrentFile;
private final Set<String> myNamesAlready;
private final List<Object> myObjects;
@NotNull private final TypeEvalContext myContext;
public ImportVariantCollector(@NotNull TypeEvalContext context) {
myContext = context;
PsiFile currentFile = myElement.getContainingFile();
currentFile = currentFile.getOriginalFile();
myCurrentFile = currentFile;
myNamesAlready = new HashSet<String>();
myObjects = new ArrayList<Object>();
}
public Object[] execute() {
int relativeLevel = -1;
InsertHandler<LookupElement> insertHandler = null;
// NOTE: could use getPointInImport()
// are we in "import _" or "from foo import _"?
PyFromImportStatement fromImport = PsiTreeUtil.getParentOfType(myElement, PyFromImportStatement.class);
if (fromImport != null && myElement.getParent() != fromImport) { // in "from foo import _"
PyReferenceExpression src = fromImport.getImportSource();
if (src != null) {
PsiElement modCandidate = src.getReference().resolve();
if (modCandidate instanceof PyExpression) {
addImportedNames(fromImport.getImportElements()); // don't propose already imported items
// try to collect submodules
PyExpression module = (PyExpression)modCandidate;
PyType qualifierType = myContext.getType(module);
if (qualifierType != null) {
ProcessingContext ctx = new ProcessingContext();
ctx.put(PyType.CTX_NAMES, myNamesAlready);
Collections.addAll(myObjects, qualifierType.getCompletionVariants(myElement.getName(), myElement, ctx));
}
return myObjects.toArray();
}
else if (modCandidate instanceof PsiDirectory) {
fillFromDir((PsiDirectory)modCandidate, ImportKeywordHandler.INSTANCE);
return myObjects.toArray();
}
}
else { // null source, must be a "from ... import"
relativeLevel = fromImport.getRelativeLevel();
if (relativeLevel > 0) {
PsiDirectory relativeDir = ResolveImportUtil.stepBackFrom(myCurrentFile, relativeLevel);
if (relativeDir != null) {
addImportedNames(fromImport.getImportElements());
fillFromDir(relativeDir, null);
}
}
}
}
else { // in "import _" or "from _ import"
ASTNode n = myElement.getNode().getTreePrev();
while (n != null && n.getElementType() == PyTokenTypes.DOT) {
relativeLevel += 1;
n = n.getTreePrev();
}
if (fromImport != null) {
addImportedNames(fromImport.getImportElements());
if (!alreadyHasImportKeyword()) {
insertHandler = ImportKeywordHandler.INSTANCE;
}
}
else {
myNamesAlready.add(PyNames.FUTURE_MODULE); // never add it to "import ..."
PyImportStatement importStatement = PsiTreeUtil.getParentOfType(myElement, PyImportStatement.class);
if (importStatement != null) {
addImportedNames(importStatement.getImportElements());
}
}
// look at dir by level
if ((relativeLevel >= 0 || !ResolveImportUtil.isAbsoluteImportEnabledFor(myCurrentFile))) {
final PsiDirectory containingDirectory = myCurrentFile.getContainingDirectory();
if (containingDirectory != null) {
QualifiedName thisQName = QualifiedNameFinder.findShortestImportableQName(containingDirectory);
if (thisQName == null || thisQName.getComponentCount() == relativeLevel) {
fillFromDir(ResolveImportUtil.stepBackFrom(myCurrentFile, relativeLevel), insertHandler);
}
else if (thisQName.getComponentCount() > relativeLevel) {
thisQName = thisQName.removeTail(relativeLevel);
fillFromQName(thisQName, insertHandler);
}
}
}
}
if (relativeLevel == -1) {
fillFromQName(QualifiedName.fromComponents(), insertHandler);
}
return ArrayUtil.toObjectArray(myObjects);
}
private void fillFromQName(QualifiedName thisQName, InsertHandler<LookupElement> insertHandler) {
QualifiedNameResolver visitor = new QualifiedNameResolverImpl(thisQName).fromElement(myCurrentFile);
for (PsiDirectory dir : visitor.resultsOfType(PsiDirectory.class)) {
fillFromDir(dir, insertHandler);
}
}
private void addImportedNames(@NotNull PyImportElement[] importElements) {
for (PyImportElement element : importElements) {
PyReferenceExpression ref = element.getImportReferenceExpression();
if (ref != null) {
String s = ref.getReferencedName();
if (s != null) myNamesAlready.add(s);
}
}
}
/**
* Adds variants found under given dir.
*/
private void fillFromDir(PsiDirectory targetDir, @Nullable InsertHandler<LookupElement> insertHandler) {
if (targetDir != null) {
PsiFile initPy = targetDir.findFile(PyNames.INIT_DOT_PY);
if (initPy instanceof PyFile) {
PyModuleType moduleType = new PyModuleType((PyFile)initPy);
ProcessingContext context = new ProcessingContext();
context.put(PyType.CTX_NAMES, myNamesAlready);
Object[] completionVariants = moduleType.getCompletionVariants("", getElement(), context);
if (insertHandler != null) {
replaceInsertHandler(completionVariants, insertHandler);
}
myObjects.addAll(Arrays.asList(completionVariants));
}
else {
myObjects.addAll(PyModuleType.getSubModuleVariants(targetDir, myElement, myNamesAlready));
}
}
}
}
/**
* Adds ' import ' text after the item.
*/
private static class ImportKeywordHandler implements InsertHandler<LookupElement> {
public static final InsertHandler<LookupElement> INSTANCE = new ImportKeywordHandler();
private static final String IMPORT_KWD = " import ";
public void handleInsert(InsertionContext context, LookupElement item) {
final Editor editor = context.getEditor();
final Document document = editor.getDocument();
int tailOffset = context.getTailOffset();
document.insertString(tailOffset, IMPORT_KWD);
editor.getCaretModel().moveToOffset(tailOffset + IMPORT_KWD.length());
}
}
}
| apache-2.0 |
joone/chromium-crosswalk | third_party/WebKit/Source/platform/exported/WebCryptoAlgorithm.cpp | 22673 | /*
* Copyright (C) 2013 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "public/platform/WebCryptoAlgorithm.h"
#include "public/platform/WebCryptoAlgorithmParams.h"
#include "wtf/Assertions.h"
#include "wtf/OwnPtr.h"
#include "wtf/StdLibExtras.h"
#include "wtf/ThreadSafeRefCounted.h"
namespace blink {
namespace {
// A mapping from the algorithm ID to information about the algorithm.
const WebCryptoAlgorithmInfo algorithmIdToInfo[] = {
{ // Index 0
"AES-CBC", {
WebCryptoAlgorithmParamsTypeAesCbcParams, // Encrypt
WebCryptoAlgorithmParamsTypeAesCbcParams, // Decrypt
WebCryptoAlgorithmInfo::Undefined, // Sign
WebCryptoAlgorithmInfo::Undefined, // Verify
WebCryptoAlgorithmInfo::Undefined, // Digest
WebCryptoAlgorithmParamsTypeAesKeyGenParams, // GenerateKey
WebCryptoAlgorithmParamsTypeNone, // ImportKey
WebCryptoAlgorithmParamsTypeAesDerivedKeyParams, // GetKeyLength
WebCryptoAlgorithmInfo::Undefined, // DeriveBits
WebCryptoAlgorithmParamsTypeAesCbcParams, // WrapKey
WebCryptoAlgorithmParamsTypeAesCbcParams // UnwrapKey
}
}, { // Index 1
"HMAC", {
WebCryptoAlgorithmInfo::Undefined, // Encrypt
WebCryptoAlgorithmInfo::Undefined, // Decrypt
WebCryptoAlgorithmParamsTypeNone, // Sign
WebCryptoAlgorithmParamsTypeNone, // Verify
WebCryptoAlgorithmInfo::Undefined, // Digest
WebCryptoAlgorithmParamsTypeHmacKeyGenParams, // GenerateKey
WebCryptoAlgorithmParamsTypeHmacImportParams, // ImportKey
WebCryptoAlgorithmParamsTypeHmacImportParams, // GetKeyLength
WebCryptoAlgorithmInfo::Undefined, // DeriveBits
WebCryptoAlgorithmInfo::Undefined, // WrapKey
WebCryptoAlgorithmInfo::Undefined // UnwrapKey
}
}, { // Index 2
"RSASSA-PKCS1-v1_5", {
WebCryptoAlgorithmInfo::Undefined, // Encrypt
WebCryptoAlgorithmInfo::Undefined, // Decrypt
WebCryptoAlgorithmParamsTypeNone, // Sign
WebCryptoAlgorithmParamsTypeNone, // Verify
WebCryptoAlgorithmInfo::Undefined, // Digest
WebCryptoAlgorithmParamsTypeRsaHashedKeyGenParams, // GenerateKey
WebCryptoAlgorithmParamsTypeRsaHashedImportParams, // ImportKey
WebCryptoAlgorithmInfo::Undefined, // GetKeyLength
WebCryptoAlgorithmInfo::Undefined, // DeriveBits
WebCryptoAlgorithmInfo::Undefined, // WrapKey
WebCryptoAlgorithmInfo::Undefined // UnwrapKey
}
}, { // Index 3
"SHA-1", {
WebCryptoAlgorithmInfo::Undefined, // Encrypt
WebCryptoAlgorithmInfo::Undefined, // Decrypt
WebCryptoAlgorithmInfo::Undefined, // Sign
WebCryptoAlgorithmInfo::Undefined, // Verify
WebCryptoAlgorithmParamsTypeNone, // Digest
WebCryptoAlgorithmInfo::Undefined, // GenerateKey
WebCryptoAlgorithmInfo::Undefined, // ImportKey
WebCryptoAlgorithmInfo::Undefined, // GetKeyLength
WebCryptoAlgorithmInfo::Undefined, // DeriveBits
WebCryptoAlgorithmInfo::Undefined, // WrapKey
WebCryptoAlgorithmInfo::Undefined // UnwrapKey
}
}, { // Index 4
"SHA-256", {
WebCryptoAlgorithmInfo::Undefined, // Encrypt
WebCryptoAlgorithmInfo::Undefined, // Decrypt
WebCryptoAlgorithmInfo::Undefined, // Sign
WebCryptoAlgorithmInfo::Undefined, // Verify
WebCryptoAlgorithmParamsTypeNone, // Digest
WebCryptoAlgorithmInfo::Undefined, // GenerateKey
WebCryptoAlgorithmInfo::Undefined, // ImportKey
WebCryptoAlgorithmInfo::Undefined, // GetKeyLength
WebCryptoAlgorithmInfo::Undefined, // DeriveBits
WebCryptoAlgorithmInfo::Undefined, // WrapKey
WebCryptoAlgorithmInfo::Undefined // UnwrapKey
}
}, { // Index 5
"SHA-384", {
WebCryptoAlgorithmInfo::Undefined, // Encrypt
WebCryptoAlgorithmInfo::Undefined, // Decrypt
WebCryptoAlgorithmInfo::Undefined, // Sign
WebCryptoAlgorithmInfo::Undefined, // Verify
WebCryptoAlgorithmParamsTypeNone, // Digest
WebCryptoAlgorithmInfo::Undefined, // GenerateKey
WebCryptoAlgorithmInfo::Undefined, // ImportKey
WebCryptoAlgorithmInfo::Undefined, // GetKeyLength
WebCryptoAlgorithmInfo::Undefined, // DeriveBits
WebCryptoAlgorithmInfo::Undefined, // WrapKey
WebCryptoAlgorithmInfo::Undefined // UnwrapKey
}
}, { // Index 6
"SHA-512", {
WebCryptoAlgorithmInfo::Undefined, // Encrypt
WebCryptoAlgorithmInfo::Undefined, // Decrypt
WebCryptoAlgorithmInfo::Undefined, // Sign
WebCryptoAlgorithmInfo::Undefined, // Verify
WebCryptoAlgorithmParamsTypeNone, // Digest
WebCryptoAlgorithmInfo::Undefined, // GenerateKey
WebCryptoAlgorithmInfo::Undefined, // ImportKey
WebCryptoAlgorithmInfo::Undefined, // GetKeyLength
WebCryptoAlgorithmInfo::Undefined, // DeriveBits
WebCryptoAlgorithmInfo::Undefined, // WrapKey
WebCryptoAlgorithmInfo::Undefined // UnwrapKey
}
}, { // Index 7
"AES-GCM", {
WebCryptoAlgorithmParamsTypeAesGcmParams, // Encrypt
WebCryptoAlgorithmParamsTypeAesGcmParams, // Decrypt
WebCryptoAlgorithmInfo::Undefined, // Sign
WebCryptoAlgorithmInfo::Undefined, // Verify
WebCryptoAlgorithmInfo::Undefined, // Digest
WebCryptoAlgorithmParamsTypeAesKeyGenParams, // GenerateKey
WebCryptoAlgorithmParamsTypeNone, // ImportKey
WebCryptoAlgorithmParamsTypeAesDerivedKeyParams, // GetKeyLength
WebCryptoAlgorithmInfo::Undefined, // DeriveBits
WebCryptoAlgorithmParamsTypeAesGcmParams, // WrapKey
WebCryptoAlgorithmParamsTypeAesGcmParams // UnwrapKey
}
}, { // Index 8
"RSA-OAEP", {
WebCryptoAlgorithmParamsTypeRsaOaepParams, // Encrypt
WebCryptoAlgorithmParamsTypeRsaOaepParams, // Decrypt
WebCryptoAlgorithmInfo::Undefined, // Sign
WebCryptoAlgorithmInfo::Undefined, // Verify
WebCryptoAlgorithmInfo::Undefined, // Digest
WebCryptoAlgorithmParamsTypeRsaHashedKeyGenParams, // GenerateKey
WebCryptoAlgorithmParamsTypeRsaHashedImportParams, // ImportKey
WebCryptoAlgorithmInfo::Undefined, // GetKeyLength
WebCryptoAlgorithmInfo::Undefined, // DeriveBits
WebCryptoAlgorithmParamsTypeRsaOaepParams, // WrapKey
WebCryptoAlgorithmParamsTypeRsaOaepParams // UnwrapKey
}
}, { // Index 9
"AES-CTR", {
WebCryptoAlgorithmParamsTypeAesCtrParams, // Encrypt
WebCryptoAlgorithmParamsTypeAesCtrParams, // Decrypt
WebCryptoAlgorithmInfo::Undefined, // Sign
WebCryptoAlgorithmInfo::Undefined, // Verify
WebCryptoAlgorithmInfo::Undefined, // Digest
WebCryptoAlgorithmParamsTypeAesKeyGenParams, // GenerateKey
WebCryptoAlgorithmParamsTypeNone, // ImportKey
WebCryptoAlgorithmParamsTypeAesDerivedKeyParams, // GetKeyLength
WebCryptoAlgorithmInfo::Undefined, // DeriveBits
WebCryptoAlgorithmParamsTypeAesCtrParams, // WrapKey
WebCryptoAlgorithmParamsTypeAesCtrParams // UnwrapKey
}
}, { // Index 10
"AES-KW", {
WebCryptoAlgorithmInfo::Undefined, // Encrypt
WebCryptoAlgorithmInfo::Undefined, // Decrypt
WebCryptoAlgorithmInfo::Undefined, // Sign
WebCryptoAlgorithmInfo::Undefined, // Verify
WebCryptoAlgorithmInfo::Undefined, // Digest
WebCryptoAlgorithmParamsTypeAesKeyGenParams, // GenerateKey
WebCryptoAlgorithmParamsTypeNone, // ImportKey
WebCryptoAlgorithmParamsTypeAesDerivedKeyParams, // GetKeyLength
WebCryptoAlgorithmInfo::Undefined, // DeriveBits
WebCryptoAlgorithmParamsTypeNone, // WrapKey
WebCryptoAlgorithmParamsTypeNone // UnwrapKey
}
}, { // Index 11
"RSA-PSS", {
WebCryptoAlgorithmInfo::Undefined, // Encrypt
WebCryptoAlgorithmInfo::Undefined, // Decrypt
WebCryptoAlgorithmParamsTypeRsaPssParams, // Sign
WebCryptoAlgorithmParamsTypeRsaPssParams, // Verify
WebCryptoAlgorithmInfo::Undefined, // Digest
WebCryptoAlgorithmParamsTypeRsaHashedKeyGenParams, // GenerateKey
WebCryptoAlgorithmParamsTypeRsaHashedImportParams, // ImportKey
WebCryptoAlgorithmInfo::Undefined, // GetKeyLength
WebCryptoAlgorithmInfo::Undefined, // DeriveBits
WebCryptoAlgorithmInfo::Undefined, // WrapKey
WebCryptoAlgorithmInfo::Undefined // UnwrapKey
}
}, { // Index 12
"ECDSA", {
WebCryptoAlgorithmInfo::Undefined, // Encrypt
WebCryptoAlgorithmInfo::Undefined, // Decrypt
WebCryptoAlgorithmParamsTypeEcdsaParams, // Sign
WebCryptoAlgorithmParamsTypeEcdsaParams, // Verify
WebCryptoAlgorithmInfo::Undefined, // Digest
WebCryptoAlgorithmParamsTypeEcKeyGenParams, // GenerateKey
WebCryptoAlgorithmParamsTypeEcKeyImportParams, // ImportKey
WebCryptoAlgorithmInfo::Undefined, // GetKeyLength
WebCryptoAlgorithmInfo::Undefined, // DeriveBits
WebCryptoAlgorithmInfo::Undefined, // WrapKey
WebCryptoAlgorithmInfo::Undefined // UnwrapKey
}
}, { // Index 13
"ECDH", {
WebCryptoAlgorithmInfo::Undefined, // Encrypt
WebCryptoAlgorithmInfo::Undefined, // Decrypt
WebCryptoAlgorithmInfo::Undefined, // Sign
WebCryptoAlgorithmInfo::Undefined, // Verify
WebCryptoAlgorithmInfo::Undefined, // Digest
WebCryptoAlgorithmParamsTypeEcKeyGenParams, // GenerateKey
WebCryptoAlgorithmParamsTypeEcKeyImportParams, // ImportKey
WebCryptoAlgorithmInfo::Undefined, // GetKeyLength
WebCryptoAlgorithmParamsTypeEcdhKeyDeriveParams, // DeriveBits
WebCryptoAlgorithmInfo::Undefined, // WrapKey
WebCryptoAlgorithmInfo::Undefined // UnwrapKey
}
}, { // Index 14
"HKDF", {
WebCryptoAlgorithmInfo::Undefined, // Encrypt
WebCryptoAlgorithmInfo::Undefined, // Decrypt
WebCryptoAlgorithmInfo::Undefined, // Sign
WebCryptoAlgorithmInfo::Undefined, // Verify
WebCryptoAlgorithmInfo::Undefined, // Digest
WebCryptoAlgorithmInfo::Undefined, // GenerateKey
WebCryptoAlgorithmParamsTypeNone, // ImportKey
WebCryptoAlgorithmParamsTypeNone, // GetKeyLength
WebCryptoAlgorithmParamsTypeHkdfParams, // DeriveBits
WebCryptoAlgorithmInfo::Undefined, // WrapKey
WebCryptoAlgorithmInfo::Undefined // UnwrapKey
}
}, { // Index 15
"PBKDF2", {
WebCryptoAlgorithmInfo::Undefined, // Encrypt
WebCryptoAlgorithmInfo::Undefined, // Decrypt
WebCryptoAlgorithmInfo::Undefined, // Sign
WebCryptoAlgorithmInfo::Undefined, // Verify
WebCryptoAlgorithmInfo::Undefined, // Digest
WebCryptoAlgorithmInfo::Undefined, // GenerateKey
WebCryptoAlgorithmParamsTypeNone, // ImportKey
WebCryptoAlgorithmParamsTypeNone, // GetKeyLength
WebCryptoAlgorithmParamsTypePbkdf2Params, // DeriveBits
WebCryptoAlgorithmInfo::Undefined, // WrapKey
WebCryptoAlgorithmInfo::Undefined // UnwrapKey
}
},
};
// Initializing the algorithmIdToInfo table above depends on knowing the enum
// values for algorithm IDs. If those ever change, the table will need to be
// updated.
static_assert(WebCryptoAlgorithmIdAesCbc == 0, "AES CBC id must match");
static_assert(WebCryptoAlgorithmIdHmac == 1, "HMAC id must match");
static_assert(WebCryptoAlgorithmIdRsaSsaPkcs1v1_5 == 2, "RSASSA-PKCS1-v1_5 id must match");
static_assert(WebCryptoAlgorithmIdSha1 == 3, "SHA1 id must match");
static_assert(WebCryptoAlgorithmIdSha256 == 4, "SHA256 id must match");
static_assert(WebCryptoAlgorithmIdSha384 == 5, "SHA384 id must match");
static_assert(WebCryptoAlgorithmIdSha512 == 6, "SHA512 id must match");
static_assert(WebCryptoAlgorithmIdAesGcm == 7, "AES GCM id must match");
static_assert(WebCryptoAlgorithmIdRsaOaep == 8, "RSA OAEP id must match");
static_assert(WebCryptoAlgorithmIdAesCtr == 9, "AES CTR id must match");
static_assert(WebCryptoAlgorithmIdAesKw == 10, "AESKW id must match");
static_assert(WebCryptoAlgorithmIdRsaPss == 11, "RSA-PSS id must match");
static_assert(WebCryptoAlgorithmIdEcdsa == 12, "ECDSA id must match");
static_assert(WebCryptoAlgorithmIdEcdh == 13, "ECDH id must match");
static_assert(WebCryptoAlgorithmIdHkdf == 14, "HKDF id must match");
static_assert(WebCryptoAlgorithmIdPbkdf2 == 15, "Pbkdf2 id must match");
static_assert(WebCryptoAlgorithmIdLast == 15, "last id must match");
static_assert(10 == WebCryptoOperationLast, "the parameter mapping needs to be updated");
} // namespace
class WebCryptoAlgorithmPrivate : public ThreadSafeRefCounted<WebCryptoAlgorithmPrivate> {
public:
WebCryptoAlgorithmPrivate(WebCryptoAlgorithmId id, PassOwnPtr<WebCryptoAlgorithmParams> params)
: id(id)
, params(std::move(params))
{
}
WebCryptoAlgorithmId id;
OwnPtr<WebCryptoAlgorithmParams> params;
};
WebCryptoAlgorithm::WebCryptoAlgorithm(WebCryptoAlgorithmId id, PassOwnPtr<WebCryptoAlgorithmParams> params)
: m_private(adoptRef(new WebCryptoAlgorithmPrivate(id, std::move(params))))
{
}
WebCryptoAlgorithm WebCryptoAlgorithm::createNull()
{
return WebCryptoAlgorithm();
}
WebCryptoAlgorithm WebCryptoAlgorithm::adoptParamsAndCreate(WebCryptoAlgorithmId id, WebCryptoAlgorithmParams* params)
{
return WebCryptoAlgorithm(id, adoptPtr(params));
}
const WebCryptoAlgorithmInfo* WebCryptoAlgorithm::lookupAlgorithmInfo(WebCryptoAlgorithmId id)
{
const unsigned idInt = id;
if (idInt >= WTF_ARRAY_LENGTH(algorithmIdToInfo))
return 0;
return &algorithmIdToInfo[id];
}
bool WebCryptoAlgorithm::isNull() const
{
return m_private.isNull();
}
WebCryptoAlgorithmId WebCryptoAlgorithm::id() const
{
ASSERT(!isNull());
return m_private->id;
}
WebCryptoAlgorithmParamsType WebCryptoAlgorithm::paramsType() const
{
ASSERT(!isNull());
if (!m_private->params)
return WebCryptoAlgorithmParamsTypeNone;
return m_private->params->type();
}
const WebCryptoAesCbcParams* WebCryptoAlgorithm::aesCbcParams() const
{
ASSERT(!isNull());
if (paramsType() == WebCryptoAlgorithmParamsTypeAesCbcParams)
return static_cast<WebCryptoAesCbcParams*>(m_private->params.get());
return 0;
}
const WebCryptoAesCtrParams* WebCryptoAlgorithm::aesCtrParams() const
{
ASSERT(!isNull());
if (paramsType() == WebCryptoAlgorithmParamsTypeAesCtrParams)
return static_cast<WebCryptoAesCtrParams*>(m_private->params.get());
return 0;
}
const WebCryptoAesKeyGenParams* WebCryptoAlgorithm::aesKeyGenParams() const
{
ASSERT(!isNull());
if (paramsType() == WebCryptoAlgorithmParamsTypeAesKeyGenParams)
return static_cast<WebCryptoAesKeyGenParams*>(m_private->params.get());
return 0;
}
const WebCryptoHmacImportParams* WebCryptoAlgorithm::hmacImportParams() const
{
ASSERT(!isNull());
if (paramsType() == WebCryptoAlgorithmParamsTypeHmacImportParams)
return static_cast<WebCryptoHmacImportParams*>(m_private->params.get());
return 0;
}
const WebCryptoHmacKeyGenParams* WebCryptoAlgorithm::hmacKeyGenParams() const
{
ASSERT(!isNull());
if (paramsType() == WebCryptoAlgorithmParamsTypeHmacKeyGenParams)
return static_cast<WebCryptoHmacKeyGenParams*>(m_private->params.get());
return 0;
}
const WebCryptoAesGcmParams* WebCryptoAlgorithm::aesGcmParams() const
{
ASSERT(!isNull());
if (paramsType() == WebCryptoAlgorithmParamsTypeAesGcmParams)
return static_cast<WebCryptoAesGcmParams*>(m_private->params.get());
return 0;
}
const WebCryptoRsaOaepParams* WebCryptoAlgorithm::rsaOaepParams() const
{
ASSERT(!isNull());
if (paramsType() == WebCryptoAlgorithmParamsTypeRsaOaepParams)
return static_cast<WebCryptoRsaOaepParams*>(m_private->params.get());
return 0;
}
const WebCryptoRsaHashedImportParams* WebCryptoAlgorithm::rsaHashedImportParams() const
{
ASSERT(!isNull());
if (paramsType() == WebCryptoAlgorithmParamsTypeRsaHashedImportParams)
return static_cast<WebCryptoRsaHashedImportParams*>(m_private->params.get());
return 0;
}
const WebCryptoRsaHashedKeyGenParams* WebCryptoAlgorithm::rsaHashedKeyGenParams() const
{
ASSERT(!isNull());
if (paramsType() == WebCryptoAlgorithmParamsTypeRsaHashedKeyGenParams)
return static_cast<WebCryptoRsaHashedKeyGenParams*>(m_private->params.get());
return 0;
}
const WebCryptoRsaPssParams* WebCryptoAlgorithm::rsaPssParams() const
{
ASSERT(!isNull());
if (paramsType() == WebCryptoAlgorithmParamsTypeRsaPssParams)
return static_cast<WebCryptoRsaPssParams*>(m_private->params.get());
return 0;
}
const WebCryptoEcdsaParams* WebCryptoAlgorithm::ecdsaParams() const
{
ASSERT(!isNull());
if (paramsType() == WebCryptoAlgorithmParamsTypeEcdsaParams)
return static_cast<WebCryptoEcdsaParams*>(m_private->params.get());
return 0;
}
const WebCryptoEcKeyGenParams* WebCryptoAlgorithm::ecKeyGenParams() const
{
ASSERT(!isNull());
if (paramsType() == WebCryptoAlgorithmParamsTypeEcKeyGenParams)
return static_cast<WebCryptoEcKeyGenParams*>(m_private->params.get());
return 0;
}
const WebCryptoEcKeyImportParams* WebCryptoAlgorithm::ecKeyImportParams() const
{
ASSERT(!isNull());
if (paramsType() == WebCryptoAlgorithmParamsTypeEcKeyImportParams)
return static_cast<WebCryptoEcKeyImportParams*>(m_private->params.get());
return 0;
}
const WebCryptoEcdhKeyDeriveParams* WebCryptoAlgorithm::ecdhKeyDeriveParams() const
{
ASSERT(!isNull());
if (paramsType() == WebCryptoAlgorithmParamsTypeEcdhKeyDeriveParams)
return static_cast<WebCryptoEcdhKeyDeriveParams*>(m_private->params.get());
return 0;
}
const WebCryptoAesDerivedKeyParams* WebCryptoAlgorithm::aesDerivedKeyParams() const
{
ASSERT(!isNull());
if (paramsType() == WebCryptoAlgorithmParamsTypeAesDerivedKeyParams)
return static_cast<WebCryptoAesDerivedKeyParams*>(m_private->params.get());
return 0;
}
const WebCryptoHkdfParams* WebCryptoAlgorithm::hkdfParams() const
{
ASSERT(!isNull());
if (paramsType() == WebCryptoAlgorithmParamsTypeHkdfParams)
return static_cast<WebCryptoHkdfParams*>(m_private->params.get());
return 0;
}
const WebCryptoPbkdf2Params* WebCryptoAlgorithm::pbkdf2Params() const
{
ASSERT(!isNull());
if (paramsType() == WebCryptoAlgorithmParamsTypePbkdf2Params)
return static_cast<WebCryptoPbkdf2Params*>(m_private->params.get());
return 0;
}
bool WebCryptoAlgorithm::isHash(WebCryptoAlgorithmId id)
{
switch (id) {
case WebCryptoAlgorithmIdSha1:
case WebCryptoAlgorithmIdSha256:
case WebCryptoAlgorithmIdSha384:
case WebCryptoAlgorithmIdSha512:
return true;
case WebCryptoAlgorithmIdAesCbc:
case WebCryptoAlgorithmIdHmac:
case WebCryptoAlgorithmIdRsaSsaPkcs1v1_5:
case WebCryptoAlgorithmIdAesGcm:
case WebCryptoAlgorithmIdRsaOaep:
case WebCryptoAlgorithmIdAesCtr:
case WebCryptoAlgorithmIdAesKw:
case WebCryptoAlgorithmIdRsaPss:
case WebCryptoAlgorithmIdEcdsa:
case WebCryptoAlgorithmIdEcdh:
case WebCryptoAlgorithmIdHkdf:
case WebCryptoAlgorithmIdPbkdf2:
break;
}
return false;
}
bool WebCryptoAlgorithm::isKdf(WebCryptoAlgorithmId id)
{
switch (id) {
case WebCryptoAlgorithmIdHkdf:
case WebCryptoAlgorithmIdPbkdf2:
return true;
case WebCryptoAlgorithmIdSha1:
case WebCryptoAlgorithmIdSha256:
case WebCryptoAlgorithmIdSha384:
case WebCryptoAlgorithmIdSha512:
case WebCryptoAlgorithmIdAesCbc:
case WebCryptoAlgorithmIdHmac:
case WebCryptoAlgorithmIdRsaSsaPkcs1v1_5:
case WebCryptoAlgorithmIdAesGcm:
case WebCryptoAlgorithmIdRsaOaep:
case WebCryptoAlgorithmIdAesCtr:
case WebCryptoAlgorithmIdAesKw:
case WebCryptoAlgorithmIdRsaPss:
case WebCryptoAlgorithmIdEcdsa:
case WebCryptoAlgorithmIdEcdh:
break;
}
return false;
}
void WebCryptoAlgorithm::assign(const WebCryptoAlgorithm& other)
{
m_private = other.m_private;
}
void WebCryptoAlgorithm::reset()
{
m_private.reset();
}
} // namespace blink
| bsd-3-clause |
jason-simmons/flutter_engine | testing/test_metal_surface_unittests.cc | 1166 | // Copyright 2013 The Flutter 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 "flutter/testing/test_metal_context.h"
#include "flutter/testing/test_metal_surface.h"
#include "flutter/testing/testing.h"
namespace flutter {
namespace testing {
#ifdef SHELL_ENABLE_METAL
TEST(TestMetalSurface, EmptySurfaceIsInvalid) {
if (!TestMetalSurface::PlatformSupportsMetal()) {
GTEST_SKIP();
}
TestMetalContext metal_context = TestMetalContext();
auto surface = TestMetalSurface::Create(metal_context);
ASSERT_NE(surface, nullptr);
ASSERT_FALSE(surface->IsValid());
}
TEST(TestMetalSurface, CanCreateValidTestMetalSurface) {
if (!TestMetalSurface::PlatformSupportsMetal()) {
GTEST_SKIP();
}
TestMetalContext metal_context = TestMetalContext();
auto surface =
TestMetalSurface::Create(metal_context, SkISize::Make(100, 100));
ASSERT_NE(surface, nullptr);
ASSERT_TRUE(surface->IsValid());
ASSERT_NE(surface->GetSurface(), nullptr);
ASSERT_NE(surface->GetGrContext(), nullptr);
}
#endif
} // namespace testing
} // namespace flutter
| bsd-3-clause |
manolama/dd-agent | dogstream/cassandra.py | 2422 | # (C) Datadog, Inc. 2010-2016
# All rights reserved
# Licensed under Simplified BSD License (see LICENSE)
from datetime import datetime
import re
from dogstream import common
LOG4J_PRIORITY = [
"TRACE",
"DEBUG",
"INFO",
"WARN",
"ERROR",
"FATAL",
]
ALERT_TYPES = {
"FATAL": "error",
"ERROR": "error",
"WARN": "warning",
"INFO": "info",
"DEBUG": "info",
"TRACE": "info",
}
EVENT_TYPE = "cassandra.compaction"
THREADS = [
"CompactionExecutor",
]
DATE_FORMAT = '%Y-%m-%d %H:%M:%S,%f'
# Parse Cassandra default system.log log4j pattern: %5p [%t] %d{ISO8601} %F (line %L) %m%n
LOG_PATTERN = re.compile(r"".join([
r"\s*(?P<priority>%s)\s+" % "|".join("(%s)" % p for p in LOG4J_PRIORITY),
r"(\[CompactionExecutor:\d*\]\s+)?", # optional thread name and number
r"((?P<timestamp>\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2},\d*)|",
r"(?P<time>\d{2}:\d{2}:\d{2},\d*))\s+",
r"(\w+\.java \(line \d+\)\s+)?", # optional source file and line
r"(?P<msg>Compact(ed|ing) .*)\s*",
]))
def parse_date(timestamp):
return common.parse_date(timestamp, DATE_FORMAT)
def parse_cassandra(log, line):
matched = LOG_PATTERN.match(line)
if matched:
event = matched.groupdict()
# Convert the timestamp string into an epoch timestamp
time_val = event.get('time', None)
if time_val:
event['timestamp'] = parse_date("%s %s" % (datetime.utcnow().strftime("%Y-%m-%d"), time_val))
else:
try:
event['timestamp'] = parse_date(event['timestamp'])
except ValueError:
# only python >= 2.6 supports %f in strptime
event
del event['time']
# Process the log priority
event['alert_type'] = ALERT_TYPES.get(event['priority'], "info")
if event['alert_type'] in ('error', 'warning'):
event['auto_priority'] = 1
else:
event['auto_priority'] = 0
del event['priority']
# Process the aggregation metadata
event['event_type'] = EVENT_TYPE
# Process the message
msg = event['msg']
if len(msg) > common.MAX_TITLE_LEN:
event['msg_title'] = msg[0:common.MAX_TITLE_LEN]
event['msg_text'] = msg
else:
event['msg_title'] = msg
del event['msg']
return [event]
else:
return None
| bsd-3-clause |
anshul313/chibleetestbackend | node_modules/grunt-protractor-coverage/node_modules/grunt-istanbul/node_modules/istanbul/node_modules/js-yaml/dist/js-yaml.js | 104940 | /* js-yaml 3.6.1 https://github.com/nodeca/js-yaml */(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.jsyaml = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
'use strict';
var loader = require('./js-yaml/loader');
var dumper = require('./js-yaml/dumper');
function deprecated(name) {
return function () {
throw new Error('Function ' + name + ' is deprecated and cannot be used.');
};
}
module.exports.Type = require('./js-yaml/type');
module.exports.Schema = require('./js-yaml/schema');
module.exports.FAILSAFE_SCHEMA = require('./js-yaml/schema/failsafe');
module.exports.JSON_SCHEMA = require('./js-yaml/schema/json');
module.exports.CORE_SCHEMA = require('./js-yaml/schema/core');
module.exports.DEFAULT_SAFE_SCHEMA = require('./js-yaml/schema/default_safe');
module.exports.DEFAULT_FULL_SCHEMA = require('./js-yaml/schema/default_full');
module.exports.load = loader.load;
module.exports.loadAll = loader.loadAll;
module.exports.safeLoad = loader.safeLoad;
module.exports.safeLoadAll = loader.safeLoadAll;
module.exports.dump = dumper.dump;
module.exports.safeDump = dumper.safeDump;
module.exports.YAMLException = require('./js-yaml/exception');
// Deprecated schema names from JS-YAML 2.0.x
module.exports.MINIMAL_SCHEMA = require('./js-yaml/schema/failsafe');
module.exports.SAFE_SCHEMA = require('./js-yaml/schema/default_safe');
module.exports.DEFAULT_SCHEMA = require('./js-yaml/schema/default_full');
// Deprecated functions from JS-YAML 1.x.x
module.exports.scan = deprecated('scan');
module.exports.parse = deprecated('parse');
module.exports.compose = deprecated('compose');
module.exports.addConstructor = deprecated('addConstructor');
},{"./js-yaml/dumper":3,"./js-yaml/exception":4,"./js-yaml/loader":5,"./js-yaml/schema":7,"./js-yaml/schema/core":8,"./js-yaml/schema/default_full":9,"./js-yaml/schema/default_safe":10,"./js-yaml/schema/failsafe":11,"./js-yaml/schema/json":12,"./js-yaml/type":13}],2:[function(require,module,exports){
'use strict';
function isNothing(subject) {
return (typeof subject === 'undefined') || (subject === null);
}
function isObject(subject) {
return (typeof subject === 'object') && (subject !== null);
}
function toArray(sequence) {
if (Array.isArray(sequence)) return sequence;
else if (isNothing(sequence)) return [];
return [ sequence ];
}
function extend(target, source) {
var index, length, key, sourceKeys;
if (source) {
sourceKeys = Object.keys(source);
for (index = 0, length = sourceKeys.length; index < length; index += 1) {
key = sourceKeys[index];
target[key] = source[key];
}
}
return target;
}
function repeat(string, count) {
var result = '', cycle;
for (cycle = 0; cycle < count; cycle += 1) {
result += string;
}
return result;
}
function isNegativeZero(number) {
return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number);
}
module.exports.isNothing = isNothing;
module.exports.isObject = isObject;
module.exports.toArray = toArray;
module.exports.repeat = repeat;
module.exports.isNegativeZero = isNegativeZero;
module.exports.extend = extend;
},{}],3:[function(require,module,exports){
'use strict';
/*eslint-disable no-use-before-define*/
var common = require('./common');
var YAMLException = require('./exception');
var DEFAULT_FULL_SCHEMA = require('./schema/default_full');
var DEFAULT_SAFE_SCHEMA = require('./schema/default_safe');
var _toString = Object.prototype.toString;
var _hasOwnProperty = Object.prototype.hasOwnProperty;
var CHAR_TAB = 0x09; /* Tab */
var CHAR_LINE_FEED = 0x0A; /* LF */
var CHAR_SPACE = 0x20; /* Space */
var CHAR_EXCLAMATION = 0x21; /* ! */
var CHAR_DOUBLE_QUOTE = 0x22; /* " */
var CHAR_SHARP = 0x23; /* # */
var CHAR_PERCENT = 0x25; /* % */
var CHAR_AMPERSAND = 0x26; /* & */
var CHAR_SINGLE_QUOTE = 0x27; /* ' */
var CHAR_ASTERISK = 0x2A; /* * */
var CHAR_COMMA = 0x2C; /* , */
var CHAR_MINUS = 0x2D; /* - */
var CHAR_COLON = 0x3A; /* : */
var CHAR_GREATER_THAN = 0x3E; /* > */
var CHAR_QUESTION = 0x3F; /* ? */
var CHAR_COMMERCIAL_AT = 0x40; /* @ */
var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */
var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */
var CHAR_GRAVE_ACCENT = 0x60; /* ` */
var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */
var CHAR_VERTICAL_LINE = 0x7C; /* | */
var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */
var ESCAPE_SEQUENCES = {};
ESCAPE_SEQUENCES[0x00] = '\\0';
ESCAPE_SEQUENCES[0x07] = '\\a';
ESCAPE_SEQUENCES[0x08] = '\\b';
ESCAPE_SEQUENCES[0x09] = '\\t';
ESCAPE_SEQUENCES[0x0A] = '\\n';
ESCAPE_SEQUENCES[0x0B] = '\\v';
ESCAPE_SEQUENCES[0x0C] = '\\f';
ESCAPE_SEQUENCES[0x0D] = '\\r';
ESCAPE_SEQUENCES[0x1B] = '\\e';
ESCAPE_SEQUENCES[0x22] = '\\"';
ESCAPE_SEQUENCES[0x5C] = '\\\\';
ESCAPE_SEQUENCES[0x85] = '\\N';
ESCAPE_SEQUENCES[0xA0] = '\\_';
ESCAPE_SEQUENCES[0x2028] = '\\L';
ESCAPE_SEQUENCES[0x2029] = '\\P';
var DEPRECATED_BOOLEANS_SYNTAX = [
'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON',
'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF'
];
function compileStyleMap(schema, map) {
var result, keys, index, length, tag, style, type;
if (map === null) return {};
result = {};
keys = Object.keys(map);
for (index = 0, length = keys.length; index < length; index += 1) {
tag = keys[index];
style = String(map[tag]);
if (tag.slice(0, 2) === '!!') {
tag = 'tag:yaml.org,2002:' + tag.slice(2);
}
type = schema.compiledTypeMap[tag];
if (type && _hasOwnProperty.call(type.styleAliases, style)) {
style = type.styleAliases[style];
}
result[tag] = style;
}
return result;
}
function encodeHex(character) {
var string, handle, length;
string = character.toString(16).toUpperCase();
if (character <= 0xFF) {
handle = 'x';
length = 2;
} else if (character <= 0xFFFF) {
handle = 'u';
length = 4;
} else if (character <= 0xFFFFFFFF) {
handle = 'U';
length = 8;
} else {
throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF');
}
return '\\' + handle + common.repeat('0', length - string.length) + string;
}
function State(options) {
this.schema = options['schema'] || DEFAULT_FULL_SCHEMA;
this.indent = Math.max(1, (options['indent'] || 2));
this.skipInvalid = options['skipInvalid'] || false;
this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']);
this.styleMap = compileStyleMap(this.schema, options['styles'] || null);
this.sortKeys = options['sortKeys'] || false;
this.lineWidth = options['lineWidth'] || 80;
this.noRefs = options['noRefs'] || false;
this.noCompatMode = options['noCompatMode'] || false;
this.implicitTypes = this.schema.compiledImplicit;
this.explicitTypes = this.schema.compiledExplicit;
this.tag = null;
this.result = '';
this.duplicates = [];
this.usedDuplicates = null;
}
// Indents every line in a string. Empty lines (\n only) are not indented.
function indentString(string, spaces) {
var ind = common.repeat(' ', spaces),
position = 0,
next = -1,
result = '',
line,
length = string.length;
while (position < length) {
next = string.indexOf('\n', position);
if (next === -1) {
line = string.slice(position);
position = length;
} else {
line = string.slice(position, next + 1);
position = next + 1;
}
if (line.length && line !== '\n') result += ind;
result += line;
}
return result;
}
function generateNextLine(state, level) {
return '\n' + common.repeat(' ', state.indent * level);
}
function testImplicitResolving(state, str) {
var index, length, type;
for (index = 0, length = state.implicitTypes.length; index < length; index += 1) {
type = state.implicitTypes[index];
if (type.resolve(str)) {
return true;
}
}
return false;
}
// [33] s-white ::= s-space | s-tab
function isWhitespace(c) {
return c === CHAR_SPACE || c === CHAR_TAB;
}
// Returns true if the character can be printed without escaping.
// From YAML 1.2: "any allowed characters known to be non-printable
// should also be escaped. [However,] This isn’t mandatory"
// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029.
function isPrintable(c) {
return (0x00020 <= c && c <= 0x00007E)
|| ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029)
|| ((0x0E000 <= c && c <= 0x00FFFD) && c !== 0xFEFF /* BOM */)
|| (0x10000 <= c && c <= 0x10FFFF);
}
// Simplified test for values allowed after the first character in plain style.
function isPlainSafe(c) {
// Uses a subset of nb-char - c-flow-indicator - ":" - "#"
// where nb-char ::= c-printable - b-char - c-byte-order-mark.
return isPrintable(c) && c !== 0xFEFF
// - c-flow-indicator
&& c !== CHAR_COMMA
&& c !== CHAR_LEFT_SQUARE_BRACKET
&& c !== CHAR_RIGHT_SQUARE_BRACKET
&& c !== CHAR_LEFT_CURLY_BRACKET
&& c !== CHAR_RIGHT_CURLY_BRACKET
// - ":" - "#"
&& c !== CHAR_COLON
&& c !== CHAR_SHARP;
}
// Simplified test for values allowed as the first character in plain style.
function isPlainSafeFirst(c) {
// Uses a subset of ns-char - c-indicator
// where ns-char = nb-char - s-white.
return isPrintable(c) && c !== 0xFEFF
&& !isWhitespace(c) // - s-white
// - (c-indicator ::=
// “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}”
&& c !== CHAR_MINUS
&& c !== CHAR_QUESTION
&& c !== CHAR_COLON
&& c !== CHAR_COMMA
&& c !== CHAR_LEFT_SQUARE_BRACKET
&& c !== CHAR_RIGHT_SQUARE_BRACKET
&& c !== CHAR_LEFT_CURLY_BRACKET
&& c !== CHAR_RIGHT_CURLY_BRACKET
// | “#” | “&” | “*” | “!” | “|” | “>” | “'” | “"”
&& c !== CHAR_SHARP
&& c !== CHAR_AMPERSAND
&& c !== CHAR_ASTERISK
&& c !== CHAR_EXCLAMATION
&& c !== CHAR_VERTICAL_LINE
&& c !== CHAR_GREATER_THAN
&& c !== CHAR_SINGLE_QUOTE
&& c !== CHAR_DOUBLE_QUOTE
// | “%” | “@” | “`”)
&& c !== CHAR_PERCENT
&& c !== CHAR_COMMERCIAL_AT
&& c !== CHAR_GRAVE_ACCENT;
}
var STYLE_PLAIN = 1,
STYLE_SINGLE = 2,
STYLE_LITERAL = 3,
STYLE_FOLDED = 4,
STYLE_DOUBLE = 5;
// Determines which scalar styles are possible and returns the preferred style.
// lineWidth = -1 => no limit.
// Pre-conditions: str.length > 0.
// Post-conditions:
// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string.
// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1).
// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1).
function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) {
var i;
var char;
var hasLineBreak = false;
var hasFoldableLine = false; // only checked if shouldTrackWidth
var shouldTrackWidth = lineWidth !== -1;
var previousLineBreak = -1; // count the first line correctly
var plain = isPlainSafeFirst(string.charCodeAt(0))
&& !isWhitespace(string.charCodeAt(string.length - 1));
if (singleLineOnly) {
// Case: no block styles.
// Check for disallowed characters to rule out plain and single.
for (i = 0; i < string.length; i++) {
char = string.charCodeAt(i);
if (!isPrintable(char)) {
return STYLE_DOUBLE;
}
plain = plain && isPlainSafe(char);
}
} else {
// Case: block styles permitted.
for (i = 0; i < string.length; i++) {
char = string.charCodeAt(i);
if (char === CHAR_LINE_FEED) {
hasLineBreak = true;
// Check if any line can be folded.
if (shouldTrackWidth) {
hasFoldableLine = hasFoldableLine ||
// Foldable line = too long, and not more-indented.
(i - previousLineBreak - 1 > lineWidth &&
string[previousLineBreak + 1] !== ' ');
previousLineBreak = i;
}
} else if (!isPrintable(char)) {
return STYLE_DOUBLE;
}
plain = plain && isPlainSafe(char);
}
// in case the end is missing a \n
hasFoldableLine = hasFoldableLine || (shouldTrackWidth &&
(i - previousLineBreak - 1 > lineWidth &&
string[previousLineBreak + 1] !== ' '));
}
// Although every style can represent \n without escaping, prefer block styles
// for multiline, since they're more readable and they don't add empty lines.
// Also prefer folding a super-long line.
if (!hasLineBreak && !hasFoldableLine) {
// Strings interpretable as another type have to be quoted;
// e.g. the string 'true' vs. the boolean true.
return plain && !testAmbiguousType(string)
? STYLE_PLAIN : STYLE_SINGLE;
}
// Edge case: block indentation indicator can only have one digit.
if (string[0] === ' ' && indentPerLevel > 9) {
return STYLE_DOUBLE;
}
// At this point we know block styles are valid.
// Prefer literal style unless we want to fold.
return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;
}
// Note: line breaking/folding is implemented for only the folded style.
// NB. We drop the last trailing newline (if any) of a returned block scalar
// since the dumper adds its own newline. This always works:
// • No ending newline => unaffected; already using strip "-" chomping.
// • Ending newline => removed then restored.
// Importantly, this keeps the "+" chomp indicator from gaining an extra line.
function writeScalar(state, string, level, iskey) {
state.dump = (function () {
if (string.length === 0) {
return "''";
}
if (!state.noCompatMode &&
DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1) {
return "'" + string + "'";
}
var indent = state.indent * Math.max(1, level); // no 0-indent scalars
// As indentation gets deeper, let the width decrease monotonically
// to the lower bound min(state.lineWidth, 40).
// Note that this implies
// state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound.
// state.lineWidth > 40 + state.indent: width decreases until the lower bound.
// This behaves better than a constant minimum width which disallows narrower options,
// or an indent threshold which causes the width to suddenly increase.
var lineWidth = state.lineWidth === -1
? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent);
// Without knowing if keys are implicit/explicit, assume implicit for safety.
var singleLineOnly = iskey
// No block styles in flow mode.
|| (state.flowLevel > -1 && level >= state.flowLevel);
function testAmbiguity(string) {
return testImplicitResolving(state, string);
}
switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity)) {
case STYLE_PLAIN:
return string;
case STYLE_SINGLE:
return "'" + string.replace(/'/g, "''") + "'";
case STYLE_LITERAL:
return '|' + blockHeader(string, state.indent)
+ dropEndingNewline(indentString(string, indent));
case STYLE_FOLDED:
return '>' + blockHeader(string, state.indent)
+ dropEndingNewline(indentString(foldString(string, lineWidth), indent));
case STYLE_DOUBLE:
return '"' + escapeString(string, lineWidth) + '"';
default:
throw new YAMLException('impossible error: invalid scalar style');
}
}());
}
// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9.
function blockHeader(string, indentPerLevel) {
var indentIndicator = (string[0] === ' ') ? String(indentPerLevel) : '';
// note the special case: the string '\n' counts as a "trailing" empty line.
var clip = string[string.length - 1] === '\n';
var keep = clip && (string[string.length - 2] === '\n' || string === '\n');
var chomp = keep ? '+' : (clip ? '' : '-');
return indentIndicator + chomp + '\n';
}
// (See the note for writeScalar.)
function dropEndingNewline(string) {
return string[string.length - 1] === '\n' ? string.slice(0, -1) : string;
}
// Note: a long line without a suitable break point will exceed the width limit.
// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0.
function foldString(string, width) {
// In folded style, $k$ consecutive newlines output as $k+1$ newlines—
// unless they're before or after a more-indented line, or at the very
// beginning or end, in which case $k$ maps to $k$.
// Therefore, parse each chunk as newline(s) followed by a content line.
var lineRe = /(\n+)([^\n]*)/g;
// first line (possibly an empty line)
var result = (function () {
var nextLF = string.indexOf('\n');
nextLF = nextLF !== -1 ? nextLF : string.length;
lineRe.lastIndex = nextLF;
return foldLine(string.slice(0, nextLF), width);
}());
// If we haven't reached the first content line yet, don't add an extra \n.
var prevMoreIndented = string[0] === '\n' || string[0] === ' ';
var moreIndented;
// rest of the lines
var match;
while ((match = lineRe.exec(string))) {
var prefix = match[1], line = match[2];
moreIndented = (line[0] === ' ');
result += prefix
+ (!prevMoreIndented && !moreIndented && line !== ''
? '\n' : '')
+ foldLine(line, width);
prevMoreIndented = moreIndented;
}
return result;
}
// Greedy line breaking.
// Picks the longest line under the limit each time,
// otherwise settles for the shortest line over the limit.
// NB. More-indented lines *cannot* be folded, as that would add an extra \n.
function foldLine(line, width) {
if (line === '' || line[0] === ' ') return line;
// Since a more-indented line adds a \n, breaks can't be followed by a space.
var breakRe = / [^ ]/g; // note: the match index will always be <= length-2.
var match;
// start is an inclusive index. end, curr, and next are exclusive.
var start = 0, end, curr = 0, next = 0;
var result = '';
// Invariants: 0 <= start <= length-1.
// 0 <= curr <= next <= max(0, length-2). curr - start <= width.
// Inside the loop:
// A match implies length >= 2, so curr and next are <= length-2.
while ((match = breakRe.exec(line))) {
next = match.index;
// maintain invariant: curr - start <= width
if (next - start > width) {
end = (curr > start) ? curr : next; // derive end <= length-2
result += '\n' + line.slice(start, end);
// skip the space that was output as \n
start = end + 1; // derive start <= length-1
}
curr = next;
}
// By the invariants, start <= length-1, so there is something left over.
// It is either the whole string or a part starting from non-whitespace.
result += '\n';
// Insert a break if the remainder is too long and there is a break available.
if (line.length - start > width && curr > start) {
result += line.slice(start, curr) + '\n' + line.slice(curr + 1);
} else {
result += line.slice(start);
}
return result.slice(1); // drop extra \n joiner
}
// Escapes a double-quoted string.
function escapeString(string) {
var result = '';
var char;
var escapeSeq;
for (var i = 0; i < string.length; i++) {
char = string.charCodeAt(i);
escapeSeq = ESCAPE_SEQUENCES[char];
result += !escapeSeq && isPrintable(char)
? string[i]
: escapeSeq || encodeHex(char);
}
return result;
}
function writeFlowSequence(state, level, object) {
var _result = '',
_tag = state.tag,
index,
length;
for (index = 0, length = object.length; index < length; index += 1) {
// Write only valid elements.
if (writeNode(state, level, object[index], false, false)) {
if (index !== 0) _result += ', ';
_result += state.dump;
}
}
state.tag = _tag;
state.dump = '[' + _result + ']';
}
function writeBlockSequence(state, level, object, compact) {
var _result = '',
_tag = state.tag,
index,
length;
for (index = 0, length = object.length; index < length; index += 1) {
// Write only valid elements.
if (writeNode(state, level + 1, object[index], true, true)) {
if (!compact || index !== 0) {
_result += generateNextLine(state, level);
}
_result += '- ' + state.dump;
}
}
state.tag = _tag;
state.dump = _result || '[]'; // Empty sequence if no valid values.
}
function writeFlowMapping(state, level, object) {
var _result = '',
_tag = state.tag,
objectKeyList = Object.keys(object),
index,
length,
objectKey,
objectValue,
pairBuffer;
for (index = 0, length = objectKeyList.length; index < length; index += 1) {
pairBuffer = '';
if (index !== 0) pairBuffer += ', ';
objectKey = objectKeyList[index];
objectValue = object[objectKey];
if (!writeNode(state, level, objectKey, false, false)) {
continue; // Skip this pair because of invalid key;
}
if (state.dump.length > 1024) pairBuffer += '? ';
pairBuffer += state.dump + ': ';
if (!writeNode(state, level, objectValue, false, false)) {
continue; // Skip this pair because of invalid value.
}
pairBuffer += state.dump;
// Both key and value are valid.
_result += pairBuffer;
}
state.tag = _tag;
state.dump = '{' + _result + '}';
}
function writeBlockMapping(state, level, object, compact) {
var _result = '',
_tag = state.tag,
objectKeyList = Object.keys(object),
index,
length,
objectKey,
objectValue,
explicitPair,
pairBuffer;
// Allow sorting keys so that the output file is deterministic
if (state.sortKeys === true) {
// Default sorting
objectKeyList.sort();
} else if (typeof state.sortKeys === 'function') {
// Custom sort function
objectKeyList.sort(state.sortKeys);
} else if (state.sortKeys) {
// Something is wrong
throw new YAMLException('sortKeys must be a boolean or a function');
}
for (index = 0, length = objectKeyList.length; index < length; index += 1) {
pairBuffer = '';
if (!compact || index !== 0) {
pairBuffer += generateNextLine(state, level);
}
objectKey = objectKeyList[index];
objectValue = object[objectKey];
if (!writeNode(state, level + 1, objectKey, true, true, true)) {
continue; // Skip this pair because of invalid key.
}
explicitPair = (state.tag !== null && state.tag !== '?') ||
(state.dump && state.dump.length > 1024);
if (explicitPair) {
if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
pairBuffer += '?';
} else {
pairBuffer += '? ';
}
}
pairBuffer += state.dump;
if (explicitPair) {
pairBuffer += generateNextLine(state, level);
}
if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {
continue; // Skip this pair because of invalid value.
}
if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
pairBuffer += ':';
} else {
pairBuffer += ': ';
}
pairBuffer += state.dump;
// Both key and value are valid.
_result += pairBuffer;
}
state.tag = _tag;
state.dump = _result || '{}'; // Empty mapping if no valid pairs.
}
function detectType(state, object, explicit) {
var _result, typeList, index, length, type, style;
typeList = explicit ? state.explicitTypes : state.implicitTypes;
for (index = 0, length = typeList.length; index < length; index += 1) {
type = typeList[index];
if ((type.instanceOf || type.predicate) &&
(!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) &&
(!type.predicate || type.predicate(object))) {
state.tag = explicit ? type.tag : '?';
if (type.represent) {
style = state.styleMap[type.tag] || type.defaultStyle;
if (_toString.call(type.represent) === '[object Function]') {
_result = type.represent(object, style);
} else if (_hasOwnProperty.call(type.represent, style)) {
_result = type.represent[style](object, style);
} else {
throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style');
}
state.dump = _result;
}
return true;
}
}
return false;
}
// Serializes `object` and writes it to global `result`.
// Returns true on success, or false on invalid object.
//
function writeNode(state, level, object, block, compact, iskey) {
state.tag = null;
state.dump = object;
if (!detectType(state, object, false)) {
detectType(state, object, true);
}
var type = _toString.call(state.dump);
if (block) {
block = (state.flowLevel < 0 || state.flowLevel > level);
}
var objectOrArray = type === '[object Object]' || type === '[object Array]',
duplicateIndex,
duplicate;
if (objectOrArray) {
duplicateIndex = state.duplicates.indexOf(object);
duplicate = duplicateIndex !== -1;
}
if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) {
compact = false;
}
if (duplicate && state.usedDuplicates[duplicateIndex]) {
state.dump = '*ref_' + duplicateIndex;
} else {
if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {
state.usedDuplicates[duplicateIndex] = true;
}
if (type === '[object Object]') {
if (block && (Object.keys(state.dump).length !== 0)) {
writeBlockMapping(state, level, state.dump, compact);
if (duplicate) {
state.dump = '&ref_' + duplicateIndex + state.dump;
}
} else {
writeFlowMapping(state, level, state.dump);
if (duplicate) {
state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
}
}
} else if (type === '[object Array]') {
if (block && (state.dump.length !== 0)) {
writeBlockSequence(state, level, state.dump, compact);
if (duplicate) {
state.dump = '&ref_' + duplicateIndex + state.dump;
}
} else {
writeFlowSequence(state, level, state.dump);
if (duplicate) {
state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
}
}
} else if (type === '[object String]') {
if (state.tag !== '?') {
writeScalar(state, state.dump, level, iskey);
}
} else {
if (state.skipInvalid) return false;
throw new YAMLException('unacceptable kind of an object to dump ' + type);
}
if (state.tag !== null && state.tag !== '?') {
state.dump = '!<' + state.tag + '> ' + state.dump;
}
}
return true;
}
function getDuplicateReferences(object, state) {
var objects = [],
duplicatesIndexes = [],
index,
length;
inspectNode(object, objects, duplicatesIndexes);
for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) {
state.duplicates.push(objects[duplicatesIndexes[index]]);
}
state.usedDuplicates = new Array(length);
}
function inspectNode(object, objects, duplicatesIndexes) {
var objectKeyList,
index,
length;
if (object !== null && typeof object === 'object') {
index = objects.indexOf(object);
if (index !== -1) {
if (duplicatesIndexes.indexOf(index) === -1) {
duplicatesIndexes.push(index);
}
} else {
objects.push(object);
if (Array.isArray(object)) {
for (index = 0, length = object.length; index < length; index += 1) {
inspectNode(object[index], objects, duplicatesIndexes);
}
} else {
objectKeyList = Object.keys(object);
for (index = 0, length = objectKeyList.length; index < length; index += 1) {
inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes);
}
}
}
}
}
function dump(input, options) {
options = options || {};
var state = new State(options);
if (!state.noRefs) getDuplicateReferences(input, state);
if (writeNode(state, 0, input, true, true)) return state.dump + '\n';
return '';
}
function safeDump(input, options) {
return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options));
}
module.exports.dump = dump;
module.exports.safeDump = safeDump;
},{"./common":2,"./exception":4,"./schema/default_full":9,"./schema/default_safe":10}],4:[function(require,module,exports){
// YAML error class. http://stackoverflow.com/questions/8458984
//
'use strict';
function YAMLException(reason, mark) {
// Super constructor
Error.call(this);
// Include stack trace in error object
if (Error.captureStackTrace) {
// Chrome and NodeJS
Error.captureStackTrace(this, this.constructor);
} else {
// FF, IE 10+ and Safari 6+. Fallback for others
this.stack = (new Error()).stack || '';
}
this.name = 'YAMLException';
this.reason = reason;
this.mark = mark;
this.message = (this.reason || '(unknown reason)') + (this.mark ? ' ' + this.mark.toString() : '');
}
// Inherit from Error
YAMLException.prototype = Object.create(Error.prototype);
YAMLException.prototype.constructor = YAMLException;
YAMLException.prototype.toString = function toString(compact) {
var result = this.name + ': ';
result += this.reason || '(unknown reason)';
if (!compact && this.mark) {
result += ' ' + this.mark.toString();
}
return result;
};
module.exports = YAMLException;
},{}],5:[function(require,module,exports){
'use strict';
/*eslint-disable max-len,no-use-before-define*/
var common = require('./common');
var YAMLException = require('./exception');
var Mark = require('./mark');
var DEFAULT_SAFE_SCHEMA = require('./schema/default_safe');
var DEFAULT_FULL_SCHEMA = require('./schema/default_full');
var _hasOwnProperty = Object.prototype.hasOwnProperty;
var CONTEXT_FLOW_IN = 1;
var CONTEXT_FLOW_OUT = 2;
var CONTEXT_BLOCK_IN = 3;
var CONTEXT_BLOCK_OUT = 4;
var CHOMPING_CLIP = 1;
var CHOMPING_STRIP = 2;
var CHOMPING_KEEP = 3;
var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/;
var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/;
var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i;
var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;
function is_EOL(c) {
return (c === 0x0A/* LF */) || (c === 0x0D/* CR */);
}
function is_WHITE_SPACE(c) {
return (c === 0x09/* Tab */) || (c === 0x20/* Space */);
}
function is_WS_OR_EOL(c) {
return (c === 0x09/* Tab */) ||
(c === 0x20/* Space */) ||
(c === 0x0A/* LF */) ||
(c === 0x0D/* CR */);
}
function is_FLOW_INDICATOR(c) {
return c === 0x2C/* , */ ||
c === 0x5B/* [ */ ||
c === 0x5D/* ] */ ||
c === 0x7B/* { */ ||
c === 0x7D/* } */;
}
function fromHexCode(c) {
var lc;
if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) {
return c - 0x30;
}
/*eslint-disable no-bitwise*/
lc = c | 0x20;
if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) {
return lc - 0x61 + 10;
}
return -1;
}
function escapedHexLen(c) {
if (c === 0x78/* x */) { return 2; }
if (c === 0x75/* u */) { return 4; }
if (c === 0x55/* U */) { return 8; }
return 0;
}
function fromDecimalCode(c) {
if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) {
return c - 0x30;
}
return -1;
}
function simpleEscapeSequence(c) {
return (c === 0x30/* 0 */) ? '\x00' :
(c === 0x61/* a */) ? '\x07' :
(c === 0x62/* b */) ? '\x08' :
(c === 0x74/* t */) ? '\x09' :
(c === 0x09/* Tab */) ? '\x09' :
(c === 0x6E/* n */) ? '\x0A' :
(c === 0x76/* v */) ? '\x0B' :
(c === 0x66/* f */) ? '\x0C' :
(c === 0x72/* r */) ? '\x0D' :
(c === 0x65/* e */) ? '\x1B' :
(c === 0x20/* Space */) ? ' ' :
(c === 0x22/* " */) ? '\x22' :
(c === 0x2F/* / */) ? '/' :
(c === 0x5C/* \ */) ? '\x5C' :
(c === 0x4E/* N */) ? '\x85' :
(c === 0x5F/* _ */) ? '\xA0' :
(c === 0x4C/* L */) ? '\u2028' :
(c === 0x50/* P */) ? '\u2029' : '';
}
function charFromCodepoint(c) {
if (c <= 0xFFFF) {
return String.fromCharCode(c);
}
// Encode UTF-16 surrogate pair
// https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF
return String.fromCharCode(((c - 0x010000) >> 10) + 0xD800,
((c - 0x010000) & 0x03FF) + 0xDC00);
}
var simpleEscapeCheck = new Array(256); // integer, for fast access
var simpleEscapeMap = new Array(256);
for (var i = 0; i < 256; i++) {
simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0;
simpleEscapeMap[i] = simpleEscapeSequence(i);
}
function State(input, options) {
this.input = input;
this.filename = options['filename'] || null;
this.schema = options['schema'] || DEFAULT_FULL_SCHEMA;
this.onWarning = options['onWarning'] || null;
this.legacy = options['legacy'] || false;
this.json = options['json'] || false;
this.listener = options['listener'] || null;
this.implicitTypes = this.schema.compiledImplicit;
this.typeMap = this.schema.compiledTypeMap;
this.length = input.length;
this.position = 0;
this.line = 0;
this.lineStart = 0;
this.lineIndent = 0;
this.documents = [];
/*
this.version;
this.checkLineBreaks;
this.tagMap;
this.anchorMap;
this.tag;
this.anchor;
this.kind;
this.result;*/
}
function generateError(state, message) {
return new YAMLException(
message,
new Mark(state.filename, state.input, state.position, state.line, (state.position - state.lineStart)));
}
function throwError(state, message) {
throw generateError(state, message);
}
function throwWarning(state, message) {
if (state.onWarning) {
state.onWarning.call(null, generateError(state, message));
}
}
var directiveHandlers = {
YAML: function handleYamlDirective(state, name, args) {
var match, major, minor;
if (state.version !== null) {
throwError(state, 'duplication of %YAML directive');
}
if (args.length !== 1) {
throwError(state, 'YAML directive accepts exactly one argument');
}
match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]);
if (match === null) {
throwError(state, 'ill-formed argument of the YAML directive');
}
major = parseInt(match[1], 10);
minor = parseInt(match[2], 10);
if (major !== 1) {
throwError(state, 'unacceptable YAML version of the document');
}
state.version = args[0];
state.checkLineBreaks = (minor < 2);
if (minor !== 1 && minor !== 2) {
throwWarning(state, 'unsupported YAML version of the document');
}
},
TAG: function handleTagDirective(state, name, args) {
var handle, prefix;
if (args.length !== 2) {
throwError(state, 'TAG directive accepts exactly two arguments');
}
handle = args[0];
prefix = args[1];
if (!PATTERN_TAG_HANDLE.test(handle)) {
throwError(state, 'ill-formed tag handle (first argument) of the TAG directive');
}
if (_hasOwnProperty.call(state.tagMap, handle)) {
throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle');
}
if (!PATTERN_TAG_URI.test(prefix)) {
throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive');
}
state.tagMap[handle] = prefix;
}
};
function captureSegment(state, start, end, checkJson) {
var _position, _length, _character, _result;
if (start < end) {
_result = state.input.slice(start, end);
if (checkJson) {
for (_position = 0, _length = _result.length;
_position < _length;
_position += 1) {
_character = _result.charCodeAt(_position);
if (!(_character === 0x09 ||
(0x20 <= _character && _character <= 0x10FFFF))) {
throwError(state, 'expected valid JSON character');
}
}
} else if (PATTERN_NON_PRINTABLE.test(_result)) {
throwError(state, 'the stream contains non-printable characters');
}
state.result += _result;
}
}
function mergeMappings(state, destination, source, overridableKeys) {
var sourceKeys, key, index, quantity;
if (!common.isObject(source)) {
throwError(state, 'cannot merge mappings; the provided source object is unacceptable');
}
sourceKeys = Object.keys(source);
for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) {
key = sourceKeys[index];
if (!_hasOwnProperty.call(destination, key)) {
destination[key] = source[key];
overridableKeys[key] = true;
}
}
}
function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode) {
var index, quantity;
keyNode = String(keyNode);
if (_result === null) {
_result = {};
}
if (keyTag === 'tag:yaml.org,2002:merge') {
if (Array.isArray(valueNode)) {
for (index = 0, quantity = valueNode.length; index < quantity; index += 1) {
mergeMappings(state, _result, valueNode[index], overridableKeys);
}
} else {
mergeMappings(state, _result, valueNode, overridableKeys);
}
} else {
if (!state.json &&
!_hasOwnProperty.call(overridableKeys, keyNode) &&
_hasOwnProperty.call(_result, keyNode)) {
throwError(state, 'duplicated mapping key');
}
_result[keyNode] = valueNode;
delete overridableKeys[keyNode];
}
return _result;
}
function readLineBreak(state) {
var ch;
ch = state.input.charCodeAt(state.position);
if (ch === 0x0A/* LF */) {
state.position++;
} else if (ch === 0x0D/* CR */) {
state.position++;
if (state.input.charCodeAt(state.position) === 0x0A/* LF */) {
state.position++;
}
} else {
throwError(state, 'a line break is expected');
}
state.line += 1;
state.lineStart = state.position;
}
function skipSeparationSpace(state, allowComments, checkIndent) {
var lineBreaks = 0,
ch = state.input.charCodeAt(state.position);
while (ch !== 0) {
while (is_WHITE_SPACE(ch)) {
ch = state.input.charCodeAt(++state.position);
}
if (allowComments && ch === 0x23/* # */) {
do {
ch = state.input.charCodeAt(++state.position);
} while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0);
}
if (is_EOL(ch)) {
readLineBreak(state);
ch = state.input.charCodeAt(state.position);
lineBreaks++;
state.lineIndent = 0;
while (ch === 0x20/* Space */) {
state.lineIndent++;
ch = state.input.charCodeAt(++state.position);
}
} else {
break;
}
}
if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) {
throwWarning(state, 'deficient indentation');
}
return lineBreaks;
}
function testDocumentSeparator(state) {
var _position = state.position,
ch;
ch = state.input.charCodeAt(_position);
// Condition state.position === state.lineStart is tested
// in parent on each call, for efficiency. No needs to test here again.
if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) &&
ch === state.input.charCodeAt(_position + 1) &&
ch === state.input.charCodeAt(_position + 2)) {
_position += 3;
ch = state.input.charCodeAt(_position);
if (ch === 0 || is_WS_OR_EOL(ch)) {
return true;
}
}
return false;
}
function writeFoldedLines(state, count) {
if (count === 1) {
state.result += ' ';
} else if (count > 1) {
state.result += common.repeat('\n', count - 1);
}
}
function readPlainScalar(state, nodeIndent, withinFlowCollection) {
var preceding,
following,
captureStart,
captureEnd,
hasPendingContent,
_line,
_lineStart,
_lineIndent,
_kind = state.kind,
_result = state.result,
ch;
ch = state.input.charCodeAt(state.position);
if (is_WS_OR_EOL(ch) ||
is_FLOW_INDICATOR(ch) ||
ch === 0x23/* # */ ||
ch === 0x26/* & */ ||
ch === 0x2A/* * */ ||
ch === 0x21/* ! */ ||
ch === 0x7C/* | */ ||
ch === 0x3E/* > */ ||
ch === 0x27/* ' */ ||
ch === 0x22/* " */ ||
ch === 0x25/* % */ ||
ch === 0x40/* @ */ ||
ch === 0x60/* ` */) {
return false;
}
if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) {
following = state.input.charCodeAt(state.position + 1);
if (is_WS_OR_EOL(following) ||
withinFlowCollection && is_FLOW_INDICATOR(following)) {
return false;
}
}
state.kind = 'scalar';
state.result = '';
captureStart = captureEnd = state.position;
hasPendingContent = false;
while (ch !== 0) {
if (ch === 0x3A/* : */) {
following = state.input.charCodeAt(state.position + 1);
if (is_WS_OR_EOL(following) ||
withinFlowCollection && is_FLOW_INDICATOR(following)) {
break;
}
} else if (ch === 0x23/* # */) {
preceding = state.input.charCodeAt(state.position - 1);
if (is_WS_OR_EOL(preceding)) {
break;
}
} else if ((state.position === state.lineStart && testDocumentSeparator(state)) ||
withinFlowCollection && is_FLOW_INDICATOR(ch)) {
break;
} else if (is_EOL(ch)) {
_line = state.line;
_lineStart = state.lineStart;
_lineIndent = state.lineIndent;
skipSeparationSpace(state, false, -1);
if (state.lineIndent >= nodeIndent) {
hasPendingContent = true;
ch = state.input.charCodeAt(state.position);
continue;
} else {
state.position = captureEnd;
state.line = _line;
state.lineStart = _lineStart;
state.lineIndent = _lineIndent;
break;
}
}
if (hasPendingContent) {
captureSegment(state, captureStart, captureEnd, false);
writeFoldedLines(state, state.line - _line);
captureStart = captureEnd = state.position;
hasPendingContent = false;
}
if (!is_WHITE_SPACE(ch)) {
captureEnd = state.position + 1;
}
ch = state.input.charCodeAt(++state.position);
}
captureSegment(state, captureStart, captureEnd, false);
if (state.result) {
return true;
}
state.kind = _kind;
state.result = _result;
return false;
}
function readSingleQuotedScalar(state, nodeIndent) {
var ch,
captureStart, captureEnd;
ch = state.input.charCodeAt(state.position);
if (ch !== 0x27/* ' */) {
return false;
}
state.kind = 'scalar';
state.result = '';
state.position++;
captureStart = captureEnd = state.position;
while ((ch = state.input.charCodeAt(state.position)) !== 0) {
if (ch === 0x27/* ' */) {
captureSegment(state, captureStart, state.position, true);
ch = state.input.charCodeAt(++state.position);
if (ch === 0x27/* ' */) {
captureStart = captureEnd = state.position;
state.position++;
} else {
return true;
}
} else if (is_EOL(ch)) {
captureSegment(state, captureStart, captureEnd, true);
writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
captureStart = captureEnd = state.position;
} else if (state.position === state.lineStart && testDocumentSeparator(state)) {
throwError(state, 'unexpected end of the document within a single quoted scalar');
} else {
state.position++;
captureEnd = state.position;
}
}
throwError(state, 'unexpected end of the stream within a single quoted scalar');
}
function readDoubleQuotedScalar(state, nodeIndent) {
var captureStart,
captureEnd,
hexLength,
hexResult,
tmp,
ch;
ch = state.input.charCodeAt(state.position);
if (ch !== 0x22/* " */) {
return false;
}
state.kind = 'scalar';
state.result = '';
state.position++;
captureStart = captureEnd = state.position;
while ((ch = state.input.charCodeAt(state.position)) !== 0) {
if (ch === 0x22/* " */) {
captureSegment(state, captureStart, state.position, true);
state.position++;
return true;
} else if (ch === 0x5C/* \ */) {
captureSegment(state, captureStart, state.position, true);
ch = state.input.charCodeAt(++state.position);
if (is_EOL(ch)) {
skipSeparationSpace(state, false, nodeIndent);
// TODO: rework to inline fn with no type cast?
} else if (ch < 256 && simpleEscapeCheck[ch]) {
state.result += simpleEscapeMap[ch];
state.position++;
} else if ((tmp = escapedHexLen(ch)) > 0) {
hexLength = tmp;
hexResult = 0;
for (; hexLength > 0; hexLength--) {
ch = state.input.charCodeAt(++state.position);
if ((tmp = fromHexCode(ch)) >= 0) {
hexResult = (hexResult << 4) + tmp;
} else {
throwError(state, 'expected hexadecimal character');
}
}
state.result += charFromCodepoint(hexResult);
state.position++;
} else {
throwError(state, 'unknown escape sequence');
}
captureStart = captureEnd = state.position;
} else if (is_EOL(ch)) {
captureSegment(state, captureStart, captureEnd, true);
writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
captureStart = captureEnd = state.position;
} else if (state.position === state.lineStart && testDocumentSeparator(state)) {
throwError(state, 'unexpected end of the document within a double quoted scalar');
} else {
state.position++;
captureEnd = state.position;
}
}
throwError(state, 'unexpected end of the stream within a double quoted scalar');
}
function readFlowCollection(state, nodeIndent) {
var readNext = true,
_line,
_tag = state.tag,
_result,
_anchor = state.anchor,
following,
terminator,
isPair,
isExplicitPair,
isMapping,
overridableKeys = {},
keyNode,
keyTag,
valueNode,
ch;
ch = state.input.charCodeAt(state.position);
if (ch === 0x5B/* [ */) {
terminator = 0x5D;/* ] */
isMapping = false;
_result = [];
} else if (ch === 0x7B/* { */) {
terminator = 0x7D;/* } */
isMapping = true;
_result = {};
} else {
return false;
}
if (state.anchor !== null) {
state.anchorMap[state.anchor] = _result;
}
ch = state.input.charCodeAt(++state.position);
while (ch !== 0) {
skipSeparationSpace(state, true, nodeIndent);
ch = state.input.charCodeAt(state.position);
if (ch === terminator) {
state.position++;
state.tag = _tag;
state.anchor = _anchor;
state.kind = isMapping ? 'mapping' : 'sequence';
state.result = _result;
return true;
} else if (!readNext) {
throwError(state, 'missed comma between flow collection entries');
}
keyTag = keyNode = valueNode = null;
isPair = isExplicitPair = false;
if (ch === 0x3F/* ? */) {
following = state.input.charCodeAt(state.position + 1);
if (is_WS_OR_EOL(following)) {
isPair = isExplicitPair = true;
state.position++;
skipSeparationSpace(state, true, nodeIndent);
}
}
_line = state.line;
composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
keyTag = state.tag;
keyNode = state.result;
skipSeparationSpace(state, true, nodeIndent);
ch = state.input.charCodeAt(state.position);
if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) {
isPair = true;
ch = state.input.charCodeAt(++state.position);
skipSeparationSpace(state, true, nodeIndent);
composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
valueNode = state.result;
}
if (isMapping) {
storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode);
} else if (isPair) {
_result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode));
} else {
_result.push(keyNode);
}
skipSeparationSpace(state, true, nodeIndent);
ch = state.input.charCodeAt(state.position);
if (ch === 0x2C/* , */) {
readNext = true;
ch = state.input.charCodeAt(++state.position);
} else {
readNext = false;
}
}
throwError(state, 'unexpected end of the stream within a flow collection');
}
function readBlockScalar(state, nodeIndent) {
var captureStart,
folding,
chomping = CHOMPING_CLIP,
didReadContent = false,
detectedIndent = false,
textIndent = nodeIndent,
emptyLines = 0,
atMoreIndented = false,
tmp,
ch;
ch = state.input.charCodeAt(state.position);
if (ch === 0x7C/* | */) {
folding = false;
} else if (ch === 0x3E/* > */) {
folding = true;
} else {
return false;
}
state.kind = 'scalar';
state.result = '';
while (ch !== 0) {
ch = state.input.charCodeAt(++state.position);
if (ch === 0x2B/* + */ || ch === 0x2D/* - */) {
if (CHOMPING_CLIP === chomping) {
chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP;
} else {
throwError(state, 'repeat of a chomping mode identifier');
}
} else if ((tmp = fromDecimalCode(ch)) >= 0) {
if (tmp === 0) {
throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one');
} else if (!detectedIndent) {
textIndent = nodeIndent + tmp - 1;
detectedIndent = true;
} else {
throwError(state, 'repeat of an indentation width identifier');
}
} else {
break;
}
}
if (is_WHITE_SPACE(ch)) {
do { ch = state.input.charCodeAt(++state.position); }
while (is_WHITE_SPACE(ch));
if (ch === 0x23/* # */) {
do { ch = state.input.charCodeAt(++state.position); }
while (!is_EOL(ch) && (ch !== 0));
}
}
while (ch !== 0) {
readLineBreak(state);
state.lineIndent = 0;
ch = state.input.charCodeAt(state.position);
while ((!detectedIndent || state.lineIndent < textIndent) &&
(ch === 0x20/* Space */)) {
state.lineIndent++;
ch = state.input.charCodeAt(++state.position);
}
if (!detectedIndent && state.lineIndent > textIndent) {
textIndent = state.lineIndent;
}
if (is_EOL(ch)) {
emptyLines++;
continue;
}
// End of the scalar.
if (state.lineIndent < textIndent) {
// Perform the chomping.
if (chomping === CHOMPING_KEEP) {
state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
} else if (chomping === CHOMPING_CLIP) {
if (didReadContent) { // i.e. only if the scalar is not empty.
state.result += '\n';
}
}
// Break this `while` cycle and go to the funciton's epilogue.
break;
}
// Folded style: use fancy rules to handle line breaks.
if (folding) {
// Lines starting with white space characters (more-indented lines) are not folded.
if (is_WHITE_SPACE(ch)) {
atMoreIndented = true;
// except for the first content line (cf. Example 8.1)
state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
// End of more-indented block.
} else if (atMoreIndented) {
atMoreIndented = false;
state.result += common.repeat('\n', emptyLines + 1);
// Just one line break - perceive as the same line.
} else if (emptyLines === 0) {
if (didReadContent) { // i.e. only if we have already read some scalar content.
state.result += ' ';
}
// Several line breaks - perceive as different lines.
} else {
state.result += common.repeat('\n', emptyLines);
}
// Literal style: just add exact number of line breaks between content lines.
} else {
// Keep all line breaks except the header line break.
state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
}
didReadContent = true;
detectedIndent = true;
emptyLines = 0;
captureStart = state.position;
while (!is_EOL(ch) && (ch !== 0)) {
ch = state.input.charCodeAt(++state.position);
}
captureSegment(state, captureStart, state.position, false);
}
return true;
}
function readBlockSequence(state, nodeIndent) {
var _line,
_tag = state.tag,
_anchor = state.anchor,
_result = [],
following,
detected = false,
ch;
if (state.anchor !== null) {
state.anchorMap[state.anchor] = _result;
}
ch = state.input.charCodeAt(state.position);
while (ch !== 0) {
if (ch !== 0x2D/* - */) {
break;
}
following = state.input.charCodeAt(state.position + 1);
if (!is_WS_OR_EOL(following)) {
break;
}
detected = true;
state.position++;
if (skipSeparationSpace(state, true, -1)) {
if (state.lineIndent <= nodeIndent) {
_result.push(null);
ch = state.input.charCodeAt(state.position);
continue;
}
}
_line = state.line;
composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true);
_result.push(state.result);
skipSeparationSpace(state, true, -1);
ch = state.input.charCodeAt(state.position);
if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) {
throwError(state, 'bad indentation of a sequence entry');
} else if (state.lineIndent < nodeIndent) {
break;
}
}
if (detected) {
state.tag = _tag;
state.anchor = _anchor;
state.kind = 'sequence';
state.result = _result;
return true;
}
return false;
}
function readBlockMapping(state, nodeIndent, flowIndent) {
var following,
allowCompact,
_line,
_tag = state.tag,
_anchor = state.anchor,
_result = {},
overridableKeys = {},
keyTag = null,
keyNode = null,
valueNode = null,
atExplicitKey = false,
detected = false,
ch;
if (state.anchor !== null) {
state.anchorMap[state.anchor] = _result;
}
ch = state.input.charCodeAt(state.position);
while (ch !== 0) {
following = state.input.charCodeAt(state.position + 1);
_line = state.line; // Save the current line.
//
// Explicit notation case. There are two separate blocks:
// first for the key (denoted by "?") and second for the value (denoted by ":")
//
if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) {
if (ch === 0x3F/* ? */) {
if (atExplicitKey) {
storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);
keyTag = keyNode = valueNode = null;
}
detected = true;
atExplicitKey = true;
allowCompact = true;
} else if (atExplicitKey) {
// i.e. 0x3A/* : */ === character after the explicit key.
atExplicitKey = false;
allowCompact = true;
} else {
throwError(state, 'incomplete explicit mapping pair; a key node is missed');
}
state.position += 1;
ch = following;
//
// Implicit notation case. Flow-style node as the key first, then ":", and the value.
//
} else if (composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) {
if (state.line === _line) {
ch = state.input.charCodeAt(state.position);
while (is_WHITE_SPACE(ch)) {
ch = state.input.charCodeAt(++state.position);
}
if (ch === 0x3A/* : */) {
ch = state.input.charCodeAt(++state.position);
if (!is_WS_OR_EOL(ch)) {
throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping');
}
if (atExplicitKey) {
storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);
keyTag = keyNode = valueNode = null;
}
detected = true;
atExplicitKey = false;
allowCompact = false;
keyTag = state.tag;
keyNode = state.result;
} else if (detected) {
throwError(state, 'can not read an implicit mapping pair; a colon is missed');
} else {
state.tag = _tag;
state.anchor = _anchor;
return true; // Keep the result of `composeNode`.
}
} else if (detected) {
throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key');
} else {
state.tag = _tag;
state.anchor = _anchor;
return true; // Keep the result of `composeNode`.
}
} else {
break; // Reading is done. Go to the epilogue.
}
//
// Common reading code for both explicit and implicit notations.
//
if (state.line === _line || state.lineIndent > nodeIndent) {
if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) {
if (atExplicitKey) {
keyNode = state.result;
} else {
valueNode = state.result;
}
}
if (!atExplicitKey) {
storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode);
keyTag = keyNode = valueNode = null;
}
skipSeparationSpace(state, true, -1);
ch = state.input.charCodeAt(state.position);
}
if (state.lineIndent > nodeIndent && (ch !== 0)) {
throwError(state, 'bad indentation of a mapping entry');
} else if (state.lineIndent < nodeIndent) {
break;
}
}
//
// Epilogue.
//
// Special case: last mapping's node contains only the key in explicit notation.
if (atExplicitKey) {
storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);
}
// Expose the resulting mapping.
if (detected) {
state.tag = _tag;
state.anchor = _anchor;
state.kind = 'mapping';
state.result = _result;
}
return detected;
}
function readTagProperty(state) {
var _position,
isVerbatim = false,
isNamed = false,
tagHandle,
tagName,
ch;
ch = state.input.charCodeAt(state.position);
if (ch !== 0x21/* ! */) return false;
if (state.tag !== null) {
throwError(state, 'duplication of a tag property');
}
ch = state.input.charCodeAt(++state.position);
if (ch === 0x3C/* < */) {
isVerbatim = true;
ch = state.input.charCodeAt(++state.position);
} else if (ch === 0x21/* ! */) {
isNamed = true;
tagHandle = '!!';
ch = state.input.charCodeAt(++state.position);
} else {
tagHandle = '!';
}
_position = state.position;
if (isVerbatim) {
do { ch = state.input.charCodeAt(++state.position); }
while (ch !== 0 && ch !== 0x3E/* > */);
if (state.position < state.length) {
tagName = state.input.slice(_position, state.position);
ch = state.input.charCodeAt(++state.position);
} else {
throwError(state, 'unexpected end of the stream within a verbatim tag');
}
} else {
while (ch !== 0 && !is_WS_OR_EOL(ch)) {
if (ch === 0x21/* ! */) {
if (!isNamed) {
tagHandle = state.input.slice(_position - 1, state.position + 1);
if (!PATTERN_TAG_HANDLE.test(tagHandle)) {
throwError(state, 'named tag handle cannot contain such characters');
}
isNamed = true;
_position = state.position + 1;
} else {
throwError(state, 'tag suffix cannot contain exclamation marks');
}
}
ch = state.input.charCodeAt(++state.position);
}
tagName = state.input.slice(_position, state.position);
if (PATTERN_FLOW_INDICATORS.test(tagName)) {
throwError(state, 'tag suffix cannot contain flow indicator characters');
}
}
if (tagName && !PATTERN_TAG_URI.test(tagName)) {
throwError(state, 'tag name cannot contain such characters: ' + tagName);
}
if (isVerbatim) {
state.tag = tagName;
} else if (_hasOwnProperty.call(state.tagMap, tagHandle)) {
state.tag = state.tagMap[tagHandle] + tagName;
} else if (tagHandle === '!') {
state.tag = '!' + tagName;
} else if (tagHandle === '!!') {
state.tag = 'tag:yaml.org,2002:' + tagName;
} else {
throwError(state, 'undeclared tag handle "' + tagHandle + '"');
}
return true;
}
function readAnchorProperty(state) {
var _position,
ch;
ch = state.input.charCodeAt(state.position);
if (ch !== 0x26/* & */) return false;
if (state.anchor !== null) {
throwError(state, 'duplication of an anchor property');
}
ch = state.input.charCodeAt(++state.position);
_position = state.position;
while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
ch = state.input.charCodeAt(++state.position);
}
if (state.position === _position) {
throwError(state, 'name of an anchor node must contain at least one character');
}
state.anchor = state.input.slice(_position, state.position);
return true;
}
function readAlias(state) {
var _position, alias,
ch;
ch = state.input.charCodeAt(state.position);
if (ch !== 0x2A/* * */) return false;
ch = state.input.charCodeAt(++state.position);
_position = state.position;
while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
ch = state.input.charCodeAt(++state.position);
}
if (state.position === _position) {
throwError(state, 'name of an alias node must contain at least one character');
}
alias = state.input.slice(_position, state.position);
if (!state.anchorMap.hasOwnProperty(alias)) {
throwError(state, 'unidentified alias "' + alias + '"');
}
state.result = state.anchorMap[alias];
skipSeparationSpace(state, true, -1);
return true;
}
function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) {
var allowBlockStyles,
allowBlockScalars,
allowBlockCollections,
indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this<parent
atNewLine = false,
hasContent = false,
typeIndex,
typeQuantity,
type,
flowIndent,
blockIndent;
if (state.listener !== null) {
state.listener('open', state);
}
state.tag = null;
state.anchor = null;
state.kind = null;
state.result = null;
allowBlockStyles = allowBlockScalars = allowBlockCollections =
CONTEXT_BLOCK_OUT === nodeContext ||
CONTEXT_BLOCK_IN === nodeContext;
if (allowToSeek) {
if (skipSeparationSpace(state, true, -1)) {
atNewLine = true;
if (state.lineIndent > parentIndent) {
indentStatus = 1;
} else if (state.lineIndent === parentIndent) {
indentStatus = 0;
} else if (state.lineIndent < parentIndent) {
indentStatus = -1;
}
}
}
if (indentStatus === 1) {
while (readTagProperty(state) || readAnchorProperty(state)) {
if (skipSeparationSpace(state, true, -1)) {
atNewLine = true;
allowBlockCollections = allowBlockStyles;
if (state.lineIndent > parentIndent) {
indentStatus = 1;
} else if (state.lineIndent === parentIndent) {
indentStatus = 0;
} else if (state.lineIndent < parentIndent) {
indentStatus = -1;
}
} else {
allowBlockCollections = false;
}
}
}
if (allowBlockCollections) {
allowBlockCollections = atNewLine || allowCompact;
}
if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) {
if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) {
flowIndent = parentIndent;
} else {
flowIndent = parentIndent + 1;
}
blockIndent = state.position - state.lineStart;
if (indentStatus === 1) {
if (allowBlockCollections &&
(readBlockSequence(state, blockIndent) ||
readBlockMapping(state, blockIndent, flowIndent)) ||
readFlowCollection(state, flowIndent)) {
hasContent = true;
} else {
if ((allowBlockScalars && readBlockScalar(state, flowIndent)) ||
readSingleQuotedScalar(state, flowIndent) ||
readDoubleQuotedScalar(state, flowIndent)) {
hasContent = true;
} else if (readAlias(state)) {
hasContent = true;
if (state.tag !== null || state.anchor !== null) {
throwError(state, 'alias node should not have any properties');
}
} else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) {
hasContent = true;
if (state.tag === null) {
state.tag = '?';
}
}
if (state.anchor !== null) {
state.anchorMap[state.anchor] = state.result;
}
}
} else if (indentStatus === 0) {
// Special case: block sequences are allowed to have same indentation level as the parent.
// http://www.yaml.org/spec/1.2/spec.html#id2799784
hasContent = allowBlockCollections && readBlockSequence(state, blockIndent);
}
}
if (state.tag !== null && state.tag !== '!') {
if (state.tag === '?') {
for (typeIndex = 0, typeQuantity = state.implicitTypes.length;
typeIndex < typeQuantity;
typeIndex += 1) {
type = state.implicitTypes[typeIndex];
// Implicit resolving is not allowed for non-scalar types, and '?'
// non-specific tag is only assigned to plain scalars. So, it isn't
// needed to check for 'kind' conformity.
if (type.resolve(state.result)) { // `state.result` updated in resolver if matched
state.result = type.construct(state.result);
state.tag = type.tag;
if (state.anchor !== null) {
state.anchorMap[state.anchor] = state.result;
}
break;
}
}
} else if (_hasOwnProperty.call(state.typeMap, state.tag)) {
type = state.typeMap[state.tag];
if (state.result !== null && type.kind !== state.kind) {
throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"');
}
if (!type.resolve(state.result)) { // `state.result` updated in resolver if matched
throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag');
} else {
state.result = type.construct(state.result);
if (state.anchor !== null) {
state.anchorMap[state.anchor] = state.result;
}
}
} else {
throwError(state, 'unknown tag !<' + state.tag + '>');
}
}
if (state.listener !== null) {
state.listener('close', state);
}
return state.tag !== null || state.anchor !== null || hasContent;
}
function readDocument(state) {
var documentStart = state.position,
_position,
directiveName,
directiveArgs,
hasDirectives = false,
ch;
state.version = null;
state.checkLineBreaks = state.legacy;
state.tagMap = {};
state.anchorMap = {};
while ((ch = state.input.charCodeAt(state.position)) !== 0) {
skipSeparationSpace(state, true, -1);
ch = state.input.charCodeAt(state.position);
if (state.lineIndent > 0 || ch !== 0x25/* % */) {
break;
}
hasDirectives = true;
ch = state.input.charCodeAt(++state.position);
_position = state.position;
while (ch !== 0 && !is_WS_OR_EOL(ch)) {
ch = state.input.charCodeAt(++state.position);
}
directiveName = state.input.slice(_position, state.position);
directiveArgs = [];
if (directiveName.length < 1) {
throwError(state, 'directive name must not be less than one character in length');
}
while (ch !== 0) {
while (is_WHITE_SPACE(ch)) {
ch = state.input.charCodeAt(++state.position);
}
if (ch === 0x23/* # */) {
do { ch = state.input.charCodeAt(++state.position); }
while (ch !== 0 && !is_EOL(ch));
break;
}
if (is_EOL(ch)) break;
_position = state.position;
while (ch !== 0 && !is_WS_OR_EOL(ch)) {
ch = state.input.charCodeAt(++state.position);
}
directiveArgs.push(state.input.slice(_position, state.position));
}
if (ch !== 0) readLineBreak(state);
if (_hasOwnProperty.call(directiveHandlers, directiveName)) {
directiveHandlers[directiveName](state, directiveName, directiveArgs);
} else {
throwWarning(state, 'unknown document directive "' + directiveName + '"');
}
}
skipSeparationSpace(state, true, -1);
if (state.lineIndent === 0 &&
state.input.charCodeAt(state.position) === 0x2D/* - */ &&
state.input.charCodeAt(state.position + 1) === 0x2D/* - */ &&
state.input.charCodeAt(state.position + 2) === 0x2D/* - */) {
state.position += 3;
skipSeparationSpace(state, true, -1);
} else if (hasDirectives) {
throwError(state, 'directives end mark is expected');
}
composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true);
skipSeparationSpace(state, true, -1);
if (state.checkLineBreaks &&
PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) {
throwWarning(state, 'non-ASCII line breaks are interpreted as content');
}
state.documents.push(state.result);
if (state.position === state.lineStart && testDocumentSeparator(state)) {
if (state.input.charCodeAt(state.position) === 0x2E/* . */) {
state.position += 3;
skipSeparationSpace(state, true, -1);
}
return;
}
if (state.position < (state.length - 1)) {
throwError(state, 'end of the stream or a document separator is expected');
} else {
return;
}
}
function loadDocuments(input, options) {
input = String(input);
options = options || {};
if (input.length !== 0) {
// Add tailing `\n` if not exists
if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ &&
input.charCodeAt(input.length - 1) !== 0x0D/* CR */) {
input += '\n';
}
// Strip BOM
if (input.charCodeAt(0) === 0xFEFF) {
input = input.slice(1);
}
}
var state = new State(input, options);
// Use 0 as string terminator. That significantly simplifies bounds check.
state.input += '\0';
while (state.input.charCodeAt(state.position) === 0x20/* Space */) {
state.lineIndent += 1;
state.position += 1;
}
while (state.position < (state.length - 1)) {
readDocument(state);
}
return state.documents;
}
function loadAll(input, iterator, options) {
var documents = loadDocuments(input, options), index, length;
for (index = 0, length = documents.length; index < length; index += 1) {
iterator(documents[index]);
}
}
function load(input, options) {
var documents = loadDocuments(input, options);
if (documents.length === 0) {
/*eslint-disable no-undefined*/
return undefined;
} else if (documents.length === 1) {
return documents[0];
}
throw new YAMLException('expected a single document in the stream, but found more');
}
function safeLoadAll(input, output, options) {
loadAll(input, output, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options));
}
function safeLoad(input, options) {
return load(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options));
}
module.exports.loadAll = loadAll;
module.exports.load = load;
module.exports.safeLoadAll = safeLoadAll;
module.exports.safeLoad = safeLoad;
},{"./common":2,"./exception":4,"./mark":6,"./schema/default_full":9,"./schema/default_safe":10}],6:[function(require,module,exports){
'use strict';
var common = require('./common');
function Mark(name, buffer, position, line, column) {
this.name = name;
this.buffer = buffer;
this.position = position;
this.line = line;
this.column = column;
}
Mark.prototype.getSnippet = function getSnippet(indent, maxLength) {
var head, start, tail, end, snippet;
if (!this.buffer) return null;
indent = indent || 4;
maxLength = maxLength || 75;
head = '';
start = this.position;
while (start > 0 && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(start - 1)) === -1) {
start -= 1;
if (this.position - start > (maxLength / 2 - 1)) {
head = ' ... ';
start += 5;
break;
}
}
tail = '';
end = this.position;
while (end < this.buffer.length && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(end)) === -1) {
end += 1;
if (end - this.position > (maxLength / 2 - 1)) {
tail = ' ... ';
end -= 5;
break;
}
}
snippet = this.buffer.slice(start, end);
return common.repeat(' ', indent) + head + snippet + tail + '\n' +
common.repeat(' ', indent + this.position - start + head.length) + '^';
};
Mark.prototype.toString = function toString(compact) {
var snippet, where = '';
if (this.name) {
where += 'in "' + this.name + '" ';
}
where += 'at line ' + (this.line + 1) + ', column ' + (this.column + 1);
if (!compact) {
snippet = this.getSnippet();
if (snippet) {
where += ':\n' + snippet;
}
}
return where;
};
module.exports = Mark;
},{"./common":2}],7:[function(require,module,exports){
'use strict';
/*eslint-disable max-len*/
var common = require('./common');
var YAMLException = require('./exception');
var Type = require('./type');
function compileList(schema, name, result) {
var exclude = [];
schema.include.forEach(function (includedSchema) {
result = compileList(includedSchema, name, result);
});
schema[name].forEach(function (currentType) {
result.forEach(function (previousType, previousIndex) {
if (previousType.tag === currentType.tag) {
exclude.push(previousIndex);
}
});
result.push(currentType);
});
return result.filter(function (type, index) {
return exclude.indexOf(index) === -1;
});
}
function compileMap(/* lists... */) {
var result = {}, index, length;
function collectType(type) {
result[type.tag] = type;
}
for (index = 0, length = arguments.length; index < length; index += 1) {
arguments[index].forEach(collectType);
}
return result;
}
function Schema(definition) {
this.include = definition.include || [];
this.implicit = definition.implicit || [];
this.explicit = definition.explicit || [];
this.implicit.forEach(function (type) {
if (type.loadKind && type.loadKind !== 'scalar') {
throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.');
}
});
this.compiledImplicit = compileList(this, 'implicit', []);
this.compiledExplicit = compileList(this, 'explicit', []);
this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit);
}
Schema.DEFAULT = null;
Schema.create = function createSchema() {
var schemas, types;
switch (arguments.length) {
case 1:
schemas = Schema.DEFAULT;
types = arguments[0];
break;
case 2:
schemas = arguments[0];
types = arguments[1];
break;
default:
throw new YAMLException('Wrong number of arguments for Schema.create function');
}
schemas = common.toArray(schemas);
types = common.toArray(types);
if (!schemas.every(function (schema) { return schema instanceof Schema; })) {
throw new YAMLException('Specified list of super schemas (or a single Schema object) contains a non-Schema object.');
}
if (!types.every(function (type) { return type instanceof Type; })) {
throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.');
}
return new Schema({
include: schemas,
explicit: types
});
};
module.exports = Schema;
},{"./common":2,"./exception":4,"./type":13}],8:[function(require,module,exports){
// Standard YAML's Core schema.
// http://www.yaml.org/spec/1.2/spec.html#id2804923
//
// NOTE: JS-YAML does not support schema-specific tag resolution restrictions.
// So, Core schema has no distinctions from JSON schema is JS-YAML.
'use strict';
var Schema = require('../schema');
module.exports = new Schema({
include: [
require('./json')
]
});
},{"../schema":7,"./json":12}],9:[function(require,module,exports){
// JS-YAML's default schema for `load` function.
// It is not described in the YAML specification.
//
// This schema is based on JS-YAML's default safe schema and includes
// JavaScript-specific types: !!js/undefined, !!js/regexp and !!js/function.
//
// Also this schema is used as default base schema at `Schema.create` function.
'use strict';
var Schema = require('../schema');
module.exports = Schema.DEFAULT = new Schema({
include: [
require('./default_safe')
],
explicit: [
require('../type/js/undefined'),
require('../type/js/regexp'),
require('../type/js/function')
]
});
},{"../schema":7,"../type/js/function":18,"../type/js/regexp":19,"../type/js/undefined":20,"./default_safe":10}],10:[function(require,module,exports){
// JS-YAML's default schema for `safeLoad` function.
// It is not described in the YAML specification.
//
// This schema is based on standard YAML's Core schema and includes most of
// extra types described at YAML tag repository. (http://yaml.org/type/)
'use strict';
var Schema = require('../schema');
module.exports = new Schema({
include: [
require('./core')
],
implicit: [
require('../type/timestamp'),
require('../type/merge')
],
explicit: [
require('../type/binary'),
require('../type/omap'),
require('../type/pairs'),
require('../type/set')
]
});
},{"../schema":7,"../type/binary":14,"../type/merge":22,"../type/omap":24,"../type/pairs":25,"../type/set":27,"../type/timestamp":29,"./core":8}],11:[function(require,module,exports){
// Standard YAML's Failsafe schema.
// http://www.yaml.org/spec/1.2/spec.html#id2802346
'use strict';
var Schema = require('../schema');
module.exports = new Schema({
explicit: [
require('../type/str'),
require('../type/seq'),
require('../type/map')
]
});
},{"../schema":7,"../type/map":21,"../type/seq":26,"../type/str":28}],12:[function(require,module,exports){
// Standard YAML's JSON schema.
// http://www.yaml.org/spec/1.2/spec.html#id2803231
//
// NOTE: JS-YAML does not support schema-specific tag resolution restrictions.
// So, this schema is not such strict as defined in the YAML specification.
// It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc.
'use strict';
var Schema = require('../schema');
module.exports = new Schema({
include: [
require('./failsafe')
],
implicit: [
require('../type/null'),
require('../type/bool'),
require('../type/int'),
require('../type/float')
]
});
},{"../schema":7,"../type/bool":15,"../type/float":16,"../type/int":17,"../type/null":23,"./failsafe":11}],13:[function(require,module,exports){
'use strict';
var YAMLException = require('./exception');
var TYPE_CONSTRUCTOR_OPTIONS = [
'kind',
'resolve',
'construct',
'instanceOf',
'predicate',
'represent',
'defaultStyle',
'styleAliases'
];
var YAML_NODE_KINDS = [
'scalar',
'sequence',
'mapping'
];
function compileStyleAliases(map) {
var result = {};
if (map !== null) {
Object.keys(map).forEach(function (style) {
map[style].forEach(function (alias) {
result[String(alias)] = style;
});
});
}
return result;
}
function Type(tag, options) {
options = options || {};
Object.keys(options).forEach(function (name) {
if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) {
throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.');
}
});
// TODO: Add tag format check.
this.tag = tag;
this.kind = options['kind'] || null;
this.resolve = options['resolve'] || function () { return true; };
this.construct = options['construct'] || function (data) { return data; };
this.instanceOf = options['instanceOf'] || null;
this.predicate = options['predicate'] || null;
this.represent = options['represent'] || null;
this.defaultStyle = options['defaultStyle'] || null;
this.styleAliases = compileStyleAliases(options['styleAliases'] || null);
if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {
throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.');
}
}
module.exports = Type;
},{"./exception":4}],14:[function(require,module,exports){
'use strict';
/*eslint-disable no-bitwise*/
var NodeBuffer;
try {
// A trick for browserified version, to not include `Buffer` shim
var _require = require;
NodeBuffer = _require('buffer').Buffer;
} catch (__) {}
var Type = require('../type');
// [ 64, 65, 66 ] -> [ padding, CR, LF ]
var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r';
function resolveYamlBinary(data) {
if (data === null) return false;
var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP;
// Convert one by one.
for (idx = 0; idx < max; idx++) {
code = map.indexOf(data.charAt(idx));
// Skip CR/LF
if (code > 64) continue;
// Fail on illegal characters
if (code < 0) return false;
bitlen += 6;
}
// If there are any bits left, source was corrupted
return (bitlen % 8) === 0;
}
function constructYamlBinary(data) {
var idx, tailbits,
input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan
max = input.length,
map = BASE64_MAP,
bits = 0,
result = [];
// Collect by 6*4 bits (3 bytes)
for (idx = 0; idx < max; idx++) {
if ((idx % 4 === 0) && idx) {
result.push((bits >> 16) & 0xFF);
result.push((bits >> 8) & 0xFF);
result.push(bits & 0xFF);
}
bits = (bits << 6) | map.indexOf(input.charAt(idx));
}
// Dump tail
tailbits = (max % 4) * 6;
if (tailbits === 0) {
result.push((bits >> 16) & 0xFF);
result.push((bits >> 8) & 0xFF);
result.push(bits & 0xFF);
} else if (tailbits === 18) {
result.push((bits >> 10) & 0xFF);
result.push((bits >> 2) & 0xFF);
} else if (tailbits === 12) {
result.push((bits >> 4) & 0xFF);
}
// Wrap into Buffer for NodeJS and leave Array for browser
if (NodeBuffer) return new NodeBuffer(result);
return result;
}
function representYamlBinary(object /*, style*/) {
var result = '', bits = 0, idx, tail,
max = object.length,
map = BASE64_MAP;
// Convert every three bytes to 4 ASCII characters.
for (idx = 0; idx < max; idx++) {
if ((idx % 3 === 0) && idx) {
result += map[(bits >> 18) & 0x3F];
result += map[(bits >> 12) & 0x3F];
result += map[(bits >> 6) & 0x3F];
result += map[bits & 0x3F];
}
bits = (bits << 8) + object[idx];
}
// Dump tail
tail = max % 3;
if (tail === 0) {
result += map[(bits >> 18) & 0x3F];
result += map[(bits >> 12) & 0x3F];
result += map[(bits >> 6) & 0x3F];
result += map[bits & 0x3F];
} else if (tail === 2) {
result += map[(bits >> 10) & 0x3F];
result += map[(bits >> 4) & 0x3F];
result += map[(bits << 2) & 0x3F];
result += map[64];
} else if (tail === 1) {
result += map[(bits >> 2) & 0x3F];
result += map[(bits << 4) & 0x3F];
result += map[64];
result += map[64];
}
return result;
}
function isBinary(object) {
return NodeBuffer && NodeBuffer.isBuffer(object);
}
module.exports = new Type('tag:yaml.org,2002:binary', {
kind: 'scalar',
resolve: resolveYamlBinary,
construct: constructYamlBinary,
predicate: isBinary,
represent: representYamlBinary
});
},{"../type":13}],15:[function(require,module,exports){
'use strict';
var Type = require('../type');
function resolveYamlBoolean(data) {
if (data === null) return false;
var max = data.length;
return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) ||
(max === 5 && (data === 'false' || data === 'False' || data === 'FALSE'));
}
function constructYamlBoolean(data) {
return data === 'true' ||
data === 'True' ||
data === 'TRUE';
}
function isBoolean(object) {
return Object.prototype.toString.call(object) === '[object Boolean]';
}
module.exports = new Type('tag:yaml.org,2002:bool', {
kind: 'scalar',
resolve: resolveYamlBoolean,
construct: constructYamlBoolean,
predicate: isBoolean,
represent: {
lowercase: function (object) { return object ? 'true' : 'false'; },
uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; },
camelcase: function (object) { return object ? 'True' : 'False'; }
},
defaultStyle: 'lowercase'
});
},{"../type":13}],16:[function(require,module,exports){
'use strict';
var common = require('../common');
var Type = require('../type');
var YAML_FLOAT_PATTERN = new RegExp(
'^(?:[-+]?(?:[0-9][0-9_]*)\\.[0-9_]*(?:[eE][-+][0-9]+)?' +
'|\\.[0-9_]+(?:[eE][-+][0-9]+)?' +
'|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*' +
'|[-+]?\\.(?:inf|Inf|INF)' +
'|\\.(?:nan|NaN|NAN))$');
function resolveYamlFloat(data) {
if (data === null) return false;
if (!YAML_FLOAT_PATTERN.test(data)) return false;
return true;
}
function constructYamlFloat(data) {
var value, sign, base, digits;
value = data.replace(/_/g, '').toLowerCase();
sign = value[0] === '-' ? -1 : 1;
digits = [];
if ('+-'.indexOf(value[0]) >= 0) {
value = value.slice(1);
}
if (value === '.inf') {
return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
} else if (value === '.nan') {
return NaN;
} else if (value.indexOf(':') >= 0) {
value.split(':').forEach(function (v) {
digits.unshift(parseFloat(v, 10));
});
value = 0.0;
base = 1;
digits.forEach(function (d) {
value += d * base;
base *= 60;
});
return sign * value;
}
return sign * parseFloat(value, 10);
}
var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;
function representYamlFloat(object, style) {
var res;
if (isNaN(object)) {
switch (style) {
case 'lowercase': return '.nan';
case 'uppercase': return '.NAN';
case 'camelcase': return '.NaN';
}
} else if (Number.POSITIVE_INFINITY === object) {
switch (style) {
case 'lowercase': return '.inf';
case 'uppercase': return '.INF';
case 'camelcase': return '.Inf';
}
} else if (Number.NEGATIVE_INFINITY === object) {
switch (style) {
case 'lowercase': return '-.inf';
case 'uppercase': return '-.INF';
case 'camelcase': return '-.Inf';
}
} else if (common.isNegativeZero(object)) {
return '-0.0';
}
res = object.toString(10);
// JS stringifier can build scientific format without dots: 5e-100,
// while YAML requres dot: 5.e-100. Fix it with simple hack
return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res;
}
function isFloat(object) {
return (Object.prototype.toString.call(object) === '[object Number]') &&
(object % 1 !== 0 || common.isNegativeZero(object));
}
module.exports = new Type('tag:yaml.org,2002:float', {
kind: 'scalar',
resolve: resolveYamlFloat,
construct: constructYamlFloat,
predicate: isFloat,
represent: representYamlFloat,
defaultStyle: 'lowercase'
});
},{"../common":2,"../type":13}],17:[function(require,module,exports){
'use strict';
var common = require('../common');
var Type = require('../type');
function isHexCode(c) {
return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) ||
((0x41/* A */ <= c) && (c <= 0x46/* F */)) ||
((0x61/* a */ <= c) && (c <= 0x66/* f */));
}
function isOctCode(c) {
return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */));
}
function isDecCode(c) {
return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */));
}
function resolveYamlInteger(data) {
if (data === null) return false;
var max = data.length,
index = 0,
hasDigits = false,
ch;
if (!max) return false;
ch = data[index];
// sign
if (ch === '-' || ch === '+') {
ch = data[++index];
}
if (ch === '0') {
// 0
if (index + 1 === max) return true;
ch = data[++index];
// base 2, base 8, base 16
if (ch === 'b') {
// base 2
index++;
for (; index < max; index++) {
ch = data[index];
if (ch === '_') continue;
if (ch !== '0' && ch !== '1') return false;
hasDigits = true;
}
return hasDigits;
}
if (ch === 'x') {
// base 16
index++;
for (; index < max; index++) {
ch = data[index];
if (ch === '_') continue;
if (!isHexCode(data.charCodeAt(index))) return false;
hasDigits = true;
}
return hasDigits;
}
// base 8
for (; index < max; index++) {
ch = data[index];
if (ch === '_') continue;
if (!isOctCode(data.charCodeAt(index))) return false;
hasDigits = true;
}
return hasDigits;
}
// base 10 (except 0) or base 60
for (; index < max; index++) {
ch = data[index];
if (ch === '_') continue;
if (ch === ':') break;
if (!isDecCode(data.charCodeAt(index))) {
return false;
}
hasDigits = true;
}
if (!hasDigits) return false;
// if !base60 - done;
if (ch !== ':') return true;
// base60 almost not used, no needs to optimize
return /^(:[0-5]?[0-9])+$/.test(data.slice(index));
}
function constructYamlInteger(data) {
var value = data, sign = 1, ch, base, digits = [];
if (value.indexOf('_') !== -1) {
value = value.replace(/_/g, '');
}
ch = value[0];
if (ch === '-' || ch === '+') {
if (ch === '-') sign = -1;
value = value.slice(1);
ch = value[0];
}
if (value === '0') return 0;
if (ch === '0') {
if (value[1] === 'b') return sign * parseInt(value.slice(2), 2);
if (value[1] === 'x') return sign * parseInt(value, 16);
return sign * parseInt(value, 8);
}
if (value.indexOf(':') !== -1) {
value.split(':').forEach(function (v) {
digits.unshift(parseInt(v, 10));
});
value = 0;
base = 1;
digits.forEach(function (d) {
value += (d * base);
base *= 60;
});
return sign * value;
}
return sign * parseInt(value, 10);
}
function isInteger(object) {
return (Object.prototype.toString.call(object)) === '[object Number]' &&
(object % 1 === 0 && !common.isNegativeZero(object));
}
module.exports = new Type('tag:yaml.org,2002:int', {
kind: 'scalar',
resolve: resolveYamlInteger,
construct: constructYamlInteger,
predicate: isInteger,
represent: {
binary: function (object) { return '0b' + object.toString(2); },
octal: function (object) { return '0' + object.toString(8); },
decimal: function (object) { return object.toString(10); },
hexadecimal: function (object) { return '0x' + object.toString(16).toUpperCase(); }
},
defaultStyle: 'decimal',
styleAliases: {
binary: [ 2, 'bin' ],
octal: [ 8, 'oct' ],
decimal: [ 10, 'dec' ],
hexadecimal: [ 16, 'hex' ]
}
});
},{"../common":2,"../type":13}],18:[function(require,module,exports){
'use strict';
var esprima;
// Browserified version does not have esprima
//
// 1. For node.js just require module as deps
// 2. For browser try to require mudule via external AMD system.
// If not found - try to fallback to window.esprima. If not
// found too - then fail to parse.
//
try {
// workaround to exclude package from browserify list.
var _require = require;
esprima = _require('esprima');
} catch (_) {
/*global window */
if (typeof window !== 'undefined') esprima = window.esprima;
}
var Type = require('../../type');
function resolveJavascriptFunction(data) {
if (data === null) return false;
try {
var source = '(' + data + ')',
ast = esprima.parse(source, { range: true });
if (ast.type !== 'Program' ||
ast.body.length !== 1 ||
ast.body[0].type !== 'ExpressionStatement' ||
ast.body[0].expression.type !== 'FunctionExpression') {
return false;
}
return true;
} catch (err) {
return false;
}
}
function constructJavascriptFunction(data) {
/*jslint evil:true*/
var source = '(' + data + ')',
ast = esprima.parse(source, { range: true }),
params = [],
body;
if (ast.type !== 'Program' ||
ast.body.length !== 1 ||
ast.body[0].type !== 'ExpressionStatement' ||
ast.body[0].expression.type !== 'FunctionExpression') {
throw new Error('Failed to resolve function');
}
ast.body[0].expression.params.forEach(function (param) {
params.push(param.name);
});
body = ast.body[0].expression.body.range;
// Esprima's ranges include the first '{' and the last '}' characters on
// function expressions. So cut them out.
/*eslint-disable no-new-func*/
return new Function(params, source.slice(body[0] + 1, body[1] - 1));
}
function representJavascriptFunction(object /*, style*/) {
return object.toString();
}
function isFunction(object) {
return Object.prototype.toString.call(object) === '[object Function]';
}
module.exports = new Type('tag:yaml.org,2002:js/function', {
kind: 'scalar',
resolve: resolveJavascriptFunction,
construct: constructJavascriptFunction,
predicate: isFunction,
represent: representJavascriptFunction
});
},{"../../type":13}],19:[function(require,module,exports){
'use strict';
var Type = require('../../type');
function resolveJavascriptRegExp(data) {
if (data === null) return false;
if (data.length === 0) return false;
var regexp = data,
tail = /\/([gim]*)$/.exec(data),
modifiers = '';
// if regexp starts with '/' it can have modifiers and must be properly closed
// `/foo/gim` - modifiers tail can be maximum 3 chars
if (regexp[0] === '/') {
if (tail) modifiers = tail[1];
if (modifiers.length > 3) return false;
// if expression starts with /, is should be properly terminated
if (regexp[regexp.length - modifiers.length - 1] !== '/') return false;
}
return true;
}
function constructJavascriptRegExp(data) {
var regexp = data,
tail = /\/([gim]*)$/.exec(data),
modifiers = '';
// `/foo/gim` - tail can be maximum 4 chars
if (regexp[0] === '/') {
if (tail) modifiers = tail[1];
regexp = regexp.slice(1, regexp.length - modifiers.length - 1);
}
return new RegExp(regexp, modifiers);
}
function representJavascriptRegExp(object /*, style*/) {
var result = '/' + object.source + '/';
if (object.global) result += 'g';
if (object.multiline) result += 'm';
if (object.ignoreCase) result += 'i';
return result;
}
function isRegExp(object) {
return Object.prototype.toString.call(object) === '[object RegExp]';
}
module.exports = new Type('tag:yaml.org,2002:js/regexp', {
kind: 'scalar',
resolve: resolveJavascriptRegExp,
construct: constructJavascriptRegExp,
predicate: isRegExp,
represent: representJavascriptRegExp
});
},{"../../type":13}],20:[function(require,module,exports){
'use strict';
var Type = require('../../type');
function resolveJavascriptUndefined() {
return true;
}
function constructJavascriptUndefined() {
/*eslint-disable no-undefined*/
return undefined;
}
function representJavascriptUndefined() {
return '';
}
function isUndefined(object) {
return typeof object === 'undefined';
}
module.exports = new Type('tag:yaml.org,2002:js/undefined', {
kind: 'scalar',
resolve: resolveJavascriptUndefined,
construct: constructJavascriptUndefined,
predicate: isUndefined,
represent: representJavascriptUndefined
});
},{"../../type":13}],21:[function(require,module,exports){
'use strict';
var Type = require('../type');
module.exports = new Type('tag:yaml.org,2002:map', {
kind: 'mapping',
construct: function (data) { return data !== null ? data : {}; }
});
},{"../type":13}],22:[function(require,module,exports){
'use strict';
var Type = require('../type');
function resolveYamlMerge(data) {
return data === '<<' || data === null;
}
module.exports = new Type('tag:yaml.org,2002:merge', {
kind: 'scalar',
resolve: resolveYamlMerge
});
},{"../type":13}],23:[function(require,module,exports){
'use strict';
var Type = require('../type');
function resolveYamlNull(data) {
if (data === null) return true;
var max = data.length;
return (max === 1 && data === '~') ||
(max === 4 && (data === 'null' || data === 'Null' || data === 'NULL'));
}
function constructYamlNull() {
return null;
}
function isNull(object) {
return object === null;
}
module.exports = new Type('tag:yaml.org,2002:null', {
kind: 'scalar',
resolve: resolveYamlNull,
construct: constructYamlNull,
predicate: isNull,
represent: {
canonical: function () { return '~'; },
lowercase: function () { return 'null'; },
uppercase: function () { return 'NULL'; },
camelcase: function () { return 'Null'; }
},
defaultStyle: 'lowercase'
});
},{"../type":13}],24:[function(require,module,exports){
'use strict';
var Type = require('../type');
var _hasOwnProperty = Object.prototype.hasOwnProperty;
var _toString = Object.prototype.toString;
function resolveYamlOmap(data) {
if (data === null) return true;
var objectKeys = [], index, length, pair, pairKey, pairHasKey,
object = data;
for (index = 0, length = object.length; index < length; index += 1) {
pair = object[index];
pairHasKey = false;
if (_toString.call(pair) !== '[object Object]') return false;
for (pairKey in pair) {
if (_hasOwnProperty.call(pair, pairKey)) {
if (!pairHasKey) pairHasKey = true;
else return false;
}
}
if (!pairHasKey) return false;
if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey);
else return false;
}
return true;
}
function constructYamlOmap(data) {
return data !== null ? data : [];
}
module.exports = new Type('tag:yaml.org,2002:omap', {
kind: 'sequence',
resolve: resolveYamlOmap,
construct: constructYamlOmap
});
},{"../type":13}],25:[function(require,module,exports){
'use strict';
var Type = require('../type');
var _toString = Object.prototype.toString;
function resolveYamlPairs(data) {
if (data === null) return true;
var index, length, pair, keys, result,
object = data;
result = new Array(object.length);
for (index = 0, length = object.length; index < length; index += 1) {
pair = object[index];
if (_toString.call(pair) !== '[object Object]') return false;
keys = Object.keys(pair);
if (keys.length !== 1) return false;
result[index] = [ keys[0], pair[keys[0]] ];
}
return true;
}
function constructYamlPairs(data) {
if (data === null) return [];
var index, length, pair, keys, result,
object = data;
result = new Array(object.length);
for (index = 0, length = object.length; index < length; index += 1) {
pair = object[index];
keys = Object.keys(pair);
result[index] = [ keys[0], pair[keys[0]] ];
}
return result;
}
module.exports = new Type('tag:yaml.org,2002:pairs', {
kind: 'sequence',
resolve: resolveYamlPairs,
construct: constructYamlPairs
});
},{"../type":13}],26:[function(require,module,exports){
'use strict';
var Type = require('../type');
module.exports = new Type('tag:yaml.org,2002:seq', {
kind: 'sequence',
construct: function (data) { return data !== null ? data : []; }
});
},{"../type":13}],27:[function(require,module,exports){
'use strict';
var Type = require('../type');
var _hasOwnProperty = Object.prototype.hasOwnProperty;
function resolveYamlSet(data) {
if (data === null) return true;
var key, object = data;
for (key in object) {
if (_hasOwnProperty.call(object, key)) {
if (object[key] !== null) return false;
}
}
return true;
}
function constructYamlSet(data) {
return data !== null ? data : {};
}
module.exports = new Type('tag:yaml.org,2002:set', {
kind: 'mapping',
resolve: resolveYamlSet,
construct: constructYamlSet
});
},{"../type":13}],28:[function(require,module,exports){
'use strict';
var Type = require('../type');
module.exports = new Type('tag:yaml.org,2002:str', {
kind: 'scalar',
construct: function (data) { return data !== null ? data : ''; }
});
},{"../type":13}],29:[function(require,module,exports){
'use strict';
var Type = require('../type');
var YAML_DATE_REGEXP = new RegExp(
'^([0-9][0-9][0-9][0-9])' + // [1] year
'-([0-9][0-9])' + // [2] month
'-([0-9][0-9])$'); // [3] day
var YAML_TIMESTAMP_REGEXP = new RegExp(
'^([0-9][0-9][0-9][0-9])' + // [1] year
'-([0-9][0-9]?)' + // [2] month
'-([0-9][0-9]?)' + // [3] day
'(?:[Tt]|[ \\t]+)' + // ...
'([0-9][0-9]?)' + // [4] hour
':([0-9][0-9])' + // [5] minute
':([0-9][0-9])' + // [6] second
'(?:\\.([0-9]*))?' + // [7] fraction
'(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour
'(?::([0-9][0-9]))?))?$'); // [11] tz_minute
function resolveYamlTimestamp(data) {
if (data === null) return false;
if (YAML_DATE_REGEXP.exec(data) !== null) return true;
if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true;
return false;
}
function constructYamlTimestamp(data) {
var match, year, month, day, hour, minute, second, fraction = 0,
delta = null, tz_hour, tz_minute, date;
match = YAML_DATE_REGEXP.exec(data);
if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data);
if (match === null) throw new Error('Date resolve error');
// match: [1] year [2] month [3] day
year = +(match[1]);
month = +(match[2]) - 1; // JS month starts with 0
day = +(match[3]);
if (!match[4]) { // no hour
return new Date(Date.UTC(year, month, day));
}
// match: [4] hour [5] minute [6] second [7] fraction
hour = +(match[4]);
minute = +(match[5]);
second = +(match[6]);
if (match[7]) {
fraction = match[7].slice(0, 3);
while (fraction.length < 3) { // milli-seconds
fraction += '0';
}
fraction = +fraction;
}
// match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute
if (match[9]) {
tz_hour = +(match[10]);
tz_minute = +(match[11] || 0);
delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds
if (match[9] === '-') delta = -delta;
}
date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
if (delta) date.setTime(date.getTime() - delta);
return date;
}
function representYamlTimestamp(object /*, style*/) {
return object.toISOString();
}
module.exports = new Type('tag:yaml.org,2002:timestamp', {
kind: 'scalar',
resolve: resolveYamlTimestamp,
construct: constructYamlTimestamp,
instanceOf: Date,
represent: representYamlTimestamp
});
},{"../type":13}],"/":[function(require,module,exports){
'use strict';
var yaml = require('./lib/js-yaml.js');
module.exports = yaml;
},{"./lib/js-yaml.js":1}]},{},[])("/")
}); | mit |
tsolucio/coreBOSTests | vendor/phpunit/phpunit/src/Runner/Filter/ExcludeGroupFilterIterator.php | 601 | <?php declare(strict_types=1);
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Runner\Filter;
use function in_array;
/**
* @internal This class is not covered by the backward compatibility promise for PHPUnit
*/
final class ExcludeGroupFilterIterator extends GroupFilterIterator
{
protected function doAccept(string $hash): bool
{
return !in_array($hash, $this->groupTests, true);
}
}
| mit |
dsebastien/DefinitelyTyped | types/xmlrpc/index.d.ts | 3078 | // Type definitions for xmlrpc 1.3.2
// Project: https://github.com/baalexander/node-xmlrpc
// Definitions by: Andrew Short <http://ajshort.me>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
declare module 'xmlrpc' {
import { EventEmitter } from 'events';
import { Server as HttpServer } from 'http';
import { Server as HttpsServer } from 'https';
import { TlsOptions } from 'tls';
interface ClientOptions {
host?: string;
path?: string;
port?: number;
url?: string;
cookies?: boolean;
headers?: { [header: string]: string };
basic_auth?: { user: string, pass: string };
method?: string;
}
interface ServerOptions {
host?: string;
path?: string;
port?: number;
}
interface DateFormatterOptions {
colons?: boolean;
hyphens?: boolean;
local?: boolean;
ms?: boolean;
offset?: boolean;
}
class Cookies {
get(name: string): string;
set(name: string, value: string, options?: { secure: boolean, expires: Date }): void;
toString(): string;
}
namespace xmlrpc {
function createClient(options: string | ClientOptions): Client;
function createSecureClient(options: string | ClientOptions): Client;
function createServer(options: string | ServerOptions, callback?: () => void): Server;
function createSecureServer(options: string | TlsOptions, callback?: () => void): Server;
interface Client {
options: ClientOptions;
isSecure: boolean;
headersProcessors: { processors: HeadersProcessor[] };
cookies?: Cookies;
methodCall(method: string, params: any[], callback: (error: Object, value: any) => void): void;
getCookie(name: string): string;
setCookie(name: string, value: string): this;
}
type ServerFunction = (error: any, params: any, callback: (error: any, value: any) => void) => void;
type ServerNotFoundFunction = (methodName: string, params: any[]) => void;
interface Server extends EventEmitter {
httpServer: HttpServer | HttpsServer;
on(eventName: 'NotFound', callback: ServerNotFoundFunction): this;
on(eventName: string, callback: ServerFunction): this;
}
type Headers = { [header: string]: string };
interface HeadersProcessor {
composeRequest(headers: Headers): void;
parseResponse(headers: Headers): void;
}
export var dateFormatter: {
setOpts(opts: DateFormatterOptions): void;
decodeIso8601(time: string): Date;
encodeIso8601(date: Date): string;
}
export class CustomType {
tagName: string;
raw: string;
constructor(raw: string);
serialize(xml: any): any; // XMLElementOrXMLNode declared by xmlbuilder
}
}
export = xmlrpc;
}
| mit |
drieks/babel | packages/babel-core/test/fixtures/traceur/Modules/Error_InvalidModuleDeclaration.module.js | 357 | // Error: 'test/feature/Modules/resources/no_such_file.js'
// Error: Specified as ./resources/no_such_file.js.
// Error: Imported by test/feature/Modules/Error_InvalidModuleDeclaration.module.js.
// Error: Normalizes to test/feature/Modules/resources/no_such_file.js
// Error: locate resolved against base
import * as b from './resources/no_such_file.js';
| mit |
Priya91/corefx-1 | src/System.Security.Cryptography.Cng/ref/System.Security.Cryptography.Cng.cs | 21352 | // 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.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace Microsoft.Win32.SafeHandles
{
public abstract partial class SafeNCryptHandle : System.Runtime.InteropServices.SafeHandle
{
protected SafeNCryptHandle() : base(default(System.IntPtr), default(bool)) { }
protected override bool ReleaseHandle() { return default(bool); }
protected abstract bool ReleaseNativeHandle();
}
public sealed partial class SafeNCryptKeyHandle : Microsoft.Win32.SafeHandles.SafeNCryptHandle
{
public SafeNCryptKeyHandle() { }
protected override bool ReleaseNativeHandle() { return default(bool); }
}
public sealed partial class SafeNCryptProviderHandle : Microsoft.Win32.SafeHandles.SafeNCryptHandle
{
public SafeNCryptProviderHandle() { }
protected override bool ReleaseNativeHandle() { return default(bool); }
}
public sealed partial class SafeNCryptSecretHandle : Microsoft.Win32.SafeHandles.SafeNCryptHandle
{
public SafeNCryptSecretHandle() { }
protected override bool ReleaseNativeHandle() { return default(bool); }
}
}
namespace System.Security.Cryptography
{
public sealed partial class CngAlgorithm : System.IEquatable<System.Security.Cryptography.CngAlgorithm>
{
public CngAlgorithm(string algorithm) { }
public string Algorithm { get { return default(string); } }
public static System.Security.Cryptography.CngAlgorithm ECDiffieHellmanP256 { get { return default(System.Security.Cryptography.CngAlgorithm); } }
public static System.Security.Cryptography.CngAlgorithm ECDiffieHellmanP384 { get { return default(System.Security.Cryptography.CngAlgorithm); } }
public static System.Security.Cryptography.CngAlgorithm ECDiffieHellmanP521 { get { return default(System.Security.Cryptography.CngAlgorithm); } }
public static System.Security.Cryptography.CngAlgorithm ECDsaP256 { get { return default(System.Security.Cryptography.CngAlgorithm); } }
public static System.Security.Cryptography.CngAlgorithm ECDsaP384 { get { return default(System.Security.Cryptography.CngAlgorithm); } }
public static System.Security.Cryptography.CngAlgorithm ECDsaP521 { get { return default(System.Security.Cryptography.CngAlgorithm); } }
public static System.Security.Cryptography.CngAlgorithm MD5 { get { return default(System.Security.Cryptography.CngAlgorithm); } }
public static System.Security.Cryptography.CngAlgorithm Rsa { get { return default(System.Security.Cryptography.CngAlgorithm); } }
public static System.Security.Cryptography.CngAlgorithm Sha1 { get { return default(System.Security.Cryptography.CngAlgorithm); } }
public static System.Security.Cryptography.CngAlgorithm Sha256 { get { return default(System.Security.Cryptography.CngAlgorithm); } }
public static System.Security.Cryptography.CngAlgorithm Sha384 { get { return default(System.Security.Cryptography.CngAlgorithm); } }
public static System.Security.Cryptography.CngAlgorithm Sha512 { get { return default(System.Security.Cryptography.CngAlgorithm); } }
public override bool Equals(object obj) { return default(bool); }
public bool Equals(System.Security.Cryptography.CngAlgorithm other) { return default(bool); }
public override int GetHashCode() { return default(int); }
public static bool operator ==(System.Security.Cryptography.CngAlgorithm left, System.Security.Cryptography.CngAlgorithm right) { return default(bool); }
public static bool operator !=(System.Security.Cryptography.CngAlgorithm left, System.Security.Cryptography.CngAlgorithm right) { return default(bool); }
public override string ToString() { return default(string); }
}
public sealed partial class CngAlgorithmGroup : System.IEquatable<System.Security.Cryptography.CngAlgorithmGroup>
{
public CngAlgorithmGroup(string algorithmGroup) { }
public string AlgorithmGroup { get { return default(string); } }
public static System.Security.Cryptography.CngAlgorithmGroup DiffieHellman { get { return default(System.Security.Cryptography.CngAlgorithmGroup); } }
public static System.Security.Cryptography.CngAlgorithmGroup Dsa { get { return default(System.Security.Cryptography.CngAlgorithmGroup); } }
public static System.Security.Cryptography.CngAlgorithmGroup ECDiffieHellman { get { return default(System.Security.Cryptography.CngAlgorithmGroup); } }
public static System.Security.Cryptography.CngAlgorithmGroup ECDsa { get { return default(System.Security.Cryptography.CngAlgorithmGroup); } }
public static System.Security.Cryptography.CngAlgorithmGroup Rsa { get { return default(System.Security.Cryptography.CngAlgorithmGroup); } }
public override bool Equals(object obj) { return default(bool); }
public bool Equals(System.Security.Cryptography.CngAlgorithmGroup other) { return default(bool); }
public override int GetHashCode() { return default(int); }
public static bool operator ==(System.Security.Cryptography.CngAlgorithmGroup left, System.Security.Cryptography.CngAlgorithmGroup right) { return default(bool); }
public static bool operator !=(System.Security.Cryptography.CngAlgorithmGroup left, System.Security.Cryptography.CngAlgorithmGroup right) { return default(bool); }
public override string ToString() { return default(string); }
}
[System.FlagsAttribute]
public enum CngExportPolicies
{
AllowArchiving = 4,
AllowExport = 1,
AllowPlaintextArchiving = 8,
AllowPlaintextExport = 2,
None = 0,
}
public sealed partial class CngKey : System.IDisposable
{
internal CngKey() { }
public System.Security.Cryptography.CngAlgorithm Algorithm { get { return default(System.Security.Cryptography.CngAlgorithm); } }
public System.Security.Cryptography.CngAlgorithmGroup AlgorithmGroup { get { return default(System.Security.Cryptography.CngAlgorithmGroup); } }
public System.Security.Cryptography.CngExportPolicies ExportPolicy { get { return default(System.Security.Cryptography.CngExportPolicies); } }
public Microsoft.Win32.SafeHandles.SafeNCryptKeyHandle Handle { get { return default(Microsoft.Win32.SafeHandles.SafeNCryptKeyHandle); } }
public bool IsEphemeral { get { return default(bool); } }
public bool IsMachineKey { get { return default(bool); } }
public string KeyName { get { return default(string); } }
public int KeySize { get { return default(int); } }
public System.Security.Cryptography.CngKeyUsages KeyUsage { get { return default(System.Security.Cryptography.CngKeyUsages); } }
public System.IntPtr ParentWindowHandle { get { return default(System.IntPtr); } set { } }
public System.Security.Cryptography.CngProvider Provider { get { return default(System.Security.Cryptography.CngProvider); } }
public Microsoft.Win32.SafeHandles.SafeNCryptProviderHandle ProviderHandle { get { return default(Microsoft.Win32.SafeHandles.SafeNCryptProviderHandle); } }
public System.Security.Cryptography.CngUIPolicy UIPolicy { get { return default(System.Security.Cryptography.CngUIPolicy); } }
public string UniqueName { get { return default(string); } }
public static System.Security.Cryptography.CngKey Create(System.Security.Cryptography.CngAlgorithm algorithm) { return default(System.Security.Cryptography.CngKey); }
public static System.Security.Cryptography.CngKey Create(System.Security.Cryptography.CngAlgorithm algorithm, string keyName) { return default(System.Security.Cryptography.CngKey); }
public static System.Security.Cryptography.CngKey Create(System.Security.Cryptography.CngAlgorithm algorithm, string keyName, System.Security.Cryptography.CngKeyCreationParameters creationParameters) { return default(System.Security.Cryptography.CngKey); }
public void Delete() { }
public void Dispose() { }
public static bool Exists(string keyName) { return default(bool); }
public static bool Exists(string keyName, System.Security.Cryptography.CngProvider provider) { return default(bool); }
public static bool Exists(string keyName, System.Security.Cryptography.CngProvider provider, System.Security.Cryptography.CngKeyOpenOptions options) { return default(bool); }
public byte[] Export(System.Security.Cryptography.CngKeyBlobFormat format) { return default(byte[]); }
public System.Security.Cryptography.CngProperty GetProperty(string name, System.Security.Cryptography.CngPropertyOptions options) { return default(System.Security.Cryptography.CngProperty); }
public bool HasProperty(string name, System.Security.Cryptography.CngPropertyOptions options) { return default(bool); }
public static System.Security.Cryptography.CngKey Import(byte[] keyBlob, System.Security.Cryptography.CngKeyBlobFormat format) { return default(System.Security.Cryptography.CngKey); }
public static System.Security.Cryptography.CngKey Import(byte[] keyBlob, System.Security.Cryptography.CngKeyBlobFormat format, System.Security.Cryptography.CngProvider provider) { return default(System.Security.Cryptography.CngKey); }
public static System.Security.Cryptography.CngKey Open(Microsoft.Win32.SafeHandles.SafeNCryptKeyHandle keyHandle, System.Security.Cryptography.CngKeyHandleOpenOptions keyHandleOpenOptions) { return default(System.Security.Cryptography.CngKey); }
public static System.Security.Cryptography.CngKey Open(string keyName) { return default(System.Security.Cryptography.CngKey); }
public static System.Security.Cryptography.CngKey Open(string keyName, System.Security.Cryptography.CngProvider provider) { return default(System.Security.Cryptography.CngKey); }
public static System.Security.Cryptography.CngKey Open(string keyName, System.Security.Cryptography.CngProvider provider, System.Security.Cryptography.CngKeyOpenOptions openOptions) { return default(System.Security.Cryptography.CngKey); }
public void SetProperty(System.Security.Cryptography.CngProperty property) { }
}
public sealed partial class CngKeyBlobFormat : System.IEquatable<System.Security.Cryptography.CngKeyBlobFormat>
{
public CngKeyBlobFormat(string format) { }
public static System.Security.Cryptography.CngKeyBlobFormat EccPrivateBlob { get { return default(System.Security.Cryptography.CngKeyBlobFormat); } }
public static System.Security.Cryptography.CngKeyBlobFormat EccPublicBlob { get { return default(System.Security.Cryptography.CngKeyBlobFormat); } }
public string Format { get { return default(string); } }
public static System.Security.Cryptography.CngKeyBlobFormat GenericPrivateBlob { get { return default(System.Security.Cryptography.CngKeyBlobFormat); } }
public static System.Security.Cryptography.CngKeyBlobFormat GenericPublicBlob { get { return default(System.Security.Cryptography.CngKeyBlobFormat); } }
public static System.Security.Cryptography.CngKeyBlobFormat OpaqueTransportBlob { get { return default(System.Security.Cryptography.CngKeyBlobFormat); } }
public static System.Security.Cryptography.CngKeyBlobFormat Pkcs8PrivateBlob { get { return default(System.Security.Cryptography.CngKeyBlobFormat); } }
public override bool Equals(object obj) { return default(bool); }
public bool Equals(System.Security.Cryptography.CngKeyBlobFormat other) { return default(bool); }
public override int GetHashCode() { return default(int); }
public static bool operator ==(System.Security.Cryptography.CngKeyBlobFormat left, System.Security.Cryptography.CngKeyBlobFormat right) { return default(bool); }
public static bool operator !=(System.Security.Cryptography.CngKeyBlobFormat left, System.Security.Cryptography.CngKeyBlobFormat right) { return default(bool); }
public override string ToString() { return default(string); }
}
[System.FlagsAttribute]
public enum CngKeyCreationOptions
{
MachineKey = 32,
None = 0,
OverwriteExistingKey = 128,
}
public sealed partial class CngKeyCreationParameters
{
public CngKeyCreationParameters() { }
public System.Nullable<System.Security.Cryptography.CngExportPolicies> ExportPolicy { get { return default(System.Nullable<System.Security.Cryptography.CngExportPolicies>); } set { } }
public System.Security.Cryptography.CngKeyCreationOptions KeyCreationOptions { get { return default(System.Security.Cryptography.CngKeyCreationOptions); } set { } }
public System.Nullable<System.Security.Cryptography.CngKeyUsages> KeyUsage { get { return default(System.Nullable<System.Security.Cryptography.CngKeyUsages>); } set { } }
public System.Security.Cryptography.CngPropertyCollection Parameters { get { return default(System.Security.Cryptography.CngPropertyCollection); } }
public System.IntPtr ParentWindowHandle { get { return default(System.IntPtr); } set { } }
public System.Security.Cryptography.CngProvider Provider { get { return default(System.Security.Cryptography.CngProvider); } set { } }
public System.Security.Cryptography.CngUIPolicy UIPolicy { get { return default(System.Security.Cryptography.CngUIPolicy); } set { } }
}
[System.FlagsAttribute]
public enum CngKeyHandleOpenOptions
{
EphemeralKey = 1,
None = 0,
}
[System.FlagsAttribute]
public enum CngKeyOpenOptions
{
MachineKey = 32,
None = 0,
Silent = 64,
UserKey = 0,
}
[System.FlagsAttribute]
public enum CngKeyUsages
{
AllUsages = 16777215,
Decryption = 1,
KeyAgreement = 4,
None = 0,
Signing = 2,
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct CngProperty : System.IEquatable<System.Security.Cryptography.CngProperty>
{
public CngProperty(string name, byte[] value, System.Security.Cryptography.CngPropertyOptions options) { throw new System.NotImplementedException(); }
public string Name { get { return default(string); } }
public System.Security.Cryptography.CngPropertyOptions Options { get { return default(System.Security.Cryptography.CngPropertyOptions); } }
public override bool Equals(object obj) { return default(bool); }
public bool Equals(System.Security.Cryptography.CngProperty other) { return default(bool); }
public override int GetHashCode() { return default(int); }
public byte[] GetValue() { return default(byte[]); }
public static bool operator ==(System.Security.Cryptography.CngProperty left, System.Security.Cryptography.CngProperty right) { return default(bool); }
public static bool operator !=(System.Security.Cryptography.CngProperty left, System.Security.Cryptography.CngProperty right) { return default(bool); }
}
public sealed partial class CngPropertyCollection : System.Collections.ObjectModel.Collection<System.Security.Cryptography.CngProperty>
{
public CngPropertyCollection() { }
}
[System.FlagsAttribute]
public enum CngPropertyOptions
{
CustomProperty = 1073741824,
None = 0,
Persist = -2147483648,
}
public sealed partial class CngProvider : System.IEquatable<System.Security.Cryptography.CngProvider>
{
public CngProvider(string provider) { }
public static System.Security.Cryptography.CngProvider MicrosoftSmartCardKeyStorageProvider { get { return default(System.Security.Cryptography.CngProvider); } }
public static System.Security.Cryptography.CngProvider MicrosoftSoftwareKeyStorageProvider { get { return default(System.Security.Cryptography.CngProvider); } }
public string Provider { get { return default(string); } }
public override bool Equals(object obj) { return default(bool); }
public bool Equals(System.Security.Cryptography.CngProvider other) { return default(bool); }
public override int GetHashCode() { return default(int); }
public static bool operator ==(System.Security.Cryptography.CngProvider left, System.Security.Cryptography.CngProvider right) { return default(bool); }
public static bool operator !=(System.Security.Cryptography.CngProvider left, System.Security.Cryptography.CngProvider right) { return default(bool); }
public override string ToString() { return default(string); }
}
public sealed partial class CngUIPolicy
{
public CngUIPolicy(System.Security.Cryptography.CngUIProtectionLevels protectionLevel) { }
public CngUIPolicy(System.Security.Cryptography.CngUIProtectionLevels protectionLevel, string friendlyName) { }
public CngUIPolicy(System.Security.Cryptography.CngUIProtectionLevels protectionLevel, string friendlyName, string description) { }
public CngUIPolicy(System.Security.Cryptography.CngUIProtectionLevels protectionLevel, string friendlyName, string description, string useContext) { }
public CngUIPolicy(System.Security.Cryptography.CngUIProtectionLevels protectionLevel, string friendlyName, string description, string useContext, string creationTitle) { }
public string CreationTitle { get { return default(string); } }
public string Description { get { return default(string); } }
public string FriendlyName { get { return default(string); } }
public System.Security.Cryptography.CngUIProtectionLevels ProtectionLevel { get { return default(System.Security.Cryptography.CngUIProtectionLevels); } }
public string UseContext { get { return default(string); } }
}
[System.FlagsAttribute]
public enum CngUIProtectionLevels
{
ForceHighProtection = 2,
None = 0,
ProtectKey = 1,
}
public sealed partial class ECDsaCng : System.Security.Cryptography.ECDsa
{
public ECDsaCng() {}
public ECDsaCng(int keySize) {}
public ECDsaCng(CngKey key) {}
public System.Security.Cryptography.CngKey Key { get { return default(System.Security.Cryptography.CngKey); } }
public override System.Security.Cryptography.KeySizes[] LegalKeySizes { get { return default(System.Security.Cryptography.KeySizes[]); } }
protected override void Dispose(bool disposing) {}
protected override byte[] HashData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { return default(byte[]); }
protected override byte[] HashData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { return default(byte[]); }
public override byte[] SignHash(byte[] hash) { return default(byte[]); }
public override bool VerifyHash(byte[] hash, byte[] signature) { return default(bool); }
}
public sealed partial class RSACng : System.Security.Cryptography.RSA
{
public RSACng() { }
public RSACng(int keySize) { }
public RSACng(System.Security.Cryptography.CngKey key) { }
public System.Security.Cryptography.CngKey Key { get { return default(System.Security.Cryptography.CngKey); } }
public override byte[] Decrypt(byte[] data, System.Security.Cryptography.RSAEncryptionPadding padding) { return default(byte[]); }
protected override void Dispose(bool disposing) { }
public override byte[] Encrypt(byte[] data, System.Security.Cryptography.RSAEncryptionPadding padding) { return default(byte[]); }
public override System.Security.Cryptography.RSAParameters ExportParameters(bool includePrivateParameters) { return default(System.Security.Cryptography.RSAParameters); }
protected override byte[] HashData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { return default(byte[]); }
protected override byte[] HashData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { return default(byte[]); }
public override void ImportParameters(System.Security.Cryptography.RSAParameters parameters) { }
public override System.Security.Cryptography.KeySizes[] LegalKeySizes { get { return default(System.Security.Cryptography.KeySizes[]); } }
public override byte[] SignHash(byte[] hash, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { return default(byte[]); }
public override bool VerifyHash(byte[] hash, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { return default(bool); }
}
}
| mit |
horacework/nutritionalDiet | node_modules/orm/node_modules/sql-query/lib/Dialects/mysql.js | 2544 | var util = require("util");
var helpers = require("../Helpers");
exports.DataTypes = {
id: 'INTEGER PRIMARY KEY AUTO_INCREMENT',
int: 'INTEGER',
float: 'FLOAT(12,2)',
bool: 'TINYINT(1)',
text: 'TEXT'
};
exports.escape = function (query, args) {
return helpers.escapeQuery(exports, query, args);
}
exports.escapeId = function () {
return Array.prototype.slice.apply(arguments).map(function (el) {
if (typeof el == "object") {
return el.str.replace(/\?:(id|value)/g, function (m) {
if (m == "?:id") {
return exports.escapeId(el.escapes.shift());
}
// ?:value
return exports.escapeVal(el.escapes.shift());
});
}
return "`" + el.replace(/`/g, '``') + "`";
}).join(".");
};
exports.escapeVal = function (val, timeZone) {
if (val === undefined || val === null) {
return 'NULL';
}
if (Buffer.isBuffer(val)) {
return bufferToString(val);
}
if (Array.isArray(val)) {
return arrayToList(val, timeZone || "local");
}
if (util.isDate(val)) {
val = helpers.dateToString(val, timeZone || "local", { dialect: 'mysql' });
} else {
switch (typeof val) {
case 'boolean':
return (val) ? 'true' : 'false';
case 'number':
if (!isFinite(val)) {
val = val.toString();
break;
}
return val + '';
case "object":
return objectToValues(val, timeZone || "Z");
case "function":
return val(exports);
}
}
val = val.replace(/[\0\n\r\b\t\\\'\"\x1a]/g, function(s) {
switch(s) {
case "\0": return "\\0";
case "\n": return "\\n";
case "\r": return "\\r";
case "\b": return "\\b";
case "\t": return "\\t";
case "\x1a": return "\\Z";
default: return "\\" + s;
}
});
return "'" + val + "'";
};
function objectToValues(object, timeZone) {
var values = [];
for (var key in object) {
var value = object[key];
if(typeof value === 'function') {
continue;
}
values.push(exports.escapeId(key) + ' = ' + exports.escapeVal(value, timeZone));
}
return values.join(', ');
}
function arrayToList(array, timeZone) {
return "(" + array.map(function(v) {
if (Array.isArray(v)) return arrayToList(v);
return exports.escapeVal(v, timeZone);
}).join(', ') + ")";
}
function bufferToString(buffer) {
var hex = '';
try {
hex = buffer.toString('hex');
} catch (err) {
// node v0.4.x does not support hex / throws unknown encoding error
for (var i = 0; i < buffer.length; i++) {
var b = buffer[i];
hex += zeroPad(b.toString(16));
}
}
return "X'" + hex+ "'";
}
exports.defaultValuesStmt = "VALUES()";
| mit |
ryantheleach/SpongeCommon | src/main/java/org/spongepowered/common/interfaces/IMixinScoreboard.java | 1358 | /*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* 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.
*/
package org.spongepowered.common.interfaces;
public interface IMixinScoreboard {
boolean isClient();
}
| mit |
saadiyadesai/saadiyadesai.github.io | node_modules/npm/node_modules/npm-registry-client/lib/dist-tags/fetch.js | 981 | module.exports = fetch
var assert = require('assert')
var url = require('url')
var npa = require('npm-package-arg')
function fetch (uri, params, cb) {
assert(typeof uri === 'string', 'must pass registry URI to distTags.fetch')
assert(
params && typeof params === 'object',
'must pass params to distTags.fetch'
)
assert(typeof cb === 'function', 'must pass callback to distTags.fetch')
assert(
typeof params.package === 'string',
'must pass package name to distTags.fetch'
)
assert(
params.auth && typeof params.auth === 'object',
'must pass auth to distTags.fetch'
)
var p = npa(params.package)
var pkg = p.scope ? params.package.replace('/', '%2f') : params.package
var rest = '-/package/' + pkg + '/dist-tags'
var options = {
method: 'GET',
auth: params.auth
}
this.request(url.resolve(uri, rest), options, function (er, data) {
if (data && typeof data === 'object') delete data._etag
cb(er, data)
})
}
| mit |
appjudo/skim | lib/temple/coffee_script/filters.rb | 214 | require "temple/coffee_script/filters/attribute_merger"
require "temple/coffee_script/filters/attribute_remover"
require "temple/coffee_script/filters/control_flow"
require "temple/coffee_script/filters/escapable"
| mit |
cmaciasg/test | application/vendor/symfony/http-foundation/Tests/RequestMatcherTest.php | 4780 | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpFoundation\Tests;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestMatcher;
class RequestMatcherTest extends TestCase
{
/**
* @dataProvider getMethodData
*/
public function testMethod($requestMethod, $matcherMethod, $isMatch)
{
$matcher = new RequestMatcher();
$matcher->matchMethod($matcherMethod);
$request = Request::create('', $requestMethod);
$this->assertSame($isMatch, $matcher->matches($request));
$matcher = new RequestMatcher(null, null, $matcherMethod);
$request = Request::create('', $requestMethod);
$this->assertSame($isMatch, $matcher->matches($request));
}
public function getMethodData()
{
return array(
array('get', 'get', true),
array('get', array('get', 'post'), true),
array('get', 'post', false),
array('get', 'GET', true),
array('get', array('GET', 'POST'), true),
array('get', 'POST', false),
);
}
public function testScheme()
{
$httpRequest = $request = $request = Request::create('');
$httpsRequest = $request = $request = Request::create('', 'get', array(), array(), array(), array('HTTPS' => 'on'));
$matcher = new RequestMatcher();
$matcher->matchScheme('https');
$this->assertFalse($matcher->matches($httpRequest));
$this->assertTrue($matcher->matches($httpsRequest));
$matcher->matchScheme('http');
$this->assertFalse($matcher->matches($httpsRequest));
$this->assertTrue($matcher->matches($httpRequest));
$matcher = new RequestMatcher();
$this->assertTrue($matcher->matches($httpsRequest));
$this->assertTrue($matcher->matches($httpRequest));
}
/**
* @dataProvider getHostData
*/
public function testHost($pattern, $isMatch)
{
$matcher = new RequestMatcher();
$request = Request::create('', 'get', array(), array(), array(), array('HTTP_HOST' => 'foo.example.com'));
$matcher->matchHost($pattern);
$this->assertSame($isMatch, $matcher->matches($request));
$matcher = new RequestMatcher(null, $pattern);
$this->assertSame($isMatch, $matcher->matches($request));
}
public function getHostData()
{
return array(
array('.*\.example\.com', true),
array('\.example\.com$', true),
array('^.*\.example\.com$', true),
array('.*\.sensio\.com', false),
array('.*\.example\.COM', true),
array('\.example\.COM$', true),
array('^.*\.example\.COM$', true),
array('.*\.sensio\.COM', false),
);
}
public function testPath()
{
$matcher = new RequestMatcher();
$request = Request::create('/admin/foo');
$matcher->matchPath('/admin/.*');
$this->assertTrue($matcher->matches($request));
$matcher->matchPath('/admin');
$this->assertTrue($matcher->matches($request));
$matcher->matchPath('^/admin/.*$');
$this->assertTrue($matcher->matches($request));
$matcher->matchMethod('/blog/.*');
$this->assertFalse($matcher->matches($request));
}
public function testPathWithLocaleIsNotSupported()
{
$matcher = new RequestMatcher();
$request = Request::create('/en/login');
$request->setLocale('en');
$matcher->matchPath('^/{_locale}/login$');
$this->assertFalse($matcher->matches($request));
}
public function testPathWithEncodedCharacters()
{
$matcher = new RequestMatcher();
$request = Request::create('/admin/fo%20o');
$matcher->matchPath('^/admin/fo o*$');
$this->assertTrue($matcher->matches($request));
}
public function testAttributes()
{
$matcher = new RequestMatcher();
$request = Request::create('/admin/foo');
$request->attributes->set('foo', 'foo_bar');
$matcher->matchAttribute('foo', 'foo_.*');
$this->assertTrue($matcher->matches($request));
$matcher->matchAttribute('foo', 'foo');
$this->assertTrue($matcher->matches($request));
$matcher->matchAttribute('foo', '^foo_bar$');
$this->assertTrue($matcher->matches($request));
$matcher->matchAttribute('foo', 'babar');
$this->assertFalse($matcher->matches($request));
}
}
| mit |
dantman/sequelize | lib/dialects/postgres/query.js | 11715 | 'use strict';
var Utils = require('../../utils')
, AbstractQuery = require('../abstract/query')
, QueryTypes = require('../../query-types')
, Promise = require('../../promise')
, sequelizeErrors = require('../../errors.js')
, _ = require('lodash');
var Query = function(client, sequelize, options) {
this.client = client;
this.sequelize = sequelize;
this.instance = options.instance;
this.model = options.model;
this.options = _.extend({
logging: console.log,
plain: false,
raw: false
}, options || {});
this.checkLoggingOption();
};
Utils.inherit(Query, AbstractQuery);
/**
* rewrite query with parameters
*/
Query.formatBindParameters = function(sql, values, dialect) {
var bindParam = [];
if (Array.isArray(values)) {
bindParam = values;
sql = AbstractQuery.formatBindParameters(sql, values, dialect, { skipValueReplace: true })[0];
} else {
var i = 0;
var seen = {};
var replacementFunc = function(match, key, values, timeZone, dialect, options) {
if (seen[key] !== undefined) {
return seen[key];
}
if (values[key] !== undefined) {
i = i + 1;
bindParam.push(values[key]);
seen[key] = '$'+i;
return '$'+i;
}
return undefined;
};
sql = AbstractQuery.formatBindParameters(sql, values, dialect, replacementFunc)[0];
}
return [sql, bindParam];
};
Query.prototype.run = function(sql, parameters) {
this.sql = sql;
if(!Utils._.isEmpty(this.options.searchPath)){
this.sql = this.sequelize.queryInterface.QueryGenerator.setSearchPath(this.options.searchPath) + sql;
}
var self = this
, receivedError = false
, query = ((parameters && parameters.length) ? this.client.query(this.sql, parameters) : this.client.query(this.sql))
, rows = [];
this.sequelize.log('Executing (' + (this.client.uuid || 'default') + '): ' + this.sql, this.options);
var promise = new Promise(function(resolve, reject) {
query.on('row', function(row) {
rows.push(row);
});
query.on('error', function(err) {
// set the client so that it will be reaped if the connection resets while executing
if(err.code === 'ECONNRESET') {
self.client._invalid = true;
}
receivedError = true;
err.sql = sql;
reject(self.formatError(err));
});
query.on('end', function(result) {
if (receivedError) {
return;
}
resolve([rows, sql, result]);
});
}).spread(function(rows, sql, result) {
var results = rows
, isTableNameQuery = (sql.indexOf('SELECT table_name FROM information_schema.tables') === 0)
, isRelNameQuery = (sql.indexOf('SELECT relname FROM pg_class WHERE oid IN') === 0);
if (isRelNameQuery) {
return rows.map(function(row) {
return {
name: row.relname,
tableName: row.relname.split('_')[0]
};
});
} else if (isTableNameQuery) {
return rows.map(function(row) { return _.values(row); });
}
if (rows[0] && rows[0].sequelize_caught_exception !== undefined) {
if (rows[0].sequelize_caught_exception !== null) {
var err = self.formatError({
code: '23505',
detail: rows[0].sequelize_caught_exception
});
throw err;
} else {
rows = rows.map(function (row) {
delete row.sequelize_caught_exception;
return row;
});
}
}
if (self.isShowIndexesQuery()) {
results.forEach(function (result) {
var attributes = /ON .*? (?:USING .*?\s)?\((.*)\)/gi.exec(result.definition)[1].split(',')
, field
, attribute
, columns;
// Map column index in table to column name
columns = _.zipObject(
result.column_indexes,
self.sequelize.queryInterface.QueryGenerator.fromArray(result.column_names)
);
delete result.column_indexes;
delete result.column_names;
// Indkey is the order of attributes in the index, specified by a string of attribute indexes
result.fields = result.indkey.split(' ').map(function (indKey, index) {
field = columns[indKey];
// for functional indices indKey = 0
if(!field) {
return null;
}
attribute = attributes[index];
return {
attribute: field,
collate: attribute.match(/COLLATE "(.*?)"/) ? /COLLATE "(.*?)"/.exec(attribute)[1] : undefined,
order: attribute.indexOf('DESC') !== -1 ? 'DESC' : attribute.indexOf('ASC') !== -1 ? 'ASC': undefined,
length: undefined
};
}).filter(function(n){ return n !== null; });
delete result.columns;
});
return results;
} else if (self.isForeignKeysQuery()) {
result = [];
rows.forEach(function(row) {
var defParts;
if (row.condef !== undefined && (defParts = row.condef.match(/FOREIGN KEY \((.+)\) REFERENCES (.+)\((.+)\)( ON (UPDATE|DELETE) (CASCADE|RESTRICT))?( ON (UPDATE|DELETE) (CASCADE|RESTRICT))?/))) {
row.id = row.constraint_name;
row.table = defParts[2];
row.from = defParts[1];
row.to = defParts[3];
var i;
for (i=5;i<=8;i+=3) {
if (/(UPDATE|DELETE)/.test(defParts[i])) {
row['on_'+defParts[i].toLowerCase()] = defParts[i+1];
}
}
}
result.push(row);
});
return result;
} else if (self.isSelectQuery()) {
// Postgres will treat tables as case-insensitive, so fix the case
// of the returned values to match attributes
if (self.options.raw === false && self.sequelize.options.quoteIdentifiers === false) {
var attrsMap = _.reduce(self.model.attributes, function(m, v, k) { m[k.toLowerCase()] = k; return m; }, {});
rows.forEach(function(row) {
_.keys(row).forEach(function(key) {
var targetAttr = attrsMap[key];
if (typeof targetAttr === 'string' && targetAttr !== key) {
row[targetAttr] = row[key];
delete row[key];
}
});
});
}
return self.handleSelectQuery(rows);
} else if (QueryTypes.DESCRIBE === self.options.type) {
result = {};
rows.forEach(function(_result) {
result[_result.Field] = {
type: _result.Type.toUpperCase(),
allowNull: (_result.Null === 'YES'),
defaultValue: _result.Default,
special: (!!_result.special ? self.sequelize.queryInterface.QueryGenerator.fromArray(_result.special) : []),
primaryKey: _result.Constraint === 'PRIMARY KEY'
};
if (result[_result.Field].type === 'BOOLEAN') {
result[_result.Field].defaultValue = { 'false': false, 'true': true }[result[_result.Field].defaultValue];
if (result[_result.Field].defaultValue === undefined) {
result[_result.Field].defaultValue = null;
}
}
if (typeof result[_result.Field].defaultValue === 'string') {
result[_result.Field].defaultValue = result[_result.Field].defaultValue.replace(/'/g, '');
if (result[_result.Field].defaultValue.indexOf('::') > -1) {
var split = result[_result.Field].defaultValue.split('::');
if (split[1].toLowerCase() !== 'regclass)') {
result[_result.Field].defaultValue = split[0];
}
}
}
});
return result;
} else if (self.isVersionQuery()) {
return results[0].server_version;
} else if (self.isShowOrDescribeQuery()) {
return results;
} else if (QueryTypes.BULKUPDATE === self.options.type) {
if (!self.options.returning) {
return parseInt(result.rowCount, 10);
}
return self.handleSelectQuery(rows);
} else if (QueryTypes.BULKDELETE === self.options.type) {
return parseInt(result.rowCount, 10);
} else if (self.isUpsertQuery()) {
return rows[0].sequelize_upsert;
} else if (self.isInsertQuery() || self.isUpdateQuery()) {
if (self.instance && self.instance.dataValues) {
for (var key in rows[0]) {
if (rows[0].hasOwnProperty(key)) {
var record = rows[0][key];
var attr = _.find(self.model.rawAttributes, function (attribute) {
return attribute.fieldName === key || attribute.field === key;
});
self.instance.dataValues[attr && attr.fieldName || key] = record;
}
}
}
return self.instance || (rows && ((self.options.plain && rows[0]) || rows)) || undefined;
} else if (self.isRawQuery()) {
return [rows, result];
} else {
return results;
}
});
return promise;
};
Query.prototype.formatError = function (err) {
var match
, table
, index
, fields
, errors
, message
, self = this;
var code = err.code || err.sqlState
, errMessage = err.message || err.messagePrimary
, errDetail = err.detail || err.messageDetail;
switch (code) {
case '23503':
index = errMessage.match(/violates foreign key constraint \"(.+?)\"/);
index = index ? index[1] : undefined;
table = errMessage.match(/on table \"(.+?)\"/);
table = table ? table[1] : undefined;
return new sequelizeErrors.ForeignKeyConstraintError({
message: errMessage,
fields: null,
index: index,
table: table,
parent: err
});
case '23505':
// there are multiple different formats of error messages for this error code
// this regex should check at least two
match = errDetail.replace(/"/g, '').match(/Key \((.*?)\)=\((.*?)\)/);
if (match) {
fields = _.zipObject(match[1].split(', '), match[2].split(', '));
errors = [];
message = 'Validation error';
_.forOwn(fields, function(value, field) {
errors.push(new sequelizeErrors.ValidationErrorItem(
self.getUniqueConstraintErrorMessage(field),
'unique violation', field, value));
});
if (this.model && this.model.uniqueKeys) {
_.forOwn(this.model.uniqueKeys, function(constraint) {
if (_.isEqual(constraint.fields, Object.keys(fields)) && !!constraint.msg) {
message = constraint.msg;
return false;
}
});
}
return new sequelizeErrors.UniqueConstraintError({
message: message,
errors: errors,
parent: err,
fields: fields
});
} else {
return new sequelizeErrors.UniqueConstraintError({
message: errMessage,
parent: err
});
}
break;
case '23P01':
match = errDetail.match(/Key \((.*?)\)=\((.*?)\)/);
if (match) {
fields = _.zipObject(match[1].split(', '), match[2].split(', '));
}
message = 'Exclusion constraint error';
return new sequelizeErrors.ExclusionConstraintError({
message: message,
constraint: err.constraint,
fields: fields,
table: err.table,
parent: err
});
default:
return new sequelizeErrors.DatabaseError(err);
}
};
Query.prototype.isForeignKeysQuery = function() {
return /SELECT conname as constraint_name, pg_catalog\.pg_get_constraintdef\(r\.oid, true\) as condef FROM pg_catalog\.pg_constraint r WHERE r\.conrelid = \(SELECT oid FROM pg_class WHERE relname = '.*' LIMIT 1\) AND r\.contype = 'f' ORDER BY 1;/.test(this.sql);
};
Query.prototype.getInsertIdField = function() {
return 'id';
};
module.exports = Query;
| mit |
novaquark/glm | test/core/core_func_noise.cpp | 565 | ///////////////////////////////////////////////////////////////////////////////////////////////////
// OpenGL Mathematics Copyright (c) 2005 - 2014 G-Truc Creation (www.g-truc.net)
///////////////////////////////////////////////////////////////////////////////////////////////////
// Created : 2011-01-15
// Updated : 2011-09-13
// Licence : This source is under MIT licence
// File : test/core/func_noise.cpp
///////////////////////////////////////////////////////////////////////////////////////////////////
int main()
{
int Failed = 0;
return Failed;
}
| mit |
EMostafaAli/mathnet-numerics | src/UnitTests/LinearAlgebraTests/Complex/Factorization/GramSchmidtTests.cs | 15264 | // <copyright file="GramSchmidtTests.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// 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.
// </copyright>
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Complex;
using MathNet.Numerics.LinearAlgebra.Complex.Factorization;
using NUnit.Framework;
namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Complex.Factorization
{
#if NOSYSNUMERICS
using Complex = Numerics.Complex;
#else
using Complex = System.Numerics.Complex;
#endif
/// <summary>
/// GramSchmidt factorization tests for a dense matrix.
/// </summary>
[TestFixture, Category("LAFactorization")]
public class GramSchmidtTests
{
/// <summary>
/// Constructor with wide matrix throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void ConstructorWideMatrixThrowsInvalidMatrixOperationException()
{
Assert.That(() => DenseGramSchmidt.Create(new DenseMatrix(3, 4)), Throws.ArgumentException);
}
/// <summary>
/// Can factorize identity matrix.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(10)]
[TestCase(100)]
public void CanFactorizeIdentity(int order)
{
var matrixI = DenseMatrix.CreateIdentity(order);
var factorGramSchmidt = matrixI.GramSchmidt();
var q = factorGramSchmidt.Q;
var r = factorGramSchmidt.R;
Assert.AreEqual(matrixI.RowCount, q.RowCount);
Assert.AreEqual(matrixI.ColumnCount, q.ColumnCount);
for (var i = 0; i < r.RowCount; i++)
{
for (var j = 0; j < r.ColumnCount; j++)
{
Assert.AreEqual(i == j ? Complex.One : Complex.Zero, r[i, j]);
}
}
for (var i = 0; i < q.RowCount; i++)
{
for (var j = 0; j < q.ColumnCount; j++)
{
Assert.AreEqual(i == j ? Complex.One : Complex.Zero, q[i, j]);
}
}
}
/// <summary>
/// Identity determinant is one.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(10)]
[TestCase(100)]
public void IdentityDeterminantIsOne(int order)
{
var matrixI = DenseMatrix.CreateIdentity(order);
var factorGramSchmidt = matrixI.GramSchmidt();
Assert.AreEqual(Complex.One, factorGramSchmidt.Determinant);
}
/// <summary>
/// Can factorize a random matrix.
/// </summary>
/// <param name="row">Matrix row number.</param>
/// <param name="column">Matrix column number.</param>
[TestCase(1, 1)]
[TestCase(2, 2)]
[TestCase(5, 5)]
[TestCase(10, 6)]
[TestCase(50, 48)]
[TestCase(100, 98)]
public void CanFactorizeRandomMatrix(int row, int column)
{
var matrixA = Matrix<Complex>.Build.Random(row, column, 1);
var factorGramSchmidt = matrixA.GramSchmidt();
var q = factorGramSchmidt.Q;
var r = factorGramSchmidt.R;
// Make sure the Q has the right dimensions.
Assert.AreEqual(row, q.RowCount);
Assert.AreEqual(column, q.ColumnCount);
// Make sure the R has the right dimensions.
Assert.AreEqual(column, r.RowCount);
Assert.AreEqual(column, r.ColumnCount);
// Make sure the R factor is upper triangular.
for (var i = 0; i < r.RowCount; i++)
{
for (var j = 0; j < r.ColumnCount; j++)
{
if (i > j)
{
Assert.AreEqual(Complex.Zero, r[i, j]);
}
}
}
// Make sure the Q*R is the original matrix.
var matrixQfromR = q * r;
for (var i = 0; i < matrixQfromR.RowCount; i++)
{
for (var j = 0; j < matrixQfromR.ColumnCount; j++)
{
AssertHelpers.AlmostEqualRelative(matrixA[i, j], matrixQfromR[i, j], 9);
}
}
// Make sure the Q is unitary --> (Q*)x(Q) = I
var matrixQсtQ = q.ConjugateTranspose() * q;
for (var i = 0; i < matrixQсtQ.RowCount; i++)
{
for (var j = 0; j < matrixQсtQ.ColumnCount; j++)
{
AssertHelpers.AlmostEqualRelative(matrixQсtQ[i, j], i == j ? Complex.One : Complex.Zero, 9);
}
}
}
/// <summary>
/// Can solve a system of linear equations for a random vector (Ax=b).
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanSolveForRandomVector(int order)
{
var matrixA = Matrix<Complex>.Build.Random(order, order, 1);
var matrixACopy = matrixA.Clone();
var factorGramSchmidt = matrixA.GramSchmidt();
var vectorb = Vector<Complex>.Build.Random(order, 1);
var resultx = factorGramSchmidt.Solve(vectorb);
Assert.AreEqual(matrixA.ColumnCount, resultx.Count);
var matrixBReconstruct = matrixA * resultx;
// Check the reconstruction.
for (var i = 0; i < order; i++)
{
AssertHelpers.AlmostEqual(vectorb[i], matrixBReconstruct[i], 10);
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
}
/// <summary>
/// Can solve a system of linear equations for a random matrix (AX=B).
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanSolveForRandomMatrix(int order)
{
var matrixA = Matrix<Complex>.Build.Random(order, order, 1);
var matrixACopy = matrixA.Clone();
var factorGramSchmidt = matrixA.GramSchmidt();
var matrixB = Matrix<Complex>.Build.Random(order, order, 1);
var matrixX = factorGramSchmidt.Solve(matrixB);
// The solution X row dimension is equal to the column dimension of A
Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount);
// The solution X has the same number of columns as B
Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);
var matrixBReconstruct = matrixA * matrixX;
// Check the reconstruction.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
AssertHelpers.AlmostEqual(matrixB[i, j], matrixBReconstruct[i, j], 10);
}
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
}
/// <summary>
/// Can solve for a random vector into a result vector.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanSolveForRandomVectorWhenResultVectorGiven(int order)
{
var matrixA = Matrix<Complex>.Build.Random(order, order, 1);
var matrixACopy = matrixA.Clone();
var factorGramSchmidt = matrixA.GramSchmidt();
var vectorb = Vector<Complex>.Build.Random(order, 1);
var vectorbCopy = vectorb.Clone();
var resultx = new DenseVector(order);
factorGramSchmidt.Solve(vectorb, resultx);
Assert.AreEqual(vectorb.Count, resultx.Count);
var matrixBReconstruct = matrixA * resultx;
// Check the reconstruction.
for (var i = 0; i < vectorb.Count; i++)
{
AssertHelpers.AlmostEqual(vectorb[i], matrixBReconstruct[i], 10);
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
// Make sure b didn't change.
for (var i = 0; i < vectorb.Count; i++)
{
Assert.AreEqual(vectorbCopy[i], vectorb[i]);
}
}
/// <summary>
/// Can solve a system of linear equations for a random matrix (AX=B) into a result matrix.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanSolveForRandomMatrixWhenResultMatrixGiven(int order)
{
var matrixA = Matrix<Complex>.Build.Random(order, order, 1);
var matrixACopy = matrixA.Clone();
var factorGramSchmidt = matrixA.GramSchmidt();
var matrixB = Matrix<Complex>.Build.Random(order, order, 1);
var matrixBCopy = matrixB.Clone();
var matrixX = new DenseMatrix(order, order);
factorGramSchmidt.Solve(matrixB, matrixX);
// The solution X row dimension is equal to the column dimension of A
Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount);
// The solution X has the same number of columns as B
Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);
var matrixBReconstruct = matrixA * matrixX;
// Check the reconstruction.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
AssertHelpers.AlmostEqual(matrixB[i, j], matrixBReconstruct[i, j], 10);
}
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
// Make sure B didn't change.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
Assert.AreEqual(matrixBCopy[i, j], matrixB[i, j]);
}
}
}
/// <summary>
/// Can solve when using a tall matrix.
/// </summary>
[Test]
public void CanSolveForMatrixWithTallRandomMatrix()
{
var matrixA = Matrix<Complex>.Build.Random(20, 10, 1);
var matrixACopy = matrixA.Clone();
var factorQR = matrixA.GramSchmidt();
var matrixB = Matrix<Complex>.Build.Random(20, 5, 1);
var matrixX = factorQR.Solve(matrixB);
// The solution X row dimension is equal to the column dimension of A
Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount);
// The solution X has the same number of columns as B
Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);
var test = (matrixA.ConjugateTranspose() * matrixA).Inverse() * matrixA.ConjugateTranspose() * matrixB;
for (var i = 0; i < matrixX.RowCount; i++)
{
for (var j = 0; j < matrixX.ColumnCount; j++)
{
AssertHelpers.AlmostEqual(test[i, j], matrixX[i, j], 12);
}
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
}
/// <summary>
/// Can solve when using a tall matrix.
/// </summary>
[Test]
public void CanSolveForVectorWithTallRandomMatrix()
{
var matrixA = Matrix<Complex>.Build.Random(20, 10, 1);
var matrixACopy = matrixA.Clone();
var factorQR = matrixA.GramSchmidt();
var vectorB = Vector<Complex>.Build.Random(20, 1);
var vectorX = factorQR.Solve(vectorB);
// The solution x dimension is equal to the column dimension of A
Assert.AreEqual(matrixA.ColumnCount, vectorX.Count);
var test = (matrixA.ConjugateTranspose() * matrixA).Inverse() * matrixA.ConjugateTranspose() * vectorB;
for (var i = 0; i < vectorX.Count; i++)
{
AssertHelpers.AlmostEqual(test[i], vectorX[i], 12);
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
}
}
}
| mit |
dm-istomin/unity-tutorial-projects | Survival Shooter/Assets/Scripts/Managers/EnemyManager.cs | 588 | using UnityEngine;
public class EnemyManager : MonoBehaviour
{
public PlayerHealth playerHealth;
public GameObject enemy;
public float spawnTime = 3f;
public Transform[] spawnPoints;
void Start ()
{
InvokeRepeating ("Spawn", spawnTime, spawnTime);
}
void Spawn ()
{
if(playerHealth.currentHealth <= 0f)
{
return;
}
int spawnPointIndex = Random.Range (0, spawnPoints.Length);
Instantiate (enemy, spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);
}
}
| mit |
lapachuka/shamshura_VPS | extension/ezjscore/design/standard/lib/yui/3.4.1/build/yui-log/yui-log-min.js | 898 | /*
YUI 3.4.1 (build 4118)
Copyright 2011 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add("yui-log",function(d){var c=d,e="yui:log",a="undefined",b={debug:1,info:1,warn:1,error:1};c.log=function(j,s,g,q){var l,p,n,k,o,i=c,r=i.config,h=(i.fire)?i:YUI.Env.globalEvents;if(r.debug){if(g){p=r.logExclude;n=r.logInclude;if(n&&!(g in n)){l=1;}else{if(n&&(g in n)){l=!n[g];}else{if(p&&(g in p)){l=p[g];}}}}if(!l){if(r.useBrowserConsole){k=(g)?g+": "+j:j;if(i.Lang.isFunction(r.logFn)){r.logFn.call(i,j,s,g);}else{if(typeof console!=a&&console.log){o=(s&&console[s]&&(s in b))?s:"log";console[o](k);}else{if(typeof opera!=a){opera.postError(k);}}}}if(h&&!q){if(h==i&&(!h.getEvent(e))){h.publish(e,{broadcast:2});}h.fire(e,{msg:j,cat:s,src:g});}}}return i;};c.message=function(){return c.log.apply(c,arguments);};},"3.4.1",{requires:["yui-base"]});
| gpl-2.0 |
Gurgel100/gcc | gcc/testsuite/g++.dg/tree-ssa/inline-4.C | 774 | /* { dg-do compile } */
/* { dg-options "-O2 -fopt-info-inline --param max-early-inliner-iterations=3" } */
/* { dg-add-options bind_pic_locally } */
namespace std {
extern "C" int puts(const char *s);
}
template <class T, class E> void
foreach (T b, T e, void (*ptr)(E))
{
for (; b != e; b++)
ptr(*b); // { dg-optimized "Inlining void inline_me\[^\\n\]* into int main\[^\\n\]*" }
}
void
inline_me (char *x)
{
std::puts(x);
}
static void
inline_me_too (char *x)
{
std::puts(x);
}
int main(int argc, char **argv)
{
foreach (argv, argv + argc, inline_me); // { dg-optimized "Inlining void foreach\[^\\n\]* into int main\[^\\n\]*" }
foreach (argv, argv + argc, inline_me_too); // { dg-optimized "Inlining void foreach\[^\\n\]* into int main\[^\\n\]*" }
}
| gpl-2.0 |
lysovannborey/Ecommerce | includes/modules/pages/product_music_info/main_template_vars.php | 8916 | <?php
/**
* product_music_info main_template_vars
*
* @package productTypes
* @copyright Copyright 2003-2012 Zen Cart Development Team
* @copyright Portions Copyright 2003 osCommerce
* @license http://www.zen-cart.com/license/2_0.txt GNU Public License V2.0
* @version GIT: $Id: Author: DrByte Fri Jul 6 11:57:44 2012 -0400 Modified in v1.5.1 $
*/
/*
* Extracts and constructs the data to be used in the product-type template tpl_TYPEHANDLER_info_display.php
*/
// This should be first line of the script:
$zco_notifier->notify('NOTIFY_MAIN_TEMPLATE_VARS_START_PRODUCT_MUSIC_INFO');
$module_show_categories = PRODUCT_INFO_CATEGORIES;
$sql = "select count(*) as total
from " . TABLE_PRODUCTS . " p, " .
TABLE_PRODUCTS_DESCRIPTION . " pd
where p.products_status = '1'
and p.products_id = '" . (int)$_GET['products_id'] . "'
and pd.products_id = p.products_id
and pd.language_id = '" . (int)$_SESSION['languages_id'] . "'";
$res = $db->Execute($sql);
if ( $res->fields['total'] < 1 ) {
$tpl_page_body = '/tpl_product_info_noproduct.php';
} else {
$tpl_page_body = '/tpl_product_music_info_display.php';
$zco_notifier->notify('NOTIFY_PRODUCT_VIEWS_HIT_INCREMENTOR', (int)$_GET['products_id']);
$sql = "select p.products_id, pd.products_name,
pd.products_description, p.products_model,
p.products_quantity, p.products_image,
pd.products_url, p.products_price,
p.products_tax_class_id, p.products_date_added,
p.products_date_available, p.manufacturers_id, p.products_quantity,
p.products_weight, p.products_priced_by_attribute, p.product_is_free,
p.products_qty_box_status,
p.products_quantity_order_max,
p.products_discount_type, p.products_discount_type_from, p.products_sort_order, p.products_price_sorter
from " . TABLE_PRODUCTS . " p, " . TABLE_PRODUCTS_DESCRIPTION . " pd
where p.products_status = '1'
and p.products_id = '" . (int)$_GET['products_id'] . "'
and pd.products_id = p.products_id
and pd.language_id = '" . (int)$_SESSION['languages_id'] . "'";
$product_info = $db->Execute($sql);
$products_price_sorter = $product_info->fields['products_price_sorter'];
$products_price = $currencies->display_price($product_info->fields['products_price'],
zen_get_tax_rate($product_info->fields['products_tax_class_id']));
$manufacturers_name = zen_get_products_manufacturers_name((int)$_GET['products_id']);
if ($new_price = zen_get_products_special_price($product_info->fields['products_id'])) {
$specials_price = $currencies->display_price($new_price,
zen_get_tax_rate($product_info->fields['products_tax_class_id']));
}
// set flag for attributes module usage:
$flag_show_weight_attrib_for_this_prod_type = SHOW_PRODUCT_MUSIC_INFO_WEIGHT_ATTRIBUTES;
// get attributes
require(DIR_WS_MODULES . zen_get_module_directory(FILENAME_ATTRIBUTES));
// if review must be approved or disabled do not show review
$review_status = " and r.status = '1'";
$reviews_query = "select count(*) as count from " . TABLE_REVIEWS . " r, "
. TABLE_REVIEWS_DESCRIPTION . " rd
where r.products_id = '" . (int)$_GET['products_id'] . "'
and r.reviews_id = rd.reviews_id
and rd.languages_id = '" . (int)$_SESSION['languages_id'] . "'" .
$review_status;
$reviews = $db->Execute($reviews_query);
}
require(DIR_WS_MODULES . zen_get_module_directory('product_prev_next.php'));
$products_name = $product_info->fields['products_name'];
$products_model = $product_info->fields['products_model'];
$products_description = $product_info->fields['products_description'];
if ($product_info->fields['products_image'] == '' and PRODUCTS_IMAGE_NO_IMAGE_STATUS == '1') {
$products_image = PRODUCTS_IMAGE_NO_IMAGE;
} else {
$products_image = $product_info->fields['products_image'];
}
$products_url = $product_info->fields['products_url'];
$products_date_available = $product_info->fields['products_date_available'];
$products_date_added = $product_info->fields['products_date_added'];
$products_manufacturer = $manufacturers_name;
$products_weight = $product_info->fields['products_weight'];
$products_quantity = $product_info->fields['products_quantity'];
$products_qty_box_status = $product_info->fields['products_qty_box_status'];
$products_quantity_order_max = $product_info->fields['products_quantity_order_max'];
$products_base_price = $currencies->display_price(zen_get_products_base_price((int)$_GET['products_id']),
zen_get_tax_rate($product_info->fields['products_tax_class_id']));
$product_is_free = $product_info->fields['product_is_free'];
$products_tax_class_id = $product_info->fields['products_tax_class_id'];
$module_show_categories = PRODUCT_INFO_CATEGORIES;
$module_next_previous = PRODUCT_INFO_PREVIOUS_NEXT;
$products_id_current = (int)$_GET['products_id'];
$products_discount_type = $product_info->fields['products_discount_type'];
$products_discount_type_from = $product_info->fields['products_discount_type_from'];
/**
* Load product-type-specific main_template_vars
*/
$prod_type_specific_vars_info = DIR_WS_MODULES . 'pages/' . $current_page_base . '/main_template_vars_product_type.php';
if (file_exists($prod_type_specific_vars_info)) {
include_once($prod_type_specific_vars_info);
}
$zco_notifier->notify('NOTIFY_MAIN_TEMPLATE_VARS_PRODUCT_TYPE_VARS_PRODUCT_MUSIC_INFO');
/**
* Load all *.PHP files from the /includes/templates/MYTEMPLATE/PAGENAME/extra_main_template_vars
*/
$extras_dir = $template->get_template_dir('.php', DIR_WS_TEMPLATE, $current_page_base . 'extra_main_template_vars', $current_page_base . '/' . 'extra_main_template_vars');
if ($dir = @dir($extras_dir)) {
while ($file = $dir->read()) {
if (!is_dir($extras_dir . '/' . $file)) {
if (preg_match('~^[^\._].*\.php$~i', $file) > 0) {
$directory_array[] = '/' . $file;
}
}
}
$dir->close();
}
if (sizeof($directory_array)) sort($directory_array);
for ($i = 0, $n = sizeof($directory_array); $i < $n; $i++) {
if (file_exists($extras_dir . $directory_array[$i])) include($extras_dir . $directory_array[$i]);
}
// build show flags from product type layout settings
$flag_show_product_info_starting_at = zen_get_show_product_switch($_GET['products_id'], 'starting_at');
$flag_show_product_info_model = zen_get_show_product_switch($_GET['products_id'], 'model');
$flag_show_product_info_weight = zen_get_show_product_switch($_GET['products_id'], 'weight');
$flag_show_product_info_quantity = zen_get_show_product_switch($_GET['products_id'], 'quantity');
$flag_show_product_info_manufacturer = zen_get_show_product_switch($_GET['products_id'], 'manufacturer');
$flag_show_product_info_in_cart_qty = zen_get_show_product_switch($_GET['products_id'], 'in_cart_qty');
$flag_show_product_info_reviews = zen_get_show_product_switch($_GET['products_id'], 'reviews');
$flag_show_product_info_reviews_count = zen_get_show_product_switch($_GET['products_id'], 'reviews_count');
$flag_show_product_info_date_available = zen_get_show_product_switch($_GET['products_id'], 'date_available');
$flag_show_product_info_date_added = zen_get_show_product_switch($_GET['products_id'], 'date_added');
$flag_show_product_info_url = zen_get_show_product_switch($_GET['products_id'], 'url');
$flag_show_product_info_additional_images = zen_get_show_product_switch($_GET['products_id'], 'additional_images');
$flag_show_product_info_free_shipping = zen_get_show_product_switch($_GET['products_id'], 'always_free_shipping_image_switch');
$flag_show_product_music_info_artist = zen_get_show_product_switch($_GET['products_id'], 'artist');
$flag_show_product_music_info_genre = zen_get_show_product_switch($_GET['products_id'], 'genre');
$flag_show_product_music_info_record_company = zen_get_show_product_switch($_GET['products_id'], 'record_company');
require(DIR_WS_MODULES . zen_get_module_directory(FILENAME_PRODUCTS_QUANTITY_DISCOUNTS));
$zco_notifier->notify('NOTIFY_MAIN_TEMPLATE_VARS_EXTRA_PRODUCT_MUSIC_INFO');
require($template->get_template_dir($tpl_page_body,DIR_WS_TEMPLATE, $current_page_base,'templates'). $tpl_page_body);
//require(DIR_WS_MODULES . zen_get_module_directory(FILENAME_ALSO_PURCHASED_PRODUCTS));
// This should be last line of the script:
$zco_notifier->notify('NOTIFY_MAIN_TEMPLATE_VARS_END_PRODUCT_MUSIC_INFO');
| gpl-2.0 |
treejames/APE_Server | deps/js/src/tests/js1_5/Array/regress-350256-01.js | 2800 | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* 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 JavaScript Engine testing utilities.
*
* The Initial Developer of the Original Code is
* Mozilla Foundation.
* Portions created by the Initial Developer are Copyright (C) 2006
* the Initial Developer. All Rights Reserved.
*
* Contributor(s): Bertrand Le Roy
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
//-----------------------------------------------------------------------------
var BUGNUMBER = 350256;
var summary = 'Array.apply maximum arguments: 2^16';
var actual = '';
var expect = '';
//-----------------------------------------------------------------------------
test(Math.pow(2, 16));
//-----------------------------------------------------------------------------
function test(length)
{
enterFunc ('test');
printBugNumber(BUGNUMBER);
printStatus (summary);
var a = new Array();
a[length - 2] = 'length-2';
a[length - 1] = 'length-1';
var b = Array.apply(null, a);
expect = length + ',length-2,length-1';
actual = b.length + "," + b[length - 2] + "," + b[length - 1];
reportCompare(expect, actual, summary);
function f() {
return arguments.length + "," + arguments[length - 2] + "," +
arguments[length - 1];
}
expect = length + ',length-2,length-1';
actual = f.apply(null, a);
reportCompare(expect, actual, summary);
exitFunc ('test');
}
| gpl-2.0 |
Esleelkartea/kz-adeada-talleres-electricos- | kzadeadatallereselectricos_v1.0.0_win32_installer/windows/xampp/php/PEAR/I18Nv2/Country/el.php | 9891 | <?php
/**
* $Id: el.php,v 1.8 2005/10/03 15:07:18 mike Exp $
*/
$this->codes = array(
'AD' => 'Ανδόρα',
'AE' => 'Ηνωμένα Αραβικά Εμιράτα',
'AF' => 'Αφγανιστάν',
'AG' => 'Αντίγκουα και Μπαρμπούντα',
'AI' => 'Ανγκουίλα',
'AL' => 'Αλβανία',
'AM' => 'Αρμενία',
'AN' => 'Ολλανδικές Αντίλλες',
'AO' => 'Ανγκόλα',
'AQ' => 'Ανταρκτική',
'AR' => 'Αργεντινή',
'AS' => 'Αμερικανική Σαμόα',
'AT' => 'Αυστρία',
'AU' => 'Αυστραλία',
'AW' => 'Αρούμπα',
'AX' => 'Νήσοι Aland',
'AZ' => 'Αζερμπαϊτζάν',
'BA' => 'Βοσνία - Ερζεγοβίνη',
'BB' => 'Μπαρμπάντος',
'BD' => 'Μπανγκλαντές',
'BE' => 'Βέλγιο',
'BF' => 'Μπουρκίνα Φάσο',
'BG' => 'Βουλγαρία',
'BH' => 'Μπαχρέιν',
'BI' => 'Μπουρούντι',
'BJ' => 'Μπένιν',
'BM' => 'Βερμούδες',
'BN' => 'Μπρουνέι Νταρουσαλάμ',
'BO' => 'Βολιβία',
'BQ' => 'British Antarctic Territory',
'BR' => 'Βραζιλία',
'BS' => 'Μπαχάμες',
'BT' => 'Μπουτάν',
'BV' => 'Νήσος Μπουβέ',
'BW' => 'Μποτσουάνα',
'BY' => 'Λευκορωσία',
'BZ' => 'Μπελίζ',
'CA' => 'Καναδάς',
'CC' => 'Νήσοι Κόκος (Κήλινγκ)',
'CD' => 'Κονγκό, Λαϊκή Δημοκρατία του',
'CF' => 'Κεντροαφρικανική Δημοκρατία',
'CG' => 'Κονγκό',
'CH' => 'Ελβετία',
'CI' => 'Ακτή Ελεφαντόδοντος',
'CK' => 'Νήσοι Κουκ',
'CL' => 'Χιλή',
'CM' => 'Καμερούν',
'CN' => 'Κίνα',
'CO' => 'Κολομβία',
'CR' => 'Κόστα Ρίκα',
'CS' => 'Σερβία και Μαυροβούνιο',
'CT' => 'Canton and Enderbury Islands',
'CU' => 'Κούβα',
'CV' => 'Νήσοι Πράσινου Ακρωτηρίου',
'CX' => 'Νήσος Χριστουγέννων',
'CY' => 'Κύπρος',
'CZ' => 'Τσεχία',
'DD' => 'East Germany',
'DE' => 'Γερμανία',
'DJ' => 'Τζιμπουτί',
'DK' => 'Δανία',
'DM' => 'Ντομίνικα',
'DO' => 'Δομινικανή Δημοκρατία',
'DZ' => 'Αλγερία',
'EC' => 'Ισημερινός',
'EE' => 'Εσθονία',
'EG' => 'Αίγυπτος',
'EH' => 'Δυτική Σαχάρα',
'ER' => 'Ερυθραία',
'ES' => 'Ισπανία',
'ET' => 'Αιθιοπία',
'FI' => 'Φινλανδία',
'FJ' => 'Φίτζι',
'FK' => 'Νήσοι Φώκλαντ',
'FM' => 'Μικρονησία, Ομόσπονδες Πολιτείες της',
'FO' => 'Νήσοι Φερόες',
'FQ' => 'French Southern and Antarctic Territories',
'FR' => 'Γαλλία',
'FX' => 'Metropolitan France',
'GA' => 'Γκαμπόν',
'GB' => 'Ηνωμένο Βασίλειο',
'GD' => 'Γρενάδα',
'GE' => 'Γεωργία',
'GF' => 'Γαλλική Γουιάνα',
'GH' => 'Γκάνα',
'GI' => 'Γιβραλτάρ',
'GL' => 'Γροιλανδία',
'GM' => 'Γκάμπια',
'GN' => 'Γουινέα',
'GP' => 'Γουαδελούπη',
'GQ' => 'Ισημερινή Γουινέα',
'GR' => 'Ελλάδα',
'GS' => 'Νότια Γεωργία και Νήσοι Νότιες Σάντουιτς',
'GT' => 'Γουατεμάλα',
'GU' => 'Γκουάμ',
'GW' => 'Γουινέα-Μπισάου',
'GY' => 'Γουιάνα',
'HK' => 'Χονγκ Κονγκ, Ειδική Διοικητική Περιφέρεια της Κίνας',
'HM' => 'Νήσοι Χερντ και Μακντόναλντ',
'HN' => 'Ονδούρα',
'HR' => 'Κροατία',
'HT' => 'Αϊτή',
'HU' => 'Ουγγαρία',
'ID' => 'Ινδονησία',
'IE' => 'Ιρλανδία',
'IL' => 'Ισραήλ',
'IN' => 'Ινδία',
'IO' => 'Βρετανικά Έδάφη Ινδικού Ωκεανού',
'IQ' => 'Ιράκ',
'IR' => 'Ιράν, Ισλαμική Δημοκρατία του',
'IS' => 'Ισλανδία',
'IT' => 'Ιταλία',
'JM' => 'Τζαμάικα',
'JO' => 'Ιορδανία',
'JP' => 'Ιαπωνία',
'JT' => 'Johnston Island',
'KE' => 'Κένυα',
'KG' => 'Κιργιζία',
'KH' => 'Καμπότζη',
'KI' => 'Κιριμπάτι',
'KM' => 'Κομόρες',
'KN' => 'Σαιντ Κιτς και Νέβις',
'KP' => 'Κορέα, Βόρεια',
'KR' => 'Κορέα, Νότια',
'KW' => 'Κουβέιτ',
'KY' => 'Νήσοι Κέιμαν',
'KZ' => 'Καζακστάν',
'LA' => 'Λατινική Αμερική',
'LB' => 'Λίβανος',
'LC' => 'Αγία Λουκία',
'LI' => 'Λιχτενστάιν',
'LK' => 'Σρι Λάνκα',
'LR' => 'Λιβερία',
'LS' => 'Λεσότο',
'LT' => 'Λιθουανία',
'LU' => 'Λουξεμβούργο',
'LV' => 'Λετονία',
'LY' => 'Λιβύη',
'MA' => 'Μαρόκο',
'MC' => 'Μονακό',
'MD' => 'Μολδαβία, Δημοκρατία της',
'MG' => 'Μαδαγασκάρη',
'MH' => 'Νήσοι Μάρσαλ',
'MI' => 'Midway Islands',
'MK' => 'ΠΓΔ Μακεδονίας',
'ML' => 'Μάλι',
'MM' => 'Μιανμάρ',
'MN' => 'Μογγολία',
'MO' => 'Μακάο, Ειδική Διοικητική Περιφέρεια της Κίνας',
'MP' => 'Νήσοι Βόρειες Μαριάνες',
'MQ' => 'Μαρτινίκα',
'MR' => 'Μαυριτανία',
'MS' => 'Μονσεράτ',
'MT' => 'Μάλτα',
'MU' => 'Μαυρίκιος',
'MV' => 'Μαλδίβες',
'MW' => 'Μαλάουι',
'MX' => 'Μεξικό',
'MY' => 'Μαλαισία',
'MZ' => 'Μοζαμβίκη',
'NA' => 'Ναμίμπια',
'NC' => 'Νέα Καληδονία',
'NE' => 'Νίγηρ',
'NF' => 'Νήσος Νόρφολκ',
'NG' => 'Νιγηρία',
'NI' => 'Νικαράγουα',
'NL' => 'Ολλανδία',
'NO' => 'Νορβηγία',
'NP' => 'Νεπάλ',
'NQ' => 'Dronning Maud Land',
'NR' => 'Ναούρου',
'NT' => 'Neutral Zone',
'NU' => 'Νιούε',
'NZ' => 'Νέα Ζηλανδία',
'OM' => 'Ομάν',
'PA' => 'Παναμάς',
'PC' => 'Pacific Islands Trust Territory',
'PE' => 'Περού',
'PF' => 'Γαλλική Πολυνησία',
'PG' => 'Παπούα - Νέα Γουινέα',
'PH' => 'Φιλιππίνες',
'PK' => 'Πακιστάν',
'PL' => 'Πολωνία',
'PM' => 'Σαιντ Πιέρ και Μικελόν',
'PN' => 'Πίτκερν',
'PR' => 'Πουέρτο Ρίκο',
'PS' => 'Παλαιστινιακά Εδάφη',
'PT' => 'Πορτογαλία',
'PU' => 'U.S. Miscellaneous Pacific Islands',
'PW' => 'Παλάου',
'PY' => 'Παραγουάη',
'PZ' => 'Panama Canal Zone',
'QA' => 'Κατάρ',
'QO' => 'Περιφερειακή Ωκεανία',
'RE' => 'Ρεϋνιόν',
'RO' => 'Ρουμανία',
'RU' => 'Ρωσία',
'RW' => 'Ρουάντα',
'SA' => 'Σαουδική Αραβία',
'SB' => 'Νήσοι Σολομώντος',
'SC' => 'Σεϋχέλλες',
'SD' => 'Σουδάν',
'SE' => 'Σουηδία',
'SG' => 'Σιγκαπούρη',
'SH' => 'Αγία Ελένη',
'SI' => 'Σλοβενία',
'SJ' => 'Νήσοι Σβάλμπαρ και Γιαν Μαγιέν',
'SK' => 'Σλοβακία',
'SL' => 'Σιέρα Λεόνε',
'SM' => 'Άγιος Μαρίνος',
'SN' => 'Σενεγάλη',
'SO' => 'Σομαλία',
'SR' => 'Σουρινάμ',
'ST' => 'Σάο Τομέ και Πρίνσιπε',
'SU' => 'Union of Soviet Socialist Republics',
'SV' => 'Ελ Σαλβαδόρ',
'SY' => 'Συρία, Αραβική Δημοκρατία της',
'SZ' => 'Σουαζιλάνδη',
'TC' => 'Νήσοι Τερκς και Κάικος',
'TD' => 'Τσαντ',
'TF' => 'Γαλλικά Νότια Εδάφη',
'TG' => 'Τόγκο',
'TH' => 'Ταϊλάνδη',
'TJ' => 'Τατζικιστάν',
'TK' => 'Τοκελάου',
'TL' => 'Ανατολικό Τιμόρ',
'TM' => 'Τουρκμενιστάν',
'TN' => 'Τυνησία',
'TO' => 'Τόνγκα',
'TR' => 'Τουρκία',
'TT' => 'Τρινιδάδ και Τομπάγκο',
'TV' => 'Τουβαλού',
'TW' => 'Ταϊβάν',
'TZ' => 'Τανζανία',
'UA' => 'Ουκρανία',
'UG' => 'Ουγκάντα',
'UM' => 'Απομακρυσμένες Νησίδες των Ηνωμένων Πολιτειών',
'US' => 'Ηνωμένες Πολιτείες',
'UY' => 'Ουρουγουάη',
'UZ' => 'Ουζμπεκιστάν',
'VA' => 'Αγία Έδρα (Βατικανό)',
'VC' => 'Άγιος Βικέντιος και Γρεναδίνες',
'VD' => 'North Vietnam',
'VE' => 'Βενεζουέλα',
'VG' => 'Βρετανικές Παρθένοι Νήσοι',
'VI' => 'Αμερικανικές Παρθένοι Νήσοι',
'VN' => 'Βιετνάμ',
'VU' => 'Βανουάτου',
'WF' => 'Νήσοι Ουαλλίς και Φουτουνά',
'WK' => 'Wake Island',
'WS' => 'Σαμόα',
'YD' => 'People\'s Democratic Republic of Yemen',
'YE' => 'Υεμένη',
'YT' => 'Μαγιότ',
'ZA' => 'Νότια Αφρική',
'ZM' => 'Ζάμπια',
'ZW' => 'Ζιμπάμπουε',
);
?>
| gpl-2.0 |
YouDiSN/OpenJDK-Research | jdk9/langtools/src/java.compiler/share/classes/javax/lang/model/util/ElementFilter.java | 11831 | /*
* Copyright (c) 2005, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.lang.model.util;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.EnumSet;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import javax.lang.model.element.*;
import javax.lang.model.element.ModuleElement.Directive;
import javax.lang.model.element.ModuleElement.DirectiveKind;
import javax.lang.model.element.ModuleElement.ExportsDirective;
import javax.lang.model.element.ModuleElement.OpensDirective;
import javax.lang.model.element.ModuleElement.ProvidesDirective;
import javax.lang.model.element.ModuleElement.RequiresDirective;
import javax.lang.model.element.ModuleElement.UsesDirective;
/**
* Filters for selecting just the elements of interest from a
* collection of elements. The returned sets and lists are new
* collections and do use the argument as a backing store. The
* methods in this class do not make any attempts to guard against
* concurrent modifications of the arguments. The returned sets and
* lists are mutable but unsafe for concurrent access. A returned set
* has the same iteration order as the argument set to a method.
*
* <p>If iterables and sets containing {@code null} are passed as
* arguments to methods in this class, a {@code NullPointerException}
* will be thrown.
*
* @author Joseph D. Darcy
* @author Scott Seligman
* @author Peter von der Ahé
* @author Martin Buchholz
* @since 1.6
*/
public class ElementFilter {
private ElementFilter() {} // Do not instantiate.
private static final Set<ElementKind> CONSTRUCTOR_KIND =
Collections.unmodifiableSet(EnumSet.of(ElementKind.CONSTRUCTOR));
private static final Set<ElementKind> FIELD_KINDS =
Collections.unmodifiableSet(EnumSet.of(ElementKind.FIELD,
ElementKind.ENUM_CONSTANT));
private static final Set<ElementKind> METHOD_KIND =
Collections.unmodifiableSet(EnumSet.of(ElementKind.METHOD));
private static final Set<ElementKind> PACKAGE_KIND =
Collections.unmodifiableSet(EnumSet.of(ElementKind.PACKAGE));
private static final Set<ElementKind> MODULE_KIND =
Collections.unmodifiableSet(EnumSet.of(ElementKind.MODULE));
private static final Set<ElementKind> TYPE_KINDS =
Collections.unmodifiableSet(EnumSet.of(ElementKind.CLASS,
ElementKind.ENUM,
ElementKind.INTERFACE,
ElementKind.ANNOTATION_TYPE));
/**
* Returns a list of fields in {@code elements}.
* @return a list of fields in {@code elements}
* @param elements the elements to filter
*/
public static List<VariableElement>
fieldsIn(Iterable<? extends Element> elements) {
return listFilter(elements, FIELD_KINDS, VariableElement.class);
}
/**
* Returns a set of fields in {@code elements}.
* @return a set of fields in {@code elements}
* @param elements the elements to filter
*/
public static Set<VariableElement>
fieldsIn(Set<? extends Element> elements) {
return setFilter(elements, FIELD_KINDS, VariableElement.class);
}
/**
* Returns a list of constructors in {@code elements}.
* @return a list of constructors in {@code elements}
* @param elements the elements to filter
*/
public static List<ExecutableElement>
constructorsIn(Iterable<? extends Element> elements) {
return listFilter(elements, CONSTRUCTOR_KIND, ExecutableElement.class);
}
/**
* Returns a set of constructors in {@code elements}.
* @return a set of constructors in {@code elements}
* @param elements the elements to filter
*/
public static Set<ExecutableElement>
constructorsIn(Set<? extends Element> elements) {
return setFilter(elements, CONSTRUCTOR_KIND, ExecutableElement.class);
}
/**
* Returns a list of methods in {@code elements}.
* @return a list of methods in {@code elements}
* @param elements the elements to filter
*/
public static List<ExecutableElement>
methodsIn(Iterable<? extends Element> elements) {
return listFilter(elements, METHOD_KIND, ExecutableElement.class);
}
/**
* Returns a set of methods in {@code elements}.
* @return a set of methods in {@code elements}
* @param elements the elements to filter
*/
public static Set<ExecutableElement>
methodsIn(Set<? extends Element> elements) {
return setFilter(elements, METHOD_KIND, ExecutableElement.class);
}
/**
* Returns a list of types in {@code elements}.
* @return a list of types in {@code elements}
* @param elements the elements to filter
*/
public static List<TypeElement>
typesIn(Iterable<? extends Element> elements) {
return listFilter(elements, TYPE_KINDS, TypeElement.class);
}
/**
* Returns a set of types in {@code elements}.
* @return a set of types in {@code elements}
* @param elements the elements to filter
*/
public static Set<TypeElement>
typesIn(Set<? extends Element> elements) {
return setFilter(elements, TYPE_KINDS, TypeElement.class);
}
/**
* Returns a list of packages in {@code elements}.
* @return a list of packages in {@code elements}
* @param elements the elements to filter
*/
public static List<PackageElement>
packagesIn(Iterable<? extends Element> elements) {
return listFilter(elements, PACKAGE_KIND, PackageElement.class);
}
/**
* Returns a set of packages in {@code elements}.
* @return a set of packages in {@code elements}
* @param elements the elements to filter
*/
public static Set<PackageElement>
packagesIn(Set<? extends Element> elements) {
return setFilter(elements, PACKAGE_KIND, PackageElement.class);
}
/**
* Returns a list of modules in {@code elements}.
* @return a list of modules in {@code elements}
* @param elements the elements to filter
* @since 9
* @spec JPMS
*/
public static List<ModuleElement>
modulesIn(Iterable<? extends Element> elements) {
return listFilter(elements, MODULE_KIND, ModuleElement.class);
}
/**
* Returns a set of modules in {@code elements}.
* @return a set of modules in {@code elements}
* @param elements the elements to filter
* @since 9
* @spec JPMS
*/
public static Set<ModuleElement>
modulesIn(Set<? extends Element> elements) {
return setFilter(elements, MODULE_KIND, ModuleElement.class);
}
// Assumes targetKinds and E are sensible.
private static <E extends Element> List<E> listFilter(Iterable<? extends Element> elements,
Set<ElementKind> targetKinds,
Class<E> clazz) {
List<E> list = new ArrayList<>();
for (Element e : elements) {
if (targetKinds.contains(e.getKind()))
list.add(clazz.cast(e));
}
return list;
}
// Assumes targetKinds and E are sensible.
private static <E extends Element> Set<E> setFilter(Set<? extends Element> elements,
Set<ElementKind> targetKinds,
Class<E> clazz) {
// Return set preserving iteration order of input set.
Set<E> set = new LinkedHashSet<>();
for (Element e : elements) {
if (targetKinds.contains(e.getKind()))
set.add(clazz.cast(e));
}
return set;
}
/**
* Returns a list of {@code exports} directives in {@code directives}.
* @return a list of {@code exports} directives in {@code directives}
* @param directives the directives to filter
* @since 9
* @spec JPMS
*/
public static List<ExportsDirective>
exportsIn(Iterable<? extends Directive> directives) {
return listFilter(directives, DirectiveKind.EXPORTS, ExportsDirective.class);
}
/**
* Returns a list of {@code opens} directives in {@code directives}.
* @return a list of {@code opens} directives in {@code directives}
* @param directives the directives to filter
* @since 9
*/
public static List<OpensDirective>
opensIn(Iterable<? extends Directive> directives) {
return listFilter(directives, DirectiveKind.OPENS, OpensDirective.class);
}
/**
* Returns a list of {@code provides} directives in {@code directives}.
* @return a list of {@code provides} directives in {@code directives}
* @param directives the directives to filter
* @since 9
* @spec JPMS
*/
public static List<ProvidesDirective>
providesIn(Iterable<? extends Directive> directives) {
return listFilter(directives, DirectiveKind.PROVIDES, ProvidesDirective.class);
}
/**
* Returns a list of {@code requires} directives in {@code directives}.
* @return a list of {@code requires} directives in {@code directives}
* @param directives the directives to filter
* @since 9
* @spec JPMS
*/
public static List<RequiresDirective>
requiresIn(Iterable<? extends Directive> directives) {
return listFilter(directives, DirectiveKind.REQUIRES, RequiresDirective.class);
}
/**
* Returns a list of {@code uses} directives in {@code directives}.
* @return a list of {@code uses} directives in {@code directives}
* @param directives the directives to filter
* @since 9
* @spec JPMS
*/
public static List<UsesDirective>
usesIn(Iterable<? extends Directive> directives) {
return listFilter(directives, DirectiveKind.USES, UsesDirective.class);
}
// Assumes directiveKind and D are sensible.
private static <D extends Directive> List<D> listFilter(Iterable<? extends Directive> directives,
DirectiveKind directiveKind,
Class<D> clazz) {
List<D> list = new ArrayList<>();
for (Directive d : directives) {
if (d.getKind() == directiveKind)
list.add(clazz.cast(d));
}
return list;
}
}
| gpl-2.0 |
langbat/Wordpress-Backbone-JS | wp-content/plugins/wysija-newsletters/views/back/tmce.php | 3991 | <?php
defined('WYSIJA') or die('Restricted access');
class WYSIJA_view_back_tmce extends WYSIJA_view_back{
var $title='Tiny';
var $icon='icon-options-general';
var $scripts=array();
function WYSIJA_view_back_tmce(){
$this->WYSIJA_view_back();
}
function getScriptsStyles(){
?>
<link rel='stylesheet' href='<?php $urlblog=get_bloginfo('wpurl');echo $urlblog ?>/wp-admin/load-styles.php?c=1&dir=ltr&load=widgets,global,wp-admin' type='text/css' media='all' />
<link rel='stylesheet' id='colors-css' href='<?php echo $urlblog ?>/wp-admin/css/colors-fresh.css' type='text/css' media='all' />
<link rel='stylesheet' id='colors-css' href='<?php echo $urlblog ?>/wp-includes/css/buttons.css' type='text/css' media='all' />
<!--[if lte IE 7]>
<link rel='stylesheet' id='ie-css' href='<?php echo $urlblog ?>/wp-admin/css/ie.css' type='text/css' media='all' />
<![endif]-->
<link rel='stylesheet' href='<?php echo $urlblog ?>/wp-content/plugins/wysija-newsletters/css/tmce/widget.css' type='text/css' media='all' />
<?php wp_print_scripts('jquery'); ?>
<script type="text/javascript" src="<?php echo $urlblog; ?>/wp-includes/js/tinymce/tiny_mce_popup.js"></script>
<script type='text/javascript' src='<?php echo $urlblog ?>/wp-content/plugins/wysija-newsletters/js/admin-tmce.js'></script>
<?php
}
function head(){
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title><?php echo $this->title; ?></title>
<?php $this->getScriptsStyles() ?>
<base target="_self" />
</head>
<body>
<?php
}
function foot(){
?>
</body>
</html>
<?php
}
function subscribersAdd($data){
$this->head();
?>
<form id="formTable" action="" style="display:block;" class="wp-core-ui" method="post" >
<div id="subscriber-ccount-form">
<select id="wysija-list">
<option value="0">All</option>
<?php foreach ($data['lists'] as $list){ ?>
<option value="<?php echo $list['list_id']; ?>"><?php echo $list['name']; ?></option>
<?php } ?>
</select>
<?php if ($data['confirm_dbleoptin']) {?>
<br /><br />
<input type="checkbox" id="confirmedSubscribers"/><label><?php echo esc_attr(__('Confirmed subscribers only', WYSIJA)); ?></label>
<?php } ?>
<br /><br />
<input type="submit" id="subscribers-insert" class="button-primary action" name="doaction" value="<?php echo esc_attr(__('Insert', WYSIJA)); ?>">
</div>
<div style="clear:both;"></div>
</form>
<?php
$this->foot();
}
function registerAdd($datawidget){
$this->head();
?>
<form id="formTable" action="" style="display:block;" class="wp-core-ui" method="post" >
<div id="widget-form">
<?php
require_once(WYSIJA_WIDGETS.'wysija_nl.php');
$widgetNL=new WYSIJA_NL_Widget(true);
$widgetNL->form($datawidget);
?>
<input type="hidden" name="widget_id" value="wysija-nl-<?php echo time(); ?>" />
<input type="submit" id="widget-insert" class="button-primary action" name="doaction" value="<?php echo esc_attr(__('Insert form', WYSIJA)); ?>">
</div>
<div style="clear:both;"></div>
</form>
<?php
$this->foot();
}
}
| gpl-2.0 |
bSr43/scummvm | backends/cloud/downloadrequest.cpp | 4567 | /* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include "backends/cloud/downloadrequest.h"
#include "backends/networking/curl/connectionmanager.h"
#include "common/textconsole.h"
namespace Cloud {
DownloadRequest::DownloadRequest(Storage *storage, Storage::BoolCallback callback, Networking::ErrorCallback ecb, Common::String remoteFileId, Common::DumpFile *dumpFile):
Request(nullptr, ecb), _boolCallback(callback), _localFile(dumpFile), _remoteFileId(remoteFileId), _storage(storage),
_remoteFileStream(nullptr), _workingRequest(nullptr), _ignoreCallback(false), _buffer(new byte[DOWNLOAD_REQUEST_BUFFER_SIZE]) {
start();
}
DownloadRequest::~DownloadRequest() {
_ignoreCallback = true;
if (_workingRequest)
_workingRequest->finish();
delete _boolCallback;
delete _localFile;
delete[] _buffer;
}
void DownloadRequest::start() {
_ignoreCallback = true;
if (_workingRequest)
_workingRequest->finish();
_remoteFileStream = nullptr;
//TODO: add some way to reopen DumpFile, so DownloadRequest could be restarted
_ignoreCallback = false;
_workingRequest = _storage->streamFileById(
_remoteFileId,
new Common::Callback<DownloadRequest, Networking::NetworkReadStreamResponse>(this, &DownloadRequest::streamCallback),
new Common::Callback<DownloadRequest, Networking::ErrorResponse>(this, &DownloadRequest::streamErrorCallback)
);
}
void DownloadRequest::streamCallback(Networking::NetworkReadStreamResponse response) {
_workingRequest = nullptr;
if (_ignoreCallback)
return;
_remoteFileStream = (Networking::NetworkReadStream *)response.value;
}
void DownloadRequest::streamErrorCallback(Networking::ErrorResponse error) {
_workingRequest = nullptr;
if (_ignoreCallback)
return;
finishError(error);
}
void DownloadRequest::handle() {
if (!_localFile) {
warning("DownloadRequest: no file to write");
finishError(Networking::ErrorResponse(this, false, true, "", -1));
return;
}
if (!_localFile->isOpen()) {
warning("DownloadRequest: failed to open file to write");
finishError(Networking::ErrorResponse(this, false, true, "", -1));
return;
}
if (!_remoteFileStream) {
//waiting for callback
return;
}
uint32 readBytes = _remoteFileStream->read(_buffer, DOWNLOAD_REQUEST_BUFFER_SIZE);
if (readBytes != 0)
if (_localFile->write(_buffer, readBytes) != readBytes) {
warning("DownloadRequest: unable to write all received bytes into output file");
finishError(Networking::ErrorResponse(this, false, true, "", -1));
return;
}
if (_remoteFileStream->eos()) {
if (_remoteFileStream->httpResponseCode() != 200) {
warning("DownloadRequest: HTTP response code is not 200 OK (it's %ld)", _remoteFileStream->httpResponseCode());
//TODO: do something about it actually
// the problem is file's already downloaded, stream is over
// so we can't return error message anymore
}
finishDownload(_remoteFileStream->httpResponseCode() == 200);
_localFile->close(); //yes, I know it's closed automatically in ~DumpFile()
}
}
void DownloadRequest::restart() {
warning("DownloadRequest: can't restart as there are no means to reopen DumpFile");
finishError(Networking::ErrorResponse(this, false, true, "", -1));
//start();
}
void DownloadRequest::finishDownload(bool success) {
Request::finishSuccess();
if (_boolCallback)
(*_boolCallback)(Storage::BoolResponse(this, success));
}
void DownloadRequest::finishError(Networking::ErrorResponse error) {
if (_localFile)
_localFile->close();
Request::finishError(error);
}
double DownloadRequest::getProgress() const {
if (_remoteFileStream)
return _remoteFileStream->getProgress();
return 0;
}
} // End of namespace Cloud
| gpl-2.0 |
qmwu2000/disconf | disconf-client/src/main/java/com/baidu/disconf/client/common/update/IDisconfUpdate.java | 265 | package com.baidu.disconf.client.common.update;
/**
* 当配置更新 时,用户可以实现此接口,用以来实现回调函数
*
* @author liaoqiqi
* @version 2014-5-20
*/
public interface IDisconfUpdate {
public void reload() throws Exception;
}
| gpl-2.0 |
Nadahar/UniversalMediaServer | src/test/java/net/pms/formats/v2/SubtitleTypeTest.java | 8624 | /*
* PS3 Media Server, for streaming any medias to your PS3.
* Copyright (C) 2012 I. Sokolov
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; version 2
* of the License only.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package net.pms.formats.v2;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import static net.pms.formats.v2.SubtitleType.*;
import static org.assertj.core.api.Assertions.*;
import org.junit.Test;
public class SubtitleTypeTest {
@Test
public void testValueOfFileExtension_matchingExtensions() throws Exception {
assertThat(valueOfFileExtension("srt")).isEqualTo(SUBRIP);
assertThat(valueOfFileExtension("txt")).isEqualTo(TEXT);
assertThat(valueOfFileExtension("sub")).isEqualTo(MICRODVD);
assertThat(valueOfFileExtension("smi")).isEqualTo(SAMI);
assertThat(valueOfFileExtension("ssa")).isEqualTo(ASS);
assertThat(valueOfFileExtension("ass")).isEqualTo(ASS);
assertThat(valueOfFileExtension("idx")).isEqualTo(VOBSUB);
assertThat(valueOfFileExtension("vtt")).isEqualTo(WEBVTT);
}
@Test
public void testValueOfLibMediaInfoCodec_matchingCodecs() throws Exception {
assertThat(valueOfLibMediaInfoCodec("s_utf8")).isEqualTo(SUBRIP);
assertThat(valueOfLibMediaInfoCodec("S_TEXT/UTF8")).isEqualTo(SUBRIP);
assertThat(valueOfLibMediaInfoCodec("Subrip")).isEqualTo(SUBRIP);
assertThat(valueOfLibMediaInfoCodec("s_ssa")).isEqualTo(ASS);
assertThat(valueOfLibMediaInfoCodec("s_ass")).isEqualTo(ASS);
assertThat(valueOfLibMediaInfoCodec("S_TEXT/SSA")).isEqualTo(ASS);
assertThat(valueOfLibMediaInfoCodec("S_TEXT/ASS")).isEqualTo(ASS);
assertThat(valueOfLibMediaInfoCodec("SSA")).isEqualTo(ASS);
assertThat(valueOfLibMediaInfoCodec("ASS")).isEqualTo(ASS);
assertThat(valueOfLibMediaInfoCodec("subp")).isEqualTo(VOBSUB);
assertThat(valueOfLibMediaInfoCodec("S_VOBSUB")).isEqualTo(VOBSUB);
assertThat(valueOfLibMediaInfoCodec("mp4s")).isEqualTo(VOBSUB);
assertThat(valueOfLibMediaInfoCodec("E0")).isEqualTo(VOBSUB);
assertThat(valueOfLibMediaInfoCodec("s_usf")).isEqualTo(USF);
assertThat(valueOfLibMediaInfoCodec("S_TEXT/USF")).isEqualTo(USF);
assertThat(valueOfLibMediaInfoCodec("S_IMAGE/BMP")).isEqualTo(BMP);
assertThat(valueOfLibMediaInfoCodec("DXSB")).isEqualTo(DIVX);
assertThat(valueOfLibMediaInfoCodec("tx3g")).isEqualTo(TX3G);
assertThat(valueOfLibMediaInfoCodec("pgs")).isEqualTo(PGS);
assertThat(valueOfLibMediaInfoCodec("S_HDMV/PGS")).isEqualTo(PGS);
assertThat(valueOfLibMediaInfoCodec("144")).isEqualTo(PGS);
assertThat(valueOfLibMediaInfoCodec("WebVTT")).isEqualTo(WEBVTT);
}
@Test
public void testGetDescription() throws Exception {
assertThat(UNKNOWN.getDescription()).isEqualTo("Generic");
assertThat(UNSUPPORTED.getDescription()).isEqualTo("Unsupported");
assertThat(SUBRIP.getDescription()).isEqualTo("SubRip");
assertThat(TEXT.getDescription()).isEqualTo("Text file");
assertThat(MICRODVD.getDescription()).isEqualTo("MicroDVD");
assertThat(SAMI.getDescription()).isEqualTo("SAMI");
assertThat(ASS.getDescription()).isEqualTo("(Advanced) SubStation Alpha");
assertThat(VOBSUB.getDescription()).isEqualTo("VobSub");
assertThat(USF.getDescription()).isEqualTo("Universal Subtitle Format");
assertThat(BMP.getDescription()).isEqualTo("BMP");
assertThat(DIVX.getDescription()).isEqualTo("DIVX subtitles");
assertThat(TX3G.getDescription()).isEqualTo("Timed text (TX3G)");
assertThat(PGS.getDescription()).isEqualTo("Blu-ray subtitles");
}
@Test
public void testGetExtension() throws Exception {
assertThat(UNKNOWN.getExtension()).isEqualTo("");
assertThat(SUBRIP.getExtension()).isEqualTo("srt");
assertThat(TEXT.getExtension()).isEqualTo("txt");
assertThat(MICRODVD.getExtension()).isEqualTo("sub");
assertThat(SAMI.getExtension()).isEqualTo("smi");
assertThat(ASS.getExtension()).isEqualTo("ass");
assertThat(VOBSUB.getExtension()).isEqualTo("idx");
assertThat(UNSUPPORTED.getExtension()).isEqualTo("");
assertThat(WEBVTT.getExtension()).isEqualTo("vtt");
}
@Test
public void testValueOfFileExtension_nullOrBlankExtension() throws Exception {
assertThat(valueOfFileExtension(null)).isEqualTo(UNKNOWN);
assertThat(valueOfFileExtension("")).isEqualTo(UNKNOWN);
}
@Test
public void testValueOfLibMediaInfoCodec_nullOrBlankCodec() throws Exception {
assertThat(valueOfLibMediaInfoCodec(null)).isEqualTo(UNKNOWN);
assertThat(valueOfLibMediaInfoCodec("")).isEqualTo(UNKNOWN);
}
@Test
public void testValueOfFileExtension_unknownExtension() throws Exception {
assertThat(valueOfFileExtension("xyz")).isEqualTo(UNKNOWN);
}
@Test
public void testValueOfLibMediaInfoCodec_unknownCodec() throws Exception {
assertThat(valueOfLibMediaInfoCodec("xyz")).isEqualTo(UNKNOWN);
}
@Test
public void testValueOfFileExtension_extensionCaseInsensitivity() throws Exception {
assertThat(valueOfFileExtension("ssA")).isEqualTo(ASS);
assertThat(valueOfFileExtension("SSA")).isEqualTo(ASS);
assertThat(valueOfFileExtension("sSa")).isEqualTo(ASS);
}
@Test
public void testValueOfLibMediaInfoCodec_CodecInsensitivity() throws Exception {
assertThat(valueOfLibMediaInfoCodec("s_TeXT/UtF8")).isEqualTo(SUBRIP);
}
@Test
public void testValueOfLibMediaInfoCodec_CodecWithExtraSpaces() throws Exception {
assertThat(valueOfLibMediaInfoCodec("s_utf8 ")).isEqualTo(SUBRIP);
assertThat(valueOfLibMediaInfoCodec(" s_utf8")).isEqualTo(SUBRIP);
assertThat(valueOfLibMediaInfoCodec(" s_utf8 ")).isEqualTo(SUBRIP);
}
@Test
public void testValueOfLibMediaInfoCodec_SubstringShouldNotMatch() throws Exception {
assertThat(valueOfLibMediaInfoCodec("S_TEXT/SSA2")).isEqualTo(UNKNOWN);
assertThat(valueOfLibMediaInfoCodec("ps_utf8")).isEqualTo(UNKNOWN);
}
@Test
public void getSupportedFileExtensions() {
Set<String> expectedExtensionsSet = new HashSet<>(Arrays.asList("srt", "txt", "sub", "smi", "ssa", "ass", "idx", "vtt"));
assertThat(SubtitleType.getSupportedFileExtensions()).isEqualTo(expectedExtensionsSet);
}
@Test
public void testGetStableIndex() {
assertThat(UNKNOWN.getStableIndex()).isEqualTo(0);
assertThat(SUBRIP.getStableIndex()).isEqualTo(1);
assertThat(TEXT.getStableIndex()).isEqualTo(2);
assertThat(MICRODVD.getStableIndex()).isEqualTo(3);
assertThat(SAMI.getStableIndex()).isEqualTo(4);
assertThat(ASS.getStableIndex()).isEqualTo(5);
assertThat(VOBSUB.getStableIndex()).isEqualTo(6);
assertThat(UNSUPPORTED.getStableIndex()).isEqualTo(7);
assertThat(USF.getStableIndex()).isEqualTo(8);
assertThat(BMP.getStableIndex()).isEqualTo(9);
assertThat(DIVX.getStableIndex()).isEqualTo(10);
assertThat(TX3G.getStableIndex()).isEqualTo(11);
assertThat(PGS.getStableIndex()).isEqualTo(12);
assertThat(WEBVTT.getStableIndex()).isEqualTo(13);
}
@Test
public void testGetStableIndex_uniqueness() {
Set<Integer> stableIndexes = new HashSet<>();
for (SubtitleType subtitleType : values()) {
assertThat(stableIndexes.contains(subtitleType.getStableIndex())).isFalse();
stableIndexes.add(subtitleType.getStableIndex());
}
}
@Test
public void testValueOfStableIndex() {
assertThat(valueOfStableIndex(0)).isEqualTo(UNKNOWN);
assertThat(valueOfStableIndex(1)).isEqualTo(SUBRIP);
assertThat(valueOfStableIndex(2)).isEqualTo(TEXT);
assertThat(valueOfStableIndex(3)).isEqualTo(MICRODVD);
assertThat(valueOfStableIndex(4)).isEqualTo(SAMI);
assertThat(valueOfStableIndex(5)).isEqualTo(ASS);
assertThat(valueOfStableIndex(6)).isEqualTo(VOBSUB);
assertThat(valueOfStableIndex(7)).isEqualTo(UNSUPPORTED);
assertThat(valueOfStableIndex(8)).isEqualTo(USF);
assertThat(valueOfStableIndex(9)).isEqualTo(BMP);
assertThat(valueOfStableIndex(10)).isEqualTo(DIVX);
assertThat(valueOfStableIndex(11)).isEqualTo(TX3G);
assertThat(valueOfStableIndex(12)).isEqualTo(PGS);
assertThat(valueOfStableIndex(13)).isEqualTo(WEBVTT);
}
@Test
public void testValueOfStableIndex_unknownIndex() {
assertThat(valueOfStableIndex(-1)).isEqualTo(UNKNOWN);
assertThat(valueOfStableIndex(456)).isEqualTo(UNKNOWN);
}
} | gpl-2.0 |
arrmo/librenms | includes/caches/devices.inc.php | 1622 | <?php
if (Auth::user()->hasGlobalRead()) {
$data['count'] = ['query' => 'SELECT COUNT(*) FROM devices'];
$data['up'] = ['query' => "SELECT COUNT(*) FROM devices WHERE `status` = '1' AND `ignore` = '0' AND `disabled` = '0'"];
$data['down'] = ['query' => "SELECT COUNT(*) FROM devices WHERE `status` = '0' AND `ignore` = '0' AND `disabled` = '0'"];
$data['ignored'] = ['query' => "SELECT COUNT(*) FROM devices WHERE `ignore` = '1' AND `disabled` = '0'"];
$data['disabled'] = ['query' => "SELECT COUNT(*) FROM devices WHERE `disabled` = '1'"];
} else {
$device_ids = Permissions::devicesForUser()->toArray() ?: [0];
$perms_sql = '`D`.`device_id` IN ' . dbGenPlaceholders(count($device_ids));
$data['count'] = [
'query' => 'SELECT COUNT(*) FROM devices AS D WHERE $perms_sql',
'params' => $device_ids,
];
$data['up'] = [
'query' => "SELECT COUNT(*) FROM devices AS D WHERE $perms_sql AND D.`status` = '1' AND D.`ignore` = '0' AND D.`disabled` = '0'",
'params' => $device_ids,
];
$data['down'] = [
'query' => "SELECT COUNT(*) FROM devices AS D WHERE $perms_sql AND D.`status` = '0' AND D.`ignore` = '0' AND D.`disabled` = '0'",
'params' => $device_ids,
];
$data['ignored'] = [
'query' => "SELECT COUNT(*) FROM devices AS D WHERE $perms_sql AND D.`ignore` = '1' AND D.`disabled` = '0'",
'params' => $device_ids,
];
$data['disabled'] = [
'query' => "SELECT COUNT(*) FROM devices AS D WHERE $perms_sql AND D.`disabled` = '1'",
'params' => $device_ids,
];
}//end if
| gpl-3.0 |
ivan73/smarthome | examples/old/js/smarthome.js | 18501 | // vim: set encoding=utf-8 tabstop=4 softtabstop=4 shiftwidth=4 expandtab
//########################################################################
// Copyright 2012-2013 KNX-User-Forum e.V. http://knx-user-forum.de/
//########################################################################
// This file is part of SmartHome.py. http://smarthome.sourceforge.net/
//
// SmartHome.py is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// SmartHome.py is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with SmartHome.py. If not, see <http://www.gnu.org/licenses/>.
//########################################################################
var shVersion = '0.9';
var shProto = 2;
var shWS = false; // WebSocket
var shLock = false;
var shRRD = {};
var shLog = {};
var shURL = '';
var shBuffer = {};
var shOpt = {};
var shMonitor = [];
// little helper functions
Array.prototype.diff = function(a) {
return this.filter(function(i) {return !(a.indexOf(i) > -1);});
};
function shUnique(arr) {
arr = arr.sort();
var ret = [arr[0]];
for (var i = 1; i < arr.length; i++) {
if (arr[i-1] !== arr[i]) {
ret.push(arr[i]);
}
}
return ret;
};
if (typeof String.prototype.startsWith != 'function') {
String.prototype.startsWith = function (str){
return this.slice(0, str.length) == str;
};
}
function shPushCycle(obj, timeout, value) {
shSendPush(obj, value);
$(obj).data('cycle', setTimeout(function(){shPushCycle(obj, timeout, value)}, timeout));
};
function shInit(url) {
// Init WebSocket
shURL = url;
shWsInit();
setTimeout(shWSCheckInit, 2000);
$(window).unload(function(){ shWS.close(); shWS = null });
// Adding Listeners
$(document).on( "pagecreate", function(){
shPageCreate();
});
$(document).on( "pageinit", function(){
shPageInit();
});
$(document).on( "pageshow", function(){
shPageShow();
});
$(document).on("click", 'a[data-logic]', function() { // Button
shTriggerLogic(this);
});
$(document).on("click", 'img[data-logic]', function() { // Logic-Trigger Button
shTriggerLogic(this);
});
$(document).on("click", 'img.switch[data-sh]', function() { // Switch Button
shSwitchButton(this);
});
$(document).on("click", 'img.set[data-sh]', function() { // Send Button
shSendFix(this);
});
$(document).on("vmousedown", 'img.push[data-sh]', function(event) { // Push Button
event.preventDefault();
var value = true;
var cycle = $(this).attr('data-cycle');
if (cycle == undefined) {
cycle = 1000;
} else {
cycle = parseInt(cycle);
};
var arr = $(this).attr('data-arr');
if (arr != undefined) {
value = [parseInt(arr), 1];
};
var path = $(this).attr('data-sh');
shPushCycle(this, cycle, value);
});
$(document).on("vmouseup", 'img.push[data-sh]', function() { // Push Button
clearTimeout($(this).data('cycle'))
var value = false;
var arr = $(this).attr('data-arr');
if (arr != undefined) {
value = [parseInt(arr), 0];
};
var path = $(this).attr('data-sh');
shSendPush(this, value);
});
$(document).on("change", 'select[data-sh]', function() { // Select
shSendSelect(this);
});
$(document).on("change", 'input[data-sh][data-type="range"]', function() { // Slider
shSendNum(this);
});
$(document).on("change", 'input[data-sh][type="time"]', function() { // Time
shSendVal(this);
});
$(document).on("change", 'input[data-sh]:text', function() { // Text
shSendVal(this);
});
$(document).on("change", 'textarea[data-sh]', function() { // Textarea
shSendVal(this);
});
$(document).on("change", 'input[data-sh][type="checkbox"]', function() { // Checkbox
shSendCheckbox(this);
});
$(document).on("change", 'input[data-sh][type="radio"]', function() { // Radio
shSendRadio(this);
});
};
function shLogUpdate(data) {
var obj, max, val;
obj = $('[data-log="' + data.name + '"]');
if (obj.length == 0) {
console.log("unknown log name: "+ data.name);
return;
}
for (var i = 0; i < data.log.length; i++) {
val = data.log[i];
if ('init' in data) { // init
$(obj).html('')
};
for (var j = val.length -1; j >= 0; j--) {
$(obj).prepend(val[j] + "\n")
};
max = $(obj).attr('data-max');
if (max != undefined) {
max = parseInt(max);
while ($(obj).children().length > max) {
$(obj).children().last().remove()
};
};
$(obj).listview('refresh');
};
};
function shRRDUpdate(data) {
var id, time, step, frame, rrds, item, value;
time = data.start * 1000;
step = data.step * 1000;
if (data.frame == 'update') {
// single value
if (data.item in shRRD) {
for (frame in shRRD[data.item]) {
if (shRRD[data.item][frame]['step'] == data.step) {
shRRD[data.item][frame]['series'].shift() // remove 'oldest' element
};
shRRD[data.item][frame]['series'].push([time, data.series[0]]);
};
};
} else {
var series = [];
//{color: 'blue', label: data.label, yaxis: 2, data: []};
for (i = 0; i < data.series.length; i++) {
series.push([time, data.series[i]]);
time += step
};
if (!(data.item in shRRD)) {
shRRD[data.item] = {};
}
shRRD[data.item][data.frame] = {'series': series, 'step': data.step};
};
$.mobile.activePage.find($("[data-rrd]")).each(function() {
rrds = $(this).attr('data-rrd').split('|');
for (i = 0; i < rrds.length; i++) {
rrd = rrds[i].split('=');
if (rrd[0] == data.item) {
// incoming item found in current graph
frame = $(this).attr('data-frame')
if (frame in shRRD[data.item]) {
shRRDDraw(this);
};
break;
};
};
});
};
function shRRDDraw(div) {
var rrds = $(div).attr('data-rrd').split('|');
var frame = $(div).attr('data-frame')
var series = [];
var options = {xaxis: {mode: "time"}};
if ($(div).attr('data-options'))
options = JSON.parse("{" + $(div).attr('data-options').replace(/'/g, '"') + "}") ;
for (i = 0; i < rrds.length; i++) {
var serie = {};
rrd = rrds[i].split('=');
var tid = rrd[0];
if (tid in shRRD) {
if (frame in shRRD[tid]) {
if (rrd[1] != undefined) {
serie = JSON.parse("{" + rrd[1].replace(/'/g, '"') + "}") ;
} else {
serie = {}
};
serie['data'] = shRRD[tid][frame]['series'];
series.push(serie);
};
};
};
if (series.length > 0) {
$.plot($(div), series, options);
};
};
function shWsInit() {
shWS = new WebSocket(shURL);
shWS.onopen = function(){
shSend({'cmd': 'proto', 'ver': shProto});
shRRD = {};
shLog = {};
shRequestData();
$('.ui-dialog').dialog('close');
};
shWS.onmessage = function(event) {
// msg format
// k (ey) = i(tem)|l(og)|r(rd)|d(ialog)
// p (aylod) = array with [id, value] arrays
// rrd: f (rame), s (tart), d (elta)
var path, val;
var data = JSON.parse(event.data);
console.log("receiving data: " + event.data);
switch(data.cmd) {
case 'item':
for (var i = 0; i < data.items.length; i++) {
path = data.items[i][0];
val = data.items[i][1];
if ( data.items[i].length > 2 ) {
shOpt[path] = data.items[i][2];
};
shLock = path;
shBuffer[path] = val;
shUpdateItem(path, val);
shLock = false;
};
break;
case 'rrd':
shRRDUpdate(data);
break;
case 'log':
shLogUpdate(data);
break;
case 'dialog':
shDialog(data.header, data.content);
break;
case 'proto':
var proto = parseInt(data.ver);
if (proto != shProto) {
shDialog('Protcol missmatch', 'Update smarthome(.min).js');
};
break;
case 'url':
shUrl(data.url);
break;
};
};
shWS.onerror = function(error){
console.log('Websocket error: ' + error);
};
shWS.onclose = function(){
shDialog('Network error', 'Could not connect to the backend!');
};
};
function shWSCheckInit() {
setInterval(shWSCheck, 2000);
};
function shWSCheck() {
// check connection
// if connection is lost try to reconnect
if ( shWS.readyState > 1 ){ shWsInit(); };
};
function shRequestData() {
shMonitor = $("[data-sh]").map(function() { if (this.tagName != 'A') { return $(this).attr("data-sh"); }}).get();
shMonitor = shUnique(shMonitor);
shSend({'cmd': 'monitor', 'items': shMonitor});
$("[data-rrd]").each( function() {
var rrds = $(this).attr('data-rrd').split('|');
var frame = $(this).attr('data-frame');
for (i = 0; i < rrds.length; i++) {
var rrd = rrds[i].split('=');
var id = rrd[0];
if (!(id in shRRD)) {
shSend({'cmd': 'rrd', 'item': rrd[0], 'frame': frame});
} else if (!(frame in shRRD[id])) {
shSend({'cmd': 'rrd', 'item': rrd[0], 'frame': frame});
};
};
});
$("[data-log]").each( function() {
var log = $(this).attr('data-log');
var max = $(this).attr('data-max');
if (!(log in shLog)) {
shSend({'cmd': 'log', 'log': log, 'max': max});
};
});
};
// page handling //
function shPageCreate() {
console.log('PageCreate');
shRequestData();
// create dialog page
if ($('#shDialog').length == 0) {
$.mobile.pageContainer.append('<div data-role="page" id="shDialog"><div data-role="header"><h1 id="shDialogHeader"></h1></div><div data-role="content"><div id="shDialogContent"></div></div></div>');
};
};
function shPageInit() {
// update page items
console.log('PageInit');
for (path in shBuffer) {
if (shMonitor.indexOf(path) != -1) { // if path in shMonitor
shUpdateItem(path, shBuffer[path]);
} else {
delete shBuffer[path];
delete shOpt[path];
};
};
};
function shPageShow() {
// check connection
if ( shWS.readyState > 1 ){ // Socket closed
shWsInit();
};
$.mobile.activePage.find($("[data-rrd]")).each(function() {
shRRDDraw(this);
});
};
// outgoing data //
function shSend(data){
// console.log("Websocket state: " + shWS.readyState);
if ( shWS.readyState > 1 ){
shWsInit();
};
if ( shWS.readyState == 1 ) {
console.log('sending data: ' + JSON.stringify(data));
shWS.send(unescape(encodeURIComponent(JSON.stringify(data))));
return true;
} else {
console.log('Websocket (' + shURL + ') not available. Could not send data.');
return false;
};
};
function shBufferUpdate(path, val, src){
if ( path in shBuffer) {
if (shBuffer[path] !== val){
console.log(path + " changed to: " + val + " (" + typeof(val) + ")");
shBuffer[path] = val;
shSend({'cmd': 'item', 'id': path, 'val': val});
shUpdateItem(path, val, src);
};
};
};
function shTriggerLogic(obj){
shSend({'cmd':'logic', 'name': $(obj).attr('data-logic'), 'val': $(obj).attr('value')});
};
function shSwitchButton(obj){
var path = $(obj).attr('data-sh');
var val = true;
if ( String($(obj).val()) == '1') {
val = false;
};
shBufferUpdate(path, val, obj);
$(obj).val(Number(val));
$(obj).attr("src", shOpt[path][Number(val)]);
};
function shSendSelect(obj){
var path = $(obj).attr('data-sh');
if ( path == shLock) { return; };
var val;
if ($(obj).attr('data-role') == 'slider') { // toggle
val = Boolean($(obj)[0].selectedIndex)
} else { // regular select
val = $(obj).val();
};
shBufferUpdate(path, val, obj);
};
function shSendFix(obj){
var path = $(obj).attr('data-sh');
if ( path == shLock) { return; };
var val = Number($(obj).attr("value"));
shBufferUpdate(path, val, obj);
};
function shSendPush(obj, val){
var path = $(obj).attr('data-sh');
if ( path == shLock) { return; };
shSend({'cmd': 'item', 'id': path, 'val': val});
};
function shSendVal(obj){
var path = $(obj).attr('data-sh');
if ( path == shLock) { return; };
var val = $(obj).val();
shBufferUpdate(path, val, obj);
};
function shSendNum(obj){
var path = $(obj).attr('data-sh');
if ( path == shLock) { return; };
var val = Number($(obj).val());
shBufferUpdate(path, val, obj);
};
function shSendRadio(obj){
var path = $(obj).attr('data-sh');
if ( path == shLock) { return; };
var val = $(obj).val();
shBufferUpdate(path, val, obj);
};
function shSendCheckbox(obj){
var path = $(obj).attr('data-sh');
if ( path == shLock) { return; };
var val = $(obj).prop('checked');
shBufferUpdate(path, val, obj);
};
// Incoming Data //
function shUpdateItem(path, val, src) {
var obj = $('[data-sh="' + path + '"]');
if (obj.length == 0) {
console.log("unknown id: "+ path);
return;
}
//console.log('update found ' + obj.length + ' elements');
$(obj).filter('[type!="radio"]').each(function() { // ignoring radio - see below
element = this.tagName;
if (src == this ) { // ignore source
return true;
};
switch(element) {
case 'DIV':
var unit = $(obj).attr('data-unit');
if (unit != null) {
val = val + ' ' + unit
};
$(this).html(val);
break;
case 'SPAN':
var unit = $(obj).attr('data-unit');
if (unit != null) {
val = val + ' ' + unit
};
$(this).html(val);
break;
case 'TEXTAREA':
$(this).val(val);
break;
case 'SELECT':
updateSelect(this, val);
break;
case 'INPUT':
updateInput(this, val);
break;
case 'UL':
updateList(this, val);
break;
case 'IMG':
if ( $(this).attr("class") != "set" && $(this).attr("class") != "push"){
if ( path in shOpt ){
$(this).attr("src", shOpt[path][Number(val)]);
$(this).val(Number(val));
} else {
$(this).attr("src", val);
};
};
break;
default:
console.log("unknown element: " + element);
break;
};
});
// special care for input radio
var radio = $(obj).filter('[type="radio"]')
radio.removeAttr('checked');
radio.filter("[value='" + val + "']").attr("checked","checked");
try {
$(radio).checkboxradio('refresh');
} catch (e) {};
};
function updateSelect(obj, val) {
if ($(obj).attr('data-role') == 'slider') { // toggle
obj.selectedIndex = val;
try {
$(obj).slider("refresh");
} catch (e) {};
} else { // select
$(obj).val(val);
try {
$(obj).selectmenu("refresh");
} catch (e) {};
};
};
function updateList(obj, val) {
$(obj).html('')
for (var i = 0; i < val.length; i++) {
if (val[i].startsWith('<li')) {
$(obj).append(val[i] + "\n")
} else {
$(obj).append("<li>" + val[i] + "</li>\n")
};
};
$(obj).listview('refresh');
};
function updateInput(obj, val) {
var type = $(obj).attr('type');
if (type == undefined) {
type = $(obj).attr('data-type');
}
//console.log('type: '+ type);
switch(type) {
case 'text': // regular text
$(obj).val(val);
break;
case 'range': // slider
try {
$(obj).val(val).slider("refresh");
} catch (e) {};
break;
case 'number': // ?
try {
$(obj).val(val).slider("refresh");
} catch (e) {};
break;
case 'checkbox': // checkbox
try {
$(obj).attr("checked",val).checkboxradio("refresh");
} catch (e) {};
break;
case 'image': // image
$(obj).val(Number(val));
$(obj).attr("src", shOpt['example.toggle'][Number(val)]); // XXX
break;
case 'time': // time
$(obj).val(val);
break;
default:
console.log("unknown type: " + type);
break;
};
};
function shDialog(header, content){
$('#shDialogHeader').html(header);
$('#shDialogContent').html(content);
//$('#shDialog').trigger('create');
$.mobile.changePage('#shDialog', {transition: 'pop', role: 'dialog'} );
};
function shUrl(url){
window.location.href=url;
};
| gpl-3.0 |
Vadavim/jsr-darkstar | scripts/zones/Port_San_dOria/npcs/Dabbio.lua | 1049 | -----------------------------------
-- Area: Port San d'Oria
-- NPC: Dabbio
-- Type: Standard NPC
-- @zone 232
-- @pos -7.819 -15 -106.990
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x02d2);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
QiuLihua83/Magento_with_some_popular_mods | app/code/core/Mage/Paypal/Model/System/Config/Source/BuyerCountry.php | 1515 | <?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* 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 [email protected] so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* @category Mage
* @package Mage_Paypal
* @copyright Copyright (c) 2006-2015 X.commerce, Inc. (http://www.magento.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Source model for buyer countries supported by PayPal
*/
class Mage_Paypal_Model_System_Config_Source_BuyerCountry
{
public function toOptionArray($isMultiselect = false)
{
$supported = Mage::getModel('paypal/config')->getSupportedBuyerCountryCodes();
$options = Mage::getResourceModel('directory/country_collection')
->addCountryCodeFilter($supported, 'iso2')
->loadData()
->toOptionArray($isMultiselect ? false : Mage::helper('adminhtml')->__('--Please Select--'));
return $options;
}
}
| gpl-3.0 |
Varentsov/servo | tests/wpt/web-platform-tests/tools/third_party/pytest/testing/test_junitxml.py | 35008 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from xml.dom import minidom
import py
import sys
import os
from _pytest.junitxml import LogXML
import pytest
def runandparse(testdir, *args):
resultpath = testdir.tmpdir.join("junit.xml")
result = testdir.runpytest("--junitxml=%s" % resultpath, *args)
xmldoc = minidom.parse(str(resultpath))
return result, DomNode(xmldoc)
def assert_attr(node, **kwargs):
__tracebackhide__ = True
def nodeval(node, name):
anode = node.getAttributeNode(name)
if anode is not None:
return anode.value
expected = dict((name, str(value)) for name, value in kwargs.items())
on_node = dict((name, nodeval(node, name)) for name in expected)
assert on_node == expected
class DomNode(object):
def __init__(self, dom):
self.__node = dom
def __repr__(self):
return self.__node.toxml()
def find_first_by_tag(self, tag):
return self.find_nth_by_tag(tag, 0)
def _by_tag(self, tag):
return self.__node.getElementsByTagName(tag)
def find_nth_by_tag(self, tag, n):
items = self._by_tag(tag)
try:
nth = items[n]
except IndexError:
pass
else:
return type(self)(nth)
def find_by_tag(self, tag):
t = type(self)
return [t(x) for x in self.__node.getElementsByTagName(tag)]
def __getitem__(self, key):
node = self.__node.getAttributeNode(key)
if node is not None:
return node.value
def assert_attr(self, **kwargs):
__tracebackhide__ = True
return assert_attr(self.__node, **kwargs)
def toxml(self):
return self.__node.toxml()
@property
def text(self):
return self.__node.childNodes[0].wholeText
@property
def tag(self):
return self.__node.tagName
@property
def next_siebling(self):
return type(self)(self.__node.nextSibling)
class TestPython(object):
def test_summing_simple(self, testdir):
testdir.makepyfile("""
import pytest
def test_pass():
pass
def test_fail():
assert 0
def test_skip():
pytest.skip("")
@pytest.mark.xfail
def test_xfail():
assert 0
@pytest.mark.xfail
def test_xpass():
assert 1
""")
result, dom = runandparse(testdir)
assert result.ret
node = dom.find_first_by_tag("testsuite")
node.assert_attr(name="pytest", errors=0, failures=1, skips=2, tests=5)
def test_summing_simple_with_errors(self, testdir):
testdir.makepyfile("""
import pytest
@pytest.fixture
def fixture():
raise Exception()
def test_pass():
pass
def test_fail():
assert 0
def test_error(fixture):
pass
@pytest.mark.xfail
def test_xfail():
assert False
@pytest.mark.xfail(strict=True)
def test_xpass():
assert True
""")
result, dom = runandparse(testdir)
assert result.ret
node = dom.find_first_by_tag("testsuite")
node.assert_attr(name="pytest", errors=1, failures=2, skips=1, tests=5)
def test_timing_function(self, testdir):
testdir.makepyfile("""
import time, pytest
def setup_module():
time.sleep(0.01)
def teardown_module():
time.sleep(0.01)
def test_sleep():
time.sleep(0.01)
""")
result, dom = runandparse(testdir)
node = dom.find_first_by_tag("testsuite")
tnode = node.find_first_by_tag("testcase")
val = tnode["time"]
assert round(float(val), 2) >= 0.03
def test_setup_error(self, testdir):
testdir.makepyfile("""
import pytest
@pytest.fixture
def arg(request):
raise ValueError()
def test_function(arg):
pass
""")
result, dom = runandparse(testdir)
assert result.ret
node = dom.find_first_by_tag("testsuite")
node.assert_attr(errors=1, tests=1)
tnode = node.find_first_by_tag("testcase")
tnode.assert_attr(
file="test_setup_error.py",
line="5",
classname="test_setup_error",
name="test_function")
fnode = tnode.find_first_by_tag("error")
fnode.assert_attr(message="test setup failure")
assert "ValueError" in fnode.toxml()
def test_teardown_error(self, testdir):
testdir.makepyfile("""
import pytest
@pytest.fixture
def arg():
yield
raise ValueError()
def test_function(arg):
pass
""")
result, dom = runandparse(testdir)
assert result.ret
node = dom.find_first_by_tag("testsuite")
tnode = node.find_first_by_tag("testcase")
tnode.assert_attr(
file="test_teardown_error.py",
line="6",
classname="test_teardown_error",
name="test_function")
fnode = tnode.find_first_by_tag("error")
fnode.assert_attr(message="test teardown failure")
assert "ValueError" in fnode.toxml()
def test_call_failure_teardown_error(self, testdir):
testdir.makepyfile("""
import pytest
@pytest.fixture
def arg():
yield
raise Exception("Teardown Exception")
def test_function(arg):
raise Exception("Call Exception")
""")
result, dom = runandparse(testdir)
assert result.ret
node = dom.find_first_by_tag("testsuite")
node.assert_attr(errors=1, failures=1, tests=1)
first, second = dom.find_by_tag("testcase")
if not first or not second or first == second:
assert 0
fnode = first.find_first_by_tag("failure")
fnode.assert_attr(message="Exception: Call Exception")
snode = second.find_first_by_tag("error")
snode.assert_attr(message="test teardown failure")
def test_skip_contains_name_reason(self, testdir):
testdir.makepyfile("""
import pytest
def test_skip():
pytest.skip("hello23")
""")
result, dom = runandparse(testdir)
assert result.ret == 0
node = dom.find_first_by_tag("testsuite")
node.assert_attr(skips=1)
tnode = node.find_first_by_tag("testcase")
tnode.assert_attr(
file="test_skip_contains_name_reason.py",
line="1",
classname="test_skip_contains_name_reason",
name="test_skip")
snode = tnode.find_first_by_tag("skipped")
snode.assert_attr(type="pytest.skip", message="hello23", )
def test_mark_skip_contains_name_reason(self, testdir):
testdir.makepyfile("""
import pytest
@pytest.mark.skip(reason="hello24")
def test_skip():
assert True
""")
result, dom = runandparse(testdir)
assert result.ret == 0
node = dom.find_first_by_tag("testsuite")
node.assert_attr(skips=1)
tnode = node.find_first_by_tag("testcase")
tnode.assert_attr(
file="test_mark_skip_contains_name_reason.py",
line="1",
classname="test_mark_skip_contains_name_reason",
name="test_skip")
snode = tnode.find_first_by_tag("skipped")
snode.assert_attr(type="pytest.skip", message="hello24", )
def test_mark_skipif_contains_name_reason(self, testdir):
testdir.makepyfile("""
import pytest
GLOBAL_CONDITION = True
@pytest.mark.skipif(GLOBAL_CONDITION, reason="hello25")
def test_skip():
assert True
""")
result, dom = runandparse(testdir)
assert result.ret == 0
node = dom.find_first_by_tag("testsuite")
node.assert_attr(skips=1)
tnode = node.find_first_by_tag("testcase")
tnode.assert_attr(
file="test_mark_skipif_contains_name_reason.py",
line="2",
classname="test_mark_skipif_contains_name_reason",
name="test_skip")
snode = tnode.find_first_by_tag("skipped")
snode.assert_attr(type="pytest.skip", message="hello25", )
def test_mark_skip_doesnt_capture_output(self, testdir):
testdir.makepyfile("""
import pytest
@pytest.mark.skip(reason="foo")
def test_skip():
print("bar!")
""")
result, dom = runandparse(testdir)
assert result.ret == 0
node_xml = dom.find_first_by_tag("testsuite").toxml()
assert "bar!" not in node_xml
def test_classname_instance(self, testdir):
testdir.makepyfile("""
class TestClass(object):
def test_method(self):
assert 0
""")
result, dom = runandparse(testdir)
assert result.ret
node = dom.find_first_by_tag("testsuite")
node.assert_attr(failures=1)
tnode = node.find_first_by_tag("testcase")
tnode.assert_attr(
file="test_classname_instance.py",
line="1",
classname="test_classname_instance.TestClass",
name="test_method")
def test_classname_nested_dir(self, testdir):
p = testdir.tmpdir.ensure("sub", "test_hello.py")
p.write("def test_func(): 0/0")
result, dom = runandparse(testdir)
assert result.ret
node = dom.find_first_by_tag("testsuite")
node.assert_attr(failures=1)
tnode = node.find_first_by_tag("testcase")
tnode.assert_attr(
file=os.path.join("sub", "test_hello.py"),
line="0",
classname="sub.test_hello",
name="test_func")
def test_internal_error(self, testdir):
testdir.makeconftest("def pytest_runtest_protocol(): 0 / 0")
testdir.makepyfile("def test_function(): pass")
result, dom = runandparse(testdir)
assert result.ret
node = dom.find_first_by_tag("testsuite")
node.assert_attr(errors=1, tests=1)
tnode = node.find_first_by_tag("testcase")
tnode.assert_attr(classname="pytest", name="internal")
fnode = tnode.find_first_by_tag("error")
fnode.assert_attr(message="internal error")
assert "Division" in fnode.toxml()
def test_failure_function(self, testdir):
testdir.makepyfile("""
import sys
def test_fail():
print ("hello-stdout")
sys.stderr.write("hello-stderr\\n")
raise ValueError(42)
""")
result, dom = runandparse(testdir)
assert result.ret
node = dom.find_first_by_tag("testsuite")
node.assert_attr(failures=1, tests=1)
tnode = node.find_first_by_tag("testcase")
tnode.assert_attr(
file="test_failure_function.py",
line="1",
classname="test_failure_function",
name="test_fail")
fnode = tnode.find_first_by_tag("failure")
fnode.assert_attr(message="ValueError: 42")
assert "ValueError" in fnode.toxml()
systemout = fnode.next_siebling
assert systemout.tag == "system-out"
assert "hello-stdout" in systemout.toxml()
systemerr = systemout.next_siebling
assert systemerr.tag == "system-err"
assert "hello-stderr" in systemerr.toxml()
def test_failure_verbose_message(self, testdir):
testdir.makepyfile("""
import sys
def test_fail():
assert 0, "An error"
""")
result, dom = runandparse(testdir)
node = dom.find_first_by_tag("testsuite")
tnode = node.find_first_by_tag("testcase")
fnode = tnode.find_first_by_tag("failure")
fnode.assert_attr(message="AssertionError: An error assert 0")
def test_failure_escape(self, testdir):
testdir.makepyfile("""
import pytest
@pytest.mark.parametrize('arg1', "<&'", ids="<&'")
def test_func(arg1):
print(arg1)
assert 0
""")
result, dom = runandparse(testdir)
assert result.ret
node = dom.find_first_by_tag("testsuite")
node.assert_attr(failures=3, tests=3)
for index, char in enumerate("<&'"):
tnode = node.find_nth_by_tag("testcase", index)
tnode.assert_attr(
file="test_failure_escape.py",
line="1",
classname="test_failure_escape",
name="test_func[%s]" % char)
sysout = tnode.find_first_by_tag('system-out')
text = sysout.text
assert text == '%s\n' % char
def test_junit_prefixing(self, testdir):
testdir.makepyfile("""
def test_func():
assert 0
class TestHello(object):
def test_hello(self):
pass
""")
result, dom = runandparse(testdir, "--junitprefix=xyz")
assert result.ret
node = dom.find_first_by_tag("testsuite")
node.assert_attr(failures=1, tests=2)
tnode = node.find_first_by_tag("testcase")
tnode.assert_attr(
file="test_junit_prefixing.py",
line="0",
classname="xyz.test_junit_prefixing",
name="test_func")
tnode = node.find_nth_by_tag("testcase", 1)
tnode.assert_attr(
file="test_junit_prefixing.py",
line="3",
classname="xyz.test_junit_prefixing."
"TestHello",
name="test_hello")
def test_xfailure_function(self, testdir):
testdir.makepyfile("""
import pytest
def test_xfail():
pytest.xfail("42")
""")
result, dom = runandparse(testdir)
assert not result.ret
node = dom.find_first_by_tag("testsuite")
node.assert_attr(skips=1, tests=1)
tnode = node.find_first_by_tag("testcase")
tnode.assert_attr(
file="test_xfailure_function.py",
line="1",
classname="test_xfailure_function",
name="test_xfail")
fnode = tnode.find_first_by_tag("skipped")
fnode.assert_attr(message="expected test failure")
# assert "ValueError" in fnode.toxml()
def test_xfailure_xpass(self, testdir):
testdir.makepyfile("""
import pytest
@pytest.mark.xfail
def test_xpass():
pass
""")
result, dom = runandparse(testdir)
# assert result.ret
node = dom.find_first_by_tag("testsuite")
node.assert_attr(skips=0, tests=1)
tnode = node.find_first_by_tag("testcase")
tnode.assert_attr(
file="test_xfailure_xpass.py",
line="1",
classname="test_xfailure_xpass",
name="test_xpass")
def test_xfailure_xpass_strict(self, testdir):
testdir.makepyfile("""
import pytest
@pytest.mark.xfail(strict=True, reason="This needs to fail!")
def test_xpass():
pass
""")
result, dom = runandparse(testdir)
# assert result.ret
node = dom.find_first_by_tag("testsuite")
node.assert_attr(skips=0, tests=1)
tnode = node.find_first_by_tag("testcase")
tnode.assert_attr(
file="test_xfailure_xpass_strict.py",
line="1",
classname="test_xfailure_xpass_strict",
name="test_xpass")
fnode = tnode.find_first_by_tag("failure")
fnode.assert_attr(message="[XPASS(strict)] This needs to fail!")
def test_collect_error(self, testdir):
testdir.makepyfile("syntax error")
result, dom = runandparse(testdir)
assert result.ret
node = dom.find_first_by_tag("testsuite")
node.assert_attr(errors=1, tests=1)
tnode = node.find_first_by_tag("testcase")
tnode.assert_attr(
file="test_collect_error.py",
name="test_collect_error")
assert tnode["line"] is None
fnode = tnode.find_first_by_tag("error")
fnode.assert_attr(message="collection failure")
assert "SyntaxError" in fnode.toxml()
def test_unicode(self, testdir):
value = 'hx\xc4\x85\xc4\x87\n'
testdir.makepyfile("""
# coding: latin1
def test_hello():
print (%r)
assert 0
""" % value)
result, dom = runandparse(testdir)
assert result.ret == 1
tnode = dom.find_first_by_tag("testcase")
fnode = tnode.find_first_by_tag("failure")
if not sys.platform.startswith("java"):
assert "hx" in fnode.toxml()
def test_assertion_binchars(self, testdir):
"""this test did fail when the escaping wasnt strict"""
testdir.makepyfile("""
M1 = '\x01\x02\x03\x04'
M2 = '\x01\x02\x03\x05'
def test_str_compare():
assert M1 == M2
""")
result, dom = runandparse(testdir)
print(dom.toxml())
def test_pass_captures_stdout(self, testdir):
testdir.makepyfile("""
def test_pass():
print('hello-stdout')
""")
result, dom = runandparse(testdir)
node = dom.find_first_by_tag("testsuite")
pnode = node.find_first_by_tag("testcase")
systemout = pnode.find_first_by_tag("system-out")
assert "hello-stdout" in systemout.toxml()
def test_pass_captures_stderr(self, testdir):
testdir.makepyfile("""
import sys
def test_pass():
sys.stderr.write('hello-stderr')
""")
result, dom = runandparse(testdir)
node = dom.find_first_by_tag("testsuite")
pnode = node.find_first_by_tag("testcase")
systemout = pnode.find_first_by_tag("system-err")
assert "hello-stderr" in systemout.toxml()
def test_setup_error_captures_stdout(self, testdir):
testdir.makepyfile("""
import pytest
@pytest.fixture
def arg(request):
print('hello-stdout')
raise ValueError()
def test_function(arg):
pass
""")
result, dom = runandparse(testdir)
node = dom.find_first_by_tag("testsuite")
pnode = node.find_first_by_tag("testcase")
systemout = pnode.find_first_by_tag("system-out")
assert "hello-stdout" in systemout.toxml()
def test_setup_error_captures_stderr(self, testdir):
testdir.makepyfile("""
import sys
import pytest
@pytest.fixture
def arg(request):
sys.stderr.write('hello-stderr')
raise ValueError()
def test_function(arg):
pass
""")
result, dom = runandparse(testdir)
node = dom.find_first_by_tag("testsuite")
pnode = node.find_first_by_tag("testcase")
systemout = pnode.find_first_by_tag("system-err")
assert "hello-stderr" in systemout.toxml()
def test_avoid_double_stdout(self, testdir):
testdir.makepyfile("""
import sys
import pytest
@pytest.fixture
def arg(request):
yield
sys.stdout.write('hello-stdout teardown')
raise ValueError()
def test_function(arg):
sys.stdout.write('hello-stdout call')
""")
result, dom = runandparse(testdir)
node = dom.find_first_by_tag("testsuite")
pnode = node.find_first_by_tag("testcase")
systemout = pnode.find_first_by_tag("system-out")
assert "hello-stdout call" in systemout.toxml()
assert "hello-stdout teardown" in systemout.toxml()
def test_mangle_test_address():
from _pytest.junitxml import mangle_test_address
address = '::'.join(
["a/my.py.thing.py", "Class", "()", "method", "[a-1-::]"])
newnames = mangle_test_address(address)
assert newnames == ["a.my.py.thing", "Class", "method", "[a-1-::]"]
def test_dont_configure_on_slaves(tmpdir):
gotten = []
class FakeConfig(object):
def __init__(self):
self.pluginmanager = self
self.option = self
def getini(self, name):
return "pytest"
junitprefix = None
# XXX: shouldnt need tmpdir ?
xmlpath = str(tmpdir.join('junix.xml'))
register = gotten.append
fake_config = FakeConfig()
from _pytest import junitxml
junitxml.pytest_configure(fake_config)
assert len(gotten) == 1
FakeConfig.slaveinput = None
junitxml.pytest_configure(fake_config)
assert len(gotten) == 1
class TestNonPython(object):
def test_summing_simple(self, testdir):
testdir.makeconftest("""
import pytest
def pytest_collect_file(path, parent):
if path.ext == ".xyz":
return MyItem(path, parent)
class MyItem(pytest.Item):
def __init__(self, path, parent):
super(MyItem, self).__init__(path.basename, parent)
self.fspath = path
def runtest(self):
raise ValueError(42)
def repr_failure(self, excinfo):
return "custom item runtest failed"
""")
testdir.tmpdir.join("myfile.xyz").write("hello")
result, dom = runandparse(testdir)
assert result.ret
node = dom.find_first_by_tag("testsuite")
node.assert_attr(errors=0, failures=1, skips=0, tests=1)
tnode = node.find_first_by_tag("testcase")
tnode.assert_attr(name="myfile.xyz")
fnode = tnode.find_first_by_tag("failure")
fnode.assert_attr(message="custom item runtest failed")
assert "custom item runtest failed" in fnode.toxml()
def test_nullbyte(testdir):
# A null byte can not occur in XML (see section 2.2 of the spec)
testdir.makepyfile("""
import sys
def test_print_nullbyte():
sys.stdout.write('Here the null -->' + chr(0) + '<--')
sys.stdout.write('In repr form -->' + repr(chr(0)) + '<--')
assert False
""")
xmlf = testdir.tmpdir.join('junit.xml')
testdir.runpytest('--junitxml=%s' % xmlf)
text = xmlf.read()
assert '\x00' not in text
assert '#x00' in text
def test_nullbyte_replace(testdir):
# Check if the null byte gets replaced
testdir.makepyfile("""
import sys
def test_print_nullbyte():
sys.stdout.write('Here the null -->' + chr(0) + '<--')
sys.stdout.write('In repr form -->' + repr(chr(0)) + '<--')
assert False
""")
xmlf = testdir.tmpdir.join('junit.xml')
testdir.runpytest('--junitxml=%s' % xmlf)
text = xmlf.read()
assert '#x0' in text
def test_invalid_xml_escape():
# Test some more invalid xml chars, the full range should be
# tested really but let's just thest the edges of the ranges
# intead.
# XXX This only tests low unicode character points for now as
# there are some issues with the testing infrastructure for
# the higher ones.
# XXX Testing 0xD (\r) is tricky as it overwrites the just written
# line in the output, so we skip it too.
global unichr
try:
unichr(65)
except NameError:
unichr = chr
invalid = (0x00, 0x1, 0xB, 0xC, 0xE, 0x19, 27, # issue #126
0xD800, 0xDFFF, 0xFFFE, 0x0FFFF) # , 0x110000)
valid = (0x9, 0xA, 0x20, )
# 0xD, 0xD7FF, 0xE000, 0xFFFD, 0x10000, 0x10FFFF)
from _pytest.junitxml import bin_xml_escape
for i in invalid:
got = bin_xml_escape(unichr(i)).uniobj
if i <= 0xFF:
expected = '#x%02X' % i
else:
expected = '#x%04X' % i
assert got == expected
for i in valid:
assert chr(i) == bin_xml_escape(unichr(i)).uniobj
def test_logxml_path_expansion(tmpdir, monkeypatch):
home_tilde = py.path.local(os.path.expanduser('~')).join('test.xml')
xml_tilde = LogXML('~%stest.xml' % tmpdir.sep, None)
assert xml_tilde.logfile == home_tilde
# this is here for when $HOME is not set correct
monkeypatch.setenv("HOME", tmpdir)
home_var = os.path.normpath(os.path.expandvars('$HOME/test.xml'))
xml_var = LogXML('$HOME%stest.xml' % tmpdir.sep, None)
assert xml_var.logfile == home_var
def test_logxml_changingdir(testdir):
testdir.makepyfile("""
def test_func():
import os
os.chdir("a")
""")
testdir.tmpdir.mkdir("a")
result = testdir.runpytest("--junitxml=a/x.xml")
assert result.ret == 0
assert testdir.tmpdir.join("a/x.xml").check()
def test_logxml_makedir(testdir):
"""--junitxml should automatically create directories for the xml file"""
testdir.makepyfile("""
def test_pass():
pass
""")
result = testdir.runpytest("--junitxml=path/to/results.xml")
assert result.ret == 0
assert testdir.tmpdir.join("path/to/results.xml").check()
def test_logxml_check_isdir(testdir):
"""Give an error if --junit-xml is a directory (#2089)"""
result = testdir.runpytest("--junit-xml=.")
result.stderr.fnmatch_lines(["*--junitxml must be a filename*"])
def test_escaped_parametrized_names_xml(testdir):
testdir.makepyfile("""
import pytest
@pytest.mark.parametrize('char', [u"\\x00"])
def test_func(char):
assert char
""")
result, dom = runandparse(testdir)
assert result.ret == 0
node = dom.find_first_by_tag("testcase")
node.assert_attr(name="test_func[\\x00]")
def test_double_colon_split_function_issue469(testdir):
testdir.makepyfile("""
import pytest
@pytest.mark.parametrize('param', ["double::colon"])
def test_func(param):
pass
""")
result, dom = runandparse(testdir)
assert result.ret == 0
node = dom.find_first_by_tag("testcase")
node.assert_attr(classname="test_double_colon_split_function_issue469")
node.assert_attr(name='test_func[double::colon]')
def test_double_colon_split_method_issue469(testdir):
testdir.makepyfile("""
import pytest
class TestClass(object):
@pytest.mark.parametrize('param', ["double::colon"])
def test_func(self, param):
pass
""")
result, dom = runandparse(testdir)
assert result.ret == 0
node = dom.find_first_by_tag("testcase")
node.assert_attr(
classname="test_double_colon_split_method_issue469.TestClass")
node.assert_attr(name='test_func[double::colon]')
def test_unicode_issue368(testdir):
path = testdir.tmpdir.join("test.xml")
log = LogXML(str(path), None)
ustr = py.builtin._totext("ВНИ!", "utf-8")
from _pytest.runner import BaseReport
class Report(BaseReport):
longrepr = ustr
sections = []
nodeid = "something"
location = 'tests/filename.py', 42, 'TestClass.method'
test_report = Report()
# hopefully this is not too brittle ...
log.pytest_sessionstart()
node_reporter = log._opentestcase(test_report)
node_reporter.append_failure(test_report)
node_reporter.append_collect_error(test_report)
node_reporter.append_collect_skipped(test_report)
node_reporter.append_error(test_report)
test_report.longrepr = "filename", 1, ustr
node_reporter.append_skipped(test_report)
test_report.longrepr = "filename", 1, "Skipped: 卡嘣嘣"
node_reporter.append_skipped(test_report)
test_report.wasxfail = ustr
node_reporter.append_skipped(test_report)
log.pytest_sessionfinish()
def test_record_property(testdir):
testdir.makepyfile("""
import pytest
@pytest.fixture
def other(record_xml_property):
record_xml_property("bar", 1)
def test_record(record_xml_property, other):
record_xml_property("foo", "<1");
""")
result, dom = runandparse(testdir, '-rw')
node = dom.find_first_by_tag("testsuite")
tnode = node.find_first_by_tag("testcase")
psnode = tnode.find_first_by_tag('properties')
pnodes = psnode.find_by_tag('property')
pnodes[0].assert_attr(name="bar", value="1")
pnodes[1].assert_attr(name="foo", value="<1")
result.stdout.fnmatch_lines([
'test_record_property.py::test_record',
'*record_xml_property*experimental*',
])
def test_record_property_same_name(testdir):
testdir.makepyfile("""
def test_record_with_same_name(record_xml_property):
record_xml_property("foo", "bar")
record_xml_property("foo", "baz")
""")
result, dom = runandparse(testdir, '-rw')
node = dom.find_first_by_tag("testsuite")
tnode = node.find_first_by_tag("testcase")
psnode = tnode.find_first_by_tag('properties')
pnodes = psnode.find_by_tag('property')
pnodes[0].assert_attr(name="foo", value="bar")
pnodes[1].assert_attr(name="foo", value="baz")
def test_random_report_log_xdist(testdir):
"""xdist calls pytest_runtest_logreport as they are executed by the slaves,
with nodes from several nodes overlapping, so junitxml must cope with that
to produce correct reports. #1064
"""
pytest.importorskip('xdist')
testdir.makepyfile("""
import pytest, time
@pytest.mark.parametrize('i', list(range(30)))
def test_x(i):
assert i != 22
""")
_, dom = runandparse(testdir, '-n2')
suite_node = dom.find_first_by_tag("testsuite")
failed = []
for case_node in suite_node.find_by_tag("testcase"):
if case_node.find_first_by_tag('failure'):
failed.append(case_node['name'])
assert failed == ['test_x[22]']
def test_runs_twice(testdir):
f = testdir.makepyfile('''
def test_pass():
pass
''')
result, dom = runandparse(testdir, f, f)
assert 'INTERNALERROR' not in result.stdout.str()
first, second = [x['classname'] for x in dom.find_by_tag("testcase")]
assert first == second
@pytest.mark.xfail(reason='hangs', run=False)
def test_runs_twice_xdist(testdir):
pytest.importorskip('xdist')
f = testdir.makepyfile('''
def test_pass():
pass
''')
result, dom = runandparse(
testdir, f,
'--dist', 'each', '--tx', '2*popen',)
assert 'INTERNALERROR' not in result.stdout.str()
first, second = [x['classname'] for x in dom.find_by_tag("testcase")]
assert first == second
def test_fancy_items_regression(testdir):
# issue 1259
testdir.makeconftest("""
import pytest
class FunItem(pytest.Item):
def runtest(self):
pass
class NoFunItem(pytest.Item):
def runtest(self):
pass
class FunCollector(pytest.File):
def collect(self):
return [
FunItem('a', self),
NoFunItem('a', self),
NoFunItem('b', self),
]
def pytest_collect_file(path, parent):
if path.check(ext='.py'):
return FunCollector(path, parent)
""")
testdir.makepyfile('''
def test_pass():
pass
''')
result, dom = runandparse(testdir)
assert 'INTERNALERROR' not in result.stdout.str()
items = sorted(
'%(classname)s %(name)s %(file)s' % x
for x in dom.find_by_tag("testcase"))
import pprint
pprint.pprint(items)
assert items == [
u'conftest a conftest.py',
u'conftest a conftest.py',
u'conftest b conftest.py',
u'test_fancy_items_regression a test_fancy_items_regression.py',
u'test_fancy_items_regression a test_fancy_items_regression.py',
u'test_fancy_items_regression b test_fancy_items_regression.py',
u'test_fancy_items_regression test_pass'
u' test_fancy_items_regression.py',
]
def test_global_properties(testdir):
path = testdir.tmpdir.join("test_global_properties.xml")
log = LogXML(str(path), None)
from _pytest.runner import BaseReport
class Report(BaseReport):
sections = []
nodeid = "test_node_id"
log.pytest_sessionstart()
log.add_global_property('foo', 1)
log.add_global_property('bar', 2)
log.pytest_sessionfinish()
dom = minidom.parse(str(path))
properties = dom.getElementsByTagName('properties')
assert (properties.length == 1), "There must be one <properties> node"
property_list = dom.getElementsByTagName('property')
assert (property_list.length == 2), "There most be only 2 property nodes"
expected = {'foo': '1', 'bar': '2'}
actual = {}
for p in property_list:
k = str(p.getAttribute('name'))
v = str(p.getAttribute('value'))
actual[k] = v
assert actual == expected
def test_url_property(testdir):
test_url = "http://www.github.com/pytest-dev"
path = testdir.tmpdir.join("test_url_property.xml")
log = LogXML(str(path), None)
from _pytest.runner import BaseReport
class Report(BaseReport):
longrepr = "FooBarBaz"
sections = []
nodeid = "something"
location = 'tests/filename.py', 42, 'TestClass.method'
url = test_url
test_report = Report()
log.pytest_sessionstart()
node_reporter = log._opentestcase(test_report)
node_reporter.append_failure(test_report)
log.pytest_sessionfinish()
test_case = minidom.parse(str(path)).getElementsByTagName('testcase')[0]
assert (test_case.getAttribute('url') == test_url), "The URL did not get written to the xml"
@pytest.mark.parametrize('suite_name', ['my_suite', ''])
def test_set_suite_name(testdir, suite_name):
if suite_name:
testdir.makeini("""
[pytest]
junit_suite_name={0}
""".format(suite_name))
expected = suite_name
else:
expected = 'pytest'
testdir.makepyfile("""
import pytest
def test_func():
pass
""")
result, dom = runandparse(testdir)
assert result.ret == 0
node = dom.find_first_by_tag("testsuite")
node.assert_attr(name=expected)
| mpl-2.0 |
jessealama/exist | src/org/exist/xquery/functions/inspect/FunctionCallVisitor.java | 825 | package org.exist.xquery.functions.inspect;
import org.exist.xquery.DefaultExpressionVisitor;
import org.exist.xquery.FunctionCall;
import org.exist.xquery.FunctionSignature;
import java.util.*;
public class FunctionCallVisitor extends DefaultExpressionVisitor {
private Set<FunctionSignature> functionCalls = new HashSet<FunctionSignature>();
public Set<FunctionSignature> getFunctionCalls() {
return functionCalls;
}
@Override
public void visitFunctionCall(FunctionCall call) {
functionCalls.add(call.getSignature());
// continue with the function arguments, but skip the body:
// we're not interested in following function calls recursively
for(int i = 0; i < call.getArgumentCount(); i++) {
call.getArgument(i).accept(this);
}
}
}
| lgpl-2.1 |
harterj/moose | modules/tensor_mechanics/src/materials/CompositeElasticityTensor.C | 1686 | //* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#include "CompositeElasticityTensor.h"
registerMooseObject("TensorMechanicsApp", CompositeElasticityTensor);
InputParameters
CompositeElasticityTensor::validParams()
{
InputParameters params = CompositeTensorBase<RankFourTensor, Material>::validParams();
params.addClassDescription("Assemble an elasticity tensor from multiple tensor contributions "
"weighted by material properties");
params.addParam<std::string>("base_name",
"Optional parameter that allows the user to define "
"multiple mechanics material systems on the same "
"block, i.e. for multiple phases");
return params;
}
CompositeElasticityTensor::CompositeElasticityTensor(const InputParameters & parameters)
: CompositeTensorBase<RankFourTensor, Material>(parameters),
_base_name(isParamValid("base_name") ? getParam<std::string>("base_name") + "_" : ""),
_M_name(_base_name + "elasticity_tensor"),
_M(declareProperty<RankFourTensor>(_M_name))
{
// we take the tensor names to be the _base names_ of the elasticity tensors
for (unsigned int i = 0; i < _num_comp; ++i)
_tensor_names[i] += "_elasticity_tensor";
initializeDerivativeProperties(_M_name);
}
void
CompositeElasticityTensor::computeQpProperties()
{
computeQpTensorProperties(_M);
}
| lgpl-2.1 |
jalexvig/tensorflow | tensorflow/contrib/nccl/python/ops/nccl_ops.py | 8580 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Ops for GPU collective operations implemented using NVIDIA nccl."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import threading
from tensorflow.contrib.nccl.ops import gen_nccl_ops
from tensorflow.contrib.util import loader
from tensorflow.python.eager import context
from tensorflow.python.framework import device
from tensorflow.python.framework import ops
from tensorflow.python.platform import resource_loader
_nccl_ops_so = None
_module_lock = threading.Lock()
_shared_name_counter = 0
def all_sum(tensors):
"""Returns a list of tensors with the all-reduce sum across `tensors`.
The computation is done with an all-reduce operation, so if only some of the
returned tensors are evaluated then the computation will hang.
Args:
tensors: The input tensors across which to sum; must be assigned
to GPU devices.
Returns:
List of tensors, each with the sum of the input tensors, where tensor i has
the same device as `tensors[i]`.
"""
return _apply_all_reduce('sum', tensors)
@ops.RegisterGradient('NcclAllReduce')
def _all_sum_grad(op, grad):
"""The gradients for `all_sum`.
Args:
op: The `all_sum` `Operation` that we are differentiating.
grad: Gradient with respect to the output of the `all_sum` op.
Returns:
The gradient with respect to the output of `all_sum`.
Raises:
LookupError: If `reduction` is not `sum`.
"""
if op.get_attr('reduction') != b'sum':
raise LookupError('No gradient defined for NcclAllReduce except sum.')
_check_device(grad, expected=op.device)
num_devices = op.get_attr('num_devices')
shared_name = op.get_attr('shared_name') + b'_grad'
with ops.device(op.device):
return gen_nccl_ops.nccl_all_reduce(
input=grad,
reduction='sum',
num_devices=num_devices,
shared_name=shared_name)
def all_prod(tensors):
"""Returns a list of tensors with the all-reduce product across `tensors`.
The computation is done with an all-reduce operation, so if only some of the
returned tensors are evaluated then the computation will hang.
Args:
tensors: The input tensors across which to multiply; must be assigned
to GPU devices.
Returns:
List of tensors, each with the product of the input tensors, where tensor i
has the same device as `tensors[i]`.
"""
return _apply_all_reduce('prod', tensors)
def all_min(tensors):
"""Returns a list of tensors with the all-reduce min across `tensors`.
The computation is done with an all-reduce operation, so if only some of the
returned tensors are evaluated then the computation will hang.
Args:
tensors: The input tensors across which to reduce; must be assigned
to GPU devices.
Returns:
List of tensors, each with the minimum of the input tensors, where tensor i
has the same device as `tensors[i]`.
"""
return _apply_all_reduce('min', tensors)
def all_max(tensors):
"""Returns a list of tensors with the all-reduce max across `tensors`.
The computation is done with an all-reduce operation, so if only some of the
returned tensors are evaluated then the computation will hang.
Args:
tensors: The input tensors across which to reduce; must be assigned
to GPU devices.
Returns:
List of tensors, each with the maximum of the input tensors, where tensor i
has the same device as `tensors[i]`.
"""
return _apply_all_reduce('max', tensors)
def reduce_sum(tensors):
"""Returns a tensor with the reduce sum across `tensors`.
The computation is done with a reduce operation, so only one tensor is
returned.
Args:
tensors: The input tensors across which to sum; must be assigned
to GPU devices.
Returns:
A tensor containing the sum of the input tensors.
Raises:
LookupError: If context is not currently using a GPU device.
"""
return _apply_reduce('sum', tensors)
@ops.RegisterGradient('NcclReduce')
def _reduce_sum_grad(op, grad):
"""The gradients for input `Operation` of `reduce_sum`.
Args:
op: The `sum send` `Operation` that we are differentiating.
grad: Gradient with respect to the output of the `reduce_sum` op.
Returns:
The gradient with respect to the input of `reduce_sum` op.
Raises:
LookupError: If the reduction attribute of op is not `sum`.
"""
if op.get_attr('reduction') != b'sum':
raise LookupError('No gradient defined for NcclReduce except sum.')
_check_device(grad, expected=op.device)
with ops.device(op.device):
result = gen_nccl_ops.nccl_broadcast(input=grad, shape=grad.shape)
return [result] * len(op.inputs)
def broadcast(tensor):
"""Returns a tensor that can be efficiently transferred to other devices.
Args:
tensor: The tensor to send; must be assigned to a GPU device.
Returns:
A tensor with the value of `src_tensor`, which can be used as input to
ops on other GPU devices.
"""
_validate_and_load_nccl_so()
_check_device(tensor)
with ops.device(tensor.device):
return gen_nccl_ops.nccl_broadcast(input=tensor, shape=tensor.shape)
@ops.RegisterGradient('NcclBroadcast')
def _broadcast_grad(op, accumulated_grad):
"""The gradients for input `Operation` of `broadcast`.
Args:
op: The `broadcast send` `Operation` that we are differentiating.
accumulated_grad: Accumulated gradients with respect to the output of the
`broadcast` op.
Returns:
Gradients with respect to the input of `broadcast`.
"""
# Grab inputs of accumulated_grad and replace accumulation with reduce_sum.
grads = [t for t in accumulated_grad.op.inputs]
for t in grads:
_check_device(t)
with ops.device(op.device):
return gen_nccl_ops.nccl_reduce(input=grads, reduction='sum')
def _apply_all_reduce(reduction, tensors):
"""Helper function for all_* functions."""
if not tensors:
raise ValueError('Must pass >0 tensors to all reduce operations')
_validate_and_load_nccl_so()
shared_name = _get_shared_name()
res = []
for t in tensors:
_check_device(t)
with ops.device(t.device):
res.append(
gen_nccl_ops.nccl_all_reduce(
input=t,
reduction=reduction,
num_devices=len(tensors),
shared_name=shared_name))
return res
def _apply_reduce(reduction, tensors):
"""Helper function for reduce_* functions."""
if not tensors:
raise ValueError('Must pass >0 tensors to reduce operations')
_validate_and_load_nccl_so()
for t in tensors:
_check_device(t)
result = gen_nccl_ops.nccl_reduce(input=tensors, reduction=reduction)
try:
next(t for t in tensors if t.device == result.device)
except StopIteration:
raise ValueError('One input tensor must be assigned to current device')
return result
def _get_shared_name():
global _shared_name_counter
with _module_lock:
val = _shared_name_counter
_shared_name_counter += 1
return 'c%s' % val
def _check_device(tensor, expected=None):
if not device.canonical_name(tensor.device):
raise ValueError('Device assignment required for nccl collective ops')
if expected and expected != tensor.device:
raise ValueError('Expected device %s, got %s' % (expected, tensor.device))
def _maybe_load_nccl_ops_so():
"""Loads nccl ops so if it hasn't been loaded already."""
with _module_lock:
global _nccl_ops_so
if not _nccl_ops_so:
_nccl_ops_so = loader.load_op_library(
resource_loader.get_path_to_datafile('_nccl_ops.so'))
def _validate_and_load_nccl_so():
"""Validates calling context and loads nccl ops so file.
Raises:
ValueError: Ops are not supported.
errors_impl.NotFoundError: nccl library is not installed.
"""
if context.executing_eagerly():
raise ValueError('Nccl ops are not supported in eager mode')
_maybe_load_nccl_ops_so()
| apache-2.0 |
royclarkson/spring-boot | spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/type/ImageConfig.java | 3607 | /*
* Copyright 2012-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.buildpack.platform.docker.type;
import java.lang.invoke.MethodHandles;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Consumer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.springframework.boot.buildpack.platform.json.MappedObject;
/**
* Image configuration information.
*
* @author Phillip Webb
* @author Andy Wilkinson
* @since 2.3.0
*/
public class ImageConfig extends MappedObject {
private final Map<String, String> labels;
private final Map<String, String> configEnv;
ImageConfig(JsonNode node) {
super(node, MethodHandles.lookup());
this.labels = extractLabels();
this.configEnv = parseConfigEnv();
}
@SuppressWarnings("unchecked")
private Map<String, String> extractLabels() {
Map<String, String> labels = valueAt("/Labels", Map.class);
if (labels == null) {
return Collections.emptyMap();
}
return labels;
}
private Map<String, String> parseConfigEnv() {
String[] entries = valueAt("/Env", String[].class);
if (entries == null) {
return Collections.emptyMap();
}
Map<String, String> env = new LinkedHashMap<>();
for (String entry : entries) {
int i = entry.indexOf('=');
String name = (i != -1) ? entry.substring(0, i) : entry;
String value = (i != -1) ? entry.substring(i + 1) : null;
env.put(name, value);
}
return Collections.unmodifiableMap(env);
}
JsonNode getNodeCopy() {
return super.getNode().deepCopy();
}
/**
* Return the image labels. If the image has no labels, an empty {@code Map} is
* returned.
* @return the image labels, never {@code null}
*/
public Map<String, String> getLabels() {
return this.labels;
}
/**
* Return the image environment variables. If the image has no environment variables,
* an empty {@code Map} is returned.
* @return the env, never {@code null}
*/
public Map<String, String> getEnv() {
return this.configEnv;
}
/**
* Create an updated copy of this image config.
* @param update consumer to apply updates
* @return an updated image config
*/
public ImageConfig copy(Consumer<Update> update) {
return new Update(this).run(update);
}
/**
* Update class used to change data when creating a copy.
*/
public static final class Update {
private final ObjectNode copy;
private Update(ImageConfig source) {
this.copy = source.getNode().deepCopy();
}
private ImageConfig run(Consumer<Update> update) {
update.accept(this);
return new ImageConfig(this.copy);
}
/**
* Update the image config with an additional label.
* @param label the label name
* @param value the label value
*/
public void withLabel(String label, String value) {
JsonNode labels = this.copy.at("/Labels");
if (labels.isMissingNode()) {
labels = this.copy.putObject("Labels");
}
((ObjectNode) labels).put(label, value);
}
}
}
| apache-2.0 |
bazelbuild/bazel | src/test/java/com/google/devtools/build/lib/bazel/rules/genrule/GenRuleWindowsConfiguredTargetTest.java | 8482 | // Copyright 2019 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.bazel.rules.genrule;
import static com.google.common.truth.Truth.assertThat;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.analysis.ShellConfiguration;
import com.google.devtools.build.lib.analysis.actions.SpawnAction;
import com.google.devtools.build.lib.analysis.util.BuildViewTestCase;
import com.google.devtools.build.lib.util.OS;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests of {@link BazelGenRule} on Windows. */
@RunWith(JUnit4.class)
public class GenRuleWindowsConfiguredTargetTest extends BuildViewTestCase {
private static final Pattern POWERSHELL_COMMAND_PATTERN =
Pattern.compile(".*'utf8';\\s+(?<command>.*)");
private static final Pattern BASH_COMMAND_PATTERN =
Pattern.compile(".*/genrule-setup.sh;\\s+(?<command>.*)");
private static void assertCommandEquals(String expected, String command, Pattern pattern) {
// Ensure the command after the genrule setup is correct.
Matcher m = pattern.matcher(command);
if (m.matches()) {
command = m.group("command");
}
assertThat(command).isEqualTo(expected);
}
private static void assertPowershellCommandEquals(String expected, String command) {
assertCommandEquals(expected, command, POWERSHELL_COMMAND_PATTERN);
}
private static void assertBashCommandEquals(String expected, String command) {
assertCommandEquals(expected, command, BASH_COMMAND_PATTERN);
}
private static String getWindowsPath(Artifact artifact) {
return artifact.getExecPathString().replace('/', '\\');
}
@Test
public void testCmdBatchIsPreferred() throws Exception {
scratch.file(
"genrule1/BUILD",
"genrule(name = 'hello_world',",
"outs = ['message.txt'],",
"cmd = 'echo \"Hello, default cmd.\" >$(location message.txt)',",
"cmd_bash = 'echo \"Hello, Bash cmd.\" >$(location message.txt)',",
"cmd_bat = 'echo \"Hello, Batch cmd.\" >$(location message.txt)')");
Artifact messageArtifact = getFileConfiguredTarget("//genrule1:message.txt").getArtifact();
SpawnAction shellAction = (SpawnAction) getGeneratingAction(messageArtifact);
assertThat(shellAction).isNotNull();
assertThat(shellAction.getOutputs()).containsExactly(messageArtifact);
String expected = "echo \"Hello, Batch cmd.\" >" + getWindowsPath(messageArtifact);
assertThat(shellAction.getArguments().get(0)).isEqualTo("cmd.exe");
int last = shellAction.getArguments().size() - 1;
assertThat(shellAction.getArguments().get(last - 1)).isEqualTo("/c");
assertThat(shellAction.getArguments().get(last)).isEqualTo(expected);
}
@Test
public void testCmdPsIsPreferred() throws Exception {
scratch.file(
"genrule1/BUILD",
"genrule(name = 'hello_world',",
"outs = ['message.txt'],",
"cmd = 'echo \"Hello, default cmd.\" >$(location message.txt)',",
"cmd_bash = 'echo \"Hello, Bash cmd.\" >$(location message.txt)',",
"cmd_bat = 'echo \"Hello, Batch cmd.\" >$(location message.txt)',",
"cmd_ps = 'echo \"Hello, Powershell cmd.\" >$(location message.txt)')");
Artifact messageArtifact = getFileConfiguredTarget("//genrule1:message.txt").getArtifact();
SpawnAction shellAction = (SpawnAction) getGeneratingAction(messageArtifact);
assertThat(shellAction).isNotNull();
assertThat(shellAction.getOutputs()).containsExactly(messageArtifact);
String expected = "echo \"Hello, Powershell cmd.\" >" + messageArtifact.getExecPathString();
assertThat(shellAction.getArguments().get(0)).isEqualTo("powershell.exe");
assertThat(shellAction.getArguments().get(1)).isEqualTo("/c");
assertPowershellCommandEquals(expected, shellAction.getArguments().get(2));
}
@Test
public void testScriptFileIsUsedForBatchCmd() throws Exception {
scratch.file(
"genrule1/BUILD",
"genrule(name = 'hello_world',",
"outs = ['message.txt'],",
"cmd_bat = ' && '.join([\"echo \\\"Hello, Batch cmd, %s.\\\" >$(location message.txt)\" %"
+ " i for i in range(1, 1000)]),)");
Artifact messageArtifact = getFileConfiguredTarget("//genrule1:message.txt").getArtifact();
SpawnAction shellAction = (SpawnAction) getGeneratingAction(messageArtifact);
assertThat(shellAction).isNotNull();
assertThat(shellAction.getOutputs()).containsExactly(messageArtifact);
String expected = "bazel-out\\k8-fastbuild\\bin\\genrule1\\hello_world.genrule_script.bat";
assertThat(shellAction.getArguments().get(0)).isEqualTo("cmd.exe");
int last = shellAction.getArguments().size() - 1;
assertThat(shellAction.getArguments().get(last - 1)).isEqualTo("/c");
assertPowershellCommandEquals(expected, shellAction.getArguments().get(last));
}
@Test
public void testScriptFileIsUsedForPowershellCmd() throws Exception {
scratch.file(
"genrule1/BUILD",
"genrule(name = 'hello_world',",
"outs = ['message.txt'],",
"cmd_ps = '; '.join([\"echo \\\"Hello, Powershell cmd, %s.\\\" >$(location message.txt)\""
+ " % i for i in range(1, 1000)]),)");
Artifact messageArtifact = getFileConfiguredTarget("//genrule1:message.txt").getArtifact();
SpawnAction shellAction = (SpawnAction) getGeneratingAction(messageArtifact);
assertThat(shellAction).isNotNull();
assertThat(shellAction.getOutputs()).containsExactly(messageArtifact);
String expected = ".\\bazel-out\\k8-fastbuild\\bin\\genrule1\\hello_world.genrule_script.ps1";
assertThat(shellAction.getArguments().get(0)).isEqualTo("powershell.exe");
assertThat(shellAction.getArguments().get(1)).isEqualTo("/c");
assertPowershellCommandEquals(expected, shellAction.getArguments().get(2));
}
@Test
public void testCmdBashIsPreferred() throws Exception {
scratch.file(
"genrule1/BUILD",
"genrule(name = 'hello_world',",
"outs = ['message.txt'],",
"cmd = 'echo \"Hello, default cmd.\" >$(location message.txt)',",
"cmd_bash = 'echo \"Hello, Bash cmd.\" >$(location message.txt)')");
Artifact messageArtifact = getFileConfiguredTarget("//genrule1:message.txt").getArtifact();
SpawnAction shellAction = (SpawnAction) getGeneratingAction(messageArtifact);
assertThat(shellAction).isNotNull();
assertThat(shellAction.getOutputs()).containsExactly(messageArtifact);
String expected = "echo \"Hello, Bash cmd.\" >" + messageArtifact.getExecPathString();
assertThat(shellAction.getArguments().get(0))
.isEqualTo(
targetConfig
.getFragment(ShellConfiguration.class)
.getShellExecutable()
.getPathString());
assertThat(shellAction.getArguments().get(1)).isEqualTo("-c");
assertBashCommandEquals(expected, shellAction.getArguments().get(2));
}
@Test
public void testMissingCmdAttributeError() throws Exception {
checkError(
"foo",
"bar",
"missing value for `cmd` attribute, you can also set `cmd_ps` or `cmd_bat` on"
+ " Windows and `cmd_bash` on other platforms.",
"genrule(name='bar'," + " srcs = []," + " outs=['out'])");
}
@Test
public void testMissingCmdAttributeErrorOnNonWindowsPlatform() throws Exception {
if (OS.getCurrent() == OS.WINDOWS) {
return;
}
checkError(
"foo",
"bar",
"missing value for `cmd` attribute, you can also set `cmd_ps` or `cmd_bat` on"
+ " Windows and `cmd_bash` on other platforms.",
"genrule(name='bar',"
+ " srcs = [],"
+ " outs=['out'],"
+ " cmd_bat='echo hello > $(@)')");
}
}
| apache-2.0 |
nvoron23/arangodb | js/apps/system/_admin/aardvark/APP/frontend/js/graphViewer/ui/arangoAdapterControls.js | 6300 | /*global $, _, d3*/
/*global document*/
/*global modalDialogHelper, uiComponentsHelper*/
////////////////////////////////////////////////////////////////////////////////
/// @brief Graph functionality
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2012 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Michael Hackstein
/// @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
function ArangoAdapterControls(list, adapter) {
"use strict";
if (list === undefined) {
throw "A list element has to be given.";
}
if (adapter === undefined) {
throw "The ArangoAdapter has to be given.";
}
this.addControlChangeCollections = function(callback) {
var prefix = "control_adapter_collections",
idprefix = prefix + "_";
adapter.getCollections(function(nodeCols, edgeCols) {
adapter.getGraphs(function(graphs) {
uiComponentsHelper.createButton(list, "Collections", prefix, function() {
modalDialogHelper.createModalDialog("Switch Collections",
idprefix, [{
type: "decission",
id: "collections",
group: "loadtype",
text: "Select existing collections",
isDefault: (adapter.getGraphName() === undefined),
interior: [
{
type: "list",
id: "node_collection",
text: "Vertex collection",
objects: nodeCols,
selected: adapter.getNodeCollection()
},{
type: "list",
id: "edge_collection",
text: "Edge collection",
objects: edgeCols,
selected: adapter.getEdgeCollection()
}
]
},{
type: "decission",
id: "graphs",
group: "loadtype",
text: "Select existing graph",
isDefault: (adapter.getGraphName() !== undefined),
interior: [
{
type: "list",
id: "graph",
objects: graphs,
selected: adapter.getGraphName()
}
]
},{
type: "checkbox",
text: "Start with random vertex",
id: "random",
selected: true
},{
type: "checkbox",
id: "undirected",
selected: (adapter.getDirection() === "any")
}], function () {
var nodes = $("#" + idprefix + "node_collection")
.children("option")
.filter(":selected")
.text(),
edges = $("#" + idprefix + "edge_collection")
.children("option")
.filter(":selected")
.text(),
graph = $("#" + idprefix + "graph")
.children("option")
.filter(":selected")
.text(),
undirected = !!$("#" + idprefix + "undirected").prop("checked"),
random = !!$("#" + idprefix + "random").prop("checked"),
selected = $("input[type='radio'][name='loadtype']:checked").prop("id");
if (selected === idprefix + "collections") {
adapter.changeToCollections(nodes, edges, undirected);
} else {
adapter.changeToGraph(graph, undirected);
}
if (random) {
adapter.loadRandomNode(callback);
return;
}
if (_.isFunction(callback)) {
callback();
}
}
);
});
});
});
};
this.addControlChangePriority = function() {
var prefix = "control_adapter_priority",
idprefix = prefix + "_",
prioList = adapter.getPrioList(),
label = "Group vertices";
uiComponentsHelper.createButton(list, label, prefix, function() {
modalDialogHelper.createModalChangeDialog(label,
idprefix, [{
type: "extendable",
id: "attribute",
objects: adapter.getPrioList()
}], function () {
var list = $("input[id^=" + idprefix + "attribute_]"),
prios = [];
list.each(function(i, t) {
var val = $(t).val();
if (val !== "") {
prios.push(val);
}
});
adapter.changeTo({
prioList: prios
});
}
);
});
/*
adapter.getCollections(function(nodeCols, edgeCols) {
uiComponentsHelper.createButton(list, "Collections", prefix, function() {
modalDialogHelper.createModalDialog("Switch Collections",
idprefix, [{
type: "list",
id: "nodecollection",
objects: nodeCols
},{
type: "list",
id: "edgecollection",
objects: edgeCols
},{
type: "checkbox",
id: "undirected"
}], function () {
var = $("#" + idprefix + "nodecollection").attr("value"),
edges = $("#" + idprefix + "edgecollection").attr("value"),
undirected = !!$("#" + idprefix + "undirected").attr("checked");
adapter.changeTo(nodes, edges, undirected);
}
);
});
});
*/
};
this.addAll = function() {
this.addControlChangeCollections();
this.addControlChangePriority();
};
}
| apache-2.0 |
lostiniceland/bnd | biz.aQute.bndlib.tests/src/test/uses/field/UsesField.java | 233 | package test.uses.field;
import javax.security.auth.Subject;
import javax.security.auth.callback.CallbackHandler;
@SuppressWarnings("unused")
public class UsesField {
public CallbackHandler config;
private Subject subject;
}
| apache-2.0 |
elvisisking/modeshape | modeshape-jcr/src/main/java/org/modeshape/jcr/cache/ReferrerCounts.java | 6656 | /*
* ModeShape (http://www.modeshape.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.modeshape.jcr.cache;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.modeshape.common.annotation.Immutable;
/**
* An immutable snapshot of the referrers to a node.
*
* @author Randall Hauch ([email protected])
*/
@Immutable
public final class ReferrerCounts {
private static final Map<NodeKey, Integer> EMPTY_COUNTS = Collections.emptyMap();
/**
* Create a new instance of the snapshot.
*
* @param strongCountsByReferrerKey the map of weak reference counts keyed by referrer's node keys; may be null or empty
* @param weakCountsByReferrerKey the map of weak reference counts keyed by referrer's node keys; may be null or empty
* @return the counts snapshot; null if there are no referrers
*/
public static ReferrerCounts create( Map<NodeKey, Integer> strongCountsByReferrerKey,
Map<NodeKey, Integer> weakCountsByReferrerKey ) {
if (strongCountsByReferrerKey == null) strongCountsByReferrerKey = EMPTY_COUNTS;
if (weakCountsByReferrerKey == null) weakCountsByReferrerKey = EMPTY_COUNTS;
if (strongCountsByReferrerKey.isEmpty() && weakCountsByReferrerKey.isEmpty()) return null;
return new ReferrerCounts(strongCountsByReferrerKey, weakCountsByReferrerKey);
}
public static MutableReferrerCounts createMutable() {
return new MutableReferrerCounts(null);
}
protected static int count( Integer count ) {
return count != null ? count.intValue() : 0;
}
private final Map<NodeKey, Integer> strongCountsByReferrerKey;
private final Map<NodeKey, Integer> weakCountsByReferrerKey;
protected ReferrerCounts( Map<NodeKey, Integer> strongCountsByReferrerKey,
Map<NodeKey, Integer> weakCountsByReferrerKey ) {
assert strongCountsByReferrerKey != null;
assert weakCountsByReferrerKey != null;
this.strongCountsByReferrerKey = strongCountsByReferrerKey;
this.weakCountsByReferrerKey = weakCountsByReferrerKey;
}
/**
* Get the set of node keys to the nodes with strong references.
*
* @return the referring node keys; never null but possibly empty
*/
public Set<NodeKey> getStrongReferrers() {
return strongCountsByReferrerKey.keySet();
}
/**
* Get the set of node keys to the nodes with weak references.
*
* @return the referring node keys; never null but possibly empty
*/
public Set<NodeKey> getWeakReferrers() {
return weakCountsByReferrerKey.keySet();
}
/**
* Get the number of strong references of a particular referring node.
*
* @param referrer the referring node
* @return the number of references, or 0 if there are none or if {@code referrer} is null
*/
public int countStrongReferencesFrom( NodeKey referrer ) {
return count(strongCountsByReferrerKey.get(referrer));
}
/**
* Get the number of weak references of a particular referring node.
*
* @param referrer the referring node
* @return the number of references, or 0 if there are none or if {@code referrer} is null
*/
public int countWeakReferencesFrom( NodeKey referrer ) {
return count(weakCountsByReferrerKey.get(referrer));
}
/**
* Get a mutable version of this snapshot.
*
* @return the mutable representation
*/
public MutableReferrerCounts mutable() {
return new MutableReferrerCounts(this);
}
public static final class MutableReferrerCounts {
private final Map<NodeKey, Integer> strongCountsByReferrerKey = new HashMap<>();
private final Map<NodeKey, Integer> weakCountsByReferrerKey = new HashMap<>();
protected MutableReferrerCounts( ReferrerCounts counts ) {
if (counts != null) {
for (NodeKey key : counts.getStrongReferrers()) {
strongCountsByReferrerKey.put(key, counts.countStrongReferencesFrom(key));
}
for (NodeKey key : counts.getStrongReferrers()) {
weakCountsByReferrerKey.put(key, counts.countWeakReferencesFrom(key));
}
}
}
/**
* Add the specified number of strong reference counts for the given key.
*
* @param key the referring node key
* @param increment the number to increase; may be negative to decrease
* @return this object for chaining method calls; never null
*/
public MutableReferrerCounts addStrong( NodeKey key,
int increment ) {
change(key, increment, strongCountsByReferrerKey);
return this;
}
/**
* Add the specified number of weak reference counts for the given key.
*
* @param key the referring node key
* @param increment the number to increase; may be negative to decrease
* @return this object for chaining method calls; never null
*/
public MutableReferrerCounts addWeak( NodeKey key,
int increment ) {
change(key, increment, weakCountsByReferrerKey);
return this;
}
/**
* Freeze this mutable object and create a new immutable {@link ReferrerCounts}.
*
* @return the immutable counts snapshot; null if there are no referrers
*/
public ReferrerCounts freeze() {
return create(strongCountsByReferrerKey, weakCountsByReferrerKey);
}
private void change( NodeKey key,
int increment,
Map<NodeKey, Integer> counts ) {
if (key == null) return;
int count = count(counts.get(key)) + increment;
if (count > 0) counts.put(key, count);
else counts.remove(key);
}
}
}
| apache-2.0 |
tzulitai/flink | flink-runtime/src/test/java/org/apache/flink/runtime/state/StateSnapshotCompressionTest.java | 6592 | /*
* 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.flink.runtime.state;
import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeutils.base.StringSerializer;
import org.apache.flink.core.fs.CloseableRegistry;
import org.apache.flink.runtime.checkpoint.CheckpointOptions;
import org.apache.flink.runtime.checkpoint.StateObjectCollection;
import org.apache.flink.runtime.query.TaskKvStateRegistry;
import org.apache.flink.runtime.state.heap.HeapKeyedStateBackend;
import org.apache.flink.runtime.state.heap.HeapKeyedStateBackendBuilder;
import org.apache.flink.runtime.state.heap.HeapPriorityQueueSetFactory;
import org.apache.flink.runtime.state.internal.InternalValueState;
import org.apache.flink.runtime.state.memory.MemCheckpointStreamFactory;
import org.apache.flink.runtime.state.ttl.TtlTimeProvider;
import org.apache.flink.util.TestLogger;
import org.apache.commons.io.IOUtils;
import org.junit.Assert;
import org.junit.Test;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.RunnableFuture;
import static org.mockito.Mockito.mock;
public class StateSnapshotCompressionTest extends TestLogger {
@Test
public void testCompressionConfiguration() throws BackendBuildingException {
ExecutionConfig executionConfig = new ExecutionConfig();
executionConfig.setUseSnapshotCompression(true);
AbstractKeyedStateBackend<String> stateBackend = getStringHeapKeyedStateBackend(executionConfig);
try {
Assert.assertTrue(
SnappyStreamCompressionDecorator.INSTANCE.equals(stateBackend.getKeyGroupCompressionDecorator()));
} finally {
IOUtils.closeQuietly(stateBackend);
stateBackend.dispose();
}
executionConfig = new ExecutionConfig();
executionConfig.setUseSnapshotCompression(false);
stateBackend = getStringHeapKeyedStateBackend(executionConfig);
try {
Assert.assertTrue(
UncompressedStreamCompressionDecorator.INSTANCE.equals(stateBackend.getKeyGroupCompressionDecorator()));
} finally {
IOUtils.closeQuietly(stateBackend);
stateBackend.dispose();
}
}
@Test
public void snapshotRestoreRoundtripWithCompression() throws Exception {
snapshotRestoreRoundtrip(true);
}
@Test
public void snapshotRestoreRoundtripUncompressed() throws Exception {
snapshotRestoreRoundtrip(false);
}
private HeapKeyedStateBackend<String> getStringHeapKeyedStateBackend(ExecutionConfig executionConfig)
throws BackendBuildingException {
return getStringHeapKeyedStateBackend(executionConfig, Collections.emptyList());
}
private HeapKeyedStateBackend<String> getStringHeapKeyedStateBackend(
ExecutionConfig executionConfig,
Collection<KeyedStateHandle> stateHandles)
throws BackendBuildingException {
return new HeapKeyedStateBackendBuilder<>(
mock(TaskKvStateRegistry.class),
StringSerializer.INSTANCE,
StateSnapshotCompressionTest.class.getClassLoader(),
16,
new KeyGroupRange(0, 15),
executionConfig,
TtlTimeProvider.DEFAULT,
stateHandles,
AbstractStateBackend.getCompressionDecorator(executionConfig),
TestLocalRecoveryConfig.disabled(),
mock(HeapPriorityQueueSetFactory.class),
true,
new CloseableRegistry()).build();
}
private void snapshotRestoreRoundtrip(boolean useCompression) throws Exception {
ExecutionConfig executionConfig = new ExecutionConfig();
executionConfig.setUseSnapshotCompression(useCompression);
KeyedStateHandle stateHandle;
ValueStateDescriptor<String> stateDescriptor = new ValueStateDescriptor<>("test", String.class);
stateDescriptor.initializeSerializerUnlessSet(executionConfig);
AbstractKeyedStateBackend<String> stateBackend = getStringHeapKeyedStateBackend(executionConfig);
try {
InternalValueState<String, VoidNamespace, String> state =
stateBackend.createInternalState(new VoidNamespaceSerializer(), stateDescriptor);
stateBackend.setCurrentKey("A");
state.setCurrentNamespace(VoidNamespace.INSTANCE);
state.update("42");
stateBackend.setCurrentKey("B");
state.setCurrentNamespace(VoidNamespace.INSTANCE);
state.update("43");
stateBackend.setCurrentKey("C");
state.setCurrentNamespace(VoidNamespace.INSTANCE);
state.update("44");
stateBackend.setCurrentKey("D");
state.setCurrentNamespace(VoidNamespace.INSTANCE);
state.update("45");
CheckpointStreamFactory streamFactory = new MemCheckpointStreamFactory(4 * 1024 * 1024);
RunnableFuture<SnapshotResult<KeyedStateHandle>> snapshot =
stateBackend.snapshot(0L, 0L, streamFactory, CheckpointOptions.forCheckpointWithDefaultLocation());
snapshot.run();
SnapshotResult<KeyedStateHandle> snapshotResult = snapshot.get();
stateHandle = snapshotResult.getJobManagerOwnedSnapshot();
} finally {
IOUtils.closeQuietly(stateBackend);
stateBackend.dispose();
}
executionConfig = new ExecutionConfig();
stateBackend = getStringHeapKeyedStateBackend(executionConfig, StateObjectCollection.singleton(stateHandle));
try {
InternalValueState<String, VoidNamespace, String> state = stateBackend.createInternalState(
new VoidNamespaceSerializer(),
stateDescriptor);
stateBackend.setCurrentKey("A");
state.setCurrentNamespace(VoidNamespace.INSTANCE);
Assert.assertEquals("42", state.value());
stateBackend.setCurrentKey("B");
state.setCurrentNamespace(VoidNamespace.INSTANCE);
Assert.assertEquals("43", state.value());
stateBackend.setCurrentKey("C");
state.setCurrentNamespace(VoidNamespace.INSTANCE);
Assert.assertEquals("44", state.value());
stateBackend.setCurrentKey("D");
state.setCurrentNamespace(VoidNamespace.INSTANCE);
Assert.assertEquals("45", state.value());
} finally {
IOUtils.closeQuietly(stateBackend);
stateBackend.dispose();
}
}
}
| apache-2.0 |
MikkelTAndersen/libgdx | extensions/gdx-bullet/jni/swig-src/collision/com/badlogic/gdx/physics/bullet/collision/btMultiSphereShape.java | 3571 | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.BulletBase;
import com.badlogic.gdx.physics.bullet.linearmath.*;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.math.Quaternion;
import com.badlogic.gdx.math.Matrix3;
import com.badlogic.gdx.math.Matrix4;
public class btMultiSphereShape extends btConvexInternalAabbCachingShape {
private long swigCPtr;
protected btMultiSphereShape(final String className, long cPtr, boolean cMemoryOwn) {
super(className, CollisionJNI.btMultiSphereShape_SWIGUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btMultiSphereShape, normally you should not need this constructor it's intended for low-level usage. */
public btMultiSphereShape(long cPtr, boolean cMemoryOwn) {
this("btMultiSphereShape", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset(long cPtr, boolean cMemoryOwn) {
if (!destroyed)
destroy();
super.reset(CollisionJNI.btMultiSphereShape_SWIGUpcast(swigCPtr = cPtr), cMemoryOwn);
}
public static long getCPtr(btMultiSphereShape obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize() throws Throwable {
if (!destroyed)
destroy();
super.finalize();
}
@Override protected synchronized void delete() {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btMultiSphereShape(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public long operatorNew(long sizeInBytes) {
return CollisionJNI.btMultiSphereShape_operatorNew__SWIG_0(swigCPtr, this, sizeInBytes);
}
public void operatorDelete(long ptr) {
CollisionJNI.btMultiSphereShape_operatorDelete__SWIG_0(swigCPtr, this, ptr);
}
public long operatorNew(long arg0, long ptr) {
return CollisionJNI.btMultiSphereShape_operatorNew__SWIG_1(swigCPtr, this, arg0, ptr);
}
public void operatorDelete(long arg0, long arg1) {
CollisionJNI.btMultiSphereShape_operatorDelete__SWIG_1(swigCPtr, this, arg0, arg1);
}
public long operatorNewArray(long sizeInBytes) {
return CollisionJNI.btMultiSphereShape_operatorNewArray__SWIG_0(swigCPtr, this, sizeInBytes);
}
public void operatorDeleteArray(long ptr) {
CollisionJNI.btMultiSphereShape_operatorDeleteArray__SWIG_0(swigCPtr, this, ptr);
}
public long operatorNewArray(long arg0, long ptr) {
return CollisionJNI.btMultiSphereShape_operatorNewArray__SWIG_1(swigCPtr, this, arg0, ptr);
}
public void operatorDeleteArray(long arg0, long arg1) {
CollisionJNI.btMultiSphereShape_operatorDeleteArray__SWIG_1(swigCPtr, this, arg0, arg1);
}
public btMultiSphereShape(Vector3[] positions, float[] radi, int numSpheres) {
this(CollisionJNI.new_btMultiSphereShape(positions, radi, numSpheres), true);
}
public int getSphereCount() {
return CollisionJNI.btMultiSphereShape_getSphereCount(swigCPtr, this);
}
public Vector3 getSpherePosition(int index) {
return CollisionJNI.btMultiSphereShape_getSpherePosition(swigCPtr, this, index);
}
public float getSphereRadius(int index) {
return CollisionJNI.btMultiSphereShape_getSphereRadius(swigCPtr, this, index);
}
}
| apache-2.0 |
chanakaudaya/wso2-axis2-transports | modules/jms/src/test/java/org/apache/axis2/transport/jms/JMSClient.java | 3367 | /*
* 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.axis2.transport.jms;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.mail.internet.ContentType;
import org.apache.axis2.transport.base.BaseConstants;
import org.apache.axis2.transport.testkit.client.ClientOptions;
import org.apache.axis2.transport.testkit.client.TestClient;
import org.apache.axis2.transport.testkit.name.Name;
import org.apache.axis2.transport.testkit.name.Named;
import org.apache.axis2.transport.testkit.tests.Setup;
import org.apache.axis2.transport.testkit.tests.TearDown;
import org.apache.axis2.transport.testkit.tests.Transient;
@Name("jms")
public class JMSClient<T> implements TestClient {
protected final JMSMessageFactory<T> jmsMessageFactory;
private @Transient Connection connection;
private @Transient Session session;
private @Transient MessageProducer producer;
private @Transient ContentTypeMode contentTypeMode;
public JMSClient(JMSMessageFactory<T> jmsMessageFactory) {
this.jmsMessageFactory = jmsMessageFactory;
}
@Named
public JMSMessageFactory<T> getJmsMessageFactory() {
return jmsMessageFactory;
}
@Setup @SuppressWarnings("unused")
private void setUp(JMSTestEnvironment env, JMSChannel channel) throws Exception {
Destination destination = channel.getDestination();
ConnectionFactory connectionFactory = env.getConnectionFactory();
connection = connectionFactory.createConnection();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
producer = session.createProducer(destination);
contentTypeMode = channel.getContentTypeMode();
}
protected String doSendMessage(ClientOptions options, ContentType contentType, T message) throws Exception {
Message jmsMessage = jmsMessageFactory.createMessage(session, message);
if (contentTypeMode == ContentTypeMode.TRANSPORT) {
jmsMessage.setStringProperty(BaseConstants.CONTENT_TYPE, contentType.toString());
}
producer.send(jmsMessage);
return jmsMessage.getJMSMessageID();
}
@TearDown @SuppressWarnings("unused")
private void tearDown() throws Exception {
producer.close();
session.close();
connection.close();
}
public ContentType getContentType(ClientOptions options, ContentType contentType) {
return contentType;
}
}
| apache-2.0 |
waiducom/Carbon-Forum | language/zh-tw/forgot.php | 886 | <?php
if (!defined('InternalAccess')) exit('error: 403 Access Denied');
if (empty($Lang) || !is_array($Lang))
$Lang = array();
$Lang = array_merge($Lang, array(
'Email' => '密保郵箱',
'Submit' => '提交',
'Forms_Can_Not_Be_Empty' => '用戶名/郵箱地址/驗證碼必填',
'User_Does_Not_Exist' => '用戶不存在',
'Email_Error' => '電子郵件輸入錯誤,該使用者郵箱位址為:{{UserMail}}',
'Verification_Code_Error' => '驗證碼錯誤',
'Email_Has_Been_Sent' => '請求成功,請登錄您的密保郵箱查收新郵件以重置密碼。',
'Email_Could_Not_Be_Sent' => '密保郵件發送失敗',
'Mail_Template_Subject' => '{{UserName}}, 密碼重置申請 - {{SiteName}}',
'Mail_Template_Body' => '<p>{{UserName}},
請在兩小時內點擊以下連結重置密碼: </p>
<p><a href="{{ResetPasswordURL}}">{{ResetPasswordURL}}</a></p>',
)); | apache-2.0 |
apixandru/intellij-community | xml/impl/src/com/intellij/featureStatistics/XmlProductivityFeatureProvider.java | 1906 | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.featureStatistics;
import com.intellij.codeInsight.completion.XmlCompletionContributor;
import com.intellij.xml.XmlBundle;
import java.util.Collections;
/**
* @author Dmitry Avdeev
*/
public class XmlProductivityFeatureProvider extends ProductivityFeaturesProvider {
@Override
public FeatureDescriptor[] getFeatureDescriptors() {
return new FeatureDescriptor[] { new FeatureDescriptor(XmlCompletionContributor.TAG_NAME_COMPLETION_FEATURE,
"completion",
"TagNameCompletion.html",
XmlBundle.message("tag.name.completion.display.name"),
0,
1,
Collections.emptySet(),
3,
this)};
}
@Override
public GroupDescriptor[] getGroupDescriptors() {
return new GroupDescriptor[0];
}
@Override
public ApplicabilityFilter[] getApplicabilityFilters() {
return new ApplicabilityFilter[0];
}
}
| apache-2.0 |
samarpanda/falcor | lib/errors/BoundJSONGraphModelError.js | 678 | /**
* When a bound model attempts to retrieve JSONGraph it should throw an
* error.
*
* @private
*/
function BoundJSONGraphModelError() {
this.message = BoundJSONGraphModelError.message;
this.stack = (new Error()).stack;
}
// instanceof will be an error, but stack will be correct because its defined in the constructor.
BoundJSONGraphModelError.prototype = new Error();
BoundJSONGraphModelError.prototype.name = "BoundJSONGraphModelError";
BoundJSONGraphModelError.message =
"It is not legal to use the JSON Graph " +
"format from a bound Model. JSON Graph format" +
" can only be used from a root model.";
module.exports = BoundJSONGraphModelError;
| apache-2.0 |
ashishb/homebrew-cask | Casks/remote-desktop-connection.rb | 401 | class RemoteDesktopConnection < Cask
version '2.1.1'
sha256 '4ebe551c9ee0e2da6b8f746be13c2df342c6f14cd3fbedbf2ab490f09b44616f'
url 'http://download.microsoft.com/download/C/F/0/CF0AE39A-3307-4D39-9D50-58E699C91B2F/RDC_2.1.1_ALL.dmg'
homepage 'http://www.microsoft.com/en-us/download/details.aspx?id=18140'
install 'RDC Installer.mpkg'
uninstall :pkgutil => 'com.microsoft.rdc.all.*'
end
| bsd-2-clause |
zhuyongyong/crosswalk-test-suite | wrt/wrt-packagemgt-windows-tests/pmwindows/Crosswalk_WebApp_Update.py | 1973 | #!/bin/bash
#Copyright (c) 2015 Intel Corporation.
#
#Redistribution and use in source and binary forms, with or without modification,
#are permitted provided that the following conditions are met:
#
#* Redistributions of works must retain the original copyright notice, this list
# of conditions and the following disclaimer.
#* Redistributions in binary form must reproduce the original 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 Intel Corporation nor the names of its contributors
# may be used to endorse or promote products derived from this work without
# specific prior written permission.
#
#THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION "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 INTEL CORPORATION 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.
#
# Authors:
# Zhu, Yongyong <[email protected]>
import unittest
import os
import commands
import comm
class TestWebAppUpdate(unittest.TestCase):
def test_update(self):
app_name = "testapp"
pkg_name = "org.xwalk." + app_name
if comm.checkInstalled(pkg_name):
comm.app_uninstall(app_name, pkg_name, self)
comm.app_install(app_name, pkg_name, self)
comm.app_install(app_name, pkg_name, self)
if __name__ == '__main__':
unittest.main()
| bsd-3-clause |
qoqa/lithium | analysis/logger/adapter/Growl.php | 8476 | <?php
/**
* Lithium: the most rad php framework
*
* @copyright Copyright 2012, Union of RAD (http://union-of-rad.org)
* @license http://opensource.org/licenses/bsd-license.php The BSD License
*/
namespace lithium\analysis\logger\adapter;
use lithium\util\Inflector;
use lithium\core\NetworkException;
/**
* The `Growl` logger implements support for the [ Growl](http://growl.info/) notification system
* for Mac OS X. Writing to this logger will display small, customizable status messages on the
* screen.
*/
class Growl extends \lithium\core\Object {
/**
* Array that maps `Logger` message priority names to Growl-compatible priority levels.
*
* @var array
*/
protected $_priorities = array(
'emergency' => 2,
'alert' => 1,
'critical' => 1,
'error' => 1,
'warning' => 0,
'notice' => -1,
'info' => -2,
'debug' => -2
);
/**
* The Growl protocol version used to send messages.
*/
const PROTOCOL_VERSION = 1;
/**
* There are two types of messages sent to Growl: one to register applications, and one to send
* notifications. This type registers the application with Growl's settings.
*/
const TYPE_REG = 0;
/**
* This message type is for sending notifications to Growl.
*/
const TYPE_NOTIFY = 1;
/**
* Holds the connection resource used to send messages to Growl.
*
* @var resource
*/
protected $_connection = null;
/**
* Flag indicating whether the logger has successfully registered with the Growl server.
* Registration only needs to happen once, but may fail for several reasons, including inability
* to connect to the server, or the server requires a password which has not been specified.
*
* @var boolean
*/
protected $_registered = false;
/**
* Allow the Growl connection resource to be auto-configured from constructor parameters.
*
* @var array
*/
protected $_autoConfig = array('connection', 'registered');
/**
* Growl logger constructor. Accepts an array of settings which are merged with the default
* settings and used to create the connection and handle notifications.
*
* @see lithium\analysis\Logger::write()
* @param array $config The settings to configure the logger. Available settings are as follows:
* - `'name`' _string_: The name of the application as it should appear in Growl's
* system settings. Defaults to the directory name containing your application.
* - `'host'` _string_: The Growl host with which to communicate, usually your
* local machine. Use this setting to send notifications to another machine on
* the network. Defaults to `'127.0.0.1'`.
* - `'port'` _integer_: Port of the host machine. Defaults to the standard Growl
* port, `9887`.
* - `'password'` _string_: Only required if the host machine requires a password.
* If notification or registration fails, check this against the host machine's
* Growl settings.
* - '`protocol'` _string_: Protocol to use when opening socket communication to
* Growl. Defaults to `'udp'`.
* - `'title'` _string_: The default title to display when showing Growl messages.
* The default value is the same as `'name'`, but can be changed on a per-message
* basis by specifying a `'title'` key in the `$options` parameter of
* `Logger::write()`.
* - `'notification'` _array_: A list of message types you wish to register with
* Growl to be able to send. Defaults to `array('Errors', 'Messages')`.
*/
public function __construct(array $config = array()) {
$name = basename(LITHIUM_APP_PATH);
$defaults = compact('name') + array(
'host' => '127.0.0.1',
'port' => 9887,
'password' => null,
'protocol' => 'udp',
'title' => Inflector::humanize($name),
'notifications' => array('Errors', 'Messages'),
'registered' => false
);
parent::__construct($config + $defaults);
}
/**
* Writes `$message` to a new Growl notification.
*
* @param string $type The `Logger`-based priority of the message. This value is mapped to
* a Growl-specific priority value if possible.
* @param string $message Message to be shown.
* @param array $options Any options that are passed to the `notify()` method. See the
* `$options` parameter of `notify()`.
* @return closure Function returning boolean `true` on successful write, `false` otherwise.
*/
public function write($type, $message, array $options = array()) {
$_self =& $this;
$_priorities = $this->_priorities;
return function($self, $params) use (&$_self, $_priorities) {
$priority = 0;
$options = $params['options'];
if (isset($options['priority']) && isset($_priorities[$options['priority']])) {
$priority = $_priorities[$options['priority']];
}
return $_self->notify($params['message'], compact('priority') + $options);
};
}
/**
* Posts a new notification to the Growl server.
*
* @param string $description Message to be displayed.
* @param array $options Options consists of:
* -'title': The title of the displayed notification. Displays the
* name of the application's parent folder by default.
* @return boolean Always returns `true`.
*/
public function notify($description = '', $options = array()) {
$this->_register();
$defaults = array('sticky' => false, 'priority' => 0, 'type' => 'Messages');
$options += $defaults + array('title' => $this->_config['title']);
$type = $options['type'];
$title = $options['title'];
$message = compact('type', 'title', 'description') + array('app' => $this->_config['name']);
$message = array_map('utf8_encode', $message);
$flags = ($options['priority'] & 7) * 2;
$flags = ($options['priority'] < 0) ? $flags |= 8 : $flags;
$flags = ($options['sticky']) ? $flags | 256 : $flags;
$params = array('c2n5', static::PROTOCOL_VERSION, static::TYPE_NOTIFY, $flags);
$lengths = array_map('strlen', $message);
$data = call_user_func_array('pack', array_merge($params, $lengths));
$data .= join('', $message);
$data .= pack('H32', md5($data . $this->_config['password']));
$this->_send($data);
return true;
}
/**
* Growl server connection registration and initialization.
*
* @return boolean True
*/
protected function _register() {
if ($this->_registered) {
return true;
}
$ct = count($this->_config['notifications']);
$app = utf8_encode($this->_config['name']);
$nameEnc = $defaultEnc = '';
foreach ($this->_config['notifications'] as $i => $name) {
$name = utf8_encode($name);
$nameEnc .= pack('n', strlen($name)) . $name;
$defaultEnc .= pack('c', $i);
}
$data = pack('c2nc2', static::PROTOCOL_VERSION, static::TYPE_REG, strlen($app), $ct, $ct);
$data .= $app . $nameEnc . $defaultEnc;
$checksum = pack('H32', md5($data . $this->_config['password']));
$data .= $checksum;
$this->_send($data);
return $this->_registered = true;
}
/**
* Creates a connection to the Growl server using the protocol, host and port configurations
* specified in the constructor.
*
* @return resource Returns a connection resource created by `fsockopen()`.
*/
protected function _connection() {
if ($this->_connection) {
return $this->_connection;
}
$host = "{$this->_config['protocol']}://{$this->_config['host']}";
if ($this->_connection = fsockopen($host, $this->_config['port'], $message, $code)) {
return $this->_connection;
}
throw new NetworkException("Growl connection failed: (`{$code}`) `{$message}`.");
}
/**
* Sends binary data to the Growl server.
*
* @throws NetworkException Throws an exception if the server connection could not be written
* to.
* @param string $data The raw binary data to send to the Growl server.
* @return boolean Always returns `true`.
*/
protected function _send($data) {
if (fwrite($this->_connection(), $data, strlen($data)) === false) {
throw new NetworkException('Could not send registration to Growl Server.');
}
return true;
}
/**
* Destructor method. Closes and releases the socket connection to Growl.
*/
public function __destruct() {
if (is_resource($this->_connection)) {
fclose($this->_connection);
unset($this->_connection);
}
}
}
?> | bsd-3-clause |
vadimtk/chrome4sdp | chrome/service/cloud_print/cloud_print_service_helpers_unittest.cc | 4009 | // Copyright 2013 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/service/cloud_print/cloud_print_service_helpers.h"
#include "base/md5.h"
#include "base/strings/stringprintf.h"
#include "base/sys_info.h"
#include "chrome/common/channel_info.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace cloud_print {
namespace {
void CheckJobStatusURLs(const GURL& server_base_url) {
std::string expected_url_base = server_base_url.spec();
if (expected_url_base[expected_url_base.length() - 1] != '/')
expected_url_base += "/";
EXPECT_EQ(base::StringPrintf(
"%scontrol?jobid=87654321&status=ERROR&connector_code=1",
expected_url_base.c_str()),
GetUrlForJobStatusUpdate(server_base_url, "87654321",
PRINT_JOB_STATUS_ERROR, 1).spec());
PrintJobDetails details;
details.status = PRINT_JOB_STATUS_IN_PROGRESS;
details.platform_status_flags = 2;
details.status_message = "Out of Paper";
details.total_pages = 345;
details.pages_printed = 47;
EXPECT_EQ(base::StringPrintf(
"%scontrol?jobid=87654321&status=IN_PROGRESS&code=2"
"&message=Out%%20of%%20Paper&numpages=345&pagesprinted=47",
expected_url_base.c_str()),
GetUrlForJobStatusUpdate(
server_base_url, "87654321", details).spec());
}
} // namespace
TEST(CloudPrintServiceHelpersTest, GetURLs) {
CheckJobStatusURLs(GURL("https://www.google.com/cloudprint"));
CheckJobStatusURLs(GURL("https://www.google.com/cloudprint/"));
CheckJobStatusURLs(GURL("http://www.myprinterserver.com"));
CheckJobStatusURLs(GURL("http://www.myprinterserver.com/"));
}
TEST(CloudPrintServiceHelpersTest, GetHashOfPrinterInfo) {
printing::PrinterBasicInfo printer_info;
printer_info.options["tag1"] = std::string("value1");
printer_info.options["tag2"] = std::string("value2");
std::string expected_list_string = base::StringPrintf(
"chrome_version%ssystem_name%ssystem_version%stag1value1tag2value2",
chrome::GetVersionString().c_str(),
base::SysInfo::OperatingSystemName().c_str(),
base::SysInfo::OperatingSystemVersion().c_str());
EXPECT_EQ(base::MD5String(expected_list_string),
GetHashOfPrinterInfo(printer_info));
}
TEST(CloudPrintServiceHelpersTest, GetPostDataForPrinterInfo) {
printing::PrinterBasicInfo printer_info;
printer_info.options["tag1"] = std::string("value1");
printer_info.options["tag2"] = std::string("value2");
std::string expected = base::StringPrintf(
"--test_mime_boundary\r\nContent-Disposition: form-data; name=\"tag\""
"\r\n\r\n__cp__chrome_version=%s\r\n"
"--test_mime_boundary\r\nContent-Disposition: form-data; name=\"tag\""
"\r\n\r\n__cp__system_name=%s\r\n"
"--test_mime_boundary\r\nContent-Disposition: form-data; name=\"tag\""
"\r\n\r\n__cp__system_version=%s\r\n"
"--test_mime_boundary\r\nContent-Disposition: form-data; name=\"tag\""
"\r\n\r\n__cp__tag1=value1\r\n"
"--test_mime_boundary\r\nContent-Disposition: form-data; name=\"tag\""
"\r\n\r\n__cp__tag2=value2\r\n"
"--test_mime_boundary\r\nContent-Disposition: form-data; name=\"tag\""
"\r\n\r\n__cp__tagshash=%s\r\n",
chrome::GetVersionString().c_str(),
base::SysInfo::OperatingSystemName().c_str(),
base::SysInfo::OperatingSystemVersion().c_str(),
GetHashOfPrinterInfo(printer_info).c_str());
EXPECT_EQ(expected, GetPostDataForPrinterInfo(
printer_info, std::string("test_mime_boundary")));
}
TEST(CloudPrintServiceHelpersTest, IsDryRunJob) {
std::vector<std::string> tags_not_dry_run;
tags_not_dry_run.push_back("tag_1");
EXPECT_FALSE(IsDryRunJob(tags_not_dry_run));
std::vector<std::string> tags_dry_run;
tags_dry_run.push_back("__cp__dry_run");
EXPECT_TRUE(IsDryRunJob(tags_dry_run));
}
} // namespace cloud_print
| bsd-3-clause |
axhm3a/ZendFrameworkCertification | vendor/phpunit/php-code-coverage/PHP/CodeCoverage/Util.php | 9974 | <?php
/**
* PHP_CodeCoverage
*
* Copyright (c) 2009-2013, Sebastian Bergmann <[email protected]>.
* 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 Sebastian Bergmann nor the names of his
* 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.
*
* @category PHP
* @package CodeCoverage
* @author Sebastian Bergmann <[email protected]>
* @copyright 2009-2013 Sebastian Bergmann <[email protected]>
* @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License
* @link http://github.com/sebastianbergmann/php-code-coverage
* @since File available since Release 1.0.0
*/
/**
* Utility methods.
*
* @category PHP
* @package CodeCoverage
* @author Sebastian Bergmann <[email protected]>
* @copyright 2009-2013 Sebastian Bergmann <[email protected]>
* @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License
* @link http://github.com/sebastianbergmann/php-code-coverage
* @since Class available since Release 1.0.0
*/
class PHP_CodeCoverage_Util
{
/**
* @var array
*/
protected static $ignoredLines = array();
/**
* @var array
*/
protected static $ids = array();
/**
* Returns the lines of a source file that should be ignored.
*
* @param string $filename
* @param boolean $cacheTokens
* @return array
* @throws PHP_CodeCoverage_Exception
*/
public static function getLinesToBeIgnored($filename, $cacheTokens = TRUE)
{
if (!is_string($filename)) {
throw PHP_CodeCoverage_Util_InvalidArgumentHelper::factory(
1, 'string'
);
}
if (!is_bool($cacheTokens)) {
throw PHP_CodeCoverage_Util_InvalidArgumentHelper::factory(
2, 'boolean'
);
}
if (!isset(self::$ignoredLines[$filename])) {
self::$ignoredLines[$filename] = array();
$ignore = FALSE;
$stop = FALSE;
$lines = file($filename);
foreach ($lines as $index => $line) {
if (!trim($line)) {
self::$ignoredLines[$filename][$index+1] = TRUE;
}
}
if ($cacheTokens) {
$tokens = PHP_Token_Stream_CachingFactory::get($filename);
} else {
$tokens = new PHP_Token_Stream($filename);
}
$classes = array_merge($tokens->getClasses(), $tokens->getTraits());
$tokens = $tokens->tokens();
foreach ($tokens as $token) {
switch (get_class($token)) {
case 'PHP_Token_COMMENT':
case 'PHP_Token_DOC_COMMENT': {
$count = substr_count($token, "\n");
$line = $token->getLine();
for ($i = $line; $i < $line + $count; $i++) {
self::$ignoredLines[$filename][$i] = TRUE;
}
if ($token instanceof PHP_Token_DOC_COMMENT) {
// Workaround for the fact the DOC_COMMENT token
// does not include the final \n character in its
// text.
if (substr(trim($lines[$i-1]), -2) == '*/') {
self::$ignoredLines[$filename][$i] = TRUE;
}
break;
}
$_token = trim($token);
if ($_token == '// @codeCoverageIgnore' ||
$_token == '//@codeCoverageIgnore') {
$ignore = TRUE;
$stop = TRUE;
}
else if ($_token == '// @codeCoverageIgnoreStart' ||
$_token == '//@codeCoverageIgnoreStart') {
$ignore = TRUE;
}
else if ($_token == '// @codeCoverageIgnoreEnd' ||
$_token == '//@codeCoverageIgnoreEnd') {
$stop = TRUE;
}
}
break;
case 'PHP_Token_INTERFACE':
case 'PHP_Token_TRAIT':
case 'PHP_Token_CLASS':
case 'PHP_Token_FUNCTION': {
$docblock = $token->getDocblock();
if (strpos($docblock, '@codeCoverageIgnore')) {
$endLine = $token->getEndLine();
for ($i = $token->getLine(); $i <= $endLine; $i++) {
self::$ignoredLines[$filename][$i] = TRUE;
}
}
else if ($token instanceof PHP_Token_INTERFACE ||
$token instanceof PHP_Token_TRAIT ||
$token instanceof PHP_Token_CLASS) {
if (empty($classes[$token->getName()]['methods'])) {
for ($i = $token->getLine();
$i <= $token->getEndLine();
$i++) {
self::$ignoredLines[$filename][$i] = TRUE;
}
} else {
$firstMethod = array_shift(
$classes[$token->getName()]['methods']
);
$lastMethod = array_pop(
$classes[$token->getName()]['methods']
);
if ($lastMethod === NULL) {
$lastMethod = $firstMethod;
}
for ($i = $token->getLine();
$i < $firstMethod['startLine'];
$i++) {
self::$ignoredLines[$filename][$i] = TRUE;
}
for ($i = $token->getEndLine();
$i > $lastMethod['endLine'];
$i--) {
self::$ignoredLines[$filename][$i] = TRUE;
}
}
}
}
break;
case 'PHP_Token_INTERFACE': {
$endLine = $token->getEndLine();
for ($i = $token->getLine(); $i <= $endLine; $i++) {
self::$ignoredLines[$filename][$i] = TRUE;
}
}
break;
case 'PHP_Token_NAMESPACE': {
self::$ignoredLines[$filename][$token->getEndLine()] = TRUE;
} // Intentional fallthrough
case 'PHP_Token_OPEN_TAG':
case 'PHP_Token_CLOSE_TAG':
case 'PHP_Token_USE': {
self::$ignoredLines[$filename][$token->getLine()] = TRUE;
}
break;
}
if ($ignore) {
self::$ignoredLines[$filename][$token->getLine()] = TRUE;
if ($stop) {
$ignore = FALSE;
$stop = FALSE;
}
}
}
}
return self::$ignoredLines[$filename];
}
/**
* @param float $a
* @param float $b
* @return float ($a / $b) * 100
*/
public static function percent($a, $b, $asString = FALSE, $fixedWidth = FALSE)
{
if ($asString && $b == 0) {
return '';
}
if ($b > 0) {
$percent = ($a / $b) * 100;
} else {
$percent = 100;
}
if ($asString) {
if ($fixedWidth) {
return sprintf('%6.2F%%', $percent);
}
return sprintf('%01.2F%%', $percent);
} else {
return $percent;
}
}
}
| bsd-3-clause |
mxOBS/deb-pkg_trusty_chromium-browser | third_party/webrtc/base/sharedexclusivelock.cc | 1145 | /*
* Copyright 2011 The WebRTC 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 in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/base/sharedexclusivelock.h"
namespace rtc {
SharedExclusiveLock::SharedExclusiveLock()
: shared_count_is_zero_(true, true),
shared_count_(0) {
}
void SharedExclusiveLock::LockExclusive() {
cs_exclusive_.Enter();
shared_count_is_zero_.Wait(rtc::kForever);
}
void SharedExclusiveLock::UnlockExclusive() {
cs_exclusive_.Leave();
}
void SharedExclusiveLock::LockShared() {
CritScope exclusive_scope(&cs_exclusive_);
CritScope shared_scope(&cs_shared_);
if (++shared_count_ == 1) {
shared_count_is_zero_.Reset();
}
}
void SharedExclusiveLock::UnlockShared() {
CritScope shared_scope(&cs_shared_);
if (--shared_count_ == 0) {
shared_count_is_zero_.Set();
}
}
} // namespace rtc
| bsd-3-clause |
webmozart/zf2 | library/Zend/Tag/Cloud/DecoratorPluginManager.php | 1784 | <?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @package Zend_Tag
*/
namespace Zend\Tag\Cloud;
use Zend\ServiceManager\AbstractPluginManager;
use Zend\Tag\Exception;
/**
* Plugin manager implementation for decorators.
*
* Enforces that decorators retrieved are instances of
* Decorator\DecoratorInterface. Additionally, it registers a number of default
* decorators available.
*
* @category Zend
* @package Zend_Tag
* @subpackage Cloud
*/
class DecoratorPluginManager extends AbstractPluginManager
{
/**
* Default set of decorators
*
* @var array
*/
protected $invokableClasses = array(
'htmlcloud' => 'Zend\Tag\Cloud\Decorator\HtmlCloud',
'htmltag' => 'Zend\Tag\Cloud\Decorator\HtmlTag',
'tag' => 'Zend\Tag\Cloud\Decorator\Tag',
);
/**
* Validate the plugin
*
* Checks that the decorator loaded is an instance
* of Decorator\DecoratorInterface.
*
* @param mixed $plugin
* @return void
* @throws Exception\InvalidArgumentException if invalid
*/
public function validatePlugin($plugin)
{
if ($plugin instanceof Decorator\DecoratorInterface) {
// we're okay
return;
}
throw new Exception\InvalidArgumentException(sprintf(
'Plugin of type %s is invalid; must implement %s\Decorator\DecoratorInterface',
(is_object($plugin) ? get_class($plugin) : gettype($plugin)),
__NAMESPACE__
));
}
}
| bsd-3-clause |
ahoy-jon/symfony-1.2 | lib/plugins/sfPropelPlugin/lib/vendor/propel/adapter/DBMSSQL.php | 5917 | <?php
/*
* $Id: DBMSSQL.php 989 2008-03-11 14:29:30Z heltem $
*
* 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.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information please see
* <http://propel.phpdb.org>.
*/
/**
* This is used to connect to a MSSQL database.
*
* @author Hans Lellelid <[email protected]> (Propel)
* @version $Revision: 989 $
* @package propel.adapter
*/
class DBMSSQL extends DBAdapter {
/**
* This method is used to ignore case.
*
* @param in The string to transform to upper case.
* @return The upper case string.
*/
public function toUpperCase($in)
{
return "UPPER(" . $in . ")";
}
/**
* This method is used to ignore case.
*
* @param in The string whose case to ignore.
* @return The string in a case that can be ignored.
*/
public function ignoreCase($in)
{
return "UPPER(" . $in . ")";
}
/**
* Returns SQL which concatenates the second string to the first.
*
* @param string String to concatenate.
* @param string String to append.
* @return string
*/
public function concatString($s1, $s2)
{
return "($s1 + $s2)";
}
/**
* Returns SQL which extracts a substring.
*
* @param string String to extract from.
* @param int Offset to start from.
* @param int Number of characters to extract.
* @return string
*/
public function subString($s, $pos, $len)
{
return "SUBSTRING($s, $pos, $len)";
}
/**
* Returns SQL which calculates the length (in chars) of a string.
*
* @param string String to calculate length of.
* @return string
*/
public function strLength($s)
{
return "LEN($s)";
}
/**
* @see DBAdapter::quoteIdentifier()
*/
public function quoteIdentifier($text)
{
return '[' . $text . ']';
}
/**
* @see DBAdapter::random()
*/
public function random($seed = null)
{
return 'rand('.((int) $seed).')';
}
/**
* Simulated Limit/Offset
* This rewrites the $sql query to apply the offset and limit.
* @see DBAdapter::applyLimit()
* @author Justin Carlson <[email protected]>
*/
public function applyLimit(&$sql, $offset, $limit)
{
// make sure offset and limit are numeric
if (!is_numeric($offset) || !is_numeric($limit)){
throw new Exception("DBMSSQL ::applyLimit() expects a number for argument 2 and 3");
}
// obtain the original select statement
preg_match('/\A(.*)select(.*)from/si',$sql,$select_segment);
if (count($select_segment)>0)
{
$original_select = $select_segment[0];
} else {
throw new Exception("DBMSSQL ::applyLimit() could not locate the select statement at the start of the query. ");
}
$modified_select = substr_replace($original_select, null, stristr($original_select,'select') , 6 );
// obtain the original order by clause, or create one if there isn't one
preg_match('/order by(.*)\Z/si',$sql,$order_segment);
if (count($order_segment)>0)
{
$order_by = $order_segment[0];
} else {
// no order by clause, if there are columns we can attempt to sort by the columns in the select statement
$select_items = split(',',$modified_select);
if (count($select_items)>0)
{
$item_number = 0;
$order_by = null;
while ($order_by === null && $item_number<count($select_items))
{
if ($select_items[$item_number]!='*' && !strstr($select_items[$item_number],'('))
{
$order_by = 'order by ' . $select_items[0] . ' asc';
}
$item_number++;
}
}
if ($order_by === null)
{
throw new Exception("DBMSSQL ::applyLimit() could not locate the order by statement at the end of your query or any columns at the start of your query. ");
} else {
$sql.= ' ' . $order_by;
}
}
// remove the original select statement
$sql = str_replace($original_select , null, $sql);
/* modify the sort order by for paging */
$inverted_order = '';
$order_columns = split(',',str_ireplace('order by ','',$order_by));
$original_order_by = $order_by;
$order_by = '';
foreach ($order_columns as $column)
{
// strip "table." from order by columns
$column = array_reverse(split("\.",$column));
$column = $column[0];
// commas if we have multiple sort columns
if (strlen($inverted_order)>0){
$order_by.= ', ';
$inverted_order.=', ';
}
// put together order for paging wrapper
if (stristr($column,' desc'))
{
$order_by .= $column;
$inverted_order .= str_ireplace(' desc',' asc',$column);
} elseif (stristr($column,' asc')) {
$order_by .= $column;
$inverted_order .= str_ireplace(' asc',' desc',$column);
} else {
$order_by .= $column;
$inverted_order .= $column .' desc';
}
}
$order_by = 'order by ' . $order_by;
$inverted_order = 'order by ' . $inverted_order;
// build the query
$offset = ($limit+$offset);
$modified_sql = 'select * from (';
$modified_sql.= 'select top '.$limit.' * from (';
$modified_sql.= 'select top '.$offset.' '.$modified_select.$sql;
$modified_sql.= ') deriveda '.$inverted_order.') derivedb '.$order_by;
$sql = $modified_sql;
}
}
| mit |
kgatjens/d8_vm_vagrant | project/modules/contrib/webform/src/Tests/WebformSubmissionListBuilderTest.php | 8816 | <?php
namespace Drupal\webform\Tests;
/**
* Tests for webform submission list builder.
*
* @group Webform
*/
class WebformSubmissionListBuilderTest extends WebformTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['node', 'webform'];
/**
* Webforms to load.
*
* @var array
*/
protected static $testWebforms = ['test_results'];
/**
* {@inheritdoc}
*/
public function setUp() {
parent::setUp();
// Create users.
$this->createUsers();
}
/**
* Tests results.
*/
public function testResults() {
global $base_path;
// Login the normal user.
$this->drupalLogin($this->ownWebformSubmissionUser);
/** @var \Drupal\webform\WebformInterface $webform */
/** @var \Drupal\webform\WebformSubmissionInterface[] $submissions */
list($webform, $submissions) = $this->createWebformWithSubmissions();
// Make the second submission to be starred (aka sticky).
$submissions[1]->setSticky(TRUE)->save();
$this->drupalLogin($this->adminSubmissionUser);
/* Filter */
$this->drupalGet('admin/structure/webform/manage/' . $webform->id() . '/results/submissions');
// Check state options with totals.
$this->assertRaw('<select data-drupal-selector="edit-state" id="edit-state" name="state" class="form-select"><option value="" selected="selected">All [3]</option><option value="starred">Starred [1]</option><option value="unstarred">Unstarred [2]</option></select>');
// Check results with no filtering.
$this->assertLinkByHref($submissions[0]->toUrl()->toString());
$this->assertLinkByHref($submissions[1]->toUrl()->toString());
$this->assertLinkByHref($submissions[2]->toUrl()->toString());
$this->assertRaw($submissions[0]->getData('first_name'));
$this->assertRaw($submissions[1]->getData('first_name'));
$this->assertRaw($submissions[2]->getData('first_name'));
$this->assertNoFieldById('edit-reset', 'reset');
// Check results filtered by key(word).
$this->drupalPostForm('admin/structure/webform/manage/' . $webform->id() . '/results/submissions', ['search' => $submissions[0]->getData('first_name')], t('Filter'));
$this->assertUrl('admin/structure/webform/manage/' . $webform->id() . '/results/submissions?search=' . $submissions[0]->getData('first_name') . '&state=');
$this->assertRaw($submissions[0]->getData('first_name'));
$this->assertNoRaw($submissions[1]->getData('first_name'));
$this->assertNoRaw($submissions[2]->getData('first_name'));
$this->assertFieldById('edit-reset', 'Reset');
// Check results filtered by state.
$this->drupalPostForm('admin/structure/webform/manage/' . $webform->id() . '/results/submissions', ['state' => 'starred'], t('Filter'));
$this->assertUrl('admin/structure/webform/manage/' . $webform->id() . '/results/submissions?search=&state=starred');
$this->assertRaw('<option value="starred" selected="selected">Starred [1]</option>');
$this->assertNoRaw($submissions[0]->getData('first_name'));
$this->assertRaw($submissions[1]->getData('first_name'));
$this->assertNoRaw($submissions[2]->getData('first_name'));
$this->assertFieldById('edit-reset', 'Reset');
/**************************************************************************/
// Customize submission results.
/**************************************************************************/
// Check that created is visible and changed is hidden.
$this->drupalGet('admin/structure/webform/manage/' . $webform->id() . '/results/submissions');
$this->assertRaw('sort by Created');
$this->assertNoRaw('sort by Changed');
// Check that first name is before last name.
$this->assertPattern('#First name.+Last name#s');
// Check that no pager is being displayed.
$this->assertNoRaw('<nav class="pager" role="navigation" aria-labelledby="pagination-heading">');
// Check that table is sorted by serial.
$this->assertRaw('<th specifier="serial" aria-sort="descending" class="is-active">');
// Check the table results order by sid.
$this->assertPattern('#Hillary.+Abraham.+George#ms');
// Customize to results table.
$edit = [
'columns[created][checkbox]' => FALSE,
'columns[changed][checkbox]' => TRUE,
'columns[element__first_name][weight]' => '8',
'columns[element__last_name][weight]' => '7',
'sort' => 'element__first_name',
'direction' => 'desc',
'limit' => 20,
];
$this->drupalPostForm('admin/structure/webform/manage/' . $webform->id() . '/results/submissions/custom', $edit, t('Save'));
$this->assertRaw('The customized table has been saved.');
// Check that sid is hidden and changed is visible.
$this->drupalGet('admin/structure/webform/manage/' . $webform->id() . '/results/submissions');
$this->assertNoRaw('sort by Created');
$this->assertRaw('sort by Changed');
// Check that first name is now after last name.
$this->assertPattern('#Last name.+First name#ms');
// Check the table results order by first name.
$this->assertPattern('#Hillary.+George.+Abraham#ms');
// Manually set the limit to 1.
$webform->setState('results.custom.limit', 1);
// Check that only one result (Hillary #2) is displayed with pager.
$this->drupalGet('admin/structure/webform/manage/' . $webform->id() . '/results/submissions');
$this->assertNoRaw($submissions[0]->getData('first_name'));
$this->assertNoRaw($submissions[1]->getData('first_name'));
$this->assertRaw($submissions[2]->getData('first_name'));
$this->assertRaw('<nav class="pager" role="navigation" aria-labelledby="pagination-heading">');
// Reset the limit to 20.
$webform->setState('results.custom.limit', 20);
// Check Header label and element value display.
$this->drupalGet('admin/structure/webform/manage/' . $webform->id() . '/results/submissions');
// Check user header and value.
$this->assertRaw('<a href="' . $base_path . 'admin/structure/webform/manage/' . $webform->id() . '/results/submissions?sort=asc&order=User" title="sort by User">User</a>');
$this->assertRaw('<td class="priority-medium">' . $this->ownWebformSubmissionUser->getAccountName() . '</td>');
// Check date of birth.
$this->assertRaw('<th specifier="element__dob"><a href="' . $base_path . 'admin/structure/webform/manage/' . $webform->id() . '/results/submissions?sort=asc&order=Date%20of%20birth" title="sort by Date of birth">Date of birth</a></th>');
$this->assertRaw('<td>Sunday, October 26, 1947</td>');
// Display Header key and element raw.
$webform->setState('results.custom.format', [
'header_format' => 'key',
'element_format' => 'raw',
]);
$this->drupalGet('admin/structure/webform/manage/' . $webform->id() . '/results/submissions');
// Check user header and value.
$this->assertRaw('<a href="' . $base_path . 'admin/structure/webform/manage/' . $webform->id() . '/results/submissions?sort=asc&order=uid" title="sort by uid">uid</a>');
$this->assertRaw('<td class="priority-medium">' . $this->ownWebformSubmissionUser->id() . '</td>');
// Check date of birth.
$this->assertRaw('<th specifier="element__dob"><a href="' . $base_path . 'admin/structure/webform/manage/' . $webform->id() . '/results/submissions?sort=asc&order=dob" title="sort by dob">dob</a></th>');
$this->assertRaw('<td>1947-10-26</td>');
/**************************************************************************/
// Customize user results.
/**************************************************************************/
$this->drupalLogin($this->ownWebformSubmissionUser);
// Check view own submissions.
$this->drupalget('/webform/' . $webform->id() . '/submissions');
$this->assertRaw('<th specifier="serial" aria-sort="descending" class="is-active">');
$this->assertRaw('<th specifier="created" class="priority-medium">');
$this->assertRaw('<th specifier="remote_addr" class="priority-low">');
// Display on first name and last name columns.
$webform->setSetting('submission_user_columns', ['element__first_name', 'element__last_name'])
->save();
// Check view own submissions only include first name and last name,
$this->drupalget('/webform/' . $webform->id() . '/submissions');
$this->assertNoRaw('<th specifier="serial" aria-sort="descending" class="is-active">');
$this->assertNoRaw('<th specifier="created" class="priority-medium">');
$this->assertNoRaw('<th specifier="remote_addr" class="priority-low">');
$this->assertRaw('<th specifier="element__first_name" aria-sort="ascending" class="is-active">');
$this->assertRaw('<th specifier="element__last_name">');
}
}
| mit |
markogresak/DefinitelyTyped | types/three/src/loaders/LoadingManager.d.ts | 2349 | import { Loader } from './Loader';
export const DefaultLoadingManager: LoadingManager;
/**
* Handles and keeps track of loaded and pending data.
*/
export class LoadingManager {
constructor(
onLoad?: () => void,
onProgress?: (url: string, loaded: number, total: number) => void,
onError?: (url: string) => void,
);
/**
* Will be called when loading of an item starts.
* @param url The url of the item that started loading.
* @param loaded The number of items already loaded so far.
* @param total The total amount of items to be loaded.
*/
onStart?: ((url: string, loaded: number, total: number) => void) | undefined;
/**
* Will be called when all items finish loading.
* The default is a function with empty body.
*/
onLoad: () => void;
/**
* Will be called for each loaded item.
* The default is a function with empty body.
* @param url The url of the item just loaded.
* @param loaded The number of items already loaded so far.
* @param total The total amount of items to be loaded.
*/
onProgress: (url: string, loaded: number, total: number) => void;
/**
* Will be called when item loading fails.
* The default is a function with empty body.
* @param url The url of the item that errored.
*/
onError: (url: string) => void;
/**
* If provided, the callback will be passed each resource URL before a request is sent.
* The callback may return the original URL, or a new URL to override loading behavior.
* This behavior can be used to load assets from .ZIP files, drag-and-drop APIs, and Data URIs.
* @param callback URL modifier callback. Called with url argument, and must return resolvedURL.
*/
setURLModifier(callback?: (url: string) => string): this;
/**
* Given a URL, uses the URL modifier callback (if any) and returns a resolved URL.
* If no URL modifier is set, returns the original URL.
* @param url the url to load
*/
resolveURL(url: string): string;
itemStart(url: string): void;
itemEnd(url: string): void;
itemError(url: string): void;
// handlers
addHandler(regex: RegExp, loader: Loader): this;
removeHandler(regex: RegExp): this;
getHandler(file: string): Loader | null;
}
| mit |
plumer/codana | tomcat_files/8.0.22/DataSourceDefinitions.java | 1181 | /*
* 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 javax.annotation.sql;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @since Common Annotations 1.1
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface DataSourceDefinitions {
DataSourceDefinition[] value();
}
| mit |
zhenlan/corefx | src/System.Runtime.Extensions/tests/System/MathF.netcoreapp.cs | 129551 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
using Xunit.Sdk;
namespace System.Tests
{
public static partial class MathFTests
{
// binary32 (float) has a machine epsilon of 2^-23 (approx. 1.19e-07). However, this
// is slightly too accurate when writing tests meant to run against libm implementations
// for various platforms. 2^-21 (approx. 4.76e-07) seems to be as accurate as we can get.
//
// The tests themselves will take CrossPlatformMachineEpsilon and adjust it according to the expected result
// so that the delta used for comparison will compare the most significant digits and ignore
// any digits that are outside the single precision range (6-9 digits).
// For example, a test with an expect result in the format of 0.xxxxxxxxx will use
// CrossPlatformMachineEpsilon for the variance, while an expected result in the format of 0.0xxxxxxxxx
// will use CrossPlatformMachineEpsilon / 10 and expected result in the format of x.xxxxxx will
// use CrossPlatformMachineEpsilon * 10.
private const float CrossPlatformMachineEpsilon = 4.76837158e-07f;
/// <summary>Verifies that two <see cref="float"/> values are equal, within the <paramref name="variance"/>.</summary>
/// <param name="expected">The expected value</param>
/// <param name="actual">The value to be compared against</param>
/// <param name="variance">The total variance allowed between the expected and actual results.</param>
/// <exception cref="EqualException">Thrown when the values are not equal</exception>
private static void AssertEqual(float expected, float actual, float variance)
{
if (float.IsNaN(expected))
{
if (float.IsNaN(actual))
{
return;
}
throw new EqualException(ToStringPadded(expected), ToStringPadded(actual));
}
else if (float.IsNaN(actual))
{
throw new EqualException(ToStringPadded(expected), ToStringPadded(actual));
}
if (float.IsNegativeInfinity(expected))
{
if (float.IsNegativeInfinity(actual))
{
return;
}
throw new EqualException(ToStringPadded(expected), ToStringPadded(actual));
}
else if (float.IsNegativeInfinity(actual))
{
throw new EqualException(ToStringPadded(expected), ToStringPadded(actual));
}
if (float.IsPositiveInfinity(expected))
{
if (float.IsPositiveInfinity(actual))
{
return;
}
throw new EqualException(ToStringPadded(expected), ToStringPadded(actual));
}
else if (float.IsPositiveInfinity(actual))
{
throw new EqualException(ToStringPadded(expected), ToStringPadded(actual));
}
if (IsNegativeZero(expected))
{
if (IsNegativeZero(actual))
{
return;
}
if (IsPositiveZero(variance) || IsNegativeZero(variance))
{
throw new EqualException(ToStringPadded(expected), ToStringPadded(actual));
}
// When the variance is not ±0.0, then we are handling a case where
// the actual result is expected to not be exactly -0.0 on some platforms
// and we should fallback to checking if it is within the allowed variance instead.
}
else if (IsNegativeZero(actual))
{
if (IsPositiveZero(variance) || IsNegativeZero(variance))
{
throw new EqualException(ToStringPadded(expected), ToStringPadded(actual));
}
// When the variance is not ±0.0, then we are handling a case where
// the actual result is expected to not be exactly -0.0 on some platforms
// and we should fallback to checking if it is within the allowed variance instead.
}
if (IsPositiveZero(expected))
{
if (IsPositiveZero(actual))
{
return;
}
if (IsPositiveZero(variance) || IsNegativeZero(variance))
{
throw new EqualException(ToStringPadded(expected), ToStringPadded(actual));
}
// When the variance is not ±0.0, then we are handling a case where
// the actual result is expected to not be exactly +0.0 on some platforms
// and we should fallback to checking if it is within the allowed variance instead.
}
else if (IsPositiveZero(actual))
{
if (IsPositiveZero(variance) || IsNegativeZero(variance))
{
throw new EqualException(ToStringPadded(expected), ToStringPadded(actual));
}
// When the variance is not ±0.0, then we are handling a case where
// the actual result is expected to not be exactly +0.0 on some platforms
// and we should fallback to checking if it is within the allowed variance instead.
}
var delta = Math.Abs(actual - expected);
if (delta > variance)
{
throw new EqualException(ToStringPadded(expected), ToStringPadded(actual));
}
}
private unsafe static bool IsNegativeZero(float value)
{
return (*(uint*)(&value)) == 0x80000000;
}
private unsafe static bool IsPositiveZero(float value)
{
return (*(uint*)(&value)) == 0x00000000;
}
// We have a custom ToString here to ensure that edge cases (specifically ±0.0,
// but also NaN and ±∞) are correctly and consistently represented.
private static string ToStringPadded(float value)
{
if (double.IsNaN(value))
{
return "NaN".PadLeft(10);
}
else if (double.IsPositiveInfinity(value))
{
return "+∞".PadLeft(10);
}
else if (double.IsNegativeInfinity(value))
{
return "-∞".PadLeft(10);
}
else if (IsNegativeZero(value))
{
return "-0.0".PadLeft(10);
}
else if (IsPositiveZero(value))
{
return "+0.0".PadLeft(10);
}
else
{
return $"{value,10:G9}";
}
}
[Theory]
[InlineData( float.NegativeInfinity, float.PositiveInfinity, 0.0f)]
[InlineData(-3.14159265f, 3.14159265f, CrossPlatformMachineEpsilon * 10)] // value: -(pi) expected: (pi)
[InlineData(-2.71828183f, 2.71828183f, CrossPlatformMachineEpsilon * 10)] // value: -(e) expected: (e)
[InlineData(-2.30258509f, 2.30258509f, CrossPlatformMachineEpsilon * 10)] // value: -(ln(10)) expected: (ln(10))
[InlineData(-1.57079633f, 1.57079633f, CrossPlatformMachineEpsilon * 10)] // value: -(pi / 2) expected: (pi / 2)
[InlineData(-1.44269504f, 1.44269504f, CrossPlatformMachineEpsilon * 10)] // value: -(log2(e)) expected: (log2(e))
[InlineData(-1.41421356f, 1.41421356f, CrossPlatformMachineEpsilon * 10)] // value: -(sqrt(2)) expected: (sqrt(2))
[InlineData(-1.12837917f, 1.12837917f, CrossPlatformMachineEpsilon * 10)] // value: -(2 / sqrt(pi)) expected: (2 / sqrt(pi))
[InlineData(-1.0f, 1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData(-0.785398163f, 0.785398163f, CrossPlatformMachineEpsilon)] // value: -(pi / 4) expected: (pi / 4)
[InlineData(-0.707106781f, 0.707106781f, CrossPlatformMachineEpsilon)] // value: -(1 / sqrt(2)) expected: (1 / sqrt(2))
[InlineData(-0.693147181f, 0.693147181f, CrossPlatformMachineEpsilon)] // value: -(ln(2)) expected: (ln(2))
[InlineData(-0.636619772f, 0.636619772f, CrossPlatformMachineEpsilon)] // value: -(2 / pi) expected: (2 / pi)
[InlineData(-0.434294482f, 0.434294482f, CrossPlatformMachineEpsilon)] // value: -(log10(e)) expected: (log10(e))
[InlineData(-0.318309886f, 0.318309886f, CrossPlatformMachineEpsilon)] // value: -(1 / pi) expected: (1 / pi)
[InlineData(-0.0f, 0.0f, 0.0f)]
[InlineData( float.NaN, float.NaN, 0.0f)]
[InlineData( 0.0f, 0.0f, 0.0f)]
[InlineData( 0.318309886f, 0.318309886f, CrossPlatformMachineEpsilon)] // value: (1 / pi) expected: (1 / pi)
[InlineData( 0.434294482f, 0.434294482f, CrossPlatformMachineEpsilon)] // value: (log10(e)) expected: (log10(e))
[InlineData( 0.636619772f, 0.636619772f, CrossPlatformMachineEpsilon)] // value: (2 / pi) expected: (2 / pi)
[InlineData( 0.693147181f, 0.693147181f, CrossPlatformMachineEpsilon)] // value: (ln(2)) expected: (ln(2))
[InlineData( 0.707106781f, 0.707106781f, CrossPlatformMachineEpsilon)] // value: (1 / sqrt(2)) expected: (1 / sqrt(2))
[InlineData( 0.785398163f, 0.785398163f, CrossPlatformMachineEpsilon)] // value: (pi / 4) expected: (pi / 4)
[InlineData( 1.0f, 1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData( 1.12837917f, 1.12837917f, CrossPlatformMachineEpsilon * 10)] // value: (2 / sqrt(pi)) expected: (2 / sqrt(pi))
[InlineData( 1.41421356f, 1.41421356f, CrossPlatformMachineEpsilon * 10)] // value: (sqrt(2)) expected: (sqrt(2))
[InlineData( 1.44269504f, 1.44269504f, CrossPlatformMachineEpsilon * 10)] // value: (log2(e)) expected: (log2(e))
[InlineData( 1.57079633f, 1.57079633f, CrossPlatformMachineEpsilon * 10)] // value: (pi / 2) expected: (pi / 2)
[InlineData( 2.30258509f, 2.30258509f, CrossPlatformMachineEpsilon * 10)] // value: (ln(10)) expected: (ln(10))
[InlineData( 2.71828183f, 2.71828183f, CrossPlatformMachineEpsilon * 10)] // value: (e) expected: (e)
[InlineData( 3.14159265f, 3.14159265f, CrossPlatformMachineEpsilon * 10)] // value: (pi) expected: (pi)
[InlineData( float.PositiveInfinity, float.PositiveInfinity, 0.0f)]
public static void Abs(float value, float expectedResult, float allowedVariance)
{
AssertEqual(expectedResult, MathF.Abs(value), allowedVariance);
}
[Theory]
[InlineData( float.NegativeInfinity, float.NaN, 0.0f)]
[InlineData(-3.14159265f, float.NaN, 0.0f)] // value: -(pi)
[InlineData(-2.71828183f, float.NaN, 0.0f)] // value: -(e)
[InlineData(-1.41421356f, float.NaN, 0.0f)] // value: -(sqrt(2))
[InlineData(-1.0f, 3.14159265f, CrossPlatformMachineEpsilon * 10)] // expected: (pi)
[InlineData(-0.911733915f, 2.71828183f, CrossPlatformMachineEpsilon * 10)] // expected: (e)
[InlineData(-0.668201510f, 2.30258509f, CrossPlatformMachineEpsilon * 10)] // expected: (ln(10))
[InlineData(-0.0f, 1.57079633f, CrossPlatformMachineEpsilon * 10)] // expected: (pi / 2)
[InlineData( float.NaN, float.NaN, 0.0f)]
[InlineData( 0.0f, 1.57079633f, CrossPlatformMachineEpsilon * 10)] // expected: (pi / 2)
[InlineData( 0.127751218f, 1.44269504f, CrossPlatformMachineEpsilon * 10)] // expected: (log2(e))
[InlineData( 0.155943695f, 1.41421356f, CrossPlatformMachineEpsilon * 10)] // expected: (sqrt(2))
[InlineData( 0.428125148f, 1.12837917f, CrossPlatformMachineEpsilon * 10)] // expected: (2 / sqrt(pi))
[InlineData( 0.540302306f, 1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData( 0.707106781f, 0.785398163f, CrossPlatformMachineEpsilon)] // expected: (pi / 4), value: (1 / sqrt(2))
[InlineData( 0.760244597f, 0.707106781f, CrossPlatformMachineEpsilon)] // expected: (1 / sqrt(2))
[InlineData( 0.769238901f, 0.693147181f, CrossPlatformMachineEpsilon)] // expected: (ln(2))
[InlineData( 0.804109828f, 0.636619772f, CrossPlatformMachineEpsilon)] // expected: (2 / pi)
[InlineData( 0.907167129f, 0.434294482f, CrossPlatformMachineEpsilon)] // expected: (log10(e))
[InlineData( 0.949765715f, 0.318309886f, CrossPlatformMachineEpsilon)] // expected: (1 / pi)
[InlineData( 1.0f, 0.0f, 0.0f)]
[InlineData( 1.41421356f, float.NaN, 0.0f)] // value: (sqrt(2))
[InlineData( 2.71828183f, float.NaN, 0.0f)] // value: (e)
[InlineData( 3.14159265f, float.NaN, 0.0f)] // value: (pi)
[InlineData( float.PositiveInfinity, float.NaN, 0.0f)]
public static void Acos(float value, float expectedResult, float allowedVariance)
{
AssertEqual(expectedResult, MathF.Acos(value), allowedVariance);
}
[Theory]
[InlineData( float.NegativeInfinity, float.NaN, 0.0f)]
[InlineData(-3.14159265f, float.NaN, 0.0f)] // value: -(pi)
[InlineData(-2.71828183f, float.NaN, 0.0f)] // value: -(e)
[InlineData(-1.41421356f, float.NaN, 0.0f)] // value: -(sqrt(2))
[InlineData(-1.0f, float.NaN, 0.0f)]
[InlineData(-0.693147181f, float.NaN, 0.0f)] // value: -(ln(2))
[InlineData(-0.434294482f, float.NaN, 0.0f)] // value: -(log10(e))
[InlineData(-0.0f, float.NaN, 0.0f)]
[InlineData( float.NaN, float.NaN, 0.0f)]
[InlineData( 0.0f, float.NaN, 0.0f)]
[InlineData( 1.0f, 0.0f, CrossPlatformMachineEpsilon)]
[InlineData( 1.05108979f, 0.318309886f, CrossPlatformMachineEpsilon)] // expected: (1 / pi)
[InlineData( 1.09579746f, 0.434294482f, CrossPlatformMachineEpsilon)] // expected: (log10(e))
[InlineData( 1.20957949f, 0.636619772f, CrossPlatformMachineEpsilon)] // expected: (2 / pi)
[InlineData( 1.25f, 0.693147181f, CrossPlatformMachineEpsilon)] // expected: (ln(2))
[InlineData( 1.26059184f, 0.707106781f, CrossPlatformMachineEpsilon)] // expected: (1 / sqrt(2))
[InlineData( 1.32460909f, 0.785398163f, CrossPlatformMachineEpsilon)] // expected: (pi / 4)
[InlineData( 1.54308063f, 1.0, CrossPlatformMachineEpsilon * 10)]
[InlineData( 1.70710014f, 1.12837917f, CrossPlatformMachineEpsilon * 10)] // expected: (2 / sqrt(pi))
[InlineData( 2.17818356f, 1.41421356f, CrossPlatformMachineEpsilon * 10)] // expected: (sqrt(2))
[InlineData( 2.23418810f, 1.44269504f, CrossPlatformMachineEpsilon * 10)] // expected: (log2(e))
[InlineData( 2.50917848f, 1.57079633f, CrossPlatformMachineEpsilon * 10)] // expected: (pi / 2)
[InlineData( 5.05f, 2.30258509f, CrossPlatformMachineEpsilon * 10)] // expected: (ln(10))
[InlineData( 7.61012514f, 2.71828183f, CrossPlatformMachineEpsilon * 10)] // expected: (e)
[InlineData( 11.5919533f, 3.14159265f, CrossPlatformMachineEpsilon * 10)] // expected: (pi)
[InlineData( float.PositiveInfinity, float.PositiveInfinity, 0.0f)]
public static void Acosh(float value, float expectedResult, float allowedVariance)
{
AssertEqual(expectedResult, MathF.Acosh(value), allowedVariance);
}
[Theory]
[InlineData( float.NegativeInfinity, float.NaN, 0.0f)]
[InlineData(-3.14159265f, float.NaN, 0.0f)] // value: -(pi)
[InlineData(-2.71828183f, float.NaN, 0.0f)] // value: -(e)
[InlineData(-1.41421356f, float.NaN, 0.0f)] // value: -(sqrt(2))
[InlineData(-1.0f, -1.57079633f, CrossPlatformMachineEpsilon * 10)] // expected: -(pi / 2)
[InlineData(-0.991806244f, -1.44269504f, CrossPlatformMachineEpsilon * 10)] // expected: -(log2(e))
[InlineData(-0.987765946f, -1.41421356f, CrossPlatformMachineEpsilon * 10)] // expected: -(sqrt(2))
[InlineData(-0.903719457f, -1.12837917f, CrossPlatformMachineEpsilon * 10)] // expected: -(2 / sqrt(pi))
[InlineData(-0.841470985f, -1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData(-0.743980337f, -0.839007561f, CrossPlatformMachineEpsilon)] // expected: -(pi - ln(10))
[InlineData(-0.707106781f, -0.785398163f, CrossPlatformMachineEpsilon)] // expected: -(pi / 4), value: (1 / sqrt(2))
[InlineData(-0.649636939f, -0.707106781f, CrossPlatformMachineEpsilon)] // expected: -(1 / sqrt(2))
[InlineData(-0.638961276f, -0.693147181f, CrossPlatformMachineEpsilon)] // expected: -(ln(2))
[InlineData(-0.594480769f, -0.636619772f, CrossPlatformMachineEpsilon)] // expected: -(2 / pi)
[InlineData(-0.420770483f, -0.434294482f, CrossPlatformMachineEpsilon)] // expected: -(log10(e))
[InlineData(-0.410781291f, -0.423310825f, CrossPlatformMachineEpsilon)] // expected: -(pi - e)
[InlineData(-0.312961796f, -0.318309886f, CrossPlatformMachineEpsilon)] // expected: -(1 / pi)
[InlineData(-0.0f, -0.0f, 0.0f)]
[InlineData( float.NaN, float.NaN, 0.0f)]
[InlineData( 0.0f, 0.0f, 0.0f)]
[InlineData( 0.312961796f, 0.318309886f, CrossPlatformMachineEpsilon)] // expected: (1 / pi)
[InlineData( 0.410781291f, 0.423310825f, CrossPlatformMachineEpsilon)] // expected: (pi - e)
[InlineData( 0.420770483f, 0.434294482f, CrossPlatformMachineEpsilon)] // expected: (log10(e))
[InlineData( 0.594480769f, 0.636619772f, CrossPlatformMachineEpsilon)] // expected: (2 / pi)
[InlineData( 0.638961276f, 0.693147181f, CrossPlatformMachineEpsilon)] // expected: (ln(2))
[InlineData( 0.649636939f, 0.707106781f, CrossPlatformMachineEpsilon)] // expected: (1 / sqrt(2))
[InlineData( 0.707106781f, 0.785398163f, CrossPlatformMachineEpsilon)] // expected: (pi / 4), value: (1 / sqrt(2))
[InlineData( 0.743980337f, 0.839007561f, CrossPlatformMachineEpsilon)] // expected: (pi - ln(10))
[InlineData( 0.841470985f, 1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData( 0.903719457f, 1.12837917f, CrossPlatformMachineEpsilon * 10)] // expected: (2 / sqrt(pi))
[InlineData( 0.987765946f, 1.41421356f, CrossPlatformMachineEpsilon * 10)] // expected: (sqrt(2))
[InlineData( 0.991806244f, 1.44269504f, CrossPlatformMachineEpsilon * 10)] // expected: (log2(e))
[InlineData( 1.0f, 1.57079633f, CrossPlatformMachineEpsilon * 10)] // expected: (pi / 2)
[InlineData( 1.41421356f, float.NaN, 0.0f)] // value: (sqrt(2))
[InlineData( 2.71828183f, float.NaN, 0.0f)] // value: (e)
[InlineData( 3.14159265f, float.NaN, 0.0f)] // value: (pi)
[InlineData( float.PositiveInfinity, float.NaN, 0.0f)]
public static void Asin(float value, float expectedResult, float allowedVariance)
{
AssertEqual(expectedResult, MathF.Asin(value), allowedVariance);
}
[Theory]
[InlineData( float.NegativeInfinity, float.NegativeInfinity, 0.0f)]
[InlineData(-11.5487394f, -3.14159265f, CrossPlatformMachineEpsilon * 10)] // expected: -(pi)
[InlineData(-7.54413710f, -2.71828183f, CrossPlatformMachineEpsilon * 10)] // expected: -(e)
[InlineData(-4.95f, -2.30258509f, CrossPlatformMachineEpsilon * 10)] // expected: -(ln(10))
[InlineData(-2.30129890f, -1.57079633f, CrossPlatformMachineEpsilon * 10)] // expected: -(pi / 2)
[InlineData(-1.99789801f, -1.44269504f, CrossPlatformMachineEpsilon * 10)] // expected: -(log2(e))
[InlineData(-1.93506682f, -1.41421356f, CrossPlatformMachineEpsilon * 10)] // expected: -(sqrt(2))
[InlineData(-1.38354288f, -1.12837917f, CrossPlatformMachineEpsilon * 10)] // expected: -(2 / sqrt(pi))
[InlineData(-1.17520119f, -1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData(-0.868670961f, -0.785398163f, CrossPlatformMachineEpsilon)] // expected: -(pi / 4)
[InlineData(-0.767523145f, -0.707106781f, CrossPlatformMachineEpsilon)] // expected: -(1 / sqrt(2))
[InlineData(-0.75f, -0.693147181f, CrossPlatformMachineEpsilon)] // expected: -(ln(2))
[InlineData(-0.680501678f, -0.636619772f, CrossPlatformMachineEpsilon)] // expected: -(2 / pi)
[InlineData(-0.448075979f, -0.434294482f, CrossPlatformMachineEpsilon)] // expected: -(log10(e))
[InlineData(-0.323712439f, -0.318309886f, CrossPlatformMachineEpsilon)] // expected: -(1 / pi)
[InlineData(-0.0f, -0.0, 0.0f)]
[InlineData( float.NaN, float.NaN, 0.0f)]
[InlineData( 0.0f, 0.0, 0.0f)]
[InlineData( 0.323712439f, 0.318309886f, CrossPlatformMachineEpsilon)] // expected: (1 / pi)
[InlineData( 0.448075979f, 0.434294482f, CrossPlatformMachineEpsilon)] // expected: (log10(e))
[InlineData( 0.680501678f, 0.636619772f, CrossPlatformMachineEpsilon)] // expected: (2 / pi)
[InlineData( 0.75f, 0.693147181f, CrossPlatformMachineEpsilon)] // expected: (ln(2))
[InlineData( 0.767523145f, 0.707106781f, CrossPlatformMachineEpsilon)] // expected: (1 / sqrt(2))
[InlineData( 0.868670961f, 0.785398163f, CrossPlatformMachineEpsilon)] // expected: (pi / 4)
[InlineData( 1.17520119f, 1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData( 1.38354288f, 1.12837917f, CrossPlatformMachineEpsilon * 10)] // expected: (2 / sqrt(pi))
[InlineData( 1.93506682f, 1.41421356f, CrossPlatformMachineEpsilon * 10)] // expected: (sqrt(2))
[InlineData( 1.99789801f, 1.44269504f, CrossPlatformMachineEpsilon * 10)] // expected: (log2(e))
[InlineData( 2.30129890f, 1.57079633f, CrossPlatformMachineEpsilon * 10)] // expected: (pi / 2)
[InlineData( 4.95f, 2.30258509f, CrossPlatformMachineEpsilon * 10)] // expected: (ln(10))
[InlineData( 7.54413710f, 2.71828183f, CrossPlatformMachineEpsilon * 10)] // expected: (e)
[InlineData( 11.5487394f, 3.14159265f, CrossPlatformMachineEpsilon * 10)] // expected: (pi)
[InlineData( float.PositiveInfinity, float.PositiveInfinity, 0.0f)]
public static void Asinh(float value, float expectedResult, float allowedVariance)
{
AssertEqual(expectedResult, MathF.Asinh(value), allowedVariance);
}
[Theory]
[InlineData( float.NegativeInfinity, -1.57079633f, CrossPlatformMachineEpsilon * 10)] // expected: -(pi / 2)
[InlineData(-7.76357567f, -1.44269504f, CrossPlatformMachineEpsilon * 10)] // expected: -(log2(e))
[InlineData(-6.33411917f, -1.41421356f, CrossPlatformMachineEpsilon * 10)] // expected: -(sqrt(2))
[InlineData(-2.11087684f, -1.12837917f, CrossPlatformMachineEpsilon * 10)] // expected: -(2 / sqrt(pi))
[InlineData(-1.55740772f, -1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData(-1.11340715f, -0.839007561f, CrossPlatformMachineEpsilon)] // expected: -(pi - ln(10))
[InlineData(-1.0f, -0.785398163f, CrossPlatformMachineEpsilon)] // expected: -(pi / 4)
[InlineData(-0.854510432f, -0.707106781f, CrossPlatformMachineEpsilon)] // expected: -(1 / sqrt(2))
[InlineData(-0.830640878f, -0.693147181f, CrossPlatformMachineEpsilon)] // expected: -(ln(2))
[InlineData(-0.739302950f, -0.636619772f, CrossPlatformMachineEpsilon)] // expected: -(2 / pi)
[InlineData(-0.463829067f, -0.434294482f, CrossPlatformMachineEpsilon)] // expected: -(log10(e))
[InlineData(-0.450549534f, -0.423310825f, CrossPlatformMachineEpsilon)] // expected: -(pi - e)
[InlineData(-0.329514733f, -0.318309886f, CrossPlatformMachineEpsilon)] // expected: -(1 / pi)
[InlineData(-0.0f, -0.0f, 0.0f)]
[InlineData( float.NaN, float.NaN, 0.0f)]
[InlineData( 0.0f, 0.0f, 0.0f)]
[InlineData( 0.329514733f, 0.318309886f, CrossPlatformMachineEpsilon)] // expected: (1 / pi)
[InlineData( 0.450549534f, 0.423310825f, CrossPlatformMachineEpsilon)] // expected: (pi - e)
[InlineData( 0.463829067f, 0.434294482f, CrossPlatformMachineEpsilon)] // expected: (log10(e))
[InlineData( 0.739302950f, 0.636619772f, CrossPlatformMachineEpsilon)] // expected: (2 / pi)
[InlineData( 0.830640878f, 0.693147181f, CrossPlatformMachineEpsilon)] // expected: (ln(2))
[InlineData( 0.854510432f, 0.707106781f, CrossPlatformMachineEpsilon)] // expected: (1 / sqrt(2))
[InlineData( 1.0f, 0.785398163f, CrossPlatformMachineEpsilon)] // expected: (pi / 4)
[InlineData( 1.11340715f, 0.839007561f, CrossPlatformMachineEpsilon)] // expected: (pi - ln(10))
[InlineData( 1.55740772f, 1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData( 2.11087684f, 1.12837917f, CrossPlatformMachineEpsilon * 10)] // expected: (2 / sqrt(pi))
[InlineData( 6.33411917f, 1.41421356f, CrossPlatformMachineEpsilon * 10)] // expected: (sqrt(2))
[InlineData( 7.76357567f, 1.44269504f, CrossPlatformMachineEpsilon * 10)] // expected: (log2(e))
[InlineData( float.PositiveInfinity, 1.57079633f, CrossPlatformMachineEpsilon * 10)] // expected: (pi / 2)
public static void Atan(float value, float expectedResult, float allowedVariance)
{
AssertEqual(expectedResult, MathF.Atan(value), allowedVariance);
}
[Theory]
[InlineData( float.NegativeInfinity, -1.0f, -1.57079633f, CrossPlatformMachineEpsilon * 10)] // expected: -(pi / 2)
[InlineData( float.NegativeInfinity, -0.0f, -1.57079633f, CrossPlatformMachineEpsilon * 10)] // expected: -(pi / 2)
[InlineData( float.NegativeInfinity, float.NaN, float.NaN, 0.0f)]
[InlineData( float.NegativeInfinity, 0.0f, -1.57079633f, CrossPlatformMachineEpsilon * 10)] // expected: -(pi / 2)
[InlineData( float.NegativeInfinity, 1.0f, -1.57079633f, CrossPlatformMachineEpsilon * 10)] // expected: -(pi / 2)
[InlineData(-1.0f, -1.0f, -2.35619449f, CrossPlatformMachineEpsilon * 10)] // expected: -(3 * pi / 4)
[InlineData(-1.0f, -0.0f, -1.57079633f, CrossPlatformMachineEpsilon * 10)] // expected: -(pi / 2)
[InlineData(-1.0f, float.NaN, float.NaN, 0.0f)]
[InlineData(-1.0f, 0.0f, -1.57079633f, CrossPlatformMachineEpsilon * 10)] // expected: -(pi / 2)
[InlineData(-1.0f, 1.0f, -0.785398163f, CrossPlatformMachineEpsilon)] // expected: -(pi / 4)
[InlineData(-1.0f, float.PositiveInfinity, -0.0f, 0.0f)]
[InlineData(-0.991806244f, -0.127751218f, -1.69889761f, CrossPlatformMachineEpsilon * 10)] // expected: -(pi - log2(e))
[InlineData(-0.991806244f, 0.127751218f, -1.44269504f, CrossPlatformMachineEpsilon * 10)] // expected: -(log2(e))
[InlineData(-0.987765946f, -0.155943695f, -1.72737909f, CrossPlatformMachineEpsilon * 10)] // expected: -(pi - sqrt(2))
[InlineData(-0.987765946f, 0.155943695f, -1.41421356f, CrossPlatformMachineEpsilon * 10)] // expected: -(sqrt(2))
[InlineData(-0.903719457f, -0.428125148f, -2.01321349f, CrossPlatformMachineEpsilon * 10)] // expected: -(pi - (2 / sqrt(pi))
[InlineData(-0.903719457f, 0.428125148f, -1.12837917f, CrossPlatformMachineEpsilon * 10)] // expected: -(2 / sqrt(pi)
[InlineData(-0.841470985f, -0.540302306f, -2.14159265f, CrossPlatformMachineEpsilon * 10)] // expected: -(pi - 1)
[InlineData(-0.841470985f, 0.540302306f, -1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData(-0.743980337f, -0.668201510f, -2.30258509f, CrossPlatformMachineEpsilon * 10)] // expected: -(ln(10))
[InlineData(-0.743980337f, 0.668201510f, -0.839007561f, CrossPlatformMachineEpsilon)] // expected: -(pi - ln(10))
[InlineData(-0.707106781f, -0.707106781f, -2.35619449f, CrossPlatformMachineEpsilon * 10)] // expected: -(3 * pi / 4), y: -(1 / sqrt(2)) x: -(1 / sqrt(2))
[InlineData(-0.707106781f, 0.707106781f, -0.785398163f, CrossPlatformMachineEpsilon)] // expected: -(pi / 4), y: -(1 / sqrt(2)) x: (1 / sqrt(2))
[InlineData(-0.649636939f, -0.760244597f, -2.43448587f, CrossPlatformMachineEpsilon * 10)] // expected: -(pi - (1 / sqrt(2))
[InlineData(-0.649636939f, 0.760244597f, -0.707106781f, CrossPlatformMachineEpsilon)] // expected: -(1 / sqrt(2))
[InlineData(-0.638961276f, -0.769238901f, -2.44844547f, CrossPlatformMachineEpsilon * 10)] // expected: -(pi - ln(2))
[InlineData(-0.638961276f, 0.769238901f, -0.693147181f, CrossPlatformMachineEpsilon)] // expected: -(ln(2))
[InlineData(-0.594480769f, -0.804109828f, -2.50497288f, CrossPlatformMachineEpsilon * 10)] // expected: -(pi - (2 / pi))
[InlineData(-0.594480769f, 0.804109828f, -0.636619772f, CrossPlatformMachineEpsilon)] // expected: -(2 / pi)
[InlineData(-0.420770483f, -0.907167129f, -2.70729817f, CrossPlatformMachineEpsilon * 10)] // expected: -(pi - log10(e))
[InlineData(-0.420770483f, 0.907167129f, -0.434294482f, CrossPlatformMachineEpsilon)] // expected: -(log10(e))
[InlineData(-0.410781291f, -0.911733915f, -2.71828183f, CrossPlatformMachineEpsilon * 10)] // expected: -(e)
[InlineData(-0.410781291f, 0.911733915f, -0.423310825f, CrossPlatformMachineEpsilon)] // expected: -(pi - e)
[InlineData(-0.312961796f, -0.949765715f, -2.82328277f, CrossPlatformMachineEpsilon * 10)] // expected: -(pi - (1 / pi))
[InlineData(-0.312961796f, 0.949765715f, -0.318309886f, CrossPlatformMachineEpsilon)] // expected: -(1 / pi)
[InlineData(-0.0f, float.NegativeInfinity, -3.14159265f, CrossPlatformMachineEpsilon * 10)] // expected: -(pi)
[InlineData(-0.0f, -1.0f, -3.14159265f, CrossPlatformMachineEpsilon * 10)] // expected: -(pi)
[InlineData(-0.0f, -0.0f, -3.14159265f, CrossPlatformMachineEpsilon * 10)] // expected: -(pi)
[InlineData(-0.0f, float.NaN, float.NaN, 0.0f)]
[InlineData(-0.0f, 0.0f, -0.0f, 0.0f)]
[InlineData(-0.0f, 1.0f, -0.0f, 0.0f)]
[InlineData(-0.0f, float.PositiveInfinity, -0.0f, 0.0f)]
[InlineData( float.NaN, float.NegativeInfinity, float.NaN, 0.0f)]
[InlineData( float.NaN, -1.0f, float.NaN, 0.0f)]
[InlineData( float.NaN, -0.0f, float.NaN, 0.0f)]
[InlineData( float.NaN, float.NaN, float.NaN, 0.0f)]
[InlineData( float.NaN, 0.0f, float.NaN, 0.0f)]
[InlineData( float.NaN, 1.0f, float.NaN, 0.0f)]
[InlineData( float.NaN, float.PositiveInfinity, float.NaN, 0.0f)]
[InlineData( 0.0f, float.NegativeInfinity, 3.14159265f, CrossPlatformMachineEpsilon * 10)] // expected: (pi)
[InlineData( 0.0f, -1.0f, 3.14159265f, CrossPlatformMachineEpsilon * 10)] // expected: (pi)
[InlineData( 0.0f, -0.0f, 3.14159265f, CrossPlatformMachineEpsilon * 10)] // expected: (pi)
[InlineData( 0.0f, float.NaN, float.NaN, 0.0f)]
[InlineData( 0.0f, 0.0f, 0.0f, 0.0f)]
[InlineData( 0.0f, 1.0f, 0.0f, 0.0f)]
[InlineData( 0.0f, float.PositiveInfinity, 0.0f, 0.0f)]
[InlineData( 0.312961796f, -0.949765715f, 2.82328277f, CrossPlatformMachineEpsilon * 10)] // expected: (pi - (1 / pi))
[InlineData( 0.312961796f, 0.949765715f, 0.318309886f, CrossPlatformMachineEpsilon)] // expected: (1 / pi)
[InlineData( 0.410781291f, -0.911733915f, 2.71828183f, CrossPlatformMachineEpsilon * 10)] // expected: (e)
[InlineData( 0.410781291f, 0.911733915f, 0.423310825f, CrossPlatformMachineEpsilon)] // expected: (pi - e)
[InlineData( 0.420770483f, -0.907167129f, 2.70729817f, CrossPlatformMachineEpsilon * 10)] // expected: (pi - log10(e))
[InlineData( 0.420770483f, 0.907167129f, 0.434294482f, CrossPlatformMachineEpsilon)] // expected: (log10(e))
[InlineData( 0.594480769f, -0.804109828f, 2.50497288f, CrossPlatformMachineEpsilon * 10)] // expected: (pi - (2 / pi))
[InlineData( 0.594480769f, 0.804109828f, 0.636619772f, CrossPlatformMachineEpsilon)] // expected: (2 / pi)
[InlineData( 0.638961276f, -0.769238901f, 2.44844547f, CrossPlatformMachineEpsilon * 10)] // expected: (pi - ln(2))
[InlineData( 0.638961276f, 0.769238901f, 0.693147181f, CrossPlatformMachineEpsilon)] // expected: (ln(2))
[InlineData( 0.649636939f, -0.760244597f, 2.43448587f, CrossPlatformMachineEpsilon * 10)] // expected: (pi - (1 / sqrt(2))
[InlineData( 0.649636939f, 0.760244597f, 0.707106781f, CrossPlatformMachineEpsilon)] // expected: (1 / sqrt(2))
[InlineData( 0.707106781f, -0.707106781f, 2.35619449f, CrossPlatformMachineEpsilon * 10)] // expected: (3 * pi / 4), y: (1 / sqrt(2)) x: -(1 / sqrt(2))
[InlineData( 0.707106781f, 0.707106781f, 0.785398163f, CrossPlatformMachineEpsilon)] // expected: (pi / 4), y: (1 / sqrt(2)) x: (1 / sqrt(2))
[InlineData( 0.743980337f, -0.668201510f, 2.30258509f, CrossPlatformMachineEpsilon * 10)] // expected: (ln(10))
[InlineData( 0.743980337f, 0.668201510f, 0.839007561f, CrossPlatformMachineEpsilon)] // expected: (pi - ln(10))
[InlineData( 0.841470985f, -0.540302306f, 2.14159265f, CrossPlatformMachineEpsilon * 10)] // expected: (pi - 1)
[InlineData( 0.841470985f, 0.540302306f, 1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData( 0.903719457f, -0.428125148f, 2.01321349f, CrossPlatformMachineEpsilon * 10)] // expected: (pi - (2 / sqrt(pi))
[InlineData( 0.903719457f, 0.428125148f, 1.12837917f, CrossPlatformMachineEpsilon * 10)] // expected: (2 / sqrt(pi))
[InlineData( 0.987765946f, -0.155943695f, 1.72737909f, CrossPlatformMachineEpsilon * 10)] // expected: (pi - sqrt(2))
[InlineData( 0.987765946f, 0.155943695f, 1.41421356f, CrossPlatformMachineEpsilon * 10)] // expected: (sqrt(2))
[InlineData( 0.991806244f, -0.127751218f, 1.69889761f, CrossPlatformMachineEpsilon * 10)] // expected: (pi - log2(e))
[InlineData( 0.991806244f, 0.127751218f, 1.44269504f, CrossPlatformMachineEpsilon * 10)] // expected: (log2(e))
[InlineData( 1.0f, -1.0f, 2.35619449f, CrossPlatformMachineEpsilon * 10)] // expected: (3 * pi / 4)
[InlineData( 1.0f, -0.0f, 1.57079633f, CrossPlatformMachineEpsilon * 10)] // expected: (pi / 2)
[InlineData( 1.0f, float.NaN, float.NaN, 0.0f)]
[InlineData( 1.0f, 0.0f, 1.57079633f, CrossPlatformMachineEpsilon * 10)] // expected: (pi / 2)
[InlineData( 1.0f, 1.0f, 0.785398163f, CrossPlatformMachineEpsilon)] // expected: (pi / 4)
[InlineData( 1.0f, float.PositiveInfinity, 0.0f, 0.0f)]
[InlineData( float.PositiveInfinity, -1.0f, 1.57079633f, CrossPlatformMachineEpsilon * 10)] // expected: (pi / 2)
[InlineData( float.PositiveInfinity, -0.0f, 1.57079633f, CrossPlatformMachineEpsilon * 10)] // expected: (pi / 2)
[InlineData( float.PositiveInfinity, float.NaN, float.NaN, 0.0f)]
[InlineData( float.PositiveInfinity, 0.0f, 1.57079633f, CrossPlatformMachineEpsilon * 10)] // expected: (pi / 2)
[InlineData( float.PositiveInfinity, 1.0f, 1.57079633f, CrossPlatformMachineEpsilon * 10)] // expected: (pi / 2)
public static void Atan2(float y, float x, float expectedResult, float allowedVariance)
{
AssertEqual(expectedResult, MathF.Atan2(y, x), allowedVariance);
}
[Theory]
[InlineData( float.NegativeInfinity, float.NegativeInfinity, -2.35619449f, CrossPlatformMachineEpsilon * 10)] // expected: -(3 * pi / 4)
[InlineData( float.NegativeInfinity, float.PositiveInfinity, -0.785398163f, CrossPlatformMachineEpsilon)] // expected: -(pi / 4)
[InlineData( float.PositiveInfinity, float.NegativeInfinity, 2.35619449f, CrossPlatformMachineEpsilon * 10)] // expected: (3 * pi / 4
[InlineData( float.PositiveInfinity, float.PositiveInfinity, 0.785398163f, CrossPlatformMachineEpsilon)] // expected: (pi / 4)
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public static void Atan2_IEEE(float y, float x, float expectedResult, float allowedVariance)
{
AssertEqual(expectedResult, MathF.Atan2(y, x), allowedVariance);
}
[Theory]
[InlineData( float.NegativeInfinity, float.NegativeInfinity, float.NaN, 0.0f)]
[InlineData( float.NegativeInfinity, float.PositiveInfinity, float.NaN, 0.0f)]
[InlineData( float.PositiveInfinity, float.NegativeInfinity, float.NaN, 0.0f)]
[InlineData( float.PositiveInfinity, float.PositiveInfinity, float.NaN, 0.0f)]
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)]
public static void Atan2_IEEE_Legacy(float y, float x, float expectedResult, float allowedVariance)
{
AssertEqual(expectedResult, MathF.Atan2(y, x), allowedVariance);
}
[Theory]
[InlineData( float.NegativeInfinity, float.NaN, 0.0f)]
[InlineData(-3.14159265f, float.NaN, 0.0f)] // value: -(pi)
[InlineData(-2.71828183f, float.NaN, 0.0f)] // value: -(e)
[InlineData(-1.41421356f, float.NaN, 0.0f)] // value: -(sqrt(2))
[InlineData(-1.0f, float.NegativeInfinity, CrossPlatformMachineEpsilon * 10)]
[InlineData(-0.996272076f, -3.14159265f, CrossPlatformMachineEpsilon * 10)] // expected: -(pi)
[InlineData(-0.991328916f, -2.71828183f, CrossPlatformMachineEpsilon * 10)] // expected: -(e)
[InlineData(-0.980198020f, -2.30258509f, CrossPlatformMachineEpsilon * 10)] // expected: -(ln(10))
[InlineData(-0.917152336f, -1.57079633f, CrossPlatformMachineEpsilon * 10)] // expected: -(pi / 2)
[InlineData(-0.894238946f, -1.44269504f, CrossPlatformMachineEpsilon * 10)] // expected: -(log2(e))
[InlineData(-0.888385562f, -1.41421356f, CrossPlatformMachineEpsilon * 10)] // expected: -(sqrt(2))
[InlineData(-0.810463806f, -1.12837917f, CrossPlatformMachineEpsilon * 10)] // expected: -(2 / sqrt(pi))
[InlineData(-0.761594156f, -1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData(-0.655794203f, -0.785398163f, CrossPlatformMachineEpsilon)] // expected: -(pi / 4)
[InlineData(-0.608859365f, -0.707106781f, CrossPlatformMachineEpsilon)] // expected: -(1 / sqrt(2))
[InlineData(-0.6f, -0.693147181f, CrossPlatformMachineEpsilon)] // expected: -(ln(2))
[InlineData(-0.562593600f, -0.636619772f, CrossPlatformMachineEpsilon)] // expected: -(2 / pi)
[InlineData(-0.408904012f, -0.434294482f, CrossPlatformMachineEpsilon)] // expected: -(log10(e))
[InlineData(-0.307977913f, -0.318309886f, CrossPlatformMachineEpsilon)] // expected: -(1 / pi)
[InlineData(-0.0f, -0.0f, 0.0f)]
[InlineData( float.NaN, float.NaN, 0.0f)]
[InlineData( 0.0, 0.0f, 0.0f)]
[InlineData( 0.307977913f, 0.318309886f, CrossPlatformMachineEpsilon)] // expected: (1 / pi)
[InlineData( 0.408904012f, 0.434294482f, CrossPlatformMachineEpsilon)] // expected: (log10(e))
[InlineData( 0.562593600f, 0.636619772f, CrossPlatformMachineEpsilon)] // expected: (2 / pi)
[InlineData( 0.6f, 0.693147181f, CrossPlatformMachineEpsilon)] // expected: (ln(2))
[InlineData( 0.608859365f, 0.707106781f, CrossPlatformMachineEpsilon)] // expected: (1 / sqrt(2))
[InlineData( 0.655794203f, 0.785398163f, CrossPlatformMachineEpsilon)] // expected: (pi / 4)
[InlineData( 0.761594156f, 1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData( 0.810463806f, 1.12837917f, CrossPlatformMachineEpsilon * 10)] // expected: (2 / sqrt(pi))
[InlineData( 0.888385562f, 1.41421356f, CrossPlatformMachineEpsilon * 10)] // expected: (sqrt(2))
[InlineData( 0.894238946f, 1.44269504f, CrossPlatformMachineEpsilon * 10)] // expected: (log2(e))
[InlineData( 0.917152336f, 1.57079633f, CrossPlatformMachineEpsilon * 10)] // expected: (pi / 2)
[InlineData( 0.980198020f, 2.30258509f, CrossPlatformMachineEpsilon * 10)] // expected: (ln(10))
[InlineData( 0.991328916f, 2.71828183f, CrossPlatformMachineEpsilon * 10)] // expected: (e)
[InlineData( 0.996272076f, 3.14159265f, CrossPlatformMachineEpsilon * 10)] // expected: (pi)
[InlineData( 1.0f, float.PositiveInfinity, 0.0f)]
[InlineData( 3.14159265f, float.NaN, 0.0f)] // value: (pi)
[InlineData( 2.71828183f, float.NaN, 0.0f)] // value: (e)
[InlineData( 1.41421356f, float.NaN, 0.0f)] // value: (sqrt(2))
[InlineData( float.PositiveInfinity, float.NaN, 0.0f)]
public static void Atanh(float value, float expectedResult, float allowedVariance)
{
AssertEqual(expectedResult, MathF.Atanh(value), allowedVariance);
}
[Theory]
[InlineData( float.NegativeInfinity, float.NegativeInfinity, 0.0f)]
[InlineData(-3.14159265f, -1.46459189f, CrossPlatformMachineEpsilon * 10)] // value: -(pi)
[InlineData(-2.71828183f, -1.39561243f, CrossPlatformMachineEpsilon * 10)] // value: -(e)
[InlineData(-2.30258509f, -1.32050048f, CrossPlatformMachineEpsilon * 10)] // value: -(ln(10))
[InlineData(-1.57079633f, -1.16244735f, CrossPlatformMachineEpsilon * 10)] // value: -(pi / 2)
[InlineData(-1.44269504f, -1.12994728f, CrossPlatformMachineEpsilon * 10)] // value: -(log2(e))
[InlineData(-1.41421356f, -1.12246205f, CrossPlatformMachineEpsilon * 10)] // value: -(sqrt(2))
[InlineData(-1.12837917f, -1.04108220f, CrossPlatformMachineEpsilon * 10)] // value: -(2 / sqrt(pi))
[InlineData(-1.0f, -1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData(-0.785398163f, -0.922635074f, CrossPlatformMachineEpsilon)] // value: -(pi / 4)
[InlineData(-0.707106781f, -0.890898718f, CrossPlatformMachineEpsilon)] // value: -(1 / sqrt(2))
[InlineData(-0.693147181f, -0.884997045f, CrossPlatformMachineEpsilon)] // value: -(ln(2))
[InlineData(-0.636619772f, -0.860254014f, CrossPlatformMachineEpsilon)] // value: -(2 / pi)
[InlineData(-0.434294482f, -0.757288631f, CrossPlatformMachineEpsilon)] // value: -(log10(e))
[InlineData(-0.318309886f, -0.682784063f, CrossPlatformMachineEpsilon)] // value: -(1 / pi)
[InlineData(-0.0f, -0.0f, 0.0f)]
[InlineData( float.NaN, float.NaN, 0.0f)]
[InlineData( 0.0f, 0.0f, 0.0f)]
[InlineData( 0.318309886f, 0.682784063f, CrossPlatformMachineEpsilon)] // value: (1 / pi)
[InlineData( 0.434294482f, 0.757288631f, CrossPlatformMachineEpsilon)] // value: (log10(e))
[InlineData( 0.636619772f, 0.860254014f, CrossPlatformMachineEpsilon)] // value: (2 / pi)
[InlineData( 0.693147181f, 0.884997045f, CrossPlatformMachineEpsilon)] // value: (ln(2))
[InlineData( 0.707106781f, 0.890898718f, CrossPlatformMachineEpsilon)] // value: (1 / sqrt(2))
[InlineData( 0.785398163f, 0.922635074f, CrossPlatformMachineEpsilon)] // value: (pi / 4)
[InlineData( 1.0f, 1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData( 1.12837917f, 1.04108220f, CrossPlatformMachineEpsilon * 10)] // value: (2 / sqrt(pi))
[InlineData( 1.41421356f, 1.12246205f, CrossPlatformMachineEpsilon * 10)] // value: (sqrt(2))
[InlineData( 1.44269504f, 1.12994728f, CrossPlatformMachineEpsilon * 10)] // value: (log2(e))
[InlineData( 1.57079633f, 1.16244735f, CrossPlatformMachineEpsilon * 10)] // value: (pi / 2)
[InlineData( 2.30258509f, 1.32050048f, CrossPlatformMachineEpsilon * 10)] // value: (ln(10))
[InlineData( 2.71828183f, 1.39561243f, CrossPlatformMachineEpsilon * 10)] // value: (e)
[InlineData( 3.14159265f, 1.46459189f, CrossPlatformMachineEpsilon * 10)] // value: (pi)
[InlineData( float.PositiveInfinity, float.PositiveInfinity, 0.0f)]
public static void Cbrt(float value, float expectedResult, float allowedVariance)
{
AssertEqual(expectedResult, MathF.Cbrt(value), allowedVariance);
}
[Theory]
[InlineData(float.NegativeInfinity, float.NegativeInfinity, 0.0f)]
[InlineData(-3.14159265f, -3.0f, 0.0f)] // value: -(pi)
[InlineData(-2.71828183f, -2.0f, 0.0f)] // value: -(e)
[InlineData(-2.30258509f, -2.0f, 0.0f)] // value: -(ln(10))
[InlineData(-1.57079633f, -1.0f, 0.0f)] // value: -(pi / 2)
[InlineData(-1.44269504f, -1.0f, 0.0f)] // value: -(log2(e))
[InlineData(-1.41421356f, -1.0f, 0.0f)] // value: -(sqrt(2))
[InlineData(-1.12837917f, -1.0f, 0.0f)] // value: -(2 / sqrt(pi))
[InlineData(-1.0f, -1.0f, 0.0f)]
[InlineData(-0.785398163f, -0.0f, 0.0f, Skip = "https://github.com/dotnet/coreclr/issues/10287")] // value: -(pi / 4)
[InlineData(-0.707106781f, -0.0f, 0.0f, Skip = "https://github.com/dotnet/coreclr/issues/10287")] // value: -(1 / sqrt(2))
[InlineData(-0.693147181f, -0.0f, 0.0f, Skip = "https://github.com/dotnet/coreclr/issues/10287")] // value: -(ln(2))
[InlineData(-0.636619772f, -0.0f, 0.0f, Skip = "https://github.com/dotnet/coreclr/issues/10287")] // value: -(2 / pi)
[InlineData(-0.434294482f, -0.0f, 0.0f, Skip = "https://github.com/dotnet/coreclr/issues/10287")] // value: -(log10(e))
[InlineData(-0.318309886f, -0.0f, 0.0f, Skip = "https://github.com/dotnet/coreclr/issues/10287")] // value: -(1 / pi)
[InlineData(-0.0f, -0.0f, 0.0f)]
[InlineData( float.NaN, float.NaN, 0.0f)]
[InlineData( 0.0f, 0.0f, 0.0f)]
[InlineData( 0.318309886f, 1.0f, 0.0f)] // value: (1 / pi)
[InlineData( 0.434294482f, 1.0f, 0.0f)] // value: (log10(e))
[InlineData( 0.636619772f, 1.0f, 0.0f)] // value: (2 / pi)
[InlineData( 0.693147181f, 1.0f, 0.0f)] // value: (ln(2))
[InlineData( 0.707106781f, 1.0f, 0.0f)] // value: (1 / sqrt(2))
[InlineData( 0.785398163f, 1.0f, 0.0f)] // value: (pi / 4)
[InlineData( 1.0f, 1.0f, 0.0f)]
[InlineData( 1.12837917f, 2.0f, 0.0f)] // value: (2 / sqrt(pi))
[InlineData( 1.41421356f, 2.0f, 0.0f)] // value: (sqrt(2))
[InlineData( 1.44269504f, 2.0f, 0.0f)] // value: (log2(e))
[InlineData( 1.57079633f, 2.0f, 0.0f)] // value: (pi / 2)
[InlineData( 2.30258509f, 3.0f, 0.0f)] // value: (ln(10))
[InlineData( 2.71828183f, 3.0f, 0.0f)] // value: (e)
[InlineData( 3.14159265f, 4.0f, 0.0f)] // value: (pi)
[InlineData(float.PositiveInfinity, float.PositiveInfinity, 0.0f)]
public static void Ceiling(float value, float expectedResult, float allowedVariance)
{
AssertEqual(expectedResult, MathF.Ceiling(value), allowedVariance);
}
[Theory]
[InlineData( float.NegativeInfinity, float.NaN, 0.0f)]
[InlineData(-3.14159265f, -1.0f, CrossPlatformMachineEpsilon * 10)] // value: -(pi)
[InlineData(-2.71828183f, -0.911733918f, CrossPlatformMachineEpsilon)] // value: -(e)
[InlineData(-2.30258509f, -0.668201510f, CrossPlatformMachineEpsilon)] // value: -(ln(10))
[InlineData(-1.57079633f, 0.0f, CrossPlatformMachineEpsilon)] // value: -(pi / 2)
[InlineData(-1.44269504f, 0.127751218f, CrossPlatformMachineEpsilon)] // value: -(log2(e))
[InlineData(-1.41421356f, 0.155943695f, CrossPlatformMachineEpsilon)] // value: -(sqrt(2))
[InlineData(-1.12837917f, 0.428125148f, CrossPlatformMachineEpsilon)] // value: -(2 / sqrt(pi))
[InlineData(-1.0f, 0.540302306f, CrossPlatformMachineEpsilon)]
[InlineData(-0.785398163f, 0.707106781f, CrossPlatformMachineEpsilon)] // value: -(pi / 4), expected: (1 / sqrt(2))
[InlineData(-0.707106781f, 0.760244597f, CrossPlatformMachineEpsilon)] // value: -(1 / sqrt(2))
[InlineData(-0.693147181f, 0.769238901f, CrossPlatformMachineEpsilon)] // value: -(ln(2))
[InlineData(-0.636619772f, 0.804109828f, CrossPlatformMachineEpsilon)] // value: -(2 / pi)
[InlineData(-0.434294482f, 0.907167129f, CrossPlatformMachineEpsilon)] // value: -(log10(e))
[InlineData(-0.318309886f, 0.949765715f, CrossPlatformMachineEpsilon)] // value: -(1 / pi)
[InlineData(-0.0f, 1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData( float.NaN, float.NaN, 0.0f)]
[InlineData( 0.0f, 1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData( 0.318309886f, 0.949765715f, CrossPlatformMachineEpsilon)] // value: (1 / pi)
[InlineData( 0.434294482f, 0.907167129f, CrossPlatformMachineEpsilon)] // value: (log10(e))
[InlineData( 0.636619772f, 0.804109828f, CrossPlatformMachineEpsilon)] // value: (2 / pi)
[InlineData( 0.693147181f, 0.769238901f, CrossPlatformMachineEpsilon)] // value: (ln(2))
[InlineData( 0.707106781f, 0.760244597f, CrossPlatformMachineEpsilon)] // value: (1 / sqrt(2))
[InlineData( 0.785398163f, 0.707106781f, CrossPlatformMachineEpsilon)] // value: (pi / 4), expected: (1 / sqrt(2))
[InlineData( 1.0f, 0.540302306f, CrossPlatformMachineEpsilon)]
[InlineData( 1.12837917f, 0.428125148f, CrossPlatformMachineEpsilon)] // value: (2 / sqrt(pi))
[InlineData( 1.41421356f, 0.155943695f, CrossPlatformMachineEpsilon)] // value: (sqrt(2))
[InlineData( 1.44269504f, 0.127751218f, CrossPlatformMachineEpsilon)] // value: (log2(e))
[InlineData( 1.57079633f, 0.0f, CrossPlatformMachineEpsilon)] // value: (pi / 2)
[InlineData( 2.30258509f, -0.668201510f, CrossPlatformMachineEpsilon)] // value: (ln(10))
[InlineData( 2.71828183f, -0.911733918f, CrossPlatformMachineEpsilon)] // value: (e)
[InlineData( 3.14159265f, -1.0f, CrossPlatformMachineEpsilon * 10)] // value: (pi)
[InlineData( float.PositiveInfinity, float.NaN, 0.0f)]
public static void Cos(float value, float expectedResult, float allowedVariance)
{
AssertEqual(expectedResult, MathF.Cos(value), allowedVariance);
}
[Theory]
[InlineData( float.NegativeInfinity, float.PositiveInfinity, 0.0f)]
[InlineData(-3.14159265f, 11.5919533f, CrossPlatformMachineEpsilon * 100)] // value: (pi)
[InlineData(-2.71828183f, 7.61012514f, CrossPlatformMachineEpsilon * 10)] // value: (e)
[InlineData(-2.30258509f, 5.05f, CrossPlatformMachineEpsilon * 10)] // value: (ln(10))
[InlineData(-1.57079633f, 2.50917848f, CrossPlatformMachineEpsilon * 10)] // value: (pi / 2)
[InlineData(-1.44269504f, 2.23418810f, CrossPlatformMachineEpsilon * 10)] // value: (log2(e))
[InlineData(-1.41421356f, 2.17818356f, CrossPlatformMachineEpsilon * 10)] // value: (sqrt(2))
[InlineData(-1.12837917f, 1.70710014f, CrossPlatformMachineEpsilon * 10)] // value: (2 / sqrt(pi))
[InlineData(-1.0f, 1.54308063f, CrossPlatformMachineEpsilon * 10)]
[InlineData(-0.785398163f, 1.32460909f, CrossPlatformMachineEpsilon * 10)] // value: (pi / 4)
[InlineData(-0.707106781f, 1.26059184f, CrossPlatformMachineEpsilon * 10)] // value: (1 / sqrt(2))
[InlineData(-0.693147181f, 1.25f, CrossPlatformMachineEpsilon * 10)] // value: (ln(2))
[InlineData(-0.636619772f, 1.20957949f, CrossPlatformMachineEpsilon * 10)] // value: (2 / pi)
[InlineData(-0.434294482f, 1.09579746f, CrossPlatformMachineEpsilon * 10)] // value: (log10(e))
[InlineData(-0.318309886f, 1.05108979f, CrossPlatformMachineEpsilon * 10)] // value: (1 / pi)
[InlineData(-0.0f, 1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData( float.NaN, float.NaN, 0.0f)]
[InlineData( 0.0f, 1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData( 0.318309886f, 1.05108979f, CrossPlatformMachineEpsilon * 10)] // value: (1 / pi)
[InlineData( 0.434294482f, 1.09579746f, CrossPlatformMachineEpsilon * 10)] // value: (log10(e))
[InlineData( 0.636619772f, 1.20957949f, CrossPlatformMachineEpsilon * 10)] // value: (2 / pi)
[InlineData( 0.693147181f, 1.25f, CrossPlatformMachineEpsilon * 10)] // value: (ln(2))
[InlineData( 0.707106781f, 1.26059184f, CrossPlatformMachineEpsilon * 10)] // value: (1 / sqrt(2))
[InlineData( 0.785398163f, 1.32460909f, CrossPlatformMachineEpsilon * 10)] // value: (pi / 4)
[InlineData( 1.0f, 1.54308063f, CrossPlatformMachineEpsilon * 10)]
[InlineData( 1.12837917f, 1.70710014f, CrossPlatformMachineEpsilon * 10)] // value: (2 / sqrt(pi))
[InlineData( 1.41421356f, 2.17818356f, CrossPlatformMachineEpsilon * 10)] // value: (sqrt(2))
[InlineData( 1.44269504f, 2.23418810f, CrossPlatformMachineEpsilon * 10)] // value: (log2(e))
[InlineData( 1.57079633f, 2.50917848f, CrossPlatformMachineEpsilon * 10)] // value: (pi / 2)
[InlineData( 2.30258509f, 5.05f, CrossPlatformMachineEpsilon * 10)] // value: (ln(10))
[InlineData( 2.71828183f, 7.61012514f, CrossPlatformMachineEpsilon * 10)] // value: (e)
[InlineData( 3.14159265f, 11.5919533f, CrossPlatformMachineEpsilon * 100)] // value: (pi)
[InlineData( float.PositiveInfinity, float.PositiveInfinity, 0.0f)]
public static void Cosh(float value, float expectedResult, float allowedVariance)
{
AssertEqual(expectedResult, MathF.Cosh(value), allowedVariance);
}
[Theory]
[InlineData( float.NegativeInfinity, 0.0f, CrossPlatformMachineEpsilon)]
[InlineData(-3.14159265f, 0.0432139183f, CrossPlatformMachineEpsilon / 10)] // value: -(pi)
[InlineData(-2.71828183f, 0.0659880358f, CrossPlatformMachineEpsilon / 10)] // value: -(e)
[InlineData(-2.30258509f, 0.1f, CrossPlatformMachineEpsilon)] // value: -(ln(10))
[InlineData(-1.57079633f, 0.207879576f, CrossPlatformMachineEpsilon)] // value: -(pi / 2)
[InlineData(-1.44269504f, 0.236290088f, CrossPlatformMachineEpsilon)] // value: -(log2(e))
[InlineData(-1.41421356f, 0.243116734f, CrossPlatformMachineEpsilon)] // value: -(sqrt(2))
[InlineData(-1.12837917f, 0.323557264f, CrossPlatformMachineEpsilon)] // value: -(2 / sqrt(pi))
[InlineData(-1.0f, 0.367879441f, CrossPlatformMachineEpsilon)]
[InlineData(-0.785398163f, 0.455938128f, CrossPlatformMachineEpsilon)] // value: -(pi / 4)
[InlineData(-0.707106781f, 0.493068691f, CrossPlatformMachineEpsilon)] // value: -(1 / sqrt(2))
[InlineData(-0.693147181f, 0.5f, CrossPlatformMachineEpsilon)] // value: -(ln(2))
[InlineData(-0.636619772f, 0.529077808f, CrossPlatformMachineEpsilon)] // value: -(2 / pi)
[InlineData(-0.434294482f, 0.647721485f, CrossPlatformMachineEpsilon)] // value: -(log10(e))
[InlineData(-0.318309886f, 0.727377349f, CrossPlatformMachineEpsilon)] // value: -(1 / pi)
[InlineData(-0.0f, 1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData( float.NaN, float.NaN, 0.0f)]
[InlineData( 0.0f, 1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData( 0.318309886f, 1.37480223f, CrossPlatformMachineEpsilon * 10)] // value: (1 / pi)
[InlineData( 0.434294482f, 1.54387344f, CrossPlatformMachineEpsilon * 10)] // value: (log10(e))
[InlineData( 0.636619772f, 1.89008116f, CrossPlatformMachineEpsilon * 10)] // value: (2 / pi)
[InlineData( 0.693147181f, 2.0f, CrossPlatformMachineEpsilon * 10)] // value: (ln(2))
[InlineData( 0.707106781f, 2.02811498f, CrossPlatformMachineEpsilon * 10)] // value: (1 / sqrt(2))
[InlineData( 0.785398163f, 2.19328005f, CrossPlatformMachineEpsilon * 10)] // value: (pi / 4)
[InlineData( 1.0f, 2.71828183f, CrossPlatformMachineEpsilon * 10)] // expected: (e)
[InlineData( 1.12837917f, 3.09064302f, CrossPlatformMachineEpsilon * 10)] // value: (2 / sqrt(pi))
[InlineData( 1.41421356f, 4.11325038f, CrossPlatformMachineEpsilon * 10)] // value: (sqrt(2))
[InlineData( 1.44269504f, 4.23208611f, CrossPlatformMachineEpsilon * 10)] // value: (log2(e))
[InlineData( 1.57079633f, 4.81047738f, CrossPlatformMachineEpsilon * 10)] // value: (pi / 2)
[InlineData( 2.30258509f, 10.0f, CrossPlatformMachineEpsilon * 100)] // value: (ln(10))
[InlineData( 2.71828183f, 15.1542622f, CrossPlatformMachineEpsilon * 100)] // value: (e)
[InlineData( 3.14159265f, 23.1406926f, CrossPlatformMachineEpsilon * 100)] // value: (pi)
[InlineData( float.PositiveInfinity, float.PositiveInfinity, 0.0f)]
public static void Exp(float value, float expectedResult, float allowedVariance)
{
AssertEqual(expectedResult, MathF.Exp(value), allowedVariance);
}
[Theory]
[InlineData(float.NegativeInfinity, float.NegativeInfinity, 0.0f)]
[InlineData(-3.14159265f, -4.0f, 0.0f)] // value: -(pi)
[InlineData(-2.71828183f, -3.0f, 0.0f)] // value: -(e)
[InlineData(-2.30258509f, -3.0f, 0.0f)] // value: -(ln(10))
[InlineData(-1.57079633f, -2.0f, 0.0f)] // value: -(pi / 2)
[InlineData(-1.44269504f, -2.0f, 0.0f)] // value: -(log2(e))
[InlineData(-1.41421356f, -2.0f, 0.0f)] // value: -(sqrt(2))
[InlineData(-1.12837917f, -2.0f, 0.0f)] // value: -(2 / sqrt(pi))
[InlineData(-1.0f, -1.0f, 0.0f)]
[InlineData(-0.785398163f, -1.0f, 0.0f)] // value: -(pi / 4)
[InlineData(-0.707106781f, -1.0f, 0.0f)] // value: -(1 / sqrt(2))
[InlineData(-0.693147181f, -1.0f, 0.0f)] // value: -(ln(2))
[InlineData(-0.636619772f, -1.0f, 0.0f)] // value: -(2 / pi)
[InlineData(-0.434294482f, -1.0f, 0.0f)] // value: -(log10(e))
[InlineData(-0.318309886f, -1.0f, 0.0f)] // value: -(1 / pi)
[InlineData(-0.0f, -0.0f, 0.0f)]
[InlineData( float.NaN, float.NaN, 0.0f)]
[InlineData( 0.0f, 0.0f, 0.0f)]
[InlineData( 0.318309886f, 0.0f, 0.0f)] // value: (1 / pi)
[InlineData( 0.434294482f, 0.0f, 0.0f)] // value: (log10(e))
[InlineData( 0.636619772f, 0.0f, 0.0f)] // value: (2 / pi)
[InlineData( 0.693147181f, 0.0f, 0.0f)] // value: (ln(2))
[InlineData( 0.707106781f, 0.0f, 0.0f)] // value: (1 / sqrt(2))
[InlineData( 0.785398163f, 0.0f, 0.0f)] // value: (pi / 4)
[InlineData( 1.0f, 1.0f, 0.0f)]
[InlineData( 1.12837917f, 1.0f, 0.0f)] // value: (2 / sqrt(pi))
[InlineData( 1.41421356f, 1.0f, 0.0f)] // value: (sqrt(2))
[InlineData( 1.44269504f, 1.0f, 0.0f)] // value: (log2(e))
[InlineData( 1.57079633f, 1.0f, 0.0f)] // value: (pi / 2)
[InlineData( 2.30258509f, 2.0f, 0.0f)] // value: (ln(10))
[InlineData( 2.71828183f, 2.0f, 0.0f)] // value: (e)
[InlineData( 3.14159265f, 3.0f, 0.0f)] // value: (pi)
[InlineData(float.PositiveInfinity, float.PositiveInfinity, 0.0f)]
public static void Floor(float value, float expectedResult, float allowedVariance)
{
AssertEqual(expectedResult, MathF.Floor(value), allowedVariance);
}
[Fact]
public static void IEEERemainder()
{
Assert.Equal(-1.0f, MathF.IEEERemainder(3.0f, 2.0f));
Assert.Equal(0.0f, MathF.IEEERemainder(4.0f, 2.0f));
Assert.Equal(1.0f, MathF.IEEERemainder(10.0f, 3.0f));
Assert.Equal(-1.0f, MathF.IEEERemainder(11.0f, 3.0f));
Assert.Equal(-2.0f, MathF.IEEERemainder(28.0f, 5.0f));
AssertEqual(1.8f, MathF.IEEERemainder(17.8f, 4.0f), CrossPlatformMachineEpsilon * 10);
AssertEqual(1.4f, MathF.IEEERemainder(17.8f, 4.1f), CrossPlatformMachineEpsilon * 10);
AssertEqual(0.1000004f, MathF.IEEERemainder(-16.3f, 4.1f), CrossPlatformMachineEpsilon / 10);
AssertEqual(1.4f, MathF.IEEERemainder(17.8f, -4.1f), CrossPlatformMachineEpsilon * 10);
AssertEqual(-1.4f, MathF.IEEERemainder(-17.8f, -4.1f), CrossPlatformMachineEpsilon * 10);
}
[Theory]
[InlineData( float.NegativeInfinity, float.NaN, 0.0f)]
[InlineData(-3.14159265f, float.NaN, 0.0f)] // value: -(pi)
[InlineData(-2.71828183f, float.NaN, 0.0f)] // value: -(e)
[InlineData(-1.41421356f, float.NaN, 0.0f)] // value: -(sqrt(2))
[InlineData(-1.0f, float.NaN, 0.0f)]
[InlineData(-0.693147181f, float.NaN, 0.0f)] // value: -(ln(2))
[InlineData(-0.434294482f, float.NaN, 0.0f)] // value: -(log10(e))
[InlineData(-0.0f, float.NegativeInfinity, 0.0f)]
[InlineData( float.NaN, float.NaN, 0.0f)]
[InlineData( 0.0f, float.NegativeInfinity, 0.0f)]
[InlineData( 0.0432139183f, -3.14159265f, CrossPlatformMachineEpsilon * 10)] // expected: -(pi)
[InlineData( 0.0659880358f, -2.71828183f, CrossPlatformMachineEpsilon * 10)] // expected: -(e)
[InlineData( 0.1f, -2.30258509f, CrossPlatformMachineEpsilon * 10)] // expected: -(ln(10))
[InlineData( 0.207879576f, -1.57079633f, CrossPlatformMachineEpsilon * 10)] // expected: -(pi / 2)
[InlineData( 0.236290088f, -1.44269504f, CrossPlatformMachineEpsilon * 10)] // expected: -(log2(e))
[InlineData( 0.243116734f, -1.41421356f, CrossPlatformMachineEpsilon * 10)] // expected: -(sqrt(2))
[InlineData( 0.323557264f, -1.12837917f, CrossPlatformMachineEpsilon * 10)] // expected: -(2 / sqrt(pi))
[InlineData( 0.367879441f, -1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData( 0.455938128f, -0.785398163f, CrossPlatformMachineEpsilon)] // expected: -(pi / 4)
[InlineData( 0.493068691f, -0.707106781f, CrossPlatformMachineEpsilon)] // expected: -(1 / sqrt(2))
[InlineData( 0.5f, -0.693147181f, CrossPlatformMachineEpsilon)] // expected: -(ln(2))
[InlineData( 0.529077808f, -0.636619772f, CrossPlatformMachineEpsilon)] // expected: -(2 / pi)
[InlineData( 0.647721485f, -0.434294482f, CrossPlatformMachineEpsilon)] // expected: -(log10(e))
[InlineData( 0.727377349f, -0.318309886f, CrossPlatformMachineEpsilon)] // expected: -(1 / pi)
[InlineData( 1.0f, 0.0f, 0.0f)]
[InlineData( 1.37480223f, 0.318309886f, CrossPlatformMachineEpsilon)] // expected: (1 / pi)
[InlineData( 1.54387344f, 0.434294482f, CrossPlatformMachineEpsilon)] // expected: (log10(e))
[InlineData( 1.89008116f, 0.636619772f, CrossPlatformMachineEpsilon)] // expected: (2 / pi)
[InlineData( 2.0f, 0.693147181f, CrossPlatformMachineEpsilon)] // expected: (ln(2))
[InlineData( 2.02811498f, 0.707106781f, CrossPlatformMachineEpsilon)] // expected: (1 / sqrt(2))
[InlineData( 2.19328005f, 0.785398163f, CrossPlatformMachineEpsilon)] // expected: (pi / 4)
[InlineData( 2.71828183f, 1.0f, CrossPlatformMachineEpsilon * 10)] // value: (e)
[InlineData( 3.09064302f, 1.12837917f, CrossPlatformMachineEpsilon * 10)] // expected: (2 / sqrt(pi))
[InlineData( 4.11325038f, 1.41421356f, CrossPlatformMachineEpsilon * 10)] // expected: (sqrt(2))
[InlineData( 4.23208611f, 1.44269504f, CrossPlatformMachineEpsilon * 10)] // expected: (log2(e))
[InlineData( 4.81047738f, 1.57079633f, CrossPlatformMachineEpsilon * 10)] // expected: (pi / 2)
[InlineData( 10.0f, 2.30258509f, CrossPlatformMachineEpsilon * 10)] // expected: (ln(10))
[InlineData( 15.1542622f, 2.71828183f, CrossPlatformMachineEpsilon * 10)] // expected: (e)
[InlineData( 23.1406926f, 3.14159265f, CrossPlatformMachineEpsilon * 10)] // expected: (pi)
[InlineData( float.PositiveInfinity, float.PositiveInfinity, 0.0f)]
public static void Log(float value, float expectedResult, float allowedVariance)
{
AssertEqual(expectedResult, MathF.Log(value), allowedVariance);
}
[Fact]
public static void LogWithBase()
{
Assert.Equal(1.0f, MathF.Log(3.0f, 3.0f));
AssertEqual(2.40217350f, MathF.Log(14.0f, 3.0f), CrossPlatformMachineEpsilon * 10);
Assert.Equal(float.NegativeInfinity, MathF.Log(0.0f, 3.0f));
Assert.Equal(float.NaN, MathF.Log(-3.0f, 3.0f));
Assert.Equal(float.NaN, MathF.Log(float.NaN, 3.0f));
Assert.Equal(float.PositiveInfinity, MathF.Log(float.PositiveInfinity, 3.0f));
Assert.Equal(float.NaN, MathF.Log(float.NegativeInfinity, 3.0f));
}
[Theory]
[InlineData( float.NegativeInfinity, float.NaN, 0.0f)]
[InlineData(-3.14159265f, float.NaN, 0.0f)] // value: -(pi)
[InlineData(-2.71828183f, float.NaN, 0.0f)] // value: -(e)
[InlineData(-1.41421356f, float.NaN, 0.0f)] // value: -(sqrt(2))
[InlineData(-1.0f, float.NaN, 0.0f)]
[InlineData(-0.693147181f, float.NaN, 0.0f)] // value: -(ln(2))
[InlineData(-0.434294482f, float.NaN, 0.0f)] // value: -(log10(e))
[InlineData(-0.0f, float.NegativeInfinity, 0.0f)]
[InlineData( float.NaN, float.NaN, 0.0f)]
[InlineData( 0.0f, float.NegativeInfinity, 0.0f)]
[InlineData( 0.000721784159f, -3.14159265f, CrossPlatformMachineEpsilon * 10)] // expected: -(pi)
[InlineData( 0.00191301410f, -2.71828183f, CrossPlatformMachineEpsilon * 10)] // expected: -(e)
[InlineData( 0.00498212830f, -2.30258509f, CrossPlatformMachineEpsilon * 10)] // expected: -(ln(10))
[InlineData( 0.0268660410f, -1.57079633f, CrossPlatformMachineEpsilon * 10)] // expected: -(pi / 2)
[InlineData( 0.0360831928f, -1.44269504f, CrossPlatformMachineEpsilon * 10)] // expected: -(log2(e))
[InlineData( 0.0385288847f, -1.41421356f, CrossPlatformMachineEpsilon * 10)] // expected: -(sqrt(2))
[InlineData( 0.0744082059f, -1.12837917f, CrossPlatformMachineEpsilon * 10)] // expected: -(2 / sqrt(pi))
[InlineData( 0.1f, -1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData( 0.163908636f, -0.785398163f, CrossPlatformMachineEpsilon)] // expected: -(pi / 4)
[InlineData( 0.196287760f, -0.707106781f, CrossPlatformMachineEpsilon)] // expected: -(1 / sqrt(2))
[InlineData( 0.202699566f, -0.693147181f, CrossPlatformMachineEpsilon)] // expected: -(ln(2))
[InlineData( 0.230876765f, -0.636619772f, CrossPlatformMachineEpsilon)] // expected: -(2 / pi)
[InlineData( 0.367879441f, -0.434294482f, CrossPlatformMachineEpsilon)] // expected: -(log10(e))
[InlineData( 0.480496373f, -0.318309886f, CrossPlatformMachineEpsilon)] // expected: -(1 / pi)
[InlineData( 1.0f, 0.0f, 0.0f)]
[InlineData( 2.08118116f, 0.318309886f, CrossPlatformMachineEpsilon)] // expected: (1 / pi)
[InlineData( 2.71828183f, 0.434294482f, CrossPlatformMachineEpsilon)] // expected: (log10(e)) value: (e)
[InlineData( 4.33131503f, 0.636619772f, CrossPlatformMachineEpsilon)] // expected: (2 / pi)
[InlineData( 4.93340967f, 0.693147181f, CrossPlatformMachineEpsilon)] // expected: (ln(2))
[InlineData( 5.09456117f, 0.707106781f, CrossPlatformMachineEpsilon)] // expected: (1 / sqrt(2))
[InlineData( 6.10095980f, 0.785398163f, CrossPlatformMachineEpsilon)] // expected: (pi / 4)
[InlineData( 10.0f, 1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData( 13.4393779f, 1.12837917f, CrossPlatformMachineEpsilon * 10)] // expected: (2 / sqrt(pi))
[InlineData( 25.9545535f, 1.41421356f, CrossPlatformMachineEpsilon * 10)] // expected: (sqrt(2))
[InlineData( 27.7137338f, 1.44269504f, CrossPlatformMachineEpsilon * 10)] // expected: (log2(e))
[InlineData( 37.2217105f, 1.57079633f, CrossPlatformMachineEpsilon * 10)] // expected: (pi / 2)
[InlineData( 200.717432f, 2.30258509f, CrossPlatformMachineEpsilon * 10)] // expected: (ln(10))
[InlineData( 522.735300f, 2.71828183f, CrossPlatformMachineEpsilon * 10)] // expected: (e)
[InlineData( 1385.45573f, 3.14159265f, CrossPlatformMachineEpsilon * 10)] // expected: (pi)
[InlineData( float.PositiveInfinity, float.PositiveInfinity, 0.0f)]
public static void Log10(float value, float expectedResult, float allowedVariance)
{
AssertEqual(expectedResult, MathF.Log10(value), allowedVariance);
}
[Fact]
public static void Max()
{
Assert.Equal(3.0f, MathF.Max(3.0f, -2.0f));
Assert.Equal(float.MaxValue, MathF.Max(float.MinValue, float.MaxValue));
Assert.Equal(float.PositiveInfinity, MathF.Max(float.NegativeInfinity, float.PositiveInfinity));
Assert.Equal(float.NaN, MathF.Max(float.PositiveInfinity, float.NaN));
Assert.Equal(float.NaN, MathF.Max(float.NaN, float.NaN));
}
[Fact]
public static void Min()
{
Assert.Equal(-2.0f, MathF.Min(3.0f, -2.0f));
Assert.Equal(float.MinValue, MathF.Min(float.MinValue, float.MaxValue));
Assert.Equal(float.NegativeInfinity, MathF.Min(float.NegativeInfinity, float.PositiveInfinity));
Assert.Equal(float.NaN, MathF.Min(float.NegativeInfinity, float.NaN));
Assert.Equal(float.NaN, MathF.Min(float.NaN, float.NaN));
}
[Theory]
[InlineData( float.NegativeInfinity, float.NegativeInfinity, 0.0f, 0.0f)]
[InlineData( float.NegativeInfinity, -1.0f, -0.0f, 0.0f)]
[InlineData( float.NegativeInfinity, -0.0f, 1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData( float.NegativeInfinity, float.NaN, float.NaN, 0.0f)]
[InlineData( float.NegativeInfinity, 0.0f, 1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData( float.NegativeInfinity, 1.0f, float.NegativeInfinity, 0.0f)]
[InlineData( float.NegativeInfinity, float.PositiveInfinity, float.PositiveInfinity, 0.0f)]
[InlineData(-10.0f, float.NegativeInfinity, 0.0f, 0.0f)]
[InlineData(-10.0f, -1.57079633f, float.NaN, 0.0f)] // y: -(pi / 2)
[InlineData(-10.0f, -1.0f, -0.1f, CrossPlatformMachineEpsilon)]
[InlineData(-10.0f, -0.785398163f, float.NaN, 0.0f)] // y: -(pi / 4)
[InlineData(-10.0f, -0.0f, 1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData(-10.0f, float.NaN, float.NaN, 0.0f)]
[InlineData(-10.0f, 0.0f, 1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData(-10.0f, 0.785398163f, float.NaN, 0.0f)] // y: (pi / 4)
[InlineData(-10.0f, 1.0f, -10.0f, CrossPlatformMachineEpsilon * 100)]
[InlineData(-10.0f, 1.57079633f, float.NaN, 0.0f)] // y: (pi / 2)
[InlineData(-10.0f, float.PositiveInfinity, float.PositiveInfinity, 0.0f)]
[InlineData(-2.71828183f, float.NegativeInfinity, 0.0f, 0.0f)] // x: -(e)
[InlineData(-2.71828183f, -1.57079633f, float.NaN, 0.0f)] // x: -(e) y: -(pi / 2)
[InlineData(-2.71828183f, -1.0f, -0.367879441f, CrossPlatformMachineEpsilon)] // x: -(e)
[InlineData(-2.71828183f, -0.785398163f, float.NaN, 0.0f)] // x: -(e) y: -(pi / 4)
[InlineData(-2.71828183f, -0.0f, 1.0f, CrossPlatformMachineEpsilon * 10)] // x: -(e)
[InlineData(-2.71828183f, float.NaN, float.NaN, 0.0f)]
[InlineData(-2.71828183f, 0.0f, 1.0f, CrossPlatformMachineEpsilon * 10)] // x: -(e)
[InlineData(-2.71828183f, 0.785398163f, float.NaN, 0.0f)] // x: -(e) y: (pi / 4)
[InlineData(-2.71828183f, 1.0f, -2.71828183f, CrossPlatformMachineEpsilon * 10)] // x: -(e) expected: (e)
[InlineData(-2.71828183f, 1.57079633f, float.NaN, 0.0f)] // x: -(e) y: (pi / 2)
[InlineData(-2.71828183f, float.PositiveInfinity, float.PositiveInfinity, 0.0f)]
[InlineData(-1.0f, -1.0f, -1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData(-1.0f, -0.0f, 1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData(-1.0f, float.NaN, float.NaN, 0.0f)]
[InlineData(-1.0f, 0.0f, 1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData(-1.0f, 1.0f, -1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData(-0.0f, float.NegativeInfinity, float.PositiveInfinity, 0.0f)]
[InlineData(-0.0f, -3.0f, float.NegativeInfinity, 0.0f)]
[InlineData(-0.0f, -2.0f, float.PositiveInfinity, 0.0f)]
[InlineData(-0.0f, -1.57079633f, float.PositiveInfinity, 0.0f)] // y: -(pi / 2)
[InlineData(-0.0f, -1.0f, float.NegativeInfinity, 0.0f)]
[InlineData(-0.0f, -0.0f, 1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData(-0.0f, float.NaN, float.NaN, 0.0f)]
[InlineData(-0.0f, 0.0f, 1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData(-0.0f, 1.0f, -0.0f, 0.0f)]
[InlineData(-0.0f, 1.57079633f, 0.0f, 0.0f)] // y: -(pi / 2)
[InlineData(-0.0f, 2.0f, 0.0f, 0.0f)]
[InlineData(-0.0f, 3.0f, -0.0f, 0.0f)]
[InlineData(-0.0f, float.PositiveInfinity, 0.0f, 0.0f)]
[InlineData( float.NaN, float.NegativeInfinity, float.NaN, 0.0f)]
[InlineData( float.NaN, -1.0f, float.NaN, 0.0f)]
[InlineData( float.NaN, float.NaN, float.NaN, 0.0f)]
[InlineData( float.NaN, 1.0f, float.NaN, 0.0f)]
[InlineData( float.NaN, float.PositiveInfinity, float.NaN, 0.0f)]
[InlineData( 0.0f, float.NegativeInfinity, float.PositiveInfinity, 0.0f)]
[InlineData( 0.0f, -3.0f, float.PositiveInfinity, 0.0f)]
[InlineData( 0.0f, -2.0f, float.PositiveInfinity, 0.0f)]
[InlineData( 0.0f, -1.57079633f, float.PositiveInfinity, 0.0f)] // y: -(pi / 2)
[InlineData( 0.0f, -1.0f, float.PositiveInfinity, 0.0f)]
[InlineData( 0.0f, -0.0f, 1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData( 0.0f, float.NaN, float.NaN, 0.0f)]
[InlineData( 0.0f, 0.0f, 1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData( 0.0f, 1.0f, 0.0f, 0.0f)]
[InlineData( 0.0f, 1.57079633f, 0.0f, 0.0f)] // y: -(pi / 2)
[InlineData( 0.0f, 2.0f, 0.0f, 0.0f)]
[InlineData( 0.0f, 3.0f, 0.0f, 0.0f)]
[InlineData( 0.0f, float.PositiveInfinity, 0.0f, 0.0f)]
[InlineData( 1.0f, float.NegativeInfinity, 1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData( 1.0f, -1.0f, 1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData( 1.0f, -0.0f, 1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData( 1.0f, 0.0f, 1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData( 1.0f, 1.0f, 1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData( 1.0f, float.PositiveInfinity, 1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData( 2.71828183f, float.NegativeInfinity, 0.0f, 0.0f)]
[InlineData( 2.71828183f, -3.14159265f, 0.0432139183f, CrossPlatformMachineEpsilon / 10)] // x: (e) y: -(pi)
[InlineData( 2.71828183f, -2.71828183f, 0.0659880358f, CrossPlatformMachineEpsilon / 10)] // x: (e) y: -(e)
[InlineData( 2.71828183f, -2.30258509f, 0.1f, CrossPlatformMachineEpsilon)] // x: (e) y: -(ln(10))
[InlineData( 2.71828183f, -1.57079633f, 0.207879576f, CrossPlatformMachineEpsilon)] // x: (e) y: -(pi / 2)
[InlineData( 2.71828183f, -1.44269504f, 0.236290088f, CrossPlatformMachineEpsilon)] // x: (e) y: -(log2(e))
[InlineData( 2.71828183f, -1.41421356f, 0.243116734f, CrossPlatformMachineEpsilon)] // x: (e) y: -(sqrt(2))
[InlineData( 2.71828183f, -1.12837917f, 0.323557264f, CrossPlatformMachineEpsilon)] // x: (e) y: -(2 / sqrt(pi))
[InlineData( 2.71828183f, -1.0f, 0.367879441f, CrossPlatformMachineEpsilon)] // x: (e)
[InlineData( 2.71828183f, -0.785398163f, 0.455938128f, CrossPlatformMachineEpsilon)] // x: (e) y: -(pi / 4)
[InlineData( 2.71828183f, -0.707106781f, 0.493068691f, CrossPlatformMachineEpsilon)] // x: (e) y: -(1 / sqrt(2))
[InlineData( 2.71828183f, -0.693147181f, 0.5f, CrossPlatformMachineEpsilon)] // x: (e) y: -(ln(2))
[InlineData( 2.71828183f, -0.636619772f, 0.529077808f, CrossPlatformMachineEpsilon)] // x: (e) y: -(2 / pi)
[InlineData( 2.71828183f, -0.434294482f, 0.647721485f, CrossPlatformMachineEpsilon)] // x: (e) y: -(log10(e))
[InlineData( 2.71828183f, -0.318309886f, 0.727377349f, CrossPlatformMachineEpsilon)] // x: (e) y: -(1 / pi)
[InlineData( 2.71828183f, -0.0f, 1.0f, CrossPlatformMachineEpsilon * 10)] // x: (e)
[InlineData( 2.71828183f, float.NaN, float.NaN, 0.0f)]
[InlineData( 2.71828183f, 0.0f, 1.0f, CrossPlatformMachineEpsilon * 10)] // x: (e)
[InlineData( 2.71828183f, 0.318309886f, 1.37480223f, CrossPlatformMachineEpsilon * 10)] // x: (e) y: (1 / pi)
[InlineData( 2.71828183f, 0.434294482f, 1.54387344f, CrossPlatformMachineEpsilon * 10)] // x: (e) y: (log10(e))
[InlineData( 2.71828183f, 0.636619772f, 1.89008116f, CrossPlatformMachineEpsilon * 10)] // x: (e) y: (2 / pi)
[InlineData( 2.71828183f, 0.693147181f, 2.0f, CrossPlatformMachineEpsilon * 10)] // x: (e) y: (ln(2))
[InlineData( 2.71828183f, 0.707106781f, 2.02811498f, CrossPlatformMachineEpsilon * 10)] // x: (e) y: (1 / sqrt(2))
[InlineData( 2.71828183f, 0.785398163f, 2.19328005f, CrossPlatformMachineEpsilon * 10)] // x: (e) y: (pi / 4)
[InlineData( 2.71828183f, 1.0f, 2.71828183f, CrossPlatformMachineEpsilon * 10)] // x: (e) expected: (e)
[InlineData( 2.71828183f, 1.12837917f, 3.09064302f, CrossPlatformMachineEpsilon * 10)] // x: (e) y: (2 / sqrt(pi))
[InlineData( 2.71828183f, 1.41421356f, 4.11325038f, CrossPlatformMachineEpsilon * 10)] // x: (e) y: (sqrt(2))
[InlineData( 2.71828183f, 1.44269504f, 4.23208611f, CrossPlatformMachineEpsilon * 10)] // x: (e) y: (log2(e))
[InlineData( 2.71828183f, 1.57079633f, 4.81047738f, CrossPlatformMachineEpsilon * 10)] // x: (e) y: (pi / 2)
[InlineData( 2.71828183f, 2.30258509f, 10.0f, CrossPlatformMachineEpsilon * 100)] // x: (e) y: (ln(10))
[InlineData( 2.71828183f, 2.71828183f, 15.1542622f, CrossPlatformMachineEpsilon * 100)] // x: (e) y: (e)
[InlineData( 2.71828183f, 3.14159265f, 23.1406926f, CrossPlatformMachineEpsilon * 100)] // x: (e) y: (pi)
[InlineData( 2.71828183f, float.PositiveInfinity, float.PositiveInfinity, 0.0f)] // x: (e)
[InlineData( 10.0f, float.NegativeInfinity, 0.0f, 0.0f)]
[InlineData( 10.0f, -3.14159265f, 0.000721784159f, CrossPlatformMachineEpsilon / 1000)] // y: -(pi)
[InlineData( 10.0f, -2.71828183f, 0.00191301410f, CrossPlatformMachineEpsilon / 100)] // y: -(e)
[InlineData( 10.0f, -2.30258509f, 0.00498212830f, CrossPlatformMachineEpsilon / 100)] // y: -(ln(10))
[InlineData( 10.0f, -1.57079633f, 0.0268660410f, CrossPlatformMachineEpsilon / 10)] // y: -(pi / 2)
[InlineData( 10.0f, -1.44269504f, 0.0360831928f, CrossPlatformMachineEpsilon / 10)] // y: -(log2(e))
[InlineData( 10.0f, -1.41421356f, 0.0385288847f, CrossPlatformMachineEpsilon / 10)] // y: -(sqrt(2))
[InlineData( 10.0f, -1.12837917f, 0.0744082059f, CrossPlatformMachineEpsilon / 10)] // y: -(2 / sqrt(pi))
[InlineData( 10.0f, -1.0f, 0.1f, CrossPlatformMachineEpsilon)]
[InlineData( 10.0f, -0.785398163f, 0.163908636f, CrossPlatformMachineEpsilon)] // y: -(pi / 4)
[InlineData( 10.0f, -0.707106781f, 0.196287760f, CrossPlatformMachineEpsilon)] // y: -(1 / sqrt(2))
[InlineData( 10.0f, -0.693147181f, 0.202699566f, CrossPlatformMachineEpsilon)] // y: -(ln(2))
[InlineData( 10.0f, -0.636619772f, 0.230876765f, CrossPlatformMachineEpsilon)] // y: -(2 / pi)
[InlineData( 10.0f, -0.434294482f, 0.367879441f, CrossPlatformMachineEpsilon)] // y: -(log10(e))
[InlineData( 10.0f, -0.318309886f, 0.480496373f, CrossPlatformMachineEpsilon)] // y: -(1 / pi)
[InlineData( 10.0f, -0.0f, 1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData( 10.0f, float.NaN, float.NaN, 0.0f)]
[InlineData( 10.0f, 0.0f, 1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData( 10.0f, 0.318309886f, 2.08118116f, CrossPlatformMachineEpsilon * 10)] // y: (1 / pi)
[InlineData( 10.0f, 0.434294482f, 2.71828183f, CrossPlatformMachineEpsilon * 10)] // y: (log10(e)) expected: (e)
[InlineData( 10.0f, 0.636619772f, 4.33131503f, CrossPlatformMachineEpsilon * 10)] // y: (2 / pi)
[InlineData( 10.0f, 0.693147181f, 4.93340967f, CrossPlatformMachineEpsilon * 10)] // y: (ln(2))
[InlineData( 10.0f, 0.707106781f, 5.09456117f, CrossPlatformMachineEpsilon * 10)] // y: (1 / sqrt(2))
[InlineData( 10.0f, 0.785398163f, 6.10095980f, CrossPlatformMachineEpsilon * 10)] // y: (pi / 4)
[InlineData( 10.0f, 1.0f, 10.0f, CrossPlatformMachineEpsilon * 100)]
[InlineData( 10.0f, 1.12837917f, 13.4393779f, CrossPlatformMachineEpsilon * 100)] // y: (2 / sqrt(pi))
[InlineData( 10.0f, 1.41421356f, 25.9545535f, CrossPlatformMachineEpsilon * 100)] // y: (sqrt(2))
[InlineData( 10.0f, 1.44269504f, 27.7137338f, CrossPlatformMachineEpsilon * 100)] // y: (log2(e))
[InlineData( 10.0f, 1.57079633f, 37.2217105f, CrossPlatformMachineEpsilon * 100)] // y: (pi / 2)
[InlineData( 10.0f, 2.30258509f, 200.717432f, CrossPlatformMachineEpsilon * 1000)] // y: (ln(10))
[InlineData( 10.0f, 2.71828183f, 522.735300f, CrossPlatformMachineEpsilon * 1000)] // y: (e)
[InlineData( 10.0f, 3.14159265f, 1385.45573f, CrossPlatformMachineEpsilon * 10000)] // y: (pi)
[InlineData( 10.0f, float.PositiveInfinity, float.PositiveInfinity, 0.0f)]
[InlineData( float.PositiveInfinity, float.NegativeInfinity, 0.0f, 0.0f)]
[InlineData( float.PositiveInfinity, -1.0f, 0.0f, 0.0f)]
[InlineData( float.PositiveInfinity, -0.0f, 1.0f, 0.0f)]
[InlineData( float.PositiveInfinity, float.NaN, float.NaN, 0.0f)]
[InlineData( float.PositiveInfinity, 0.0f, 1.0f, 0.0f)]
[InlineData( float.PositiveInfinity, 1.0f, float.PositiveInfinity, 0.0f)]
[InlineData( float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, 0.0f)]
public static void Pow(float x, float y, float expectedResult, float allowedVariance)
{
AssertEqual(expectedResult, MathF.Pow(x, y), allowedVariance);
}
[Theory]
[InlineData(-1.0f, float.NegativeInfinity, 1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData(-1.0f, float.PositiveInfinity, 1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData( float.NaN, -0.0f, 1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData( float.NaN, 0.0f, 1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData( 1.0f, float.NaN, 1.0f, CrossPlatformMachineEpsilon * 10)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public static void Pow_IEEE(float x, float y, float expectedResult, float allowedVariance)
{
AssertEqual(expectedResult, MathF.Pow(x, y), allowedVariance);
}
[Theory]
[InlineData(-1.0f, float.NegativeInfinity, float.NaN, 0.0f)]
[InlineData(-1.0f, float.PositiveInfinity, float.NaN, 0.0f)]
[InlineData( float.NaN,-0.0f, float.NaN, 0.0f)]
[InlineData( float.NaN, 0.0f, float.NaN, 0.0f)]
[InlineData( 1.0f, float.NaN, float.NaN, 0.0f)]
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)]
public static void Pow_IEEE_Legacy(float x, float y, float expectedResult, float allowedVariance)
{
AssertEqual(expectedResult, MathF.Pow(x, y), allowedVariance);
}
[Fact]
public static void Round()
{
Assert.Equal(0.0f, MathF.Round(0.0f));
Assert.Equal(1.0f, MathF.Round(1.4f));
Assert.Equal(2.0f, MathF.Round(1.5f));
Assert.Equal(2e7f, MathF.Round(2e7f));
Assert.Equal(0.0f, MathF.Round(-0.0f));
Assert.Equal(-1.0f, MathF.Round(-1.4f));
Assert.Equal(-2.0f, MathF.Round(-1.5f));
Assert.Equal(-2e7f, MathF.Round(-2e7f));
}
[Fact]
public static void Round_Digits()
{
AssertEqual(3.422f, MathF.Round(3.42156f, 3, MidpointRounding.AwayFromZero), CrossPlatformMachineEpsilon * 10);
AssertEqual(-3.422f, MathF.Round(-3.42156f, 3, MidpointRounding.AwayFromZero), CrossPlatformMachineEpsilon * 10);
Assert.Equal(0.0f, MathF.Round(0.0f, 3, MidpointRounding.AwayFromZero));
Assert.Equal(float.NaN, MathF.Round(float.NaN, 3, MidpointRounding.AwayFromZero));
Assert.Equal(float.PositiveInfinity, MathF.Round(float.PositiveInfinity, 3, MidpointRounding.AwayFromZero));
Assert.Equal(float.NegativeInfinity, MathF.Round(float.NegativeInfinity, 3, MidpointRounding.AwayFromZero));
}
[Fact]
public static void Sign()
{
Assert.Equal(0, MathF.Sign(0.0f));
Assert.Equal(0, MathF.Sign(-0.0f));
Assert.Equal(-1, MathF.Sign(-3.14f));
Assert.Equal(1, MathF.Sign(3.14f));
Assert.Equal(-1, MathF.Sign(float.NegativeInfinity));
Assert.Equal(1, MathF.Sign(float.PositiveInfinity));
Assert.Throws<ArithmeticException>(() => MathF.Sign(float.NaN));
}
[Theory]
[InlineData( float.NegativeInfinity, float.NaN, 0.0f)]
[InlineData(-3.14159265f, -0.0f, CrossPlatformMachineEpsilon)] // value: -(pi)
[InlineData(-2.71828183f, -0.410781291f, CrossPlatformMachineEpsilon)] // value: -(e)
[InlineData(-2.30258509f, -0.743980337f, CrossPlatformMachineEpsilon)] // value: -(ln(10))
[InlineData(-1.57079633f, -1.0f, CrossPlatformMachineEpsilon * 10)] // value: -(pi / 2)
[InlineData(-1.44269504f, -0.991806244f, CrossPlatformMachineEpsilon)] // value: -(log2(e))
[InlineData(-1.41421356f, -0.987765946f, CrossPlatformMachineEpsilon)] // value: -(sqrt(2))
[InlineData(-1.12837917f, -0.903719457f, CrossPlatformMachineEpsilon)] // value: -(2 / sqrt(pi))
[InlineData(-1.0f, -0.841470985f, CrossPlatformMachineEpsilon)]
[InlineData(-0.785398163f, -0.707106781f, CrossPlatformMachineEpsilon)] // value: -(pi / 4), expected: -(1 / sqrt(2))
[InlineData(-0.707106781f, -0.649636939f, CrossPlatformMachineEpsilon)] // value: -(1 / sqrt(2))
[InlineData(-0.693147181f, -0.638961276f, CrossPlatformMachineEpsilon)] // value: -(ln(2))
[InlineData(-0.636619772f, -0.594480769f, CrossPlatformMachineEpsilon)] // value: -(2 / pi)
[InlineData(-0.434294482f, -0.420770483f, CrossPlatformMachineEpsilon)] // value: -(log10(e))
[InlineData(-0.318309886f, -0.312961796f, CrossPlatformMachineEpsilon)] // value: -(1 / pi)
[InlineData(-0.0f, -0.0f, 0.0f)]
[InlineData( float.NaN, float.NaN, 0.0f)]
[InlineData( 0.0f, 0.0f, 0.0f)]
[InlineData( 0.318309886f, 0.312961796f, CrossPlatformMachineEpsilon)] // value: (1 / pi)
[InlineData( 0.434294482f, 0.420770483f, CrossPlatformMachineEpsilon)] // value: (log10(e))
[InlineData( 0.636619772f, 0.594480769f, CrossPlatformMachineEpsilon)] // value: (2 / pi)
[InlineData( 0.693147181f, 0.638961276f, CrossPlatformMachineEpsilon)] // value: (ln(2))
[InlineData( 0.707106781f, 0.649636939f, CrossPlatformMachineEpsilon)] // value: (1 / sqrt(2))
[InlineData( 0.785398163f, 0.707106781f, CrossPlatformMachineEpsilon)] // value: (pi / 4), expected: (1 / sqrt(2))
[InlineData( 1.0f, 0.841470985f, CrossPlatformMachineEpsilon)]
[InlineData( 1.12837917f, 0.903719457f, CrossPlatformMachineEpsilon)] // value: (2 / sqrt(pi))
[InlineData( 1.41421356f, 0.987765946f, CrossPlatformMachineEpsilon)] // value: (sqrt(2))
[InlineData( 1.44269504f, 0.991806244f, CrossPlatformMachineEpsilon)] // value: (log2(e))
[InlineData( 1.57079633f, 1.0f, CrossPlatformMachineEpsilon * 10)] // value: (pi / 2)
[InlineData( 2.30258509f, 0.743980337f, CrossPlatformMachineEpsilon)] // value: (ln(10))
[InlineData( 2.71828183f, 0.410781291f, CrossPlatformMachineEpsilon)] // value: (e)
[InlineData( 3.14159265f, 0.0f, CrossPlatformMachineEpsilon)] // value: (pi)
[InlineData( float.PositiveInfinity, float.NaN, 0.0f)]
public static void Sin(float value, float expectedResult, float allowedVariance)
{
AssertEqual(expectedResult, MathF.Sin(value), allowedVariance);
}
[Theory]
[InlineData( float.NegativeInfinity, float.NegativeInfinity, 0.0f)]
[InlineData(-3.14159265f, -11.5487394f, CrossPlatformMachineEpsilon * 100)] // value: -(pi)
[InlineData(-2.71828183f, -7.54413710f, CrossPlatformMachineEpsilon * 10)] // value: -(e)
[InlineData(-2.30258509f, -4.95f, CrossPlatformMachineEpsilon * 10)] // value: -(ln(10))
[InlineData(-1.57079633f, -2.30129890f, CrossPlatformMachineEpsilon * 10)] // value: -(pi / 2)
[InlineData(-1.44269504f, -1.99789801f, CrossPlatformMachineEpsilon * 10)] // value: -(log2(e))
[InlineData(-1.41421356f, -1.93506682f, CrossPlatformMachineEpsilon * 10)] // value: -(sqrt(2))
[InlineData(-1.12837917f, -1.38354288f, CrossPlatformMachineEpsilon * 10)] // value: -(2 / sqrt(pi))
[InlineData(-1.0f, -1.17520119f, CrossPlatformMachineEpsilon * 10)]
[InlineData(-0.785398163f, -0.868670961f, CrossPlatformMachineEpsilon)] // value: -(pi / 4)
[InlineData(-0.707106781f, -0.767523145f, CrossPlatformMachineEpsilon)] // value: -(1 / sqrt(2))
[InlineData(-0.693147181f, -0.75f, CrossPlatformMachineEpsilon)] // value: -(ln(2))
[InlineData(-0.636619772f, -0.680501678f, CrossPlatformMachineEpsilon)] // value: -(2 / pi)
[InlineData(-0.434294482f, -0.448075979f, CrossPlatformMachineEpsilon)] // value: -(log10(e))
[InlineData(-0.318309886f, -0.323712439f, CrossPlatformMachineEpsilon)] // value: -(1 / pi)
[InlineData(-0.0f, -0.0f, 0.0f)]
[InlineData( float.NaN, float.NaN, 0.0f)]
[InlineData( 0.0f, 0.0f, 0.0f)]
[InlineData( 0.318309886f, 0.323712439f, CrossPlatformMachineEpsilon)] // value: (1 / pi)
[InlineData( 0.434294482f, 0.448075979f, CrossPlatformMachineEpsilon)] // value: (log10(e))
[InlineData( 0.636619772f, 0.680501678f, CrossPlatformMachineEpsilon)] // value: (2 / pi)
[InlineData( 0.693147181f, 0.75f, CrossPlatformMachineEpsilon)] // value: (ln(2))
[InlineData( 0.707106781f, 0.767523145f, CrossPlatformMachineEpsilon)] // value: (1 / sqrt(2))
[InlineData( 0.785398163f, 0.868670961f, CrossPlatformMachineEpsilon)] // value: (pi / 4)
[InlineData( 1.0f, 1.17520119f, CrossPlatformMachineEpsilon * 10)]
[InlineData( 1.12837917f, 1.38354288f, CrossPlatformMachineEpsilon * 10)] // value: (2 / sqrt(pi))
[InlineData( 1.41421356f, 1.93506682f, CrossPlatformMachineEpsilon * 10)] // value: (sqrt(2))
[InlineData( 1.44269504f, 1.99789801f, CrossPlatformMachineEpsilon * 10)] // value: (log2(e))
[InlineData( 1.57079633f, 2.30129890f, CrossPlatformMachineEpsilon * 10)] // value: (pi / 2)
[InlineData( 2.30258509f, 4.95f, CrossPlatformMachineEpsilon * 10)] // value: (ln(10))
[InlineData( 2.71828183f, 7.54413710f, CrossPlatformMachineEpsilon * 10)] // value: (e)
[InlineData( 3.14159265f, 11.5487394f, CrossPlatformMachineEpsilon * 100)] // value: (pi)
[InlineData( float.PositiveInfinity, float.PositiveInfinity, 0.0f)]
public static void Sinh(float value, float expectedResult, float allowedVariance)
{
AssertEqual(expectedResult, MathF.Sinh(value), allowedVariance);
}
[Theory]
[InlineData( float.NegativeInfinity, float.NaN, 0.0f)]
[InlineData(-3.14159265f, float.NaN, 0.0f)] // value: (pi)
[InlineData(-2.71828183f, float.NaN, 0.0f)] // value: (e)
[InlineData(-2.30258509f, float.NaN, 0.0f)] // value: (ln(10))
[InlineData(-1.57079633f, float.NaN, 0.0f)] // value: (pi / 2)
[InlineData(-1.44269504f, float.NaN, 0.0f)] // value: (log2(e))
[InlineData(-1.41421356f, float.NaN, 0.0f)] // value: (sqrt(2))
[InlineData(-1.12837917f, float.NaN, 0.0f)] // value: (2 / sqrt(pi))
[InlineData(-1.0f, float.NaN, 0.0f)]
[InlineData(-0.785398163f, float.NaN, 0.0f)] // value: (pi / 4)
[InlineData(-0.707106781f, float.NaN, 0.0f)] // value: (1 / sqrt(2))
[InlineData(-0.693147181f, float.NaN, 0.0f)] // value: (ln(2))
[InlineData(-0.636619772f, float.NaN, 0.0f)] // value: (2 / pi)
[InlineData(-0.434294482f, float.NaN, 0.0f)] // value: (log10(e))
[InlineData(-0.318309886f, float.NaN, 0.0f)] // value: (1 / pi)
[InlineData(-0.0f, -0.0f, 0.0f)]
[InlineData( float.NaN, float.NaN, 0.0f)]
[InlineData( 0.0f, 0.0f, 0.0f)]
[InlineData( 0.318309886f, 0.564189584f, CrossPlatformMachineEpsilon)] // value: (1 / pi)
[InlineData( 0.434294482f, 0.659010229f, CrossPlatformMachineEpsilon)] // value: (log10(e))
[InlineData( 0.636619772f, 0.797884561f, CrossPlatformMachineEpsilon)] // value: (2 / pi)
[InlineData( 0.693147181f, 0.832554611f, CrossPlatformMachineEpsilon)] // value: (ln(2))
[InlineData( 0.707106781f, 0.840896415f, CrossPlatformMachineEpsilon)] // value: (1 / sqrt(2))
[InlineData( 0.785398163f, 0.886226925f, CrossPlatformMachineEpsilon)] // value: (pi / 4)
[InlineData( 1.0f, 1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData( 1.12837917f, 1.06225193f, CrossPlatformMachineEpsilon * 10)] // value: (2 / sqrt(pi))
[InlineData( 1.41421356f, 1.18920712f, CrossPlatformMachineEpsilon * 10)] // value: (sqrt(2))
[InlineData( 1.44269504f, 1.20112241f, CrossPlatformMachineEpsilon * 10)] // value: (log2(e))
[InlineData( 1.57079633f, 1.25331414f, CrossPlatformMachineEpsilon * 10)] // value: (pi / 2)
[InlineData( 2.30258509f, 1.51742713f, CrossPlatformMachineEpsilon * 10)] // value: (ln(10))
[InlineData( 2.71828183f, 1.64872127f, CrossPlatformMachineEpsilon * 10)] // value: (e)
[InlineData( 3.14159265f, 1.77245385F, CrossPlatformMachineEpsilon * 10)] // value: (pi)
[InlineData( float.PositiveInfinity, float.PositiveInfinity, 0.0f)]
public static void Sqrt(float value, float expectedResult, float allowedVariance)
{
AssertEqual(expectedResult, MathF.Sqrt(value), allowedVariance);
}
[Theory]
[InlineData( float.NegativeInfinity, float.NaN, 0.0f)]
[InlineData(-3.14159265f, -0.0f, CrossPlatformMachineEpsilon)] // value: -(pi)
[InlineData(-2.71828183f, 0.450549534f, CrossPlatformMachineEpsilon)] // value: -(e)
[InlineData(-2.30258509f, 1.11340715f, CrossPlatformMachineEpsilon * 10)] // value: -(ln(10))
[InlineData(-1.57079633f, 22877332.0f, 10.0f)] // value: -(pi / 2)
[InlineData(-1.44269504f, -7.76357567f, CrossPlatformMachineEpsilon * 10)] // value: -(log2(e))
[InlineData(-1.41421356f, -6.33411917f, CrossPlatformMachineEpsilon * 10)] // value: -(sqrt(2))
[InlineData(-1.12837917f, -2.11087684f, CrossPlatformMachineEpsilon * 10)] // value: -(2 / sqrt(pi))
[InlineData(-1.0f, -1.55740772f, CrossPlatformMachineEpsilon * 10)]
[InlineData(-0.785398163f, -1.0f, CrossPlatformMachineEpsilon * 10)] // value: -(pi / 4)
[InlineData(-0.707106781f, -0.854510432f, CrossPlatformMachineEpsilon)] // value: -(1 / sqrt(2))
[InlineData(-0.693147181f, -0.830640878f, CrossPlatformMachineEpsilon)] // value: -(ln(2))
[InlineData(-0.636619772f, -0.739302950f, CrossPlatformMachineEpsilon)] // value: -(2 / pi)
[InlineData(-0.434294482f, -0.463829067f, CrossPlatformMachineEpsilon)] // value: -(log10(e))
[InlineData(-0.318309886f, -0.329514733f, CrossPlatformMachineEpsilon)] // value: -(1 / pi)
[InlineData(-0.0f, -0.0f, 0.0f)]
[InlineData( float.NaN, float.NaN, 0.0f)]
[InlineData( 0.0f, 0.0f, 0.0f)]
[InlineData( 0.318309886f, 0.329514733f, CrossPlatformMachineEpsilon)] // value: (1 / pi)
[InlineData( 0.434294482f, 0.463829067f, CrossPlatformMachineEpsilon)] // value: (log10(e))
[InlineData( 0.636619772f, 0.739302950f, CrossPlatformMachineEpsilon)] // value: (2 / pi)
[InlineData( 0.693147181f, 0.830640878f, CrossPlatformMachineEpsilon)] // value: (ln(2))
[InlineData( 0.707106781f, 0.854510432f, CrossPlatformMachineEpsilon)] // value: (1 / sqrt(2))
[InlineData( 0.785398163f, 1.0f, CrossPlatformMachineEpsilon * 10)] // value: (pi / 4)
[InlineData( 1.0f, 1.55740772f, CrossPlatformMachineEpsilon * 10)]
[InlineData( 1.12837917f, 2.11087684f, CrossPlatformMachineEpsilon * 10)] // value: (2 / sqrt(pi))
[InlineData( 1.41421356f, 6.33411917f, CrossPlatformMachineEpsilon * 10)] // value: (sqrt(2))
[InlineData( 1.44269504f, 7.76357567f, CrossPlatformMachineEpsilon * 10)] // value: (log2(e))
[InlineData( 1.57079633f, -22877332.0f, 10.0f)] // value: (pi / 2)
[InlineData( 2.30258509f, -1.11340715f, CrossPlatformMachineEpsilon * 10)] // value: (ln(10))
[InlineData( 2.71828183f, -0.450549534f, CrossPlatformMachineEpsilon)] // value: (e)
[InlineData( 3.14159265f, 0.0f, CrossPlatformMachineEpsilon)] // value: (pi)
[InlineData( float.PositiveInfinity, float.NaN, 0.0f)]
public static void Tan(float value, float expectedResult, float allowedVariance)
{
AssertEqual(expectedResult, MathF.Tan(value), allowedVariance);
}
[Theory]
[InlineData( float.NegativeInfinity, -1.0f, CrossPlatformMachineEpsilon * 10)]
[InlineData(-3.14159265f, -0.996272076f, CrossPlatformMachineEpsilon)] // value: -(pi)
[InlineData(-2.71828183f, -0.991328916f, CrossPlatformMachineEpsilon)] // value: -(e)
[InlineData(-2.30258509f, -0.980198020f, CrossPlatformMachineEpsilon)] // value: -(ln(10))
[InlineData(-1.57079633f, -0.917152336f, CrossPlatformMachineEpsilon)] // value: -(pi / 2)
[InlineData(-1.44269504f, -0.894238946f, CrossPlatformMachineEpsilon)] // value: -(log2(e))
[InlineData(-1.41421356f, -0.888385562f, CrossPlatformMachineEpsilon)] // value: -(sqrt(2))
[InlineData(-1.12837917f, -0.810463806f, CrossPlatformMachineEpsilon)] // value: -(2 / sqrt(pi))
[InlineData(-1.0f, -0.761594156f, CrossPlatformMachineEpsilon)]
[InlineData(-0.785398163f, -0.655794203f, CrossPlatformMachineEpsilon)] // value: -(pi / 4)
[InlineData(-0.707106781f, -0.608859365f, CrossPlatformMachineEpsilon)] // value: -(1 / sqrt(2))
[InlineData(-0.693147181f, -0.6f, CrossPlatformMachineEpsilon)] // value: -(ln(2))
[InlineData(-0.636619772f, -0.562593600f, CrossPlatformMachineEpsilon)] // value: -(2 / pi)
[InlineData(-0.434294482f, -0.408904012f, CrossPlatformMachineEpsilon)] // value: -(log10(e))
[InlineData(-0.318309886f, -0.307977913f, CrossPlatformMachineEpsilon)] // value: -(1 / pi)
[InlineData(-0.0f, -0.0f, 0.0f)]
[InlineData( float.NaN, float.NaN, 0.0f)]
[InlineData( 0.0f, 0.0f, 0.0f)]
[InlineData( 0.318309886f, 0.307977913f, CrossPlatformMachineEpsilon)] // value: (1 / pi)
[InlineData( 0.434294482f, 0.408904012f, CrossPlatformMachineEpsilon)] // value: (log10(e))
[InlineData( 0.636619772f, 0.562593600f, CrossPlatformMachineEpsilon)] // value: (2 / pi)
[InlineData( 0.693147181f, 0.6f, CrossPlatformMachineEpsilon)] // value: (ln(2))
[InlineData( 0.707106781f, 0.608859365f, CrossPlatformMachineEpsilon)] // value: (1 / sqrt(2))
[InlineData( 0.785398163f, 0.655794203f, CrossPlatformMachineEpsilon)] // value: (pi / 4)
[InlineData( 1.0f, 0.761594156f, CrossPlatformMachineEpsilon)]
[InlineData( 1.12837917f, 0.810463806f, CrossPlatformMachineEpsilon)] // value: (2 / sqrt(pi))
[InlineData( 1.41421356f, 0.888385562f, CrossPlatformMachineEpsilon)] // value: (sqrt(2))
[InlineData( 1.44269504f, 0.894238946f, CrossPlatformMachineEpsilon)] // value: (log2(e))
[InlineData( 1.57079633f, 0.917152336f, CrossPlatformMachineEpsilon)] // value: (pi / 2)
[InlineData( 2.30258509f, 0.980198020f, CrossPlatformMachineEpsilon)] // value: (ln(10))
[InlineData( 2.71828183f, 0.991328916f, CrossPlatformMachineEpsilon)] // value: (e)
[InlineData( 3.14159265f, 0.996272076f, CrossPlatformMachineEpsilon)] // value: (pi)
[InlineData( float.PositiveInfinity, 1.0f, CrossPlatformMachineEpsilon * 10)]
public static void Tanh(float value, float expectedResult, float allowedVariance)
{
AssertEqual(expectedResult, MathF.Tanh(value), allowedVariance);
}
[Fact]
public static void Truncate()
{
Assert.Equal(0.0f, MathF.Truncate(0.12345f));
Assert.Equal(3.0f, MathF.Truncate(3.14159f));
Assert.Equal(-3.0f, MathF.Truncate(-3.14159f));
}
}
}
| mit |
grasshopper-cms/grasshopper-cms | plugins/admin/dist/public/vendor/ace/lib/ace/mode/sjs.js | 2693 | /* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2010, Ajax.org B.V.
* 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 Ajax.org B.V. 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 AJAX.ORG B.V. 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.
*
* ***** END LICENSE BLOCK ***** */
define(function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var JSMode = require("./javascript").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var SJSHighlightRules = require("./sjs_highlight_rules").SJSHighlightRules;
var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent;
var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour;
var CStyleFoldMode = require("./folding/cstyle").FoldMode;
var Mode = function() {
var highlighter = new SJSHighlightRules();
this.$tokenizer = new Tokenizer(highlighter.getRules());
this.$outdent = new MatchingBraceOutdent();
this.$behaviour = new CstyleBehaviour();
this.$keywordList = highlighter.$keywordList;
this.foldingRules = new CStyleFoldMode();
};
oop.inherits(Mode, JSMode);
(function() {
// disable jshint
this.createWorker = function(session) {
return null;
}
this.$id = "ace/mode/sjs";
}).call(Mode.prototype);
exports.Mode = Mode;
});
| mit |
markogresak/DefinitelyTyped | types/jqgrid/index.d.ts | 18960 | // Type definitions for jQuery jqgrid Plugin 1.3
// Project: https://github.com/tonytomov/jqGrid
// Definitions by: Lokesh Peta <https://github.com/lokeshpeta>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
///<reference types="jquery" />
// http://www.trirand.com/jqgridwiki/doku.php?id=wiki:colmodel_options
interface JQueryJqGridColumn {
/**
* Defines the alignment of the cell in the Body layer, not in header cell. Possible values: left, center, right
*/
align?: "left" | "center" | "right" | undefined;
/**
* This function add attributes to the cell during the creation of the data - i.e dynamically.
* By example all valid attributes for the table cell can be used or a style attribute with different properties.
* @param rowId the id of the row
* @param val the value which will be added in the cell
* @param rowObject the raw object of the data row - i.e if datatype is json - array, if datatype is xml xml node.
* @param cm all the properties of this column listed in the colModel
* @param rdata the data row which will be inserted in the row. This parameter is array of type name:value, where name is the name in colModel
* @returns {}
*/
cellattr?: ((rowId: any, val: any, rowObject: any, cm: any, rdata: any) => string) | undefined;
/**
* This option allow to add classes to the column. If more than one class will be used a space should be set.
* By example classes:'class1 class2' will set a class1 and class2 to every cell on that column.
* In the grid css there is a predefined class ui-ellipsis which allow to attach ellipsis to a particular row.
* Also this will work in FireFox too.
*/
classes?: string | undefined;
/**
* Governs format of sorttype:date (when datetype is set to local) and editrules {date:true} fields.
* Determines the expected date format for that column. Uses a PHP-like date formatting. Currently "/", "-", and "." are supported as date separators. Valid formats are:
* y,Y,yyyy for four digits year
* YY, yy for two digits year
* m,mm for months
* d,dd for days.
*/
datefmt?: string | undefined;
/**
* Defines if the field is editable. This option is used in cell, inline and form modules.
*/
editable?: boolean | undefined;
/**
* The predefined types (string) or custom function name that controls the format of this field
* @param cellvalue is the value to be formatted
* @param options is an object containing the following element: rowId - is the id of the row colModel is the object of the properties for this column getted from colModel array of jqGrid
* @param rowObject is a row data represented in the format determined from datatype option. If we have datatype: xml/xmlstring - the rowObject is xml node,provided according to the rules from xmlReader If we have datatype: json/jsonstring - the rowObject is array, provided according to the rules from jsonReader
* @returns {} the formatted value
*/
formatter?: "integer" | "number" | "currency" | "date" | "email" | "link" | "showlink" | "checkbox" | "select" | "actions" | ((cellvalue: any, options: { rowId: any, colModel: any }, rowObject: any) => any) | undefined;
/**
* Defines if this column is hidden at initialization.
*/
hidden?: boolean | undefined;
/**
* Set the index name when sorting. Passed as sidx parameter.
*/
index?: string | undefined;
/**
* Overwrite the id (defined in readers) from server. Can be set as id for the unique row id. Only one column can have this property.
* This option have higher priority as those from the readers.
* If there are more than one key set the grid finds the first one and the second is ignored.
*/
key?: boolean | undefined;
/**
* When colNames array is empty, defines the heading for this column.
* If both the colNames array and this setting are empty, the heading for this column comes from the name property.
*/
label?: string | undefined;
/**
* Set the unique name in the grid for the column.
* This property is required.
* As well as other words used as property/event names, the reserved words (which cannot be used for names) include subgrid, cb and rn.
*/
name: string;
/**
* When used in search modules, disables or enables searching on that column
*/
search?: boolean | undefined;
/**
* Defines is this can be sorted
*/
sortable?: boolean | undefined;
/**
* Set the initial width of the column, in pixels. This value currently can not be set as percentage
*/
width?: number | undefined;
}
interface IJqGridJsonReader {
/**
* tells jqGrid that the information for the data in the row is repeatable - i.e. the elements have the same tag cell described in cell element. Setting this option to false instructs jqGrid to search elements in the json data by name.
* This is the name from colModel or the name described with the jsonmap option in colModel
*/
repeatitems: boolean;
/**
* Name of the root property
* @param obj
* @returns {}
*/
root: string | ((obj: any) => any);
/**
* current page of the query
* @param obj
* @returns {}
*/
page: string | ((obj: any) => number);
/**
* total pages for the query
* @param obj
* @returns {}
*/
total: string | ((obj: any) => number);
/**
* total number of records for the query
* @param obj
* @returns {}
*/
records: string | ((obj: {data: any[]}) => number);
}
interface JQueryJqGridOptions {
/**
* When set to true encodes (html encode) the incoming (from server) and posted data (from editing modules).
*/
autoencode?: boolean | undefined;
/**
* When set to true, the grid width is recalculated automatically to the width of the parent element.
* This is done only initially when the grid is created.
* In order to resize the grid when the parent element changes width you should apply custom code and use the setGridWidth method for this purpose
*/
autoWidth?: boolean | undefined;
/**
* Defines the caption for the grid. This caption appears in the caption layer, which is above the header layer
*/
caption?: string | undefined;
/**
* Array which describes the parameters of the columns. This is the most important part of the grid.
*/
colModel?: JQueryJqGridColumn[] | undefined;
/**
* An array in which we place the names of the columns.
* This is the text that appears in the head of the grid (header layer). The names are separated with commas.
* Note that the number of elements in this array should be equal of the number elements in the colModel array.
*/
colNames?: string[] | undefined;
/**
* An array that stores the local data passed to the grid. You can directly point to this variable in case you want to load an array data.
* It can replace the addRowData method which is slow on relative big data
*/
data?: any[] | undefined;
/**
* Defines in what format to expect the data that fills the grid.
* Valid options are xml (we expect data in xml format), xmlstring (we expect xml data as string), json (we expect data in JSON format),
* jsonstring (we expect JSON data as a string), local (we expect data defined at client side (array data)),
* javascript (we expect javascript as data), function (custom defined function for retrieving data),
* or clientSide to manually load data via the data array
*/
datatype?: "xml" | "xmlstring" | "json" | "jsonstring" | "local" | "javascript" | Function | "clientSide" | undefined;
/**
* If set to true, and a column's width is changed, the adjacent column (to the right) will resize so that the overall grid width is maintained
* (e.g., reducing the width of column 2 by 30px will increase the size of column 3 by 30px). In this case there is no horizontal scrollbar.
* Note: This option is not compatible with shrinkToFit option - i.e if shrinkToFit is set to false, forceFit is ignored.
*/
forceFit?: boolean | undefined;
/**
* What will be the result if we insert all the data at once?
* Yes, this can be done with a help of gridview option (set it to true).
* The result is a grid that is 5 to 10 times faster. Of course, when this option is set to true we have some limitations.
* If set to true we can not use treeGrid, subGrid, or the afterInsertRow event.
* If you do not use these three options in the grid you can set this option to true and enjoy the speed.
*/
gridview?: boolean | undefined;
/**
* The height of the grid.
* Can be set as number (in this case we mean pixels) or as percentage (only 100% is accepted) or value of auto is acceptable.
*/
height?: number | string | "auto" | undefined;
/**
* If this flag is set to true, the grid loads the data from the server only once (using the appropriate datatype).
* After the first request, the datatype parameter is automatically changed to local and all further manipulations are done on the client side.
* The functions of the pager (if present) are disabled.
*/
loadonce?: boolean | undefined;
/**
* An array which describes the structure of the expected json data.
*/
jsonReader?: IJqGridJsonReader | undefined;
/**
* Defines the type of request to make ("POST" or "GET")
*/
mtype?: "GET" | "POST" | undefined;
/**
* This option works only when the multiselect option is set to true.
* When multiselect is set to true, clicking anywhere on a row selects that row;
* when multiboxonly is also set to true, the multiselection is done only when the checkbox is clicked (Yahoo style).
* Clicking in any other row (suppose the checkbox is not clicked) deselects all rows and selects the current row.
*/
multiboxonly?: boolean | undefined;
/**
* If this flag is set to true a multi selection of rows is enabled. A new column at left side containing checkboxes is added.
* Can be used with any datatype option
*/
multiselect?: boolean | undefined;
/**
* Defines that we want to use a pager bar to navigate through the records.
* This must be a valid HTML element; in our example we gave the div the id of "pager", but any name is acceptable.
* Note that the navigation layer (the "pager" div) can be positioned anywhere you want, determined by your HTML;
* in our example we specified that the pager will appear after the body layer.
* The valid settings can be (in the context of our example) pager, #pager, jQuery('#pager').
* I recommend to use the second one - #pager
*/
pager?: string | undefined;
/**
* An array to construct a select box element in the pager in which we can change the number of the visible rows.
* When changed during the execution, this parameter replaces the rowNum parameter that is passed to the url.
* If the array is empty, this element does not appear in the pager. Typically you can set this like [10,20,30].
* If the rowNum parameter is set to 30 then the selected value in the select box is 30
*/
rowList?: number[] | undefined;
/**
* Sets how many records we want to view in the grid. This parameter is passed to the url for use by the server routine retrieving the data.
* Note that if you set this parameter to 10 (i.e. retrieve 10 records) and your server return 15 then only 10 records will be loaded
*/
rowNum?: number | undefined;
/**
* This option, if set, defines how the the width of the columns of the grid should be re-calculated, taking into consideration the width of the grid.
* If this value is true, and the width of the columns is also set, then every column is scaled in proportion to its width.
* For example, if we define two columns with widths 80 and 120 pixels, but want the grid to have a width of 300 pixels,
* then the columns will stretch to fit the entire grid, and the extra width assigned to them will depend on the width of the columns themselves and the extra width available.
* The re-calculation is done as follows: the first column gets the width (300(new width)/200(sum of all widths))*80(first column width) = 120 pixels,
* and the second column gets the width (300(new width)/200(sum of all widths))*120(second column width) = 180 pixels.
* Now the widths of the columns sum up to 300 pixels, which is the width of the grid.
* If the value is false and the value in width option is set, then no re-sizing happens whatsoever.
* So in this example, if shrinkToFit is set to false, column one will have a width of 80 pixels,
* column two will have a width of 120 pixels and the grid will retain the width of 300 pixels.
* If the value of shrinkToFit is an integer, the width is calculated according to it.
*/
shrinkToFit?: boolean | number | undefined;
/**
* The column according to which the data is to be sorted when it is initially loaded from the server
* (note that you will have to use datatypes xml or json to load remote data). This parameter is appended to the url.
* If this value is set and the index (name) matches the name from colModel,
* then an icon indicating that the grid is sorted according to this column is added to the column header.
* This icon also indicates the sorting order - descending or ascending (see the parameter sortorder). Also see prmNames
*/
sortname?: string | undefined;
/**
* The initial sorting order (ascending or descending) when we fetch data from the server using datatypes xml or json.
* This parameter is appended to the url - see prnNames. The two allowed values are - asc or desc.
*/
sortorder?: "asc" | "desc" | undefined;
/**
* The url of the file that returns the data needed to populate the grid. May be set to clientArray to manualy post data to server
*/
url?: string | "clientArray" | undefined;
/**
* If true, jqGrid displays the beginning and ending record number in the grid, out of the total number of records in the query.
* This information is shown in the pager bar (bottom right by default)in this format: "View X to Y out of Z".
* If this value is true, there are other parameters that can be adjusted, including emptyrecords and recordtext.
*/
viewrecords?: boolean | undefined;
/**
* If this option is not set, the width of the grid is the sum of the widths of the columns defined in the colModel (in pixels).
* If this option is set, the initial width of each column is set according to the value of the shrinkToFit option.
*/
width?: number | undefined;
// events
/**
* This fires after all the data is loaded into the grid and all other processes are complete.
* Also the event fires independent from the datatype parameter and after sorting paging and etc.
* @returns {}
*/
gridComplete?: (() => void) | undefined;
/**
* Raised immediately after row was right clicked
* @param rowid is the id of the row
* @param iRow is the index of the row (do not mix this with the rowid)
* @param iCol is the index of the cell
* @param e is the event object
* @returns {}
*/
onRightClickRow?: ((rowid: any, iRow: number, iCol: number, e: Event) => void) | undefined;
/**
* Raised immediately after row was clicked.
* @param id is the id of the row
* @param status is the status of the selection
* @param e is the event object. Can be used when multiselect is set to true. true if the row is selected, false if the row is deselected.
* @returns {}
*/
onSelectRow?: ((id: string, status: any, e: Event) => void) | undefined;
}
interface JQueryJqGridStatic {
(): JQuery;
(gridName: string): any;
(gridName: string, propName: string): any;
(gridName: string, obj: any): any;
(gridName: string, id: any, colname: any): any;
(options: JQueryJqGridOptions): JQuery;
}
interface JQueryStatic {
jqGrid?: JQueryJqGridStatic | undefined;
}
interface JQuery {
jqGrid?: JQueryJqGridStatic | undefined;
/**
* Populates a grid with the passed data (an array)
* @param data
* @returns {}
*/
addJSONData(data: any[]): void;
/**
* Edits the row specified by rowid.
* keys is a boolean value, indicating if to use the Enter key to accept the value ane Esc to cancel the edit, or not.
* @param rowid the id of the row to edit
* @param keys when set to true we can use [Enter] key to save the row and [Esc] to cancel editing
* @returns {}
*/
editRow(rowid: any, keys?: boolean): void;
/**
* Returns the value of the requested parameter. name is the name from the options array. If the name is not set, the entry options are returned.
* @param name
* @returns {}
*/
getGridParam(name: string): any;
/**
* This method restores the data to original values before the editing of the row
* @param rowId the row to restore
* @param afterRestoreFunc if defined this function is called in after the row is restored.
* @returns {}
*/
restoreRow(rowId: any, afterRestoreFunc?: (response: any) => void): void;
/**
* Saves the edited row.
* @param rowid the id of the row to save
* @param successfunc
* @param url if defined, this parameter replaces the editurl parameter from the options array. If set to 'clientArray', the data is not posted to the server but rather is saved only to the grid (presumably for later manual saving).
* @param extraparam an array of type name: value. When set these values are posted along with the other values to the server.
* @returns {}
*/
saveRow(rowid: string, successfunc?: (response: any) => boolean, url?: string, extraparam?: any): void;
/**
* Saves the edited row.
* @param rowid the id of the row to save
* @param successfunc
* @param url
* @param extraparam
* @returns {}
*/
saveRow(rowid: string, successfunc?: boolean, url?: string, extraparam?: any): void;
/**
* Sets a particular parameter.
* Note - for some parameters to take effect a trigger("reloadGrid") should be executed.
* Note that with this method we can override events.
* The name (in the name:value pair) is the name from options array
* @param obj
* @returns {}
*/
setGridParam(obj: any): void;
}
| mit |
dsebastien/DefinitelyTyped | types/ncp/index.d.ts | 2012 | // Type definitions for ncp 2.0
// Project: https://github.com/AvianFlu/ncp
// Definitions by: Bart van der Schoor <https://github.com/bartvds>
// Benoit Lemaire <https://github.com/belemaire>
// ExE Boss <https://github.com/ExE-Boss>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
import * as fs from 'fs';
declare namespace ncp {
interface File {
name: string;
mode: number;
/** Accessed time */
atime: Date;
/** Modified time */
mtime: Date;
}
interface Options {
filter?: RegExp | ((filename: string) => boolean);
transform?: (read: NodeJS.ReadableStream, write: NodeJS.WritableStream, file: File) => void;
clobber?: boolean;
dereference?: boolean;
stopOnErr?: boolean;
errs?: fs.PathLike;
limit?: number;
}
}
declare const ncp: {
(source: string, destination: string, callback: (err: Error[] | null) => void): void;
(
source: string,
destination: string,
options: ncp.Options & { stopOnErr: true },
callback: (err: Error | null) => void,
): void;
(
source: string,
destination: string,
options: ncp.Options & { errs?: undefined },
callback: (err: Error[] | null) => void,
): void;
(
source: string,
destination: string,
options: ncp.Options & { errs: fs.PathLike },
callback: (err: fs.WriteStream | null) => void,
): void;
(
source: string,
destination: string,
options: ncp.Options,
callback: (err: Error | Error[] | fs.WriteStream | null) => void,
): void;
ncp: typeof ncp;
/**
* **NOTE:** This function provides design-time support for util.promisify.
*
* It does not exist at runtime.
*/
__promisify__(source: string, destination: string, options?: ncp.Options): Promise<void>;
};
export = ncp;
| mit |
abbasmhd/DefinitelyTyped | types/deepmerge/index.d.ts | 755 | // Type definitions for deepmerge 1.3
// Project: https://github.com/KyleAMathews/deepmerge
// Definitions by: marvinscharle <https://github.com/marvinscharle>
// syy1125 <https://github.com/syy1125>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
export = deepmerge;
declare function deepmerge<T>(x: Partial<T>, y: Partial<T>, options?: deepmerge.Options): T;
declare function deepmerge<T1, T2>(x: T1, y: T2, options?: deepmerge.Options): T1 & T2;
declare namespace deepmerge {
interface Options {
clone?: boolean;
arrayMerge?(destination: any[], source: any[], options?: Options): any[];
}
function all<T>(objects: Array<Partial<T>>, options?: Options): T;
}
| mit |
afuechsel/openhab2 | addons/io/org.openhab.io.transport.modbus/src/main/java/org/openhab/io/transport/modbus/BasicWriteTask.java | 1975 | /**
* Copyright (c) 2010-2019 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.io.transport.modbus;
import org.apache.commons.lang.builder.StandardToStringStyle;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.io.transport.modbus.endpoint.ModbusSlaveEndpoint;
/**
* Simple implementation for Modbus write requests
*
* @author Sami Salonen - Initial contribution
*
*/
@NonNullByDefault
public class BasicWriteTask implements WriteTask {
private static final StandardToStringStyle TO_STRING_STYLE = new StandardToStringStyle();
static {
TO_STRING_STYLE.setUseShortClassName(true);
}
private ModbusSlaveEndpoint endpoint;
private ModbusWriteRequestBlueprint request;
private ModbusWriteCallback callback;
public BasicWriteTask(ModbusSlaveEndpoint endpoint, ModbusWriteRequestBlueprint request,
ModbusWriteCallback callback) {
super();
this.endpoint = endpoint;
this.request = request;
this.callback = callback;
}
@Override
public ModbusSlaveEndpoint getEndpoint() {
return endpoint;
}
@Override
public ModbusWriteRequestBlueprint getRequest() {
return request;
}
@Override
public @Nullable ModbusWriteCallback getCallback() {
return callback;
}
@Override
public String toString() {
return new ToStringBuilder(this, TO_STRING_STYLE).append("request", request).append("endpoint", endpoint)
.append("callback", getCallback()).toString();
}
}
| epl-1.0 |
runuo/runuo | Scripts/Engines/BulkOrders/SmallSmithBOD.cs | 6596 | using System;
using System.Collections.Generic;
using Server;
using Server.Engines.Craft;
using Server.Items;
using Mat = Server.Engines.BulkOrders.BulkMaterialType;
namespace Server.Engines.BulkOrders
{
[TypeAlias( "Scripts.Engines.BulkOrders.SmallSmithBOD" )]
public class SmallSmithBOD : SmallBOD
{
public static double[] m_BlacksmithMaterialChances = new double[]
{
0.501953125, // None
0.250000000, // Dull Copper
0.125000000, // Shadow Iron
0.062500000, // Copper
0.031250000, // Bronze
0.015625000, // Gold
0.007812500, // Agapite
0.003906250, // Verite
0.001953125 // Valorite
};
public override int ComputeFame()
{
return SmithRewardCalculator.Instance.ComputeFame( this );
}
public override int ComputeGold()
{
return SmithRewardCalculator.Instance.ComputeGold( this );
}
public override List<Item> ComputeRewards( bool full )
{
List<Item> list = new List<Item>();
RewardGroup rewardGroup = SmithRewardCalculator.Instance.LookupRewards( SmithRewardCalculator.Instance.ComputePoints( this ) );
if ( rewardGroup != null )
{
if ( full )
{
for ( int i = 0; i < rewardGroup.Items.Length; ++i )
{
Item item = rewardGroup.Items[i].Construct();
if ( item != null )
list.Add( item );
}
}
else
{
RewardItem rewardItem = rewardGroup.AcquireItem();
if ( rewardItem != null )
{
Item item = rewardItem.Construct();
if ( item != null )
list.Add( item );
}
}
}
return list;
}
public static SmallSmithBOD CreateRandomFor( Mobile m )
{
SmallBulkEntry[] entries;
bool useMaterials;
if ( useMaterials = Utility.RandomBool() )
entries = SmallBulkEntry.BlacksmithArmor;
else
entries = SmallBulkEntry.BlacksmithWeapons;
if ( entries.Length > 0 )
{
double theirSkill = m.Skills[SkillName.Blacksmith].Base;
int amountMax;
if ( theirSkill >= 70.1 )
amountMax = Utility.RandomList( 10, 15, 20, 20 );
else if ( theirSkill >= 50.1 )
amountMax = Utility.RandomList( 10, 15, 15, 20 );
else
amountMax = Utility.RandomList( 10, 10, 15, 20 );
BulkMaterialType material = BulkMaterialType.None;
if ( useMaterials && theirSkill >= 70.1 )
{
for ( int i = 0; i < 20; ++i )
{
BulkMaterialType check = GetRandomMaterial( BulkMaterialType.DullCopper, m_BlacksmithMaterialChances );
double skillReq = 0.0;
switch ( check )
{
case BulkMaterialType.DullCopper: skillReq = 65.0; break;
case BulkMaterialType.ShadowIron: skillReq = 70.0; break;
case BulkMaterialType.Copper: skillReq = 75.0; break;
case BulkMaterialType.Bronze: skillReq = 80.0; break;
case BulkMaterialType.Gold: skillReq = 85.0; break;
case BulkMaterialType.Agapite: skillReq = 90.0; break;
case BulkMaterialType.Verite: skillReq = 95.0; break;
case BulkMaterialType.Valorite: skillReq = 100.0; break;
case BulkMaterialType.Spined: skillReq = 65.0; break;
case BulkMaterialType.Horned: skillReq = 80.0; break;
case BulkMaterialType.Barbed: skillReq = 99.0; break;
}
if ( theirSkill >= skillReq )
{
material = check;
break;
}
}
}
double excChance = 0.0;
if ( theirSkill >= 70.1 )
excChance = (theirSkill + 80.0) / 200.0;
bool reqExceptional = ( excChance > Utility.RandomDouble() );
CraftSystem system = DefBlacksmithy.CraftSystem;
List<SmallBulkEntry> validEntries = new List<SmallBulkEntry>();
for ( int i = 0; i < entries.Length; ++i )
{
CraftItem item = system.CraftItems.SearchFor( entries[i].Type );
if ( item != null )
{
bool allRequiredSkills = true;
double chance = item.GetSuccessChance( m, null, system, false, ref allRequiredSkills );
if ( allRequiredSkills && chance >= 0.0 )
{
if ( reqExceptional )
chance = item.GetExceptionalChance( system, chance, m );
if ( chance > 0.0 )
validEntries.Add( entries[i] );
}
}
}
if ( validEntries.Count > 0 )
{
SmallBulkEntry entry = validEntries[Utility.Random( validEntries.Count )];
return new SmallSmithBOD( entry, material, amountMax, reqExceptional );
}
}
return null;
}
private SmallSmithBOD( SmallBulkEntry entry, BulkMaterialType material, int amountMax, bool reqExceptional )
{
this.Hue = 0x44E;
this.AmountMax = amountMax;
this.Type = entry.Type;
this.Number = entry.Number;
this.Graphic = entry.Graphic;
this.RequireExceptional = reqExceptional;
this.Material = material;
}
[Constructable]
public SmallSmithBOD()
{
SmallBulkEntry[] entries;
bool useMaterials;
if ( useMaterials = Utility.RandomBool() )
entries = SmallBulkEntry.BlacksmithArmor;
else
entries = SmallBulkEntry.BlacksmithWeapons;
if ( entries.Length > 0 )
{
int hue = 0x44E;
int amountMax = Utility.RandomList( 10, 15, 20 );
BulkMaterialType material;
if ( useMaterials )
material = GetRandomMaterial( BulkMaterialType.DullCopper, m_BlacksmithMaterialChances );
else
material = BulkMaterialType.None;
bool reqExceptional = Utility.RandomBool() || (material == BulkMaterialType.None);
SmallBulkEntry entry = entries[Utility.Random( entries.Length )];
this.Hue = hue;
this.AmountMax = amountMax;
this.Type = entry.Type;
this.Number = entry.Number;
this.Graphic = entry.Graphic;
this.RequireExceptional = reqExceptional;
this.Material = material;
}
}
public SmallSmithBOD( int amountCur, int amountMax, Type type, int number, int graphic, bool reqExceptional, BulkMaterialType mat )
{
this.Hue = 0x44E;
this.AmountMax = amountMax;
this.AmountCur = amountCur;
this.Type = type;
this.Number = number;
this.Graphic = graphic;
this.RequireExceptional = reqExceptional;
this.Material = mat;
}
public SmallSmithBOD( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
} | gpl-2.0 |
nhicher/ansible | lib/ansible/modules/cloud/azure/azure_rm_aks.py | 22127 | #!/usr/bin/python
#
# Copyright (c) 2018 Sertac Ozercan, <[email protected]>
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: azure_rm_aks
version_added: "2.6"
short_description: Manage a managed Azure Container Service (AKS) Instance.
description:
- Create, update and delete a managed Azure Container Service (AKS) Instance.
options:
resource_group:
description:
- Name of a resource group where the managed Azure Container Services (AKS) exists or will be created.
required: true
name:
description:
- Name of the managed Azure Container Services (AKS) instance.
required: true
state:
description:
- Assert the state of the AKS. Use C(present) to create or update an AKS and C(absent) to delete it.
default: present
choices:
- absent
- present
location:
description:
- Valid azure location. Defaults to location of the resource group.
dns_prefix:
description:
- DNS prefix specified when creating the managed cluster.
kubernetes_version:
description:
- Version of Kubernetes specified when creating the managed cluster.
linux_profile:
description:
- The linux profile suboptions.
suboptions:
admin_username:
description:
- The Admin Username for the Cluster.
required: true
ssh_key:
description:
- The Public SSH Key used to access the cluster.
required: true
agent_pool_profiles:
description:
- The agent pool profile suboptions.
suboptions:
name:
description:
- Unique name of the agent pool profile in the context of the subscription and resource group.
required: true
count:
description:
- Number of agents (VMs) to host docker containers.
- Allowed values must be in the range of 1 to 100 (inclusive).
required: true
vm_size:
description:
- The VM Size of each of the Agent Pool VM's (e.g. Standard_F1 / Standard_D2v2).
required: true
os_disk_size_gb:
description:
- Size of the OS disk.
service_principal:
description:
- The service principal suboptions.
suboptions:
client_id:
description:
- The ID for the Service Principal.
required: true
client_secret:
description:
- The secret password associated with the service principal.
required: true
extends_documentation_fragment:
- azure
- azure_tags
author:
- "Sertac Ozercan (@sozercan)"
- "Yuwei Zhou (@yuwzho)"
'''
EXAMPLES = '''
- name: Create a managed Azure Container Services (AKS) instance
azure_rm_aks:
name: acctestaks1
location: eastus
resource_group: Testing
dns_prefix: akstest
linux_profile:
admin_username: azureuser
ssh_key: ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAA...
service_principal:
client_id: "cf72ca99-f6b9-4004-b0e0-bee10c521948"
client_secret: "mySPNp@ssw0rd!"
agent_pool_profiles:
- name: default
count: 5
vm_size: Standard_D2_v2
tags:
Environment: Production
- name: Remove a managed Azure Container Services (AKS) instance
azure_rm_aks:
name: acctestaks3
resource_group: Testing
state: absent
'''
RETURN = '''
state:
description: Current state of the Azure Container Service (AKS)
returned: always
type: dict
example:
agent_pool_profiles:
- count: 1
dns_prefix: Null
name: default
os_disk_size_gb: Null
os_type: Linux
ports: Null
storage_profile: ManagedDisks
vm_size: Standard_DS1_v2
vnet_subnet_id: Null
changed: false
dns_prefix: aks9860bdcd89
id: "/subscriptions/XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX/resourcegroups/yuwzhoaks/providers/Microsoft.ContainerService/managedClusters/aks9860bdc"
kube_config: "......"
kubernetes_version: 1.7.7
linux_profile:
admin_username: azureuser
ssh_key: ssh-rsa AAAAB3NzaC1yc2EAAAADA.....
location: eastus
name: aks9860bdc
provisioning_state: Succeeded
service_principal_profile:
client_id: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
tags: {}
type: Microsoft.ContainerService/ManagedClusters
'''
from ansible.module_utils.azure_rm_common import AzureRMModuleBase
import base64
try:
from msrestazure.azure_exceptions import CloudError
from azure.mgmt.containerservice.models import (
ManagedCluster, ContainerServiceServicePrincipalProfile,
ContainerServiceAgentPoolProfile, ContainerServiceLinuxProfile,
ContainerServiceSshConfiguration, ContainerServiceSshPublicKey
)
except ImportError:
# This is handled in azure_rm_common
pass
def create_agent_pool_profile_instance(agentpoolprofile):
'''
Helper method to serialize a dict to a ContainerServiceAgentPoolProfile
:param: agentpoolprofile: dict with the parameters to setup the ContainerServiceAgentPoolProfile
:return: ContainerServiceAgentPoolProfile
'''
return ContainerServiceAgentPoolProfile(
name=agentpoolprofile['name'],
count=agentpoolprofile['count'],
vm_size=agentpoolprofile['vm_size'],
os_disk_size_gb=agentpoolprofile['os_disk_size_gb'],
dns_prefix=agentpoolprofile.get('dns_prefix'),
ports=agentpoolprofile.get('ports'),
storage_profile=agentpoolprofile.get('storage_profile'),
vnet_subnet_id=agentpoolprofile.get('vnet_subnet_id'),
os_type=agentpoolprofile.get('os_type')
)
def create_service_principal_profile_instance(spnprofile):
'''
Helper method to serialize a dict to a ContainerServiceServicePrincipalProfile
:param: spnprofile: dict with the parameters to setup the ContainerServiceServicePrincipalProfile
:return: ContainerServiceServicePrincipalProfile
'''
return ContainerServiceServicePrincipalProfile(
client_id=spnprofile['client_id'],
secret=spnprofile['client_secret']
)
def create_linux_profile_instance(linuxprofile):
'''
Helper method to serialize a dict to a ContainerServiceLinuxProfile
:param: linuxprofile: dict with the parameters to setup the ContainerServiceLinuxProfile
:return: ContainerServiceLinuxProfile
'''
return ContainerServiceLinuxProfile(
admin_username=linuxprofile['admin_username'],
ssh=create_ssh_configuration_instance(linuxprofile['ssh_key'])
)
def create_ssh_configuration_instance(sshconf):
'''
Helper method to serialize a dict to a ContainerServiceSshConfiguration
:param: sshconf: dict with the parameters to setup the ContainerServiceSshConfiguration
:return: ContainerServiceSshConfiguration
'''
return ContainerServiceSshConfiguration(
public_keys=[ContainerServiceSshPublicKey(key_data=str(sshconf))]
)
def create_aks_dict(aks):
'''
Helper method to deserialize a ContainerService to a dict
:param: aks: ContainerService or AzureOperationPoller with the Azure callback object
:return: dict with the state on Azure
'''
return dict(
id=aks.id,
name=aks.name,
location=aks.location,
dns_prefix=aks.dns_prefix,
kubernetes_version=aks.kubernetes_version,
tags=aks.tags,
linux_profile=create_linux_profile_dict(aks.linux_profile),
service_principal_profile=create_service_principal_profile_dict(
aks.service_principal_profile),
provisioning_state=aks.provisioning_state,
agent_pool_profiles=create_agent_pool_profiles_dict(
aks.agent_pool_profiles),
type=aks.type,
kube_config=aks.kube_config
)
def create_linux_profile_dict(linuxprofile):
'''
Helper method to deserialize a ContainerServiceLinuxProfile to a dict
:param: linuxprofile: ContainerServiceLinuxProfile with the Azure callback object
:return: dict with the state on Azure
'''
return dict(
ssh_key=linuxprofile.ssh.public_keys[0].key_data,
admin_username=linuxprofile.admin_username
)
def create_service_principal_profile_dict(serviceprincipalprofile):
'''
Helper method to deserialize a ContainerServiceServicePrincipalProfile to a dict
Note: For security reason, the service principal secret is skipped on purpose.
:param: serviceprincipalprofile: ContainerServiceServicePrincipalProfile with the Azure callback object
:return: dict with the state on Azure
'''
return dict(
client_id=serviceprincipalprofile.client_id
)
def create_agent_pool_profiles_dict(agentpoolprofiles):
'''
Helper method to deserialize a ContainerServiceAgentPoolProfile to a dict
:param: agentpoolprofiles: ContainerServiceAgentPoolProfile with the Azure callback object
:return: dict with the state on Azure
'''
return [dict(
count=profile.count,
vm_size=profile.vm_size,
name=profile.name,
os_disk_size_gb=profile.os_disk_size_gb,
dns_prefix=profile.dns_prefix,
ports=profile.ports,
storage_profile=profile.storage_profile,
vnet_subnet_id=profile.vnet_subnet_id,
os_type=profile.os_type
) for profile in agentpoolprofiles] if agentpoolprofiles else None
linux_profile_spec = dict(
admin_username=dict(type='str', required=True),
ssh_key=dict(type='str', required=True)
)
service_principal_spec = dict(
client_id=dict(type='str', required=True),
client_secret=dict(type='str')
)
agent_pool_profile_spec = dict(
name=dict(type='str', required=True),
count=dict(type='int', required=True),
vm_size=dict(type='str', required=True),
os_disk_size_gb=dict(type='int'),
dns_prefix=dict(type='str'),
ports=dict(type='list', elements='int'),
storage_profiles=dict(type='str', choices=[
'StorageAccount', 'ManagedDisks']),
vnet_subnet_id=dict(type='str'),
os_type=dict(type='str', choices=['Linux', 'Windows'])
)
class AzureRMManagedCluster(AzureRMModuleBase):
"""Configuration class for an Azure RM container service (AKS) resource"""
def __init__(self):
self.module_arg_spec = dict(
resource_group=dict(
type='str',
required=True
),
name=dict(
type='str',
required=True
),
state=dict(
type='str',
default='present',
choices=['present', 'absent']
),
location=dict(
type='str'
),
dns_prefix=dict(
type='str'
),
kubernetes_version=dict(
type='str'
),
linux_profile=dict(
type='dict',
options=linux_profile_spec
),
agent_pool_profiles=dict(
type='list',
elements='dict',
options=agent_pool_profile_spec
),
service_principal=dict(
type='dict',
options=service_principal_spec
),
)
self.resource_group = None
self.name = None
self.location = None
self.dns_prefix = None
self.kubernetes_version = None
self.tags = None
self.state = None
self.linux_profile = None
self.agent_pool_profiles = None
self.service_principal = None
required_if = [
('state', 'present', [
'dns_prefix', 'linux_profile', 'agent_pool_profiles', 'service_principal'])
]
self.results = dict(changed=False)
super(AzureRMManagedCluster, self).__init__(derived_arg_spec=self.module_arg_spec,
supports_check_mode=True,
supports_tags=True,
required_if=required_if)
def exec_module(self, **kwargs):
"""Main module execution method"""
for key in list(self.module_arg_spec.keys()) + ['tags']:
setattr(self, key, kwargs[key])
resource_group = None
to_be_updated = False
resource_group = self.get_resource_group(self.resource_group)
if not self.location:
self.location = resource_group.location
response = self.get_aks()
# Check if the AKS instance already present in the RG
if self.state == 'present':
# For now Agent Pool cannot be more than 1, just remove this part in the future if it change
agentpoolcount = len(self.agent_pool_profiles)
if agentpoolcount > 1:
self.fail(
'You cannot specify more than one agent_pool_profiles currently')
if response:
self.results = response
if not response:
to_be_updated = True
else:
self.log('Results : {0}'.format(response))
update_tags, response['tags'] = self.update_tags(
response['tags'])
if response['provisioning_state'] == "Succeeded":
if update_tags:
to_be_updated = True
def is_property_changed(profile, property, ignore_case=False):
base = response[profile].get(property)
new = getattr(self, profile).get(property)
if ignore_case:
return base.lower() != new.lower()
else:
return base != new
# Cannot Update the SSH Key for now // Let service to handle it
if is_property_changed('linux_profile', 'ssh_key'):
self.log(("Linux Profile Diff SSH, Was {0} / Now {1}"
.format(response['linux_profile']['ssh_key'], self.linux_profile.get('ssh_key'))))
to_be_updated = True
# self.module.warn("linux_profile.ssh_key cannot be updated")
# self.log("linux_profile response : {0}".format(response['linux_profile'].get('admin_username')))
# self.log("linux_profile self : {0}".format(self.linux_profile[0].get('admin_username')))
# Cannot Update the Username for now // Let service to handle it
if is_property_changed('linux_profile', 'admin_username'):
self.log(("Linux Profile Diff User, Was {0} / Now {1}"
.format(response['linux_profile']['admin_username'], self.linux_profile.get('admin_username'))))
to_be_updated = True
# self.module.warn("linux_profile.admin_username cannot be updated")
# Cannot have more that one agent pool profile for now
if len(response['agent_pool_profiles']) != len(self.agent_pool_profiles):
self.log("Agent Pool count is diff, need to updated")
to_be_updated = True
if response['kubernetes_version'] != self.kubernetes_version:
to_be_updated = True
for profile_result in response['agent_pool_profiles']:
matched = False
for profile_self in self.agent_pool_profiles:
if profile_result['name'] == profile_self['name']:
matched = True
if profile_result['count'] != profile_self['count'] \
or profile_result['vm_size'] != profile_self['vm_size'] \
or profile_result['os_disk_size_gb'] != profile_self['os_disk_size_gb'] \
or profile_result['dns_prefix'] != profile_self['dns_prefix'] \
or profile_result['vnet_subnet_id'] != profile_self.get('vnet_subnet_id') \
or set(profile_result['ports'] or []) != set(profile_self.get('ports') or []):
self.log(
("Agent Profile Diff - Origin {0} / Update {1}".format(str(profile_result), str(profile_self))))
to_be_updated = True
if not matched:
self.log("Agent Pool not found")
to_be_updated = True
if to_be_updated:
self.log("Need to Create / Update the AKS instance")
if not self.check_mode:
self.results = self.create_update_aks()
self.log("Creation / Update done")
self.results['changed'] = True
return self.results
elif self.state == 'absent' and response:
self.log("Need to Delete the AKS instance")
self.results['changed'] = True
if self.check_mode:
return self.results
self.delete_aks()
self.log("AKS instance deleted")
return self.results
def create_update_aks(self):
'''
Creates or updates a managed Azure container service (AKS) with the specified configuration of agents.
:return: deserialized AKS instance state dictionary
'''
self.log("Creating / Updating the AKS instance {0}".format(self.name))
agentpools = []
if self.agent_pool_profiles:
agentpools = [create_agent_pool_profile_instance(
profile) for profile in self.agent_pool_profiles]
service_principal_profile = create_service_principal_profile_instance(
self.service_principal)
parameters = ManagedCluster(
location=self.location,
dns_prefix=self.dns_prefix,
kubernetes_version=self.kubernetes_version,
tags=self.tags,
service_principal_profile=service_principal_profile,
agent_pool_profiles=agentpools,
linux_profile=create_linux_profile_instance(self.linux_profile)
)
# self.log("service_principal_profile : {0}".format(parameters.service_principal_profile))
# self.log("linux_profile : {0}".format(parameters.linux_profile))
# self.log("ssh from yaml : {0}".format(results.get('linux_profile')[0]))
# self.log("ssh : {0}".format(parameters.linux_profile.ssh))
# self.log("agent_pool_profiles : {0}".format(parameters.agent_pool_profiles))
try:
poller = self.containerservice_client.managed_clusters.create_or_update(self.resource_group, self.name, parameters)
response = self.get_poller_result(poller)
response.kube_config = self.get_aks_kubeconfig()
return create_aks_dict(response)
except CloudError as exc:
self.log('Error attempting to create the AKS instance.')
self.fail("Error creating the AKS instance: {0}".format(exc.message))
def delete_aks(self):
'''
Deletes the specified managed container service (AKS) in the specified subscription and resource group.
:return: True
'''
self.log("Deleting the AKS instance {0}".format(self.name))
try:
poller = self.containerservice_client.managed_clusters.delete(
self.resource_group, self.name)
self.get_poller_result(poller)
return True
except CloudError as e:
self.log('Error attempting to delete the AKS instance.')
self.fail("Error deleting the AKS instance: {0}".format(e.message))
return False
def get_aks(self):
'''
Gets the properties of the specified container service.
:return: deserialized AKS instance state dictionary
'''
self.log(
"Checking if the AKS instance {0} is present".format(self.name))
try:
response = self.containerservice_client.managed_clusters.get(
self.resource_group, self.name)
self.log("Response : {0}".format(response))
self.log("AKS instance : {0} found".format(response.name))
response.kube_config = self.get_aks_kubeconfig()
return create_aks_dict(response)
except CloudError:
self.log('Did not find the AKS instance.')
return False
def get_aks_kubeconfig(self):
'''
Gets kubeconfig for the specified AKS instance.
:return: AKS instance kubeconfig
'''
access_profile = self.containerservice_client.managed_clusters.get_access_profiles(
self.resource_group, self.name, "clusterUser")
return base64.b64decode(access_profile.kube_config)
def main():
"""Main execution"""
AzureRMManagedCluster()
if __name__ == '__main__':
main()
| gpl-3.0 |
artsmorgan/crmtecnosagot | app/protected/extensions/geocoder/libraries/Driver.php | 5257 | <?php
/**
* Copyright (c) 2009 Brian Armstrong
*
* 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.
*/
/**
* The base class for all the GeoCode Drivers. It defines the
* base functionality for the classes, as well as handles
* the factory methods
*
* @package GeoCoder
* @author Brian Armstrong <[email protected]>
* @copyright (C) 2009 Brian Armstrong
* @link http://barmstrongconsulting.com/
* @version 1.0
*/
abstract class GeoCode_Driver
{
/**
* The api key for the driver
*
* @var string
*/
protected $api_key = null;
/**
* Create a new instance of a driver
*
* @param string $driver
* @param string $api_key
* @return GeoCode_Driver
*/
public static function factory($driver, $api_key = null)
{
// Rewrite the driver proper name if a dot is found
if (strpos($driver, '.') !== false)
{
// Uppercase the word after each dot and replace the '.' with 'Dot'
$driver = str_replace(' ', 'Dot', ucwords(str_replace('.', ' ', $driver)));
}
// Generate the class name for the driver
$class = 'GeoCode_Driver_'.ucfirst( strtolower($driver) );
// If we can't autoload the class, throw an exception
if (class_exists($class, true) === false)
throw new GeoCode_Exception("Invalid driver '{$driver}' specified");
// Create and initialize the driver
$driver = new $class($api_key);
$driver->init();
// Return the driver
return $driver;
}
/**
* Make the constructor protected to force everything to use
* the factory method.
*
* @param string $api_key
*/
protected function __construct($api_key = null)
{
// Set values
$this->api_key = $api_key;
}
/**
* Set the api key for the driver
*
* @param string $api_key
*/
public function setApiKey($api_key)
{
$this->api_key = $api_key;
}
/**
* Get the api key for the driver
*
* @return string
*/
public function getApiKey()
{
return $this->api_key;
}
/**
* Initialize the driver
*/
abstract public function init();
/**
* Send a query to the geocode API
*
* @param mixed $query
* @return GeoCode_Result
*/
abstract public function query($query);
/**
* Get the name of the driver in use
*
* @return string
*/
abstract public function getDriverName();
/**
* Get the last query that we ran
*
* @return string
*/
abstract public function getLastQuery();
/**
* Get the raw response as returned by the API call
*
* @return string
*/
abstract public function getRawResponse();
/**
* This method is used to translate a given status constant
* into a human-readable and meaningful string
*
* @param integer $const
* @return string
*/
abstract public function getStatusString($const);
/**
* This method is used to translate a given accuracy constant
* into a human-readable and meaningful string
*
* @param integer $const
* @return string
*/
abstract public function getAccuracyString($const);
/**
* This method is used to translate a given error or status constant
* into a human-readable and meaningful error string that can be
* displayed to the end user.
*
* @param integer $const
* @return string
*/
abstract public function getErrorMessage($const);
}
?> | agpl-3.0 |
bengusty/cbioportal | core/src/main/java/org/mskcc/cbio/portal/authentication/googleplus/GoogleplusUserDetailsService.java | 3701 | /*
* Copyright (c) 2015 Memorial Sloan-Kettering Cancer Center.
*
* 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. The software and documentation provided hereunder
* is on an "as is" basis, and Memorial Sloan-Kettering Cancer Center has no
* obligations to provide maintenance, support, updates, enhancements or
* modifications. In no event shall Memorial Sloan-Kettering Cancer Center be
* liable to any party for direct, indirect, special, incidental or
* consequential damages, including lost profits, arising out of the use of this
* software and its documentation, even if Memorial Sloan-Kettering Cancer
* Center has been advised of the possibility of such damage.
*/
/*
* This file is part of cBioPortal.
*
* cBioPortal is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mskcc.cbio.portal.authentication.googleplus;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.social.security.SocialUser;
import org.springframework.social.security.SocialUserDetailsService;
public class GoogleplusUserDetailsService implements SocialUserDetailsService {
private static final Logger LOGGER = LoggerFactory.getLogger(GoogleplusUserDetailsService.class);
private UserDetailsService userDetailsService;
public GoogleplusUserDetailsService(UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
/**
* Loads the username by using the account ID of the user.
* @param userId The account ID of the requested user.
* @return The information of the requested user.
* @throws UsernameNotFoundException Thrown if no user is found.
* @throws DataAccessException
*/
@Override
public org.springframework.social.security.SocialUserDetails loadUserByUserId(String userId) throws UsernameNotFoundException, DataAccessException {
Preconditions.checkArgument(!Strings.isNullOrEmpty(userId), "A userid is required");
LOGGER.debug("Loading user by user id: {}", userId);
UserDetails ud = userDetailsService.loadUserByUsername(userId);
LOGGER.debug("Found user details: " +ud.getUsername());
/**
* Map Spring Security UserDetails implementation to a Spring Social SocialUser instance
*/
return new SocialUser(ud.getUsername(),
ud.getPassword(),
ud.isEnabled(),
ud.isAccountNonExpired(),
ud.isCredentialsNonExpired(),
ud.isAccountNonLocked(),
ud.getAuthorities());
}
}
| agpl-3.0 |
kerautret/DGtal0.6-ForIPOL | src/boost-1.75/boost/container/pmr/memory_resource.hpp | 4824 | //////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2015-2015. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/container for documentation.
//
//////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_CONTAINER_PMR_MEMORY_RESOURCE_HPP
#define BOOST_CONTAINER_PMR_MEMORY_RESOURCE_HPP
#if defined (_MSC_VER)
# pragma once
#endif
#include <boost/container/detail/config_begin.hpp>
#include <boost/container/detail/workaround.hpp>
#include <boost/container/container_fwd.hpp>
#include <boost/move/detail/type_traits.hpp>
#include <cstddef>
namespace boost {
namespace container {
namespace pmr {
//! The memory_resource class is an abstract interface to an
//! unbounded set of classes encapsulating memory resources.
class memory_resource
{
public:
// For exposition only
static BOOST_CONSTEXPR_OR_CONST std::size_t max_align =
boost::move_detail::alignment_of<boost::move_detail::max_align_t>::value;
//! <b>Effects</b>: Destroys
//! this memory_resource.
virtual ~memory_resource(){}
//! <b>Effects</b>: Equivalent to
//! `return do_allocate(bytes, alignment);`
void* allocate(std::size_t bytes, std::size_t alignment = max_align)
{ return this->do_allocate(bytes, alignment); }
//! <b>Effects</b>: Equivalent to
//! `return do_deallocate(bytes, alignment);`
void deallocate(void* p, std::size_t bytes, std::size_t alignment = max_align)
{ return this->do_deallocate(p, bytes, alignment); }
//! <b>Effects</b>: Equivalent to
//! `return return do_is_equal(other);`
bool is_equal(const memory_resource& other) const BOOST_NOEXCEPT
{ return this->do_is_equal(other); }
#if !defined(BOOST_EMBTC)
//! <b>Returns</b>:
//! `&a == &b || a.is_equal(b)`.
friend bool operator==(const memory_resource& a, const memory_resource& b) BOOST_NOEXCEPT
{ return &a == &b || a.is_equal(b); }
//! <b>Returns</b>:
//! !(a == b).
friend bool operator!=(const memory_resource& a, const memory_resource& b) BOOST_NOEXCEPT
{ return !(a == b); }
#else
//! <b>Returns</b>:
//! `&a == &b || a.is_equal(b)`.
friend bool operator==(const memory_resource& a, const memory_resource& b) BOOST_NOEXCEPT;
//! <b>Returns</b>:
//! !(a == b).
friend bool operator!=(const memory_resource& a, const memory_resource& b) BOOST_NOEXCEPT;
#endif
protected:
//! <b>Requires</b>: Alignment shall be a power of two.
//!
//! <b>Returns</b>: A derived class shall implement this function to return a pointer
//! to allocated storage with a size of at least bytes. The returned storage is
//! aligned to the specified alignment, if such alignment is supported; otherwise
//! it is aligned to max_align.
//!
//! <b>Throws</b>: A derived class implementation shall throw an appropriate exception if
//! it is unable to allocate memory with the requested size and alignment.
virtual void* do_allocate(std::size_t bytes, std::size_t alignment) = 0;
//! <b>Requires</b>: p shall have been returned from a prior call to
//! `allocate(bytes, alignment)` on a memory resource equal to *this, and the storage
//! at p shall not yet have been deallocated.
//!
//! <b>Effects</b>: A derived class shall implement this function to dispose of allocated storage.
//!
//! <b>Throws</b>: Nothing.
virtual void do_deallocate(void* p, std::size_t bytes, std::size_t alignment) = 0;
//! <b>Returns</b>: A derived class shall implement this function to return true if memory
//! allocated from this can be deallocated from other and vice-versa; otherwise it shall
//! return false. <i>[Note: The most-derived type of other might not match the type of this.
//! For a derived class, D, a typical implementation of this function will compute
//! `dynamic_cast<const D*>(&other)` and go no further (i.e., return false)
//! if it returns nullptr. - end note]</i>.
virtual bool do_is_equal(const memory_resource& other) const BOOST_NOEXCEPT = 0;
};
#if defined(BOOST_EMBTC)
//! <b>Returns</b>:
//! `&a == &b || a.is_equal(b)`.
inline bool operator==(const memory_resource& a, const memory_resource& b) BOOST_NOEXCEPT
{ return &a == &b || a.is_equal(b); }
//! <b>Returns</b>:
//! !(a == b).
inline bool operator!=(const memory_resource& a, const memory_resource& b) BOOST_NOEXCEPT
{ return !(a == b); }
#endif
} //namespace pmr {
} //namespace container {
} //namespace boost {
#include <boost/container/detail/config_end.hpp>
#endif //BOOST_CONTAINER_PMR_MEMORY_RESOURCE_HPP
| lgpl-3.0 |
duanjiangwei/jmtp | c++/src/Com.cpp | 2755 | /*
* Copyright 2007 Pieter De Rycke
*
* This file is part of JMTP.
*
* JTMP 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 3 of
* the License, or any later version.
*
* JMTP 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 LesserGeneral Public
* License along with JMTP. If not, see <http://www.gnu.org/licenses/>.
*/
#include <objbase.h>
#include "be_derycke_pieter_com_COM.h"
#include "be_derycke_pieter_com_COMReference.h"
#include "jmtp.h"
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved)
{
CoInitializeEx(NULL, COINIT_MULTITHREADED);
return JNI_VERSION_1_6;
}
JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *vm, void *reserved)
{
CoUninitialize();
}
JNIEXPORT jobject JNICALL Java_be_derycke_pieter_com_COM_CoCreateInstance
(JNIEnv* env, jclass guidCls, jobject rclsidObj, jlong pUnkOuter,
jlong dwClsContext, jobject riidObj)
{
HRESULT hr;
IID rclsid;
IID riid;
LPVOID reference;
jclass cls;
jmethodID mid;
rclsid = ConvertJavaToGuid(env, rclsidObj);
riid = ConvertJavaToGuid(env, riidObj);
//niet 100% want een dword is een unsigned long een een jlong een signed long
//maar doet het voor nu wel
hr = CoCreateInstance(rclsid, (LPUNKNOWN)pUnkOuter, (DWORD)dwClsContext, riid, &reference);
if(SUCCEEDED(hr))
{
//smart reference object aanmaken
cls = env->FindClass("be/derycke/pieter/com/COMReference");
mid = env->GetMethodID(cls, "<init>", "(J)V");
return env->NewObject(cls, mid, reference);
}
else {
ThrowCOMException(env, L"Couldn't create the COM-object", hr);
return NULL;
}
}
JNIEXPORT jlong JNICALL Java_be_derycke_pieter_com_COMReference_release
(JNIEnv* env, jobject obj)
{
jfieldID fid = env->GetFieldID(env->GetObjectClass(obj), "pIUnknown", "J");
LPUNKNOWN pointer = (LPUNKNOWN)env->GetLongField(obj, fid);
__try
{
return pointer->Release();
}
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION)
{
return 0;
}
}
JNIEXPORT jlong JNICALL Java_be_derycke_pieter_com_COMReference_addRef
(JNIEnv* env, jobject obj)
{
jfieldID fid = env->GetFieldID(env->GetObjectClass(obj), "pIUnknown", "J");
LPUNKNOWN pointer = (LPUNKNOWN)env->GetLongField(obj, fid);
__try
{
return pointer->AddRef();
}
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION)
{
return 0;
}
} | lgpl-3.0 |
llvm-mirror/clang | test/CodeGen/address-safety-attr-flavors.cpp | 3591 | // Make sure the sanitize_address attribute is emitted when using ASan, KASan or
// HWASan. Either __attribute__((no_sanitize("address")) or
// __attribute__((no_sanitize("kernel-address")) disables both ASan and KASan
// instrumentation.
// Same for __attribute__((no_sanitize("hwaddress")) and
// __attribute__((no_sanitize("kernel-hwddress")) and HWASan and KHWASan.
// RUN: %clang_cc1 -triple i386-unknown-linux -disable-O0-optnone \
// RUN: -emit-llvm -o - %s | FileCheck -check-prefix=CHECK-NOASAN %s
// RUN: %clang_cc1 -triple i386-unknown-linux -fsanitize=address \
// RUN: -disable-O0-optnone -emit-llvm -o - %s | \
// RUN: FileCheck -check-prefix=CHECK-ASAN %s
// RUN: %clang_cc1 -triple i386-unknown-linux -fsanitize=kernel-address \
// RUN: -disable-O0-optnone -emit-llvm -o - %s | \
// RUN: FileCheck -check-prefix=CHECK-KASAN %s
// RUN: %clang_cc1 -triple i386-unknown-linux -fsanitize=hwaddress \
// RUN: -disable-O0-optnone -emit-llvm -o - %s | \
// RUN: FileCheck -check-prefix=CHECK-HWASAN %s
// RUN: %clang_cc1 -triple i386-unknown-linux -fsanitize=kernel-hwaddress \
// RUN: -disable-O0-optnone -emit-llvm -o - %s | \
// RUN: FileCheck -check-prefix=CHECK-KHWASAN %s
int HasSanitizeAddress() { return 1; }
// CHECK-NOASAN: {{Function Attrs: noinline nounwind$}}
// CHECK-ASAN: Function Attrs: noinline nounwind sanitize_address
// CHECK-KASAN: Function Attrs: noinline nounwind sanitize_address
// CHECK-HWASAN: Function Attrs: noinline nounwind sanitize_hwaddress
// CHECK-KHWASAN: Function Attrs: noinline nounwind sanitize_hwaddress
__attribute__((no_sanitize("address"))) int NoSanitizeQuoteAddress() {
return 0;
}
// CHECK-NOASAN: {{Function Attrs: noinline nounwind$}}
// CHECK-ASAN: {{Function Attrs: noinline nounwind$}}
// CHECK-KASAN: {{Function Attrs: noinline nounwind$}}
// CHECK-HWASAN: {{Function Attrs: noinline nounwind sanitize_hwaddress$}}
// CHECK-KHWASAN: {{Function Attrs: noinline nounwind sanitize_hwaddress$}}
__attribute__((no_sanitize_address)) int NoSanitizeAddress() { return 0; }
// CHECK-NOASAN: {{Function Attrs: noinline nounwind$}}
// CHECK-ASAN: {{Function Attrs: noinline nounwind$}}
// CHECK-KASAN: {{Function Attrs: noinline nounwind$}}
// CHECK-HWASAN: {{Function Attrs: noinline nounwind sanitize_hwaddress$}}
// CHECK-KHWASAN: {{Function Attrs: noinline nounwind sanitize_hwaddress$}}
__attribute__((no_sanitize("kernel-address"))) int NoSanitizeKernelAddress() {
return 0;
}
// CHECK-NOASAN: {{Function Attrs: noinline nounwind$}}
// CHECK-ASAN: {{Function Attrs: noinline nounwind$}}
// CHECK-KASAN: {{Function Attrs: noinline nounwind$}}
// CHECK-HWASAN: {{Function Attrs: noinline nounwind sanitize_hwaddress$}}
// CHECK-KHWASAN: {{Function Attrs: noinline nounwind sanitize_hwaddress$}}
__attribute__((no_sanitize("hwaddress"))) int NoSanitizeHWAddress() {
return 0;
}
// CHECK-NOASAN: {{Function Attrs: noinline nounwind$}}
// CHECK-ASAN: {{Function Attrs: noinline nounwind sanitize_address$}}
// CHECK-KASAN: {{Function Attrs: noinline nounwind sanitize_address$}}
// CHECK-HWASAN: {{Function Attrs: noinline nounwind$}}
// CHECK-KHWASAN: {{Function Attrs: noinline nounwind$}}
__attribute__((no_sanitize("kernel-hwaddress"))) int NoSanitizeKernelHWAddress() {
return 0;
}
// CHECK-NOASAN: {{Function Attrs: noinline nounwind$}}
// CHECK-ASAN: {{Function Attrs: noinline nounwind sanitize_address$}}
// CHECK-KASAN: {{Function Attrs: noinline nounwind sanitize_address$}}
// CHECK-HWASAN: {{Function Attrs: noinline nounwind$}}
// CHECK-KHWASAN: {{Function Attrs: noinline nounwind$}}
| apache-2.0 |
tony810430/flink | flink-connectors/flink-connector-kinesis/src/test/java/org/apache/flink/streaming/connectors/kinesis/internals/publisher/fanout/StreamConsumerRegistrarTest.java | 15923 | /*
* 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.flink.streaming.connectors.kinesis.internals.publisher.fanout;
import org.apache.flink.streaming.connectors.kinesis.FlinkKinesisException.FlinkKinesisTimeoutException;
import org.apache.flink.streaming.connectors.kinesis.proxy.FullJitterBackoff;
import org.apache.flink.streaming.connectors.kinesis.proxy.KinesisProxyV2Interface;
import org.apache.flink.streaming.connectors.kinesis.testutils.FakeKinesisFanOutBehavioursFactory;
import org.apache.flink.streaming.connectors.kinesis.testutils.FakeKinesisFanOutBehavioursFactory.StreamConsumerFakeKinesis;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import software.amazon.awssdk.services.kinesis.model.ResourceNotFoundException;
import java.util.Properties;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.apache.flink.streaming.connectors.kinesis.config.ConsumerConfigConstants.DEREGISTER_STREAM_BACKOFF_BASE;
import static org.apache.flink.streaming.connectors.kinesis.config.ConsumerConfigConstants.DEREGISTER_STREAM_BACKOFF_EXPONENTIAL_CONSTANT;
import static org.apache.flink.streaming.connectors.kinesis.config.ConsumerConfigConstants.DEREGISTER_STREAM_BACKOFF_MAX;
import static org.apache.flink.streaming.connectors.kinesis.config.ConsumerConfigConstants.DEREGISTER_STREAM_TIMEOUT_SECONDS;
import static org.apache.flink.streaming.connectors.kinesis.config.ConsumerConfigConstants.EFORegistrationType.LAZY;
import static org.apache.flink.streaming.connectors.kinesis.config.ConsumerConfigConstants.EFO_CONSUMER_NAME;
import static org.apache.flink.streaming.connectors.kinesis.config.ConsumerConfigConstants.EFO_REGISTRATION_TYPE;
import static org.apache.flink.streaming.connectors.kinesis.config.ConsumerConfigConstants.RECORD_PUBLISHER_TYPE;
import static org.apache.flink.streaming.connectors.kinesis.config.ConsumerConfigConstants.REGISTER_STREAM_BACKOFF_BASE;
import static org.apache.flink.streaming.connectors.kinesis.config.ConsumerConfigConstants.REGISTER_STREAM_BACKOFF_EXPONENTIAL_CONSTANT;
import static org.apache.flink.streaming.connectors.kinesis.config.ConsumerConfigConstants.REGISTER_STREAM_BACKOFF_MAX;
import static org.apache.flink.streaming.connectors.kinesis.config.ConsumerConfigConstants.REGISTER_STREAM_TIMEOUT_SECONDS;
import static org.apache.flink.streaming.connectors.kinesis.config.ConsumerConfigConstants.RecordPublisherType.EFO;
import static org.apache.flink.streaming.connectors.kinesis.config.ConsumerConfigConstants.efoConsumerArn;
import static org.apache.flink.streaming.connectors.kinesis.testutils.FakeKinesisFanOutBehavioursFactory.STREAM_CONSUMER_ARN_EXISTING;
import static org.apache.flink.streaming.connectors.kinesis.testutils.FakeKinesisFanOutBehavioursFactory.STREAM_CONSUMER_ARN_NEW;
import static org.apache.flink.streaming.connectors.kinesis.testutils.FakeKinesisFanOutBehavioursFactory.StreamConsumerFakeKinesis.NUMBER_OF_DESCRIBE_REQUESTS_TO_ACTIVATE;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.anyDouble;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** Tests for {@link StreamConsumerRegistrar}. */
public class StreamConsumerRegistrarTest {
private static final String STREAM = "stream";
private static final long EXPECTED_REGISTRATION_MAX = 1;
private static final long EXPECTED_REGISTRATION_BASE = 2;
private static final double EXPECTED_REGISTRATION_POW = 0.5;
private static final long EXPECTED_DEREGISTRATION_MAX = 2;
private static final long EXPECTED_DEREGISTRATION_BASE = 4;
private static final double EXPECTED_DEREGISTRATION_POW = 1;
@Rule public final ExpectedException thrown = ExpectedException.none();
@Test
public void testStreamNotFoundWhenRegisteringThrowsException() throws Exception {
thrown.expect(ResourceNotFoundException.class);
KinesisProxyV2Interface kinesis = FakeKinesisFanOutBehavioursFactory.streamNotFound();
StreamConsumerRegistrar registrar = createRegistrar(kinesis, mock(FullJitterBackoff.class));
registrar.registerStreamConsumer(STREAM, "name");
}
@Test
public void testRegisterStreamConsumerRegistersNewStreamConsumer() throws Exception {
FullJitterBackoff backoff = mock(FullJitterBackoff.class);
KinesisProxyV2Interface kinesis =
FakeKinesisFanOutBehavioursFactory.streamConsumerNotFound();
StreamConsumerRegistrar registrar = createRegistrar(kinesis, backoff);
String result = registrar.registerStreamConsumer(STREAM, "name");
assertEquals(STREAM_CONSUMER_ARN_NEW, result);
}
@Test
public void testRegisterStreamConsumerThatAlreadyExistsAndActive() throws Exception {
FullJitterBackoff backoff = mock(FullJitterBackoff.class);
KinesisProxyV2Interface kinesis =
FakeKinesisFanOutBehavioursFactory.existingActiveConsumer();
StreamConsumerRegistrar registrar = createRegistrar(kinesis, backoff);
String result = registrar.registerStreamConsumer(STREAM, "name");
verify(backoff, never()).sleep(anyLong());
assertEquals(STREAM_CONSUMER_ARN_EXISTING, result);
}
@Test
public void testRegisterStreamConsumerWaitsForConsumerToBecomeActive() throws Exception {
FullJitterBackoff backoff = mock(FullJitterBackoff.class);
StreamConsumerFakeKinesis kinesis =
FakeKinesisFanOutBehavioursFactory.registerExistingConsumerAndWaitToBecomeActive();
StreamConsumerRegistrar registrar = createRegistrar(kinesis, backoff);
String result = registrar.registerStreamConsumer(STREAM, "name");
// we backoff on each retry
verify(backoff, times(NUMBER_OF_DESCRIBE_REQUESTS_TO_ACTIVATE - 1)).sleep(anyLong());
assertEquals(STREAM_CONSUMER_ARN_EXISTING, result);
// We will invoke describe stream until the stream consumer is activated
assertEquals(
NUMBER_OF_DESCRIBE_REQUESTS_TO_ACTIVATE,
kinesis.getNumberOfDescribeStreamConsumerInvocations());
for (int i = 1; i < NUMBER_OF_DESCRIBE_REQUESTS_TO_ACTIVATE; i++) {
verify(backoff).calculateFullJitterBackoff(anyLong(), anyLong(), anyDouble(), eq(i));
}
}
@Test
public void testRegisterStreamConsumerTimeoutWaitingForConsumerToBecomeActive()
throws Exception {
thrown.expect(FlinkKinesisTimeoutException.class);
thrown.expectMessage(
"Timeout waiting for stream consumer to become active: name on stream-arn");
StreamConsumerFakeKinesis kinesis =
FakeKinesisFanOutBehavioursFactory.registerExistingConsumerAndWaitToBecomeActive();
Properties configProps = createEfoProperties();
configProps.setProperty(REGISTER_STREAM_TIMEOUT_SECONDS, "1");
FanOutRecordPublisherConfiguration configuration =
new FanOutRecordPublisherConfiguration(configProps, singletonList(STREAM));
StreamConsumerRegistrar registrar =
new StreamConsumerRegistrar(kinesis, configuration, backoffFor(1001));
registrar.registerStreamConsumer(STREAM, "name");
}
@Test
public void testRegistrationBackoffForLazy() throws Exception {
FullJitterBackoff backoff = mock(FullJitterBackoff.class);
KinesisProxyV2Interface kinesis =
FakeKinesisFanOutBehavioursFactory.existingActiveConsumer();
Properties efoProperties = createEfoProperties();
efoProperties.setProperty(EFO_REGISTRATION_TYPE, LAZY.name());
FanOutRecordPublisherConfiguration configuration =
new FanOutRecordPublisherConfiguration(efoProperties, emptyList());
StreamConsumerRegistrar registrar =
new StreamConsumerRegistrar(kinesis, configuration, backoff);
String result = registrar.registerStreamConsumer(STREAM, "name");
verify(backoff).sleep(anyLong());
assertEquals(STREAM_CONSUMER_ARN_EXISTING, result);
}
@Test
public void testDeregisterStreamConsumerAndWaitForDeletingStatus() throws Exception {
FullJitterBackoff backoff = mock(FullJitterBackoff.class);
StreamConsumerFakeKinesis kinesis =
FakeKinesisFanOutBehavioursFactory.existingActiveConsumer();
StreamConsumerRegistrar registrar = createRegistrar(kinesis, backoff);
registrar.deregisterStreamConsumer(STREAM);
// We will invoke describe stream until the stream consumer is in the DELETING state
assertEquals(2, kinesis.getNumberOfDescribeStreamConsumerInvocations());
for (int i = 1; i < 2; i++) {
verify(backoff).calculateFullJitterBackoff(anyLong(), anyLong(), anyDouble(), eq(i));
}
}
@Test
public void testDeregisterStreamConsumerTimeoutWaitingForConsumerToDeregister()
throws Exception {
thrown.expect(FlinkKinesisTimeoutException.class);
thrown.expectMessage(
"Timeout waiting for stream consumer to deregister: stream-consumer-arn");
StreamConsumerFakeKinesis kinesis =
FakeKinesisFanOutBehavioursFactory.existingActiveConsumer();
Properties configProps = createEfoProperties();
configProps.setProperty(DEREGISTER_STREAM_TIMEOUT_SECONDS, "1");
FanOutRecordPublisherConfiguration configuration =
new FanOutRecordPublisherConfiguration(configProps, singletonList(STREAM));
StreamConsumerRegistrar registrar =
new StreamConsumerRegistrar(kinesis, configuration, backoffFor(1001));
registrar.deregisterStreamConsumer(STREAM);
}
@Test
public void testDeregisterStreamConsumerNotFound() throws Exception {
FullJitterBackoff backoff = mock(FullJitterBackoff.class);
StreamConsumerFakeKinesis kinesis =
FakeKinesisFanOutBehavioursFactory.streamConsumerNotFound();
StreamConsumerRegistrar registrar = createRegistrar(kinesis, backoff);
registrar.deregisterStreamConsumer(STREAM);
assertEquals(1, kinesis.getNumberOfDescribeStreamConsumerInvocations());
}
@Test
public void testDeregisterStreamConsumerArnNotFound() throws Exception {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Stream consumer ARN not found for stream: not-found");
FullJitterBackoff backoff = mock(FullJitterBackoff.class);
StreamConsumerFakeKinesis kinesis =
FakeKinesisFanOutBehavioursFactory.streamConsumerNotFound();
StreamConsumerRegistrar registrar = createRegistrar(kinesis, backoff);
registrar.deregisterStreamConsumer("not-found");
}
@Test
public void testRegistrationBackoff() throws Exception {
FanOutRecordPublisherConfiguration configuration = createConfiguration();
FullJitterBackoff backoff = mock(FullJitterBackoff.class);
when(backoff.calculateFullJitterBackoff(anyLong(), anyLong(), anyDouble(), anyInt()))
.thenReturn(5L);
StreamConsumerRegistrar registrar =
new StreamConsumerRegistrar(
mock(KinesisProxyV2Interface.class), configuration, backoff);
registrar.registrationBackoff(configuration, backoff, 10);
verify(backoff).sleep(5);
verify(backoff)
.calculateFullJitterBackoff(
EXPECTED_REGISTRATION_BASE,
EXPECTED_REGISTRATION_MAX,
EXPECTED_REGISTRATION_POW,
10);
}
@Test
public void testDeregistrationBackoff() throws Exception {
FanOutRecordPublisherConfiguration configuration = createConfiguration();
FullJitterBackoff backoff = mock(FullJitterBackoff.class);
when(backoff.calculateFullJitterBackoff(anyLong(), anyLong(), anyDouble(), anyInt()))
.thenReturn(5L);
StreamConsumerRegistrar registrar =
new StreamConsumerRegistrar(
mock(KinesisProxyV2Interface.class), configuration, backoff);
registrar.deregistrationBackoff(configuration, backoff, 11);
verify(backoff).sleep(5);
verify(backoff)
.calculateFullJitterBackoff(
EXPECTED_DEREGISTRATION_BASE,
EXPECTED_DEREGISTRATION_MAX,
EXPECTED_DEREGISTRATION_POW,
11);
}
@Test
public void testCloseClosesProxy() {
KinesisProxyV2Interface kinesis = mock(KinesisProxyV2Interface.class);
StreamConsumerRegistrar registrar = createRegistrar(kinesis, mock(FullJitterBackoff.class));
registrar.close();
verify(kinesis).close();
}
private StreamConsumerRegistrar createRegistrar(
final KinesisProxyV2Interface kinesis, final FullJitterBackoff backoff) {
FanOutRecordPublisherConfiguration configuration = createConfiguration();
return new StreamConsumerRegistrar(kinesis, configuration, backoff);
}
private FanOutRecordPublisherConfiguration createConfiguration() {
return new FanOutRecordPublisherConfiguration(createEfoProperties(), singletonList(STREAM));
}
private Properties createEfoProperties() {
Properties config = new Properties();
config.setProperty(RECORD_PUBLISHER_TYPE, EFO.name());
config.setProperty(EFO_CONSUMER_NAME, "dummy-efo-consumer");
config.setProperty(
REGISTER_STREAM_BACKOFF_BASE, String.valueOf(EXPECTED_REGISTRATION_BASE));
config.setProperty(REGISTER_STREAM_BACKOFF_MAX, String.valueOf(EXPECTED_REGISTRATION_MAX));
config.setProperty(
REGISTER_STREAM_BACKOFF_EXPONENTIAL_CONSTANT,
String.valueOf(EXPECTED_REGISTRATION_POW));
config.setProperty(
DEREGISTER_STREAM_BACKOFF_BASE, String.valueOf(EXPECTED_DEREGISTRATION_BASE));
config.setProperty(
DEREGISTER_STREAM_BACKOFF_MAX, String.valueOf(EXPECTED_DEREGISTRATION_MAX));
config.setProperty(
DEREGISTER_STREAM_BACKOFF_EXPONENTIAL_CONSTANT,
String.valueOf(EXPECTED_DEREGISTRATION_POW));
config.setProperty(efoConsumerArn(STREAM), "stream-consumer-arn");
return config;
}
private FullJitterBackoff backoffFor(final long millisToBackoffFor) {
FullJitterBackoff backoff = spy(new FullJitterBackoff());
when(backoff.calculateFullJitterBackoff(anyLong(), anyLong(), anyDouble(), anyInt()))
.thenReturn(millisToBackoffFor);
return backoff;
}
}
| apache-2.0 |
LauhLemus10/geojsoncesium | Specs/Renderer/AutomaticUniformSpec.js | 57850 | defineSuite([
'Core/Cartesian2',
'Core/Cartesian3',
'Core/Color',
'Core/defaultValue',
'Core/Matrix4',
'Core/OrthographicFrustum',
'Core/OrthographicOffCenterFrustum',
'Renderer/Pass',
'Renderer/Texture',
'Scene/SceneMode',
'Specs/createCamera',
'Specs/createContext',
'Specs/createFrameState'
], 'Renderer/AutomaticUniforms', function(
Cartesian2,
Cartesian3,
Color,
defaultValue,
Matrix4,
OrthographicFrustum,
OrthographicOffCenterFrustum,
Pass,
Texture,
SceneMode,
createCamera,
createContext,
createFrameState) {
'use strict';
var context;
beforeAll(function() {
context = createContext();
});
afterAll(function() {
context.destroyForSpecs();
});
function createMockCamera(view, projection, infiniteProjection, position, direction, right, up) {
return {
viewMatrix : defaultValue(view, Matrix4.clone(Matrix4.IDENTITY)),
inverseViewMatrix : Matrix4.inverseTransformation(defaultValue(view, Matrix4.clone(Matrix4.IDENTITY)), new Matrix4()),
frustum : {
near : 1.0,
far : 1000.0,
top : 2.0,
bottom : -2.0,
left : -1.0,
right : 1.0,
projectionMatrix : defaultValue(projection, Matrix4.clone(Matrix4.IDENTITY)),
infiniteProjectionMatrix : defaultValue(infiniteProjection, Matrix4.clone(Matrix4.IDENTITY)),
computeCullingVolume : function() {
return undefined;
},
getPixelSize : function() {
return new Cartesian2(1.0, 0.1);
}
},
position : defaultValue(position, Cartesian3.clone(Cartesian3.ZERO)),
positionWC : defaultValue(position, Cartesian3.clone(Cartesian3.ZERO)),
directionWC : defaultValue(direction, Cartesian3.clone(Cartesian3.UNIT_Z)),
rightWC : defaultValue(right, Cartesian3.clone(Cartesian3.UNIT_X)),
upWC : defaultValue(up, Cartesian3.clone(Cartesian3.UNIT_Y))
};
}
it('can declare automatic uniforms', function() {
var fs =
'void main() { ' +
' gl_FragColor = vec4((czm_viewport.x == 0.0) && (czm_viewport.y == 0.0) && (czm_viewport.z == 1.0) && (czm_viewport.w == 1.0)); ' +
'}';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_viewport', function() {
var fs =
'void main() { ' +
' gl_FragColor = vec4((czm_viewport.x == 0.0) && (czm_viewport.y == 0.0) && (czm_viewport.z == 1.0) && (czm_viewport.w == 1.0)); ' +
'}';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_viewportOrthographic', function() {
var fs =
'void main() { ' +
' bool b0 = (czm_viewportOrthographic[0][0] != 0.0) && (czm_viewportOrthographic[1][0] == 0.0) && (czm_viewportOrthographic[2][0] == 0.0) && (czm_viewportOrthographic[3][0] != 0.0); ' +
' bool b1 = (czm_viewportOrthographic[0][1] == 0.0) && (czm_viewportOrthographic[1][1] != 0.0) && (czm_viewportOrthographic[2][1] == 0.0) && (czm_viewportOrthographic[3][1] != 0.0); ' +
' bool b2 = (czm_viewportOrthographic[0][2] == 0.0) && (czm_viewportOrthographic[1][2] == 0.0) && (czm_viewportOrthographic[2][2] != 0.0) && (czm_viewportOrthographic[3][2] != 0.0); ' +
' bool b3 = (czm_viewportOrthographic[0][3] == 0.0) && (czm_viewportOrthographic[1][3] == 0.0) && (czm_viewportOrthographic[2][3] == 0.0) && (czm_viewportOrthographic[3][3] == 1.0); ' +
' gl_FragColor = vec4(b0 && b1 && b2 && b3); ' +
'}';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_viewportTransformation', function() {
var fs =
'void main() { ' +
' bool b0 = (czm_viewportTransformation[0][0] != 0.0) && (czm_viewportTransformation[1][0] == 0.0) && (czm_viewportTransformation[2][0] == 0.0) && (czm_viewportTransformation[3][0] != 0.0); ' +
' bool b1 = (czm_viewportTransformation[0][1] == 0.0) && (czm_viewportTransformation[1][1] != 0.0) && (czm_viewportTransformation[2][1] == 0.0) && (czm_viewportTransformation[3][1] != 0.0); ' +
' bool b2 = (czm_viewportTransformation[0][2] == 0.0) && (czm_viewportTransformation[1][2] == 0.0) && (czm_viewportTransformation[2][2] != 0.0) && (czm_viewportTransformation[3][2] != 0.0); ' +
' bool b3 = (czm_viewportTransformation[0][3] == 0.0) && (czm_viewportTransformation[1][3] == 0.0) && (czm_viewportTransformation[2][3] == 0.0) && (czm_viewportTransformation[3][3] == 1.0); ' +
' gl_FragColor = vec4(b0 && b1 && b2 && b3); ' +
'}';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_globeDepthTexture', function() {
context.uniformState.globeDepthTexture = new Texture({
context : context,
source : {
width : 1,
height : 1,
arrayBufferView : new Uint8Array([255, 255, 255, 255])
}
});
var fs =
'void main() { ' +
' gl_FragColor = vec4(texture2D(czm_globeDepthTexture, vec2(0.5, 0.5)).r == 1.0);' +
'}';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_model', function() {
var fs =
'void main() { ' +
' bool b0 = (czm_model[0][0] == 1.0) && (czm_model[1][0] == 2.0) && (czm_model[2][0] == 3.0) && (czm_model[3][0] == 4.0); ' +
' bool b1 = (czm_model[0][1] == 5.0) && (czm_model[1][1] == 6.0) && (czm_model[2][1] == 7.0) && (czm_model[3][1] == 8.0); ' +
' bool b2 = (czm_model[0][2] == 9.0) && (czm_model[1][2] == 10.0) && (czm_model[2][2] == 11.0) && (czm_model[3][2] == 12.0); ' +
' bool b3 = (czm_model[0][3] == 13.0) && (czm_model[1][3] == 14.0) && (czm_model[2][3] == 15.0) && (czm_model[3][3] == 16.0); ' +
' gl_FragColor = vec4(b0 && b1 && b2 && b3); ' +
'}';
var m = new Matrix4(
1.0, 2.0, 3.0, 4.0,
5.0, 6.0, 7.0, 8.0,
9.0, 10.0, 11.0, 12.0,
13.0, 14.0, 15.0, 16.0);
expect({
context : context,
fragmentShader : fs,
modelMatrix : m
}).contextToRender();
});
it('has czm_inverseModel', function() {
var fs =
'void main() { ' +
' bool b0 = (czm_inverseModel[0][0] == 0.0) && (czm_inverseModel[1][0] == 1.0) && (czm_inverseModel[2][0] == 0.0) && (czm_inverseModel[3][0] == -2.0); ' +
' bool b1 = (czm_inverseModel[0][1] == -1.0) && (czm_inverseModel[1][1] == 0.0) && (czm_inverseModel[2][1] == 0.0) && (czm_inverseModel[3][1] == 1.0); ' +
' bool b2 = (czm_inverseModel[0][2] == 0.0) && (czm_inverseModel[1][2] == 0.0) && (czm_inverseModel[2][2] == 1.0) && (czm_inverseModel[3][2] == 0.0); ' +
' bool b3 = (czm_inverseModel[0][3] == 0.0) && (czm_inverseModel[1][3] == 0.0) && (czm_inverseModel[2][3] == 0.0) && (czm_inverseModel[3][3] == 1.0); ' +
' gl_FragColor = vec4(b0 && b1 && b2 && b3); ' +
'}';
var m = new Matrix4(
0.0, -1.0, 0.0, 1.0,
1.0, 0.0, 0.0, 2.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0);
expect({
context : context,
fragmentShader : fs,
modelMatrix : m
}).contextToRender();
});
it('has czm_view', function() {
var us = context.uniformState;
us.update(createFrameState(context, createMockCamera(
new Matrix4(
1.0, 2.0, 3.0, 4.0,
5.0, 6.0, 7.0, 8.0,
9.0, 10.0, 11.0, 12.0,
13.0, 14.0, 15.0, 16.0))));
var fs =
'void main() { ' +
' bool b0 = (czm_view[0][0] == 1.0) && (czm_view[1][0] == 2.0) && (czm_view[2][0] == 3.0) && (czm_view[3][0] == 4.0); ' +
' bool b1 = (czm_view[0][1] == 5.0) && (czm_view[1][1] == 6.0) && (czm_view[2][1] == 7.0) && (czm_view[3][1] == 8.0); ' +
' bool b2 = (czm_view[0][2] == 9.0) && (czm_view[1][2] == 10.0) && (czm_view[2][2] == 11.0) && (czm_view[3][2] == 12.0); ' +
' bool b3 = (czm_view[0][3] == 13.0) && (czm_view[1][3] == 14.0) && (czm_view[2][3] == 15.0) && (czm_view[3][3] == 16.0); ' +
' gl_FragColor = vec4(b0 && b1 && b2 && b3); ' +
'}';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_view3D', function() {
var us = context.uniformState;
us.update(createFrameState(context, createMockCamera(
new Matrix4(
1.0, 2.0, 3.0, 4.0,
5.0, 6.0, 7.0, 8.0,
9.0, 10.0, 11.0, 12.0,
13.0, 14.0, 15.0, 16.0))));
var fs =
'void main() { ' +
' bool b0 = (czm_view3D[0][0] == 1.0) && (czm_view3D[1][0] == 2.0) && (czm_view3D[2][0] == 3.0) && (czm_view3D[3][0] == 4.0); ' +
' bool b1 = (czm_view3D[0][1] == 5.0) && (czm_view3D[1][1] == 6.0) && (czm_view3D[2][1] == 7.0) && (czm_view3D[3][1] == 8.0); ' +
' bool b2 = (czm_view3D[0][2] == 9.0) && (czm_view3D[1][2] == 10.0) && (czm_view3D[2][2] == 11.0) && (czm_view3D[3][2] == 12.0); ' +
' bool b3 = (czm_view3D[0][3] == 13.0) && (czm_view3D[1][3] == 14.0) && (czm_view3D[2][3] == 15.0) && (czm_view3D[3][3] == 16.0); ' +
' gl_FragColor = vec4(b0 && b1 && b2 && b3); ' +
'}';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_viewRotation', function() {
var us = context.uniformState;
us.update(createFrameState(context, createMockCamera(
new Matrix4(
1.0, 2.0, 3.0, 4.0,
5.0, 6.0, 7.0, 8.0,
9.0, 10.0, 11.0, 12.0,
13.0, 14.0, 15.0, 16.0))));
var fs =
'void main() { ' +
' bool b0 = (czm_viewRotation[0][0] == 1.0) && (czm_viewRotation[1][0] == 2.0) && (czm_viewRotation[2][0] == 3.0); ' +
' bool b1 = (czm_viewRotation[0][1] == 5.0) && (czm_viewRotation[1][1] == 6.0) && (czm_viewRotation[2][1] == 7.0); ' +
' bool b2 = (czm_viewRotation[0][2] == 9.0) && (czm_viewRotation[1][2] == 10.0) && (czm_viewRotation[2][2] == 11.0); ' +
' gl_FragColor = vec4(b0 && b1 && b2); ' +
'}';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_viewRotation3D', function() {
var us = context.uniformState;
us.update(createFrameState(context, createMockCamera(
new Matrix4(
1.0, 2.0, 3.0, 4.0,
5.0, 6.0, 7.0, 8.0,
9.0, 10.0, 11.0, 12.0,
13.0, 14.0, 15.0, 16.0))));
var fs =
'void main() { ' +
' bool b0 = (czm_viewRotation3D[0][0] == 1.0) && (czm_viewRotation3D[1][0] == 2.0) && (czm_viewRotation3D[2][0] == 3.0); ' +
' bool b1 = (czm_viewRotation3D[0][1] == 5.0) && (czm_viewRotation3D[1][1] == 6.0) && (czm_viewRotation3D[2][1] == 7.0); ' +
' bool b2 = (czm_viewRotation3D[0][2] == 9.0) && (czm_viewRotation3D[1][2] == 10.0) && (czm_viewRotation3D[2][2] == 11.0); ' +
' gl_FragColor = vec4(b0 && b1 && b2); ' +
'}';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_inverseView', function() {
var us = context.uniformState;
us.update(createFrameState(context, createMockCamera(
new Matrix4(
0.0, -1.0, 0.0, 7.0,
1.0, 0.0, 0.0, 8.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0))));
var fs =
'void main() { ' +
' gl_FragColor = vec4(' +
' (czm_inverseView[0][0] == 0.0) && (czm_inverseView[1][0] == 1.0) && (czm_inverseView[2][0] == 0.0) && (czm_inverseView[3][0] == -8.0) &&' +
' (czm_inverseView[0][1] == -1.0) && (czm_inverseView[1][1] == 0.0) && (czm_inverseView[2][1] == 0.0) && (czm_inverseView[3][1] == 7.0) &&' +
' (czm_inverseView[0][2] == 0.0) && (czm_inverseView[1][2] == 0.0) && (czm_inverseView[2][2] == 1.0) && (czm_inverseView[3][2] == 0.0)' +
' ); ' +
'}';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_inverseView3D', function() {
var us = context.uniformState;
us.update(createFrameState(context, createMockCamera(
new Matrix4(
0.0, -1.0, 0.0, 7.0,
1.0, 0.0, 0.0, 8.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0))));
var fs =
'void main() { ' +
' gl_FragColor = vec4(' +
' (czm_inverseView3D[0][0] == 0.0) && (czm_inverseView3D[1][0] == 1.0) && (czm_inverseView3D[2][0] == 0.0) && (czm_inverseView3D[3][0] == -8.0) &&' +
' (czm_inverseView3D[0][1] == -1.0) && (czm_inverseView3D[1][1] == 0.0) && (czm_inverseView3D[2][1] == 0.0) && (czm_inverseView3D[3][1] == 7.0) &&' +
' (czm_inverseView3D[0][2] == 0.0) && (czm_inverseView3D[1][2] == 0.0) && (czm_inverseView3D[2][2] == 1.0) && (czm_inverseView3D[3][2] == 0.0)' +
' ); ' +
'}';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_inverseViewRotation', function() {
var us = context.uniformState;
us.update(createFrameState(context, createMockCamera(
new Matrix4(
0.0, -1.0, 0.0, 7.0,
1.0, 0.0, 0.0, 8.0,
0.0, 0.0, 1.0, 9.0,
0.0, 0.0, 0.0, 1.0))));
var fs =
'void main() { ' +
' gl_FragColor = vec4(' +
' (czm_inverseViewRotation[0][0] == 0.0) && (czm_inverseViewRotation[1][0] == 1.0) && (czm_inverseViewRotation[2][0] == 0.0) && ' +
' (czm_inverseViewRotation[0][1] == -1.0) && (czm_inverseViewRotation[1][1] == 0.0) && (czm_inverseViewRotation[2][1] == 0.0) && ' +
' (czm_inverseViewRotation[0][2] == 0.0) && (czm_inverseViewRotation[1][2] == 0.0) && (czm_inverseViewRotation[2][2] == 1.0) ' +
' ); ' +
'}';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_inverseViewRotation3D', function() {
var us = context.uniformState;
us.update(createFrameState(context, createMockCamera(
new Matrix4(
0.0, -1.0, 0.0, 7.0,
1.0, 0.0, 0.0, 8.0,
0.0, 0.0, 1.0, 9.0,
0.0, 0.0, 0.0, 1.0))));
var fs =
'void main() { ' +
' gl_FragColor = vec4(' +
' (czm_inverseViewRotation3D[0][0] == 0.0) && (czm_inverseViewRotation3D[1][0] == 1.0) && (czm_inverseViewRotation3D[2][0] == 0.0) && ' +
' (czm_inverseViewRotation3D[0][1] == -1.0) && (czm_inverseViewRotation3D[1][1] == 0.0) && (czm_inverseViewRotation3D[2][1] == 0.0) && ' +
' (czm_inverseViewRotation3D[0][2] == 0.0) && (czm_inverseViewRotation3D[1][2] == 0.0) && (czm_inverseViewRotation3D[2][2] == 1.0) ' +
' ); ' +
'}';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_projection', function() {
var us = context.uniformState;
us.update(createFrameState(context, createMockCamera(
undefined,
new Matrix4(
1.0, 2.0, 3.0, 4.0,
5.0, 6.0, 7.0, 8.0,
9.0, 10.0, 11.0, 12.0,
13.0, 14.0, 15.0, 16.0))));
var fs =
'void main() { ' +
' bool b0 = (czm_projection[0][0] == 1.0) && (czm_projection[1][0] == 2.0) && (czm_projection[2][0] == 3.0) && (czm_projection[3][0] == 4.0); ' +
' bool b1 = (czm_projection[0][1] == 5.0) && (czm_projection[1][1] == 6.0) && (czm_projection[2][1] == 7.0) && (czm_projection[3][1] == 8.0); ' +
' bool b2 = (czm_projection[0][2] == 9.0) && (czm_projection[1][2] == 10.0) && (czm_projection[2][2] == 11.0) && (czm_projection[3][2] == 12.0); ' +
' bool b3 = (czm_projection[0][3] == 13.0) && (czm_projection[1][3] == 14.0) && (czm_projection[2][3] == 15.0) && (czm_projection[3][3] == 16.0); ' +
' gl_FragColor = vec4(b0 && b1 && b2 && b3); ' +
'}';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_inverseProjection', function() {
var us = context.uniformState;
us.update(createFrameState(context, createMockCamera(
undefined,
new Matrix4(
0.0, -1.0, 0.0, 1.0,
1.0, 0.0, 0.0, 2.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0))));
var fs =
'void main() { ' +
' bool b0 = (czm_inverseProjection[0][0] == 0.0) && (czm_inverseProjection[1][0] == 1.0) && (czm_inverseProjection[2][0] == 0.0) && (czm_inverseProjection[3][0] == -2.0); ' +
' bool b1 = (czm_inverseProjection[0][1] == -1.0) && (czm_inverseProjection[1][1] == 0.0) && (czm_inverseProjection[2][1] == 0.0) && (czm_inverseProjection[3][1] == 1.0); ' +
' bool b2 = (czm_inverseProjection[0][2] == 0.0) && (czm_inverseProjection[1][2] == 0.0) && (czm_inverseProjection[2][2] == 1.0) && (czm_inverseProjection[3][2] == 0.0); ' +
' bool b3 = (czm_inverseProjection[0][3] == 0.0) && (czm_inverseProjection[1][3] == 0.0) && (czm_inverseProjection[2][3] == 0.0) && (czm_inverseProjection[3][3] == 1.0); ' +
' gl_FragColor = vec4(b0 && b1 && b2 && b3); ' +
'}';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_inverseProjection in 2D', function() {
var frameState = createFrameState(context, createMockCamera(
undefined,
new Matrix4(
0.0, -1.0, 0.0, 1.0,
1.0, 0.0, 0.0, 2.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0)));
frameState.mode = SceneMode.SCENE2D;
var us = context.uniformState;
us.update(frameState);
var fs =
'void main() { ' +
' bool b0 = (czm_inverseProjection[0][0] == 0.0) && (czm_inverseProjection[1][0] == 0.0) && (czm_inverseProjection[2][0] == 0.0) && (czm_inverseProjection[3][0] == 0.0); ' +
' bool b1 = (czm_inverseProjection[0][1] == 0.0) && (czm_inverseProjection[1][1] == 0.0) && (czm_inverseProjection[2][1] == 0.0) && (czm_inverseProjection[3][1] == 0.0); ' +
' bool b2 = (czm_inverseProjection[0][2] == 0.0) && (czm_inverseProjection[1][2] == 0.0) && (czm_inverseProjection[2][2] == 0.0) && (czm_inverseProjection[3][2] == 0.0); ' +
' bool b3 = (czm_inverseProjection[0][3] == 0.0) && (czm_inverseProjection[1][3] == 0.0) && (czm_inverseProjection[2][3] == 0.0) && (czm_inverseProjection[3][3] == 0.0); ' +
' gl_FragColor = vec4(b0 && b1 && b2 && b3); ' +
'}';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_inverseProjection in 3D with orthographic projection', function() {
var frameState = createFrameState(context, createMockCamera(
undefined,
new Matrix4(
0.0, -1.0, 0.0, 1.0,
1.0, 0.0, 0.0, 2.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0)));
var frustum = new OrthographicFrustum();
frustum.aspectRatio = 1.0;
frustum.width = 1.0;
frameState.camera.frustum = frustum;
var us = context.uniformState;
us.update(frameState);
var fs =
'void main() { ' +
' bool b0 = (czm_inverseProjection[0][0] == 0.0) && (czm_inverseProjection[1][0] == 0.0) && (czm_inverseProjection[2][0] == 0.0) && (czm_inverseProjection[3][0] == 0.0); ' +
' bool b1 = (czm_inverseProjection[0][1] == 0.0) && (czm_inverseProjection[1][1] == 0.0) && (czm_inverseProjection[2][1] == 0.0) && (czm_inverseProjection[3][1] == 0.0); ' +
' bool b2 = (czm_inverseProjection[0][2] == 0.0) && (czm_inverseProjection[1][2] == 0.0) && (czm_inverseProjection[2][2] == 0.0) && (czm_inverseProjection[3][2] == 0.0); ' +
' bool b3 = (czm_inverseProjection[0][3] == 0.0) && (czm_inverseProjection[1][3] == 0.0) && (czm_inverseProjection[2][3] == 0.0) && (czm_inverseProjection[3][3] == 0.0); ' +
' gl_FragColor = vec4(b0 && b1 && b2 && b3); ' +
'}';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_infiniteProjection', function() {
var us = context.uniformState;
us.update(createFrameState(context, createMockCamera(undefined, undefined,
new Matrix4(1.0, 2.0, 3.0, 4.0,
5.0, 6.0, 7.0, 8.0,
9.0, 10.0, 11.0, 12.0,
13.0, 14.0, 15.0, 16.0))));
var fs =
'void main() { ' +
' bool b0 = (czm_infiniteProjection[0][0] == 1.0) && (czm_infiniteProjection[1][0] == 2.0) && (czm_infiniteProjection[2][0] == 3.0) && (czm_infiniteProjection[3][0] == 4.0); ' +
' bool b1 = (czm_infiniteProjection[0][1] == 5.0) && (czm_infiniteProjection[1][1] == 6.0) && (czm_infiniteProjection[2][1] == 7.0) && (czm_infiniteProjection[3][1] == 8.0); ' +
' bool b2 = (czm_infiniteProjection[0][2] == 9.0) && (czm_infiniteProjection[1][2] == 10.0) && (czm_infiniteProjection[2][2] == 11.0) && (czm_infiniteProjection[3][2] == 12.0); ' +
' bool b3 = (czm_infiniteProjection[0][3] == 13.0) && (czm_infiniteProjection[1][3] == 14.0) && (czm_infiniteProjection[2][3] == 15.0) && (czm_infiniteProjection[3][3] == 16.0); ' +
' gl_FragColor = vec4(b0 && b1 && b2 && b3); ' +
'}';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_modelView', function() {
var us = context.uniformState;
us.update(createFrameState(context, createMockCamera(
new Matrix4(
1.0, 0.0, 0.0, 1.0,
0.0, 1.0, 0.0, 1.0,
0.0, 0.0, 1.0, 1.0,
0.0, 0.0, 0.0, 1.0))));
var fs =
'void main() { ' +
' bool b0 = (czm_modelView[0][0] == 2.0) && (czm_modelView[1][0] == 0.0) && (czm_modelView[2][0] == 0.0) && (czm_modelView[3][0] == 1.0); ' +
' bool b1 = (czm_modelView[0][1] == 0.0) && (czm_modelView[1][1] == 2.0) && (czm_modelView[2][1] == 0.0) && (czm_modelView[3][1] == 1.0); ' +
' bool b2 = (czm_modelView[0][2] == 0.0) && (czm_modelView[1][2] == 0.0) && (czm_modelView[2][2] == 2.0) && (czm_modelView[3][2] == 1.0); ' +
' bool b3 = (czm_modelView[0][3] == 0.0) && (czm_modelView[1][3] == 0.0) && (czm_modelView[2][3] == 0.0) && (czm_modelView[3][3] == 1.0); ' +
' gl_FragColor = vec4(b0 && b1 && b2 && b3); ' +
'}';
var m = new Matrix4(
2.0, 0.0, 0.0, 0.0,
0.0, 2.0, 0.0, 0.0,
0.0, 0.0, 2.0, 0.0,
0.0, 0.0, 0.0, 1.0);
expect({
context : context,
fragmentShader : fs,
modelMatrix : m
}).contextToRender();
});
it('has czm_modelView3D', function() {
var us = context.uniformState;
us.update(createFrameState(context, createMockCamera(
new Matrix4(
1.0, 0.0, 0.0, 1.0,
0.0, 1.0, 0.0, 1.0,
0.0, 0.0, 1.0, 1.0,
0.0, 0.0, 0.0, 1.0))));
var fs =
'void main() { ' +
' bool b0 = (czm_modelView3D[0][0] == 2.0) && (czm_modelView3D[1][0] == 0.0) && (czm_modelView3D[2][0] == 0.0) && (czm_modelView3D[3][0] == 1.0); ' +
' bool b1 = (czm_modelView3D[0][1] == 0.0) && (czm_modelView3D[1][1] == 2.0) && (czm_modelView3D[2][1] == 0.0) && (czm_modelView3D[3][1] == 1.0); ' +
' bool b2 = (czm_modelView3D[0][2] == 0.0) && (czm_modelView3D[1][2] == 0.0) && (czm_modelView3D[2][2] == 2.0) && (czm_modelView3D[3][2] == 1.0); ' +
' bool b3 = (czm_modelView3D[0][3] == 0.0) && (czm_modelView3D[1][3] == 0.0) && (czm_modelView3D[2][3] == 0.0) && (czm_modelView3D[3][3] == 1.0); ' +
' gl_FragColor = vec4(b0 && b1 && b2 && b3); ' +
'}';
var m = new Matrix4(
2.0, 0.0, 0.0, 0.0,
0.0, 2.0, 0.0, 0.0,
0.0, 0.0, 2.0, 0.0,
0.0, 0.0, 0.0, 1.0);
expect({
context : context,
fragmentShader : fs,
modelMatrix : m
}).contextToRender();
});
it('has czm_modelViewRelativeToEye', function() {
var us = context.uniformState;
us.update(createFrameState(context, createMockCamera(
new Matrix4(
1.0, 0.0, 0.0, 1.0,
0.0, 1.0, 0.0, 1.0,
0.0, 0.0, 1.0, 1.0,
0.0, 0.0, 0.0, 1.0))));
var fs =
'void main() { ' +
' bool b0 = (czm_modelViewRelativeToEye[0][0] == 2.0) && (czm_modelViewRelativeToEye[1][0] == 0.0) && (czm_modelViewRelativeToEye[2][0] == 0.0) && (czm_modelViewRelativeToEye[3][0] == 0.0); ' +
' bool b1 = (czm_modelViewRelativeToEye[0][1] == 0.0) && (czm_modelViewRelativeToEye[1][1] == 2.0) && (czm_modelViewRelativeToEye[2][1] == 0.0) && (czm_modelViewRelativeToEye[3][1] == 0.0); ' +
' bool b2 = (czm_modelViewRelativeToEye[0][2] == 0.0) && (czm_modelViewRelativeToEye[1][2] == 0.0) && (czm_modelViewRelativeToEye[2][2] == 2.0) && (czm_modelViewRelativeToEye[3][2] == 0.0); ' +
' bool b3 = (czm_modelViewRelativeToEye[0][3] == 0.0) && (czm_modelViewRelativeToEye[1][3] == 0.0) && (czm_modelViewRelativeToEye[2][3] == 0.0) && (czm_modelViewRelativeToEye[3][3] == 1.0); ' +
' gl_FragColor = vec4(b0 && b1 && b2 && b3); ' +
'}';
var m = new Matrix4(
2.0, 0.0, 0.0, 0.0,
0.0, 2.0, 0.0, 0.0,
0.0, 0.0, 2.0, 0.0,
0.0, 0.0, 0.0, 1.0);
expect({
context : context,
fragmentShader : fs,
modelMatrix : m
}).contextToRender();
});
it('has czm_inverseModelView', function() {
var us = context.uniformState;
us.update(createFrameState(context, createMockCamera(Matrix4.clone(Matrix4.IDENTITY))));
var fs =
'void main() { ' +
' bool b0 = (czm_inverseModelView[0][0] == 0.0) && (czm_inverseModelView[1][0] == 1.0) && (czm_inverseModelView[2][0] == 0.0) && (czm_inverseModelView[3][0] == -2.0); ' +
' bool b1 = (czm_inverseModelView[0][1] == -1.0) && (czm_inverseModelView[1][1] == 0.0) && (czm_inverseModelView[2][1] == 0.0) && (czm_inverseModelView[3][1] == 1.0); ' +
' bool b2 = (czm_inverseModelView[0][2] == 0.0) && (czm_inverseModelView[1][2] == 0.0) && (czm_inverseModelView[2][2] == 1.0) && (czm_inverseModelView[3][2] == 0.0); ' +
' bool b3 = (czm_inverseModelView[0][3] == 0.0) && (czm_inverseModelView[1][3] == 0.0) && (czm_inverseModelView[2][3] == 0.0) && (czm_inverseModelView[3][3] == 1.0); ' +
' gl_FragColor = vec4(b0 && b1 && b2 && b3); ' +
'}';
var m = new Matrix4(
0.0, -1.0, 0.0, 1.0,
1.0, 0.0, 0.0, 2.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0);
expect({
context : context,
fragmentShader : fs,
modelMatrix : m
}).contextToRender();
});
it('has czm_inverseModelView3D', function() {
var us = context.uniformState;
us.update(createFrameState(context, createMockCamera(Matrix4.clone(Matrix4.IDENTITY))));
var fs =
'void main() { ' +
' bool b0 = (czm_inverseModelView3D[0][0] == 0.0) && (czm_inverseModelView3D[1][0] == 1.0) && (czm_inverseModelView3D[2][0] == 0.0) && (czm_inverseModelView3D[3][0] == -2.0); ' +
' bool b1 = (czm_inverseModelView3D[0][1] == -1.0) && (czm_inverseModelView3D[1][1] == 0.0) && (czm_inverseModelView3D[2][1] == 0.0) && (czm_inverseModelView3D[3][1] == 1.0); ' +
' bool b2 = (czm_inverseModelView3D[0][2] == 0.0) && (czm_inverseModelView3D[1][2] == 0.0) && (czm_inverseModelView3D[2][2] == 1.0) && (czm_inverseModelView3D[3][2] == 0.0); ' +
' bool b3 = (czm_inverseModelView3D[0][3] == 0.0) && (czm_inverseModelView3D[1][3] == 0.0) && (czm_inverseModelView3D[2][3] == 0.0) && (czm_inverseModelView3D[3][3] == 1.0); ' +
' gl_FragColor = vec4(b0 && b1 && b2 && b3); ' +
'}';
var m = new Matrix4(
0.0, -1.0, 0.0, 1.0,
1.0, 0.0, 0.0, 2.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0);
expect({
context : context,
fragmentShader : fs,
modelMatrix : m
}).contextToRender();
});
it('has czm_viewProjection', function() {
var us = context.uniformState;
us.update(createFrameState(context, createMockCamera(
new Matrix4(1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 8.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0),
new Matrix4(1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 9.0,
0.0, 0.0, 0.0, 1.0))));
var fs =
'void main() { ' +
' bool b0 = (czm_viewProjection[0][0] == 1.0) && (czm_viewProjection[1][0] == 0.0) && (czm_viewProjection[2][0] == 0.0) && (czm_viewProjection[3][0] == 0.0); ' +
' bool b1 = (czm_viewProjection[0][1] == 0.0) && (czm_viewProjection[1][1] == 1.0) && (czm_viewProjection[2][1] == 0.0) && (czm_viewProjection[3][1] == 8.0); ' +
' bool b2 = (czm_viewProjection[0][2] == 0.0) && (czm_viewProjection[1][2] == 0.0) && (czm_viewProjection[2][2] == 1.0) && (czm_viewProjection[3][2] == 9.0); ' +
' bool b3 = (czm_viewProjection[0][3] == 0.0) && (czm_viewProjection[1][3] == 0.0) && (czm_viewProjection[2][3] == 0.0) && (czm_viewProjection[3][3] == 1.0); ' +
' gl_FragColor = vec4(b0 && b1 && b2 && b3); ' +
'}';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_inverseViewProjection', function() {
var us = context.uniformState;
us.update(createFrameState(context, createMockCamera(
new Matrix4(1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 8.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0),
new Matrix4(1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 9.0,
0.0, 0.0, 0.0, 1.0))));
var fs =
'void main() { ' +
' bool b0 = (czm_inverseViewProjection[0][0] == 1.0) && (czm_inverseViewProjection[1][0] == 0.0) && (czm_inverseViewProjection[2][0] == 0.0) && (czm_inverseViewProjection[3][0] == 0.0); ' +
' bool b1 = (czm_inverseViewProjection[0][1] == 0.0) && (czm_inverseViewProjection[1][1] == 1.0) && (czm_inverseViewProjection[2][1] == 0.0) && (czm_inverseViewProjection[3][1] == -8.0); ' +
' bool b2 = (czm_inverseViewProjection[0][2] == 0.0) && (czm_inverseViewProjection[1][2] == 0.0) && (czm_inverseViewProjection[2][2] == 1.0) && (czm_inverseViewProjection[3][2] == -9.0); ' +
' bool b3 = (czm_inverseViewProjection[0][3] == 0.0) && (czm_inverseViewProjection[1][3] == 0.0) && (czm_inverseViewProjection[2][3] == 0.0) && (czm_inverseViewProjection[3][3] == 1.0); ' +
' gl_FragColor = vec4(b0 && b1 && b2 && b3); ' +
'}';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_modelViewProjection', function() {
var us = context.uniformState;
us.update(createFrameState(context, createMockCamera(
new Matrix4(1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 8.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0),
new Matrix4(1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 9.0,
0.0, 0.0, 0.0, 1.0))));
var fs =
'void main() { ' +
' bool b0 = (czm_modelViewProjection[0][0] == 1.0) && (czm_modelViewProjection[1][0] == 0.0) && (czm_modelViewProjection[2][0] == 0.0) && (czm_modelViewProjection[3][0] == 7.0); ' +
' bool b1 = (czm_modelViewProjection[0][1] == 0.0) && (czm_modelViewProjection[1][1] == 1.0) && (czm_modelViewProjection[2][1] == 0.0) && (czm_modelViewProjection[3][1] == 8.0); ' +
' bool b2 = (czm_modelViewProjection[0][2] == 0.0) && (czm_modelViewProjection[1][2] == 0.0) && (czm_modelViewProjection[2][2] == 1.0) && (czm_modelViewProjection[3][2] == 9.0); ' +
' bool b3 = (czm_modelViewProjection[0][3] == 0.0) && (czm_modelViewProjection[1][3] == 0.0) && (czm_modelViewProjection[2][3] == 0.0) && (czm_modelViewProjection[3][3] == 1.0); ' +
' gl_FragColor = vec4(b0 && b1 && b2 && b3); ' +
'}';
var m = new Matrix4(
1.0, 0.0, 0.0, 7.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0);
expect({
context : context,
fragmentShader : fs,
modelMatrix : m
}).contextToRender();
});
it('has czm_inverseModelViewProjection', function() {
var us = context.uniformState;
us.update(createFrameState(context, createMockCamera(
new Matrix4(1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 8.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0),
new Matrix4(1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 9.0,
0.0, 0.0, 0.0, 1.0))));
var fs =
'void main() { ' +
' bool b0 = (czm_inverseModelViewProjection[0][0] == 1.0) && (czm_inverseModelViewProjection[1][0] == 0.0) && (czm_inverseModelViewProjection[2][0] == 0.0) && (czm_inverseModelViewProjection[3][0] == -7.0); ' +
' bool b1 = (czm_inverseModelViewProjection[0][1] == 0.0) && (czm_inverseModelViewProjection[1][1] == 1.0) && (czm_inverseModelViewProjection[2][1] == 0.0) && (czm_inverseModelViewProjection[3][1] == -8.0); ' +
' bool b2 = (czm_inverseModelViewProjection[0][2] == 0.0) && (czm_inverseModelViewProjection[1][2] == 0.0) && (czm_inverseModelViewProjection[2][2] == 1.0) && (czm_inverseModelViewProjection[3][2] == -9.0); ' +
' bool b3 = (czm_inverseModelViewProjection[0][3] == 0.0) && (czm_inverseModelViewProjection[1][3] == 0.0) && (czm_inverseModelViewProjection[2][3] == 0.0) && (czm_inverseModelViewProjection[3][3] == 1.0); ' +
' gl_FragColor = vec4(b0 && b1 && b2 && b3); ' +
'}';
var m = new Matrix4(
1.0, 0.0, 0.0, 7.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0);
expect({
context : context,
fragmentShader : fs,
modelMatrix : m
}).contextToRender();
});
it('has czm_modelViewProjectionRelativeToEye', function() {
var us = context.uniformState;
us.update(createFrameState(context, createMockCamera(
new Matrix4(1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 8.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0),
new Matrix4(1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 9.0,
0.0, 0.0, 0.0, 1.0))));
var fs =
'void main() { ' +
' bool b0 = (czm_modelViewProjectionRelativeToEye[0][0] == 1.0) && (czm_modelViewProjectionRelativeToEye[1][0] == 0.0) && (czm_modelViewProjectionRelativeToEye[2][0] == 0.0) && (czm_modelViewProjectionRelativeToEye[3][0] == 0.0); ' +
' bool b1 = (czm_modelViewProjectionRelativeToEye[0][1] == 0.0) && (czm_modelViewProjectionRelativeToEye[1][1] == 1.0) && (czm_modelViewProjectionRelativeToEye[2][1] == 0.0) && (czm_modelViewProjectionRelativeToEye[3][1] == 0.0); ' +
' bool b2 = (czm_modelViewProjectionRelativeToEye[0][2] == 0.0) && (czm_modelViewProjectionRelativeToEye[1][2] == 0.0) && (czm_modelViewProjectionRelativeToEye[2][2] == 1.0) && (czm_modelViewProjectionRelativeToEye[3][2] == 9.0); ' +
' bool b3 = (czm_modelViewProjectionRelativeToEye[0][3] == 0.0) && (czm_modelViewProjectionRelativeToEye[1][3] == 0.0) && (czm_modelViewProjectionRelativeToEye[2][3] == 0.0) && (czm_modelViewProjectionRelativeToEye[3][3] == 1.0); ' +
' gl_FragColor = vec4(b0 && b1 && b2 && b3); ' +
'}';
var m = new Matrix4(
1.0, 0.0, 0.0, 7.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0);
expect({
context : context,
fragmentShader : fs,
modelMatrix : m
}).contextToRender();
});
it('has czm_modelViewInfiniteProjection', function() {
var us = context.uniformState;
us.update(createFrameState(context, createMockCamera(
new Matrix4(1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 8.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0),
undefined,
new Matrix4(1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 9.0,
0.0, 0.0, 0.0, 1.0))));
var fs =
'void main() { ' +
' bool b0 = (czm_modelViewInfiniteProjection[0][0] == 1.0) && (czm_modelViewInfiniteProjection[1][0] == 0.0) && (czm_modelViewInfiniteProjection[2][0] == 0.0) && (czm_modelViewInfiniteProjection[3][0] == 7.0); ' +
' bool b1 = (czm_modelViewInfiniteProjection[0][1] == 0.0) && (czm_modelViewInfiniteProjection[1][1] == 1.0) && (czm_modelViewInfiniteProjection[2][1] == 0.0) && (czm_modelViewInfiniteProjection[3][1] == 8.0); ' +
' bool b2 = (czm_modelViewInfiniteProjection[0][2] == 0.0) && (czm_modelViewInfiniteProjection[1][2] == 0.0) && (czm_modelViewInfiniteProjection[2][2] == 1.0) && (czm_modelViewInfiniteProjection[3][2] == 9.0); ' +
' bool b3 = (czm_modelViewInfiniteProjection[0][3] == 0.0) && (czm_modelViewInfiniteProjection[1][3] == 0.0) && (czm_modelViewInfiniteProjection[2][3] == 0.0) && (czm_modelViewInfiniteProjection[3][3] == 1.0); ' +
' gl_FragColor = vec4(b0 && b1 && b2 && b3); ' +
'}';
var m = new Matrix4(
1.0, 0.0, 0.0, 7.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0);
expect({
context : context,
fragmentShader : fs,
modelMatrix : m
}).contextToRender();
});
it('has czm_normal', function() {
var fs =
'void main() { ' +
' gl_FragColor = vec4(' +
' (czm_normal[0][0] == 1.0) && (czm_normal[1][0] == 0.0) && (czm_normal[2][0] == 0.0) && ' +
' (czm_normal[0][1] == 0.0) && (czm_normal[1][1] == 1.0) && (czm_normal[2][1] == 0.0) && ' +
' (czm_normal[0][2] == 0.0) && (czm_normal[1][2] == 0.0) && (czm_normal[2][2] == 1.0) ' +
' ); ' +
'}';
var m = new Matrix4(
1.0, 0.0, 0.0, 7.0,
0.0, 1.0, 0.0, 8.0,
0.0, 0.0, 1.0, 9.0,
0.0, 0.0, 0.0, 1.0);
expect({
context : context,
fragmentShader : fs,
modelMatrix : m
}).contextToRender();
});
it('has czm_inverseNormal', function() {
var fs =
'void main() { ' +
' gl_FragColor = vec4(' +
' (czm_inverseNormal[0][0] == 0.0) && (czm_inverseNormal[1][0] == 1.0) && (czm_inverseNormal[2][0] == 0.0) && ' +
' (czm_inverseNormal[0][1] == -1.0) && (czm_inverseNormal[1][1] == 0.0) && (czm_inverseNormal[2][1] == 0.0) && ' +
' (czm_inverseNormal[0][2] == 0.0) && (czm_inverseNormal[1][2] == 0.0) && (czm_inverseNormal[2][2] == 1.0) ' +
' ); ' +
'}';
var m = new Matrix4(
0.0, -1.0, 0.0, 7.0,
1.0, 0.0, 0.0, 8.0,
0.0, 0.0, 1.0, 9.0,
0.0, 0.0, 0.0, 1.0);
expect({
context : context,
fragmentShader : fs,
modelMatrix : m
}).contextToRender();
});
it('has czm_normal3D', function() {
var fs =
'void main() { ' +
' gl_FragColor = vec4(' +
' (czm_normal3D[0][0] == 1.0) && (czm_normal3D[1][0] == 0.0) && (czm_normal3D[2][0] == 0.0) && ' +
' (czm_normal3D[0][1] == 0.0) && (czm_normal3D[1][1] == 1.0) && (czm_normal3D[2][1] == 0.0) && ' +
' (czm_normal3D[0][2] == 0.0) && (czm_normal3D[1][2] == 0.0) && (czm_normal3D[2][2] == 1.0) ' +
' ); ' +
'}';
var m = new Matrix4(
1.0, 0.0, 0.0, 7.0,
0.0, 1.0, 0.0, 8.0,
0.0, 0.0, 1.0, 9.0,
0.0, 0.0, 0.0, 1.0);
expect({
context : context,
fragmentShader : fs,
modelMatrix : m
}).contextToRender();
});
it('has czm_inverseNormal3D', function() {
var fs =
'void main() { ' +
' gl_FragColor = vec4(' +
' (czm_inverseNormal3D[0][0] == 0.0) && (czm_inverseNormal3D[1][0] == 1.0) && (czm_inverseNormal3D[2][0] == 0.0) && ' +
' (czm_inverseNormal3D[0][1] == -1.0) && (czm_inverseNormal3D[1][1] == 0.0) && (czm_inverseNormal3D[2][1] == 0.0) && ' +
' (czm_inverseNormal3D[0][2] == 0.0) && (czm_inverseNormal3D[1][2] == 0.0) && (czm_inverseNormal3D[2][2] == 1.0) ' +
' ); ' +
'}';
var m = new Matrix4(
0.0, -1.0, 0.0, 7.0,
1.0, 0.0, 0.0, 8.0,
0.0, 0.0, 1.0, 9.0,
0.0, 0.0, 0.0, 1.0);
expect({
context : context,
fragmentShader : fs,
modelMatrix : m
}).contextToRender();
});
it('has czm_encodedCameraPositionMCHigh and czm_encodedCameraPositionMCLow', function() {
var us = context.uniformState;
us.update(createFrameState(context, createMockCamera(undefined, undefined, undefined, new Cartesian3(-1000.0, 0.0, 100000.0))));
var fs =
'void main() { ' +
' bool b = (czm_encodedCameraPositionMCHigh + czm_encodedCameraPositionMCLow == vec3(-1000.0, 0.0, 100000.0)); ' +
' gl_FragColor = vec4(b); ' +
'}';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_entireFrustum', function() {
var us = context.uniformState;
us.update(createFrameState(context, createMockCamera()));
var fs = 'void main() { gl_FragColor = vec4((czm_entireFrustum.x == 1.0) && (czm_entireFrustum.y == 1000.0)); }';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_frustumPlanes', function() {
var us = context.uniformState;
us.update(createFrameState(context, createMockCamera()));
var fs = 'void main() { gl_FragColor = vec4(equal(czm_frustumPlanes, vec4(2.0, -2.0, -1.0, 1.0))); }';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_sunPositionWC', function() {
var us = context.uniformState;
us.update(createFrameState(context, createMockCamera()));
var fs = 'void main() { gl_FragColor = vec4(czm_sunPositionWC != vec3(0.0)); }';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_sunPositionColumbusView', function() {
var us = context.uniformState;
us.update(createFrameState(context, createMockCamera()));
var fs = 'void main() { gl_FragColor = vec4(czm_sunPositionColumbusView != vec3(0.0)); }';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_sunDirectionEC', function() {
var us = context.uniformState;
us.update(createFrameState(context, createMockCamera()));
var fs = 'void main() { gl_FragColor = vec4(czm_sunDirectionEC != vec3(0.0)); }';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_sunDirectionWC', function() {
var us = context.uniformState;
us.update(createFrameState(context, createMockCamera()));
var fs = 'void main() { gl_FragColor = vec4(czm_sunDirectionWC != vec3(0.0)); }';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_moonDirectionEC', function() {
var us = context.uniformState;
us.update(createFrameState(context, createMockCamera()));
var fs = 'void main() { gl_FragColor = vec4(czm_moonDirectionEC != vec3(0.0)); }';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_viewerPositionWC', function() {
var us = context.uniformState;
us.update(createFrameState(context, createMockCamera()));
var fs = 'void main() { gl_FragColor = vec4(czm_viewerPositionWC == vec3(0.0)); }';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_frameNumber', function() {
var fs =
'void main() { ' +
' gl_FragColor = vec4(czm_frameNumber != 0.0); ' +
'}';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_morphTime', function() {
var fs =
'void main() { ' +
' gl_FragColor = vec4(czm_morphTime == 1.0); ' + // 3D
'}';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_temeToPseudoFixed', function() {
var us = context.uniformState;
us.update(createFrameState(context, createMockCamera()));
var fs =
'void main() { ' +
' gl_FragColor = vec4(' +
' (czm_temeToPseudoFixed[0][0] != 0.0) && (czm_temeToPseudoFixed[1][0] != 0.0) && (czm_temeToPseudoFixed[2][0] == 0.0) && ' +
' (czm_temeToPseudoFixed[0][1] != 0.0) && (czm_temeToPseudoFixed[1][1] != 0.0) && (czm_temeToPseudoFixed[2][1] == 0.0) && ' +
' (czm_temeToPseudoFixed[0][2] == 0.0) && (czm_temeToPseudoFixed[1][2] == 0.0) && (czm_temeToPseudoFixed[2][2] == 1.0) ' +
' ); ' +
'}';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_pass and czm_passEnvironment', function() {
var us = context.uniformState;
us.updatePass(Pass.ENVIRONMENT);
var fs =
'void main() { ' +
' gl_FragColor = vec4(czm_pass == czm_passEnvironment);' +
'}';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_pass and czm_passCompute', function() {
var us = context.uniformState;
us.updatePass(Pass.COMPUTE);
var fs =
'void main() { ' +
' gl_FragColor = vec4(czm_pass == czm_passCompute);' +
'}';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_pass and czm_passGlobe', function() {
var us = context.uniformState;
us.updatePass(Pass.GLOBE);
var fs =
'void main() { ' +
' gl_FragColor = vec4(czm_pass == czm_passGlobe);' +
'}';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_pass and czm_passTerrainClassification', function() {
var us = context.uniformState;
us.updatePass(Pass.TERRAIN_CLASSIFICATION);
var fs =
'void main() { ' +
' gl_FragColor = vec4(czm_pass == czm_passTerrainClassification);' +
'}';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_pass and czm_passCesium3DTileClassification', function() {
var us = context.uniformState;
us.updatePass(Pass.CESIUM_3D_TILE_CLASSIFICATION);
var fs =
'void main() { ' +
' gl_FragColor = vec4(czm_pass == czm_passCesium3DTileClassification);' +
'}';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_pass and czm_passOpaque', function() {
var us = context.uniformState;
us.updatePass(Pass.OPAQUE);
var fs =
'void main() { ' +
' gl_FragColor = vec4(czm_pass == czm_passOpaque);' +
'}';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_pass and czm_passTranslucent', function() {
var us = context.uniformState;
us.updatePass(Pass.TRANSLUCENT);
var fs =
'void main() { ' +
' gl_FragColor = vec4(czm_pass == czm_passTranslucent);' +
'}';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_pass and czm_passOverlay', function() {
var us = context.uniformState;
us.updatePass(Pass.OVERLAY);
var fs =
'void main() { ' +
' gl_FragColor = vec4(czm_pass == czm_passOverlay);' +
'}';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_sceneMode', function() {
var fs =
'void main() { ' +
' gl_FragColor = vec4(czm_sceneMode == 3.0); ' + // 3D
'}';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_sceneMode2D', function() {
var fs =
'void main() { ' +
' gl_FragColor = vec4(czm_sceneMode2D == 2.0); ' +
'}';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_sceneModeColumbusView', function() {
var fs =
'void main() { ' +
' gl_FragColor = vec4(czm_sceneModeColumbusView == 1.0); ' +
'}';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_sceneMode3D', function() {
var fs =
'void main() { ' +
' gl_FragColor = vec4(czm_sceneMode3D == 3.0); ' +
'}';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_sceneModeMorphing', function() {
var fs =
'void main() { ' +
' gl_FragColor = vec4(czm_sceneModeMorphing == 0.0); ' +
'}';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_eyeHeight2D == 0,0 in Scene3D', function() {
var fs =
'void main() { ' +
' gl_FragColor = vec4(czm_eyeHeight2D.x == 0.0, czm_eyeHeight2D.y == 0.0, 1.0, 1.0); ' +
'}';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_eyeHeight2D in Scene2D', function() {
var us = context.uniformState;
var camera = createCamera();
var frustum = new OrthographicOffCenterFrustum();
frustum.near = 1.0;
frustum.far = 2.0;
frustum.left = -2.0;
frustum.right = 2.0;
frustum.top = 1.0;
frustum.bottom = -1.0;
camera.frustum = frustum;
var frameState = createFrameState(context, camera);
frameState.mode = SceneMode.SCENE2D;
us.update(frameState);
var fs =
'void main() { ' +
' gl_FragColor = vec4(czm_eyeHeight2D.x == 2.0, czm_eyeHeight2D.y == 4.0, 1.0, 1.0); ' +
'}';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_imagerySplitPosition', function() {
var fs =
'void main() { ' +
' gl_FragColor = vec4(czm_imagerySplitPosition == 0.0); ' +
'}';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_backgroundColor', function() {
var frameState = createFrameState(context, createMockCamera());
frameState.backgroundColor = new Color(0.0, 0.25, 0.75, 1.0);
context.uniformState.update(frameState);
var fs =
'void main() { ' +
' gl_FragColor = vec4(czm_backgroundColor.r == 0.0, czm_backgroundColor.g == 0.25, czm_backgroundColor.b == 0.75, czm_backgroundColor.a == 1.0); ' +
'}';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
it('has czm_minimumDisableDepthTestDistance', function() {
var frameState = createFrameState(context, createMockCamera());
context.uniformState.update(frameState);
var fs =
'void main() {' +
' gl_FragColor = vec4(czm_minimumDisableDepthTestDistance == 0.0);' +
'}';
expect({
context : context,
fragmentShader : fs
}).contextToRender();
});
}, 'WebGL');
| apache-2.0 |
nakul02/incubator-systemml | src/test/java/org/apache/sysml/test/integration/functions/binary/matrix/ElementwiseAdditionTest.java | 8129 | /*
* 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.sysml.test.integration.functions.binary.matrix;
import org.junit.Test;
import org.apache.sysml.api.DMLException;
import org.apache.sysml.test.integration.AutomatedTestBase;
import org.apache.sysml.test.integration.TestConfiguration;
public class ElementwiseAdditionTest extends AutomatedTestBase
{
private final static String TEST_DIR = "functions/binary/matrix/";
private final static String TEST_CLASS_DIR = TEST_DIR + ElementwiseAdditionTest.class.getSimpleName() + "/";
@Override
public void setUp() {
// positive tests
addTestConfiguration("DenseTest",
new TestConfiguration(TEST_CLASS_DIR, "ElementwiseAdditionTest", new String[] { "c" }));
addTestConfiguration("SparseTest",
new TestConfiguration(TEST_CLASS_DIR, "ElementwiseAdditionTest", new String[] { "c" }));
addTestConfiguration("EmptyTest",
new TestConfiguration(TEST_CLASS_DIR, "ElementwiseAdditionTest", new String[] { "c" }));
addTestConfiguration("WrongDimensionLessRowsTest",
new TestConfiguration(TEST_CLASS_DIR, "ElementwiseAdditionVariableDimensionsTest", new String[] { "c" }));
addTestConfiguration("WrongDimensionMoreRowsTest",
new TestConfiguration(TEST_CLASS_DIR, "ElementwiseAdditionVariableDimensionsTest", new String[] { "c" }));
addTestConfiguration("WrongDimensionLessColsTest",
new TestConfiguration(TEST_CLASS_DIR, "ElementwiseAdditionVariableDimensionsTest", new String[] { "c" }));
addTestConfiguration("WrongDimensionMoreColsTest",
new TestConfiguration(TEST_CLASS_DIR, "ElementwiseAdditionVariableDimensionsTest", new String[] { "c" }));
addTestConfiguration("WrongDimensionLessRowsLessColsTest",
new TestConfiguration(TEST_CLASS_DIR, "ElementwiseAdditionVariableDimensionsTest", new String[] { "c" }));
addTestConfiguration("WrongDimensionMoreRowsMoreColsTest",
new TestConfiguration(TEST_CLASS_DIR, "ElementwiseAdditionVariableDimensionsTest", new String[] { "c" }));
addTestConfiguration("WrongDimensionLessRowsMoreColsTest",
new TestConfiguration(TEST_CLASS_DIR, "ElementwiseAdditionVariableDimensionsTest", new String[] { "c" }));
addTestConfiguration("WrongDimensionMoreRowsLessColsTest",
new TestConfiguration(TEST_CLASS_DIR, "ElementwiseAdditionVariableDimensionsTest", new String[] { "c" }));
// negative tests
}
@Test
public void testDense() {
int rows = 10;
int cols = 10;
TestConfiguration config = availableTestConfigurations.get("DenseTest");
config.addVariable("rows", rows);
config.addVariable("cols", cols);
loadTestConfiguration(config);
double[][] a = getRandomMatrix(rows, cols, -1, 1, 1, -1);
double[][] b = getRandomMatrix(rows, cols, -1, 1, 1, -1);
double[][] c = new double[rows][cols];
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
c[i][j] = a[i][j] + b[i][j];
}
}
writeInputMatrix("a", a);
writeInputMatrix("b", b);
writeExpectedMatrix("c", c);
runTest();
compareResults();
}
@Test
public void testSparse() {
int rows = 50;
int cols = 50;
TestConfiguration config = availableTestConfigurations.get("SparseTest");
config.addVariable("rows", rows);
config.addVariable("cols", cols);
loadTestConfiguration(config);
double[][] a = getRandomMatrix(rows, cols, -1, 1, 0.05, -1);
double[][] b = getRandomMatrix(rows, cols, -1, 1, 0.05, -1);
double[][] c = new double[rows][cols];
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
c[i][j] = a[i][j] + b[i][j];
}
}
writeInputMatrix("a", a);
writeInputMatrix("b", b);
writeExpectedMatrix("c", c);
runTest();
compareResults();
}
@Test
public void testWrongDimensionsLessRows() {
int rows1 = 8;
int cols1 = 10;
int rows2 = 10;
int cols2 = 10;
TestConfiguration config = availableTestConfigurations.get("WrongDimensionLessRowsTest");
config.addVariable("rows1", rows1);
config.addVariable("cols1", cols1);
config.addVariable("rows2", rows2);
config.addVariable("cols2", cols2);
loadTestConfiguration(config);
runTest(true, DMLException.class);
}
@Test
public void testWrongDimensionsMoreRows() {
int rows1 = 12;
int cols1 = 10;
int rows2 = 10;
int cols2 = 10;
TestConfiguration config = availableTestConfigurations.get("WrongDimensionMoreRowsTest");
config.addVariable("rows1", rows1);
config.addVariable("cols1", cols1);
config.addVariable("rows2", rows2);
config.addVariable("cols2", cols2);
loadTestConfiguration(config);
runTest(true, DMLException.class);
}
@Test
public void testWrongDimensionsLessCols() {
int rows1 = 10;
int cols1 = 8;
int rows2 = 10;
int cols2 = 10;
TestConfiguration config = availableTestConfigurations.get("WrongDimensionLessColsTest");
config.addVariable("rows1", rows1);
config.addVariable("cols1", cols1);
config.addVariable("rows2", rows2);
config.addVariable("cols2", cols2);
loadTestConfiguration(config);
runTest(true, DMLException.class);
}
@Test
public void testWrongDimensionsMoreCols() {
int rows1 = 10;
int cols1 = 12;
int rows2 = 10;
int cols2 = 10;
TestConfiguration config = availableTestConfigurations.get("WrongDimensionMoreColsTest");
config.addVariable("rows1", rows1);
config.addVariable("cols1", cols1);
config.addVariable("rows2", rows2);
config.addVariable("cols2", cols2);
loadTestConfiguration(config);
runTest(true, DMLException.class);
}
@Test
public void testWrongDimensionsLessRowsLessCols() {
int rows1 = 8;
int cols1 = 8;
int rows2 = 10;
int cols2 = 10;
TestConfiguration config = availableTestConfigurations.get("WrongDimensionLessRowsLessColsTest");
config.addVariable("rows1", rows1);
config.addVariable("cols1", cols1);
config.addVariable("rows2", rows2);
config.addVariable("cols2", cols2);
loadTestConfiguration(config);
runTest(true, DMLException.class);
}
@Test
public void testWrongDimensionsMoreRowsMoreCols() {
int rows1 = 12;
int cols1 = 12;
int rows2 = 10;
int cols2 = 10;
TestConfiguration config = availableTestConfigurations.get("WrongDimensionMoreRowsMoreColsTest");
config.addVariable("rows1", rows1);
config.addVariable("cols1", cols1);
config.addVariable("rows2", rows2);
config.addVariable("cols2", cols2);
loadTestConfiguration(config);
runTest(true, DMLException.class);
}
@Test
public void testWrongDimensionsLessRowsMoreCols() {
int rows1 = 8;
int cols1 = 12;
int rows2 = 10;
int cols2 = 10;
TestConfiguration config = availableTestConfigurations.get("WrongDimensionLessRowsMoreColsTest");
config.addVariable("rows1", rows1);
config.addVariable("cols1", cols1);
config.addVariable("rows2", rows2);
config.addVariable("cols2", cols2);
loadTestConfiguration(config);
runTest(true, DMLException.class);
}
@Test
public void testWrongDimensionsMoreRowsLessCols() {
int rows1 = 12;
int cols1 = 8;
int rows2 = 10;
int cols2 = 10;
TestConfiguration config = availableTestConfigurations.get("WrongDimensionMoreRowsLessColsTest");
config.addVariable("rows1", rows1);
config.addVariable("cols1", cols1);
config.addVariable("rows2", rows2);
config.addVariable("cols2", cols2);
loadTestConfiguration(config);
runTest(true, DMLException.class);
}
}
| apache-2.0 |
KalicyZhou/incubator-weex | android/sdk/src/main/java/com/taobao/weex/appfram/websocket/IWebSocketAdapterFactory.java | 990 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.taobao.weex.appfram.websocket;
/**
* Created by moxun on 16/12/28.
*/
public interface IWebSocketAdapterFactory {
IWebSocketAdapter createWebSocketAdapter();
}
| apache-2.0 |
jessicastillop/geojsoncesium | Source/Scene/EllipsoidPrimitive.js | 18082 | define([
'../Core/BoundingSphere',
'../Core/BoxGeometry',
'../Core/Cartesian3',
'../Core/combine',
'../Core/defaultValue',
'../Core/defined',
'../Core/destroyObject',
'../Core/DeveloperError',
'../Core/Matrix4',
'../Core/VertexFormat',
'../Renderer/BufferUsage',
'../Renderer/DrawCommand',
'../Renderer/Pass',
'../Renderer/RenderState',
'../Renderer/ShaderProgram',
'../Renderer/ShaderSource',
'../Renderer/VertexArray',
'../Shaders/EllipsoidFS',
'../Shaders/EllipsoidVS',
'./BlendingState',
'./CullFace',
'./Material',
'./SceneMode'
], function(
BoundingSphere,
BoxGeometry,
Cartesian3,
combine,
defaultValue,
defined,
destroyObject,
DeveloperError,
Matrix4,
VertexFormat,
BufferUsage,
DrawCommand,
Pass,
RenderState,
ShaderProgram,
ShaderSource,
VertexArray,
EllipsoidFS,
EllipsoidVS,
BlendingState,
CullFace,
Material,
SceneMode) {
'use strict';
var attributeLocations = {
position : 0
};
/**
* A renderable ellipsoid. It can also draw spheres when the three {@link EllipsoidPrimitive#radii} components are equal.
* <p>
* This is only supported in 3D. The ellipsoid is not shown in 2D or Columbus view.
* </p>
*
* @alias EllipsoidPrimitive
* @constructor
*
* @param {Object} [options] Object with the following properties:
* @param {Cartesian3} [options.center=Cartesian3.ZERO] The center of the ellipsoid in the ellipsoid's model coordinates.
* @param {Cartesian3} [options.radii] The radius of the ellipsoid along the <code>x</code>, <code>y</code>, and <code>z</code> axes in the ellipsoid's model coordinates.
* @param {Matrix4} [options.modelMatrix=Matrix4.IDENTITY] The 4x4 transformation matrix that transforms the ellipsoid from model to world coordinates.
* @param {Boolean} [options.show=true] Determines if this primitive will be shown.
* @param {Material} [options.material=Material.ColorType] The surface appearance of the primitive.
* @param {Object} [options.id] A user-defined object to return when the instance is picked with {@link Scene#pick}
* @param {Boolean} [options.debugShowBoundingVolume=false] For debugging only. Determines if this primitive's commands' bounding spheres are shown.
*
* @private
*/
function EllipsoidPrimitive(options) {
options = defaultValue(options, defaultValue.EMPTY_OBJECT);
/**
* The center of the ellipsoid in the ellipsoid's model coordinates.
* <p>
* The default is {@link Cartesian3.ZERO}.
* </p>
*
* @type {Cartesian3}
* @default {@link Cartesian3.ZERO}
*
* @see EllipsoidPrimitive#modelMatrix
*/
this.center = Cartesian3.clone(defaultValue(options.center, Cartesian3.ZERO));
this._center = new Cartesian3();
/**
* The radius of the ellipsoid along the <code>x</code>, <code>y</code>, and <code>z</code> axes in the ellipsoid's model coordinates.
* When these are the same, the ellipsoid is a sphere.
* <p>
* The default is <code>undefined</code>. The ellipsoid is not drawn until a radii is provided.
* </p>
*
* @type {Cartesian3}
* @default undefined
*
*
* @example
* // A sphere with a radius of 2.0
* e.radii = new Cesium.Cartesian3(2.0, 2.0, 2.0);
*
* @see EllipsoidPrimitive#modelMatrix
*/
this.radii = Cartesian3.clone(options.radii);
this._radii = new Cartesian3();
this._oneOverEllipsoidRadiiSquared = new Cartesian3();
this._boundingSphere = new BoundingSphere();
/**
* The 4x4 transformation matrix that transforms the ellipsoid from model to world coordinates.
* When this is the identity matrix, the ellipsoid is drawn in world coordinates, i.e., Earth's WGS84 coordinates.
* Local reference frames can be used by providing a different transformation matrix, like that returned
* by {@link Transforms.eastNorthUpToFixedFrame}.
*
* @type {Matrix4}
* @default {@link Matrix4.IDENTITY}
*
* @example
* var origin = Cesium.Cartesian3.fromDegrees(-95.0, 40.0, 200000.0);
* e.modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(origin);
*/
this.modelMatrix = Matrix4.clone(defaultValue(options.modelMatrix, Matrix4.IDENTITY));
this._modelMatrix = new Matrix4();
this._computedModelMatrix = new Matrix4();
/**
* Determines if the ellipsoid primitive will be shown.
*
* @type {Boolean}
* @default true
*/
this.show = defaultValue(options.show, true);
/**
* The surface appearance of the ellipsoid. This can be one of several built-in {@link Material} objects or a custom material, scripted with
* {@link https://github.com/AnalyticalGraphicsInc/cesium/wiki/Fabric|Fabric}.
* <p>
* The default material is <code>Material.ColorType</code>.
* </p>
*
* @type {Material}
* @default Material.fromType(Material.ColorType)
*
*
* @example
* // 1. Change the color of the default material to yellow
* e.material.uniforms.color = new Cesium.Color(1.0, 1.0, 0.0, 1.0);
*
* // 2. Change material to horizontal stripes
* e.material = Cesium.Material.fromType(Cesium.Material.StripeType);
*
* @see {@link https://github.com/AnalyticalGraphicsInc/cesium/wiki/Fabric|Fabric}
*/
this.material = defaultValue(options.material, Material.fromType(Material.ColorType));
this._material = undefined;
this._translucent = undefined;
/**
* User-defined object returned when the ellipsoid is picked.
*
* @type Object
*
* @default undefined
*
* @see Scene#pick
*/
this.id = options.id;
this._id = undefined;
/**
* This property is for debugging only; it is not for production use nor is it optimized.
* <p>
* Draws the bounding sphere for each draw command in the primitive.
* </p>
*
* @type {Boolean}
*
* @default false
*/
this.debugShowBoundingVolume = defaultValue(options.debugShowBoundingVolume, false);
/**
* @private
*/
this.onlySunLighting = defaultValue(options.onlySunLighting, false);
this._onlySunLighting = false;
/**
* @private
*/
this._depthTestEnabled = defaultValue(options.depthTestEnabled, true);
this._sp = undefined;
this._rs = undefined;
this._va = undefined;
this._pickSP = undefined;
this._pickId = undefined;
this._colorCommand = new DrawCommand({
owner : defaultValue(options._owner, this)
});
this._pickCommand = new DrawCommand({
owner : defaultValue(options._owner, this)
});
var that = this;
this._uniforms = {
u_radii : function() {
return that.radii;
},
u_oneOverEllipsoidRadiiSquared : function() {
return that._oneOverEllipsoidRadiiSquared;
}
};
this._pickUniforms = {
czm_pickColor : function() {
return that._pickId.color;
}
};
}
function getVertexArray(context) {
var vertexArray = context.cache.ellipsoidPrimitive_vertexArray;
if (defined(vertexArray)) {
return vertexArray;
}
var geometry = BoxGeometry.createGeometry(BoxGeometry.fromDimensions({
dimensions : new Cartesian3(2.0, 2.0, 2.0),
vertexFormat : VertexFormat.POSITION_ONLY
}));
vertexArray = VertexArray.fromGeometry({
context : context,
geometry : geometry,
attributeLocations : attributeLocations,
bufferUsage : BufferUsage.STATIC_DRAW,
interleave : true
});
context.cache.ellipsoidPrimitive_vertexArray = vertexArray;
return vertexArray;
}
/**
* Called when {@link Viewer} or {@link CesiumWidget} render the scene to
* get the draw commands needed to render this primitive.
* <p>
* Do not call this function directly. This is documented just to
* list the exceptions that may be propagated when the scene is rendered:
* </p>
*
* @exception {DeveloperError} this.material must be defined.
*/
EllipsoidPrimitive.prototype.update = function(frameState) {
if (!this.show ||
(frameState.mode !== SceneMode.SCENE3D) ||
(!defined(this.center)) ||
(!defined(this.radii))) {
return;
}
//>>includeStart('debug', pragmas.debug);
if (!defined(this.material)) {
throw new DeveloperError('this.material must be defined.');
}
//>>includeEnd('debug');
var context = frameState.context;
var translucent = this.material.isTranslucent();
var translucencyChanged = this._translucent !== translucent;
if (!defined(this._rs) || translucencyChanged) {
this._translucent = translucent;
// If this render state is ever updated to use a non-default
// depth range, the hard-coded values in EllipsoidVS.glsl need
// to be updated as well.
this._rs = RenderState.fromCache({
// Cull front faces - not back faces - so the ellipsoid doesn't
// disappear if the viewer enters the bounding box.
cull : {
enabled : true,
face : CullFace.FRONT
},
depthTest : {
enabled : this._depthTestEnabled
},
// Only write depth when EXT_frag_depth is supported since the depth for
// the bounding box is wrong; it is not the true depth of the ray casted ellipsoid.
depthMask : !translucent && context.fragmentDepth,
blending : translucent ? BlendingState.ALPHA_BLEND : undefined
});
}
if (!defined(this._va)) {
this._va = getVertexArray(context);
}
var boundingSphereDirty = false;
var radii = this.radii;
if (!Cartesian3.equals(this._radii, radii)) {
Cartesian3.clone(radii, this._radii);
var r = this._oneOverEllipsoidRadiiSquared;
r.x = 1.0 / (radii.x * radii.x);
r.y = 1.0 / (radii.y * radii.y);
r.z = 1.0 / (radii.z * radii.z);
boundingSphereDirty = true;
}
if (!Matrix4.equals(this.modelMatrix, this._modelMatrix) || !Cartesian3.equals(this.center, this._center)) {
Matrix4.clone(this.modelMatrix, this._modelMatrix);
Cartesian3.clone(this.center, this._center);
// Translate model coordinates used for rendering such that the origin is the center of the ellipsoid.
Matrix4.multiplyByTranslation(this.modelMatrix, this.center, this._computedModelMatrix);
boundingSphereDirty = true;
}
if (boundingSphereDirty) {
Cartesian3.clone(Cartesian3.ZERO, this._boundingSphere.center);
this._boundingSphere.radius = Cartesian3.maximumComponent(radii);
BoundingSphere.transform(this._boundingSphere, this._computedModelMatrix, this._boundingSphere);
}
var materialChanged = this._material !== this.material;
this._material = this.material;
this._material.update(context);
var lightingChanged = this.onlySunLighting !== this._onlySunLighting;
this._onlySunLighting = this.onlySunLighting;
var colorCommand = this._colorCommand;
var fs;
// Recompile shader when material, lighting, or translucency changes
if (materialChanged || lightingChanged || translucencyChanged) {
fs = new ShaderSource({
sources : [this.material.shaderSource, EllipsoidFS]
});
if (this.onlySunLighting) {
fs.defines.push('ONLY_SUN_LIGHTING');
}
if (!translucent && context.fragmentDepth) {
fs.defines.push('WRITE_DEPTH');
}
this._sp = ShaderProgram.replaceCache({
context : context,
shaderProgram : this._sp,
vertexShaderSource : EllipsoidVS,
fragmentShaderSource : fs,
attributeLocations : attributeLocations
});
colorCommand.vertexArray = this._va;
colorCommand.renderState = this._rs;
colorCommand.shaderProgram = this._sp;
colorCommand.uniformMap = combine(this._uniforms, this.material._uniforms);
colorCommand.executeInClosestFrustum = translucent;
}
var commandList = frameState.commandList;
var passes = frameState.passes;
if (passes.render) {
colorCommand.boundingVolume = this._boundingSphere;
colorCommand.debugShowBoundingVolume = this.debugShowBoundingVolume;
colorCommand.modelMatrix = this._computedModelMatrix;
colorCommand.pass = translucent ? Pass.TRANSLUCENT : Pass.OPAQUE;
commandList.push(colorCommand);
}
if (passes.pick) {
var pickCommand = this._pickCommand;
if (!defined(this._pickId) || (this._id !== this.id)) {
this._id = this.id;
this._pickId = this._pickId && this._pickId.destroy();
this._pickId = context.createPickId({
primitive : this,
id : this.id
});
}
// Recompile shader when material changes
if (materialChanged || lightingChanged || !defined(this._pickSP)) {
fs = new ShaderSource({
sources : [this.material.shaderSource, EllipsoidFS],
pickColorQualifier : 'uniform'
});
if (this.onlySunLighting) {
fs.defines.push('ONLY_SUN_LIGHTING');
}
if (!translucent && context.fragmentDepth) {
fs.defines.push('WRITE_DEPTH');
}
this._pickSP = ShaderProgram.replaceCache({
context : context,
shaderProgram : this._pickSP,
vertexShaderSource : EllipsoidVS,
fragmentShaderSource : fs,
attributeLocations : attributeLocations
});
pickCommand.vertexArray = this._va;
pickCommand.renderState = this._rs;
pickCommand.shaderProgram = this._pickSP;
pickCommand.uniformMap = combine(combine(this._uniforms, this._pickUniforms), this.material._uniforms);
pickCommand.executeInClosestFrustum = translucent;
}
pickCommand.boundingVolume = this._boundingSphere;
pickCommand.modelMatrix = this._computedModelMatrix;
pickCommand.pass = translucent ? Pass.TRANSLUCENT : Pass.OPAQUE;
commandList.push(pickCommand);
}
};
/**
* Returns true if this object was destroyed; otherwise, false.
* <br /><br />
* If this object was destroyed, it should not be used; calling any function other than
* <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
*
* @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
*
* @see EllipsoidPrimitive#destroy
*/
EllipsoidPrimitive.prototype.isDestroyed = function() {
return false;
};
/**
* Destroys the WebGL resources held by this object. Destroying an object allows for deterministic
* release of WebGL resources, instead of relying on the garbage collector to destroy this object.
* <br /><br />
* Once an object is destroyed, it should not be used; calling any function other than
* <code>isDestroyed</code> will result in a {@link DeveloperError} exception. Therefore,
* assign the return value (<code>undefined</code>) to the object as done in the example.
*
* @returns {undefined}
*
* @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
*
*
* @example
* e = e && e.destroy();
*
* @see EllipsoidPrimitive#isDestroyed
*/
EllipsoidPrimitive.prototype.destroy = function() {
this._sp = this._sp && this._sp.destroy();
this._pickSP = this._pickSP && this._pickSP.destroy();
this._pickId = this._pickId && this._pickId.destroy();
return destroyObject(this);
};
return EllipsoidPrimitive;
});
| apache-2.0 |
bclau/nova | nova/api/openstack/compute/contrib/used_limits_for_admin.py | 1061 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from nova.api.openstack import extensions
class Used_limits_for_admin(extensions.ExtensionDescriptor):
"""Provide data to admin on limited resources used by other tenants."""
name = "UsedLimitsForAdmin"
alias = "os-used-limits-for-admin"
namespace = ("http://docs.openstack.org/compute/ext/used_limits_for_admin"
"/api/v1.1")
updated = "2013-05-02T00:00:00+00:00"
| apache-2.0 |
ibinti/intellij-community | plugins/ant/src/com/intellij/lang/ant/config/impl/AntKeymapExtension.java | 3212 | /*
* 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.lang.ant.config.impl;
import com.intellij.icons.AllIcons;
import com.intellij.lang.ant.config.AntBuildFile;
import com.intellij.lang.ant.config.AntConfiguration;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.ex.ActionManagerEx;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.keymap.KeyMapBundle;
import com.intellij.openapi.keymap.KeymapExtension;
import com.intellij.openapi.keymap.KeymapGroup;
import com.intellij.openapi.keymap.KeymapGroupFactory;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Condition;
import com.intellij.util.containers.HashMap;
import java.util.Arrays;
import java.util.Map;
/**
* @author Vladislav.Kaznacheev
*/
class AntKeymapExtension implements KeymapExtension {
private static final Logger LOG = Logger.getInstance("#com.intellij.lang.ant.config.impl.AntProjectKeymap");
public KeymapGroup createGroup(final Condition<AnAction> filtered, Project project) {
final Map<AntBuildFile, KeymapGroup> buildFileToGroup = new HashMap<>();
final KeymapGroup result = KeymapGroupFactory.getInstance().createGroup(KeyMapBundle.message("ant.targets.group.title"),
AllIcons.Nodes.KeymapAnt);
final ActionManagerEx actionManager = ActionManagerEx.getInstanceEx();
final String[] ids = actionManager.getActionIds(project != null? AntConfiguration.getActionIdPrefix(project) : AntConfiguration.ACTION_ID_PREFIX);
Arrays.sort(ids);
if (project != null) {
final AntConfiguration antConfiguration = AntConfiguration.getInstance(project);
ApplicationManager.getApplication().runReadAction(() -> {
for (final String id : ids) {
if (filtered != null && !filtered.value(actionManager.getActionOrStub(id))) {
continue;
}
final AntBuildFile buildFile = antConfiguration.findBuildFileByActionId(id);
if (buildFile != null) {
KeymapGroup subGroup = buildFileToGroup.get(buildFile);
if (subGroup == null) {
subGroup = KeymapGroupFactory.getInstance().createGroup(buildFile.getPresentableName());
buildFileToGroup.put(buildFile, subGroup);
result.addGroup(subGroup);
}
subGroup.addActionId(id);
}
else {
LOG.info("no buildfile found for actionId=" + id);
}
}
});
}
return result;
}
}
| apache-2.0 |
tony810430/flink | flink-java/src/main/java/org/apache/flink/api/java/operators/NoOpOperator.java | 1638 | /*
* 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.flink.api.java.operators;
import org.apache.flink.annotation.Internal;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.util.Preconditions;
/**
* This operator will be ignored during translation.
*
* @param <IN> The type of the data set passed through the operator.
*/
@Internal
public class NoOpOperator<IN> extends DataSet<IN> {
private DataSet<IN> input;
public NoOpOperator(DataSet<IN> input, TypeInformation<IN> resultType) {
super(input.getExecutionEnvironment(), resultType);
this.input = input;
}
public DataSet<IN> getInput() {
return input;
}
public void setInput(DataSet<IN> input) {
Preconditions.checkNotNull(input);
this.input = input;
}
}
| apache-2.0 |
MsysTechnologiesllc/azure-xplat-cli | test/recordings/cli.storage.blob-tests/cli_storage_container_delete_should_delete_the_specified_container.nock.js | 1620 | // This file has been autogenerated.
var profile = require('../../../lib/util/profile');
exports.getMockedProfile = function () {
var newProfile = new profile.Profile();
newProfile.addSubscription(new profile.Subscription({
id: 'a0d901ba-9956-4f7d-830c-2d7974c36666',
name: 'Azure Storage DM Dev',
user: {
name: '[email protected]',
type: 'user'
},
tenantId: '72f988bf-86f1-41af-91ab-2d7cd011db47',
state: 'Enabled',
registeredProviders: [],
_eventsCount: '1',
isDefault: true
}, newProfile.environments['AzureCloud']));
return newProfile;
};
exports.setEnvironment = function() {
process.env['AZURE_STORAGE_CONNECTION_STRING'] = 'DefaultEndpointsProtocol=https;AccountName=xplat;AccountKey=null';
};
exports.scopes = [[function (nock) {
var result =
nock('http://xplat.blob.core.windows.net:443')
.delete('/storageclitest?restype=container')
.reply(202, "", { 'transfer-encoding': 'chunked',
server: 'Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': 'da6e05b9-0001-004d-63aa-3f50e5000000',
'x-ms-version': '2015-12-11',
date: 'Wed, 16 Nov 2016 01:40:21 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('https://xplat.blob.core.windows.net:443')
.delete('/storageclitest?restype=container')
.reply(202, "", { 'transfer-encoding': 'chunked',
server: 'Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': 'da6e05b9-0001-004d-63aa-3f50e5000000',
'x-ms-version': '2015-12-11',
date: 'Wed, 16 Nov 2016 01:40:21 GMT',
connection: 'close' });
return result; }]]; | apache-2.0 |
Shopify/dd-agent | ci/common.rb | 5570 | require 'colorize'
require 'httparty'
require 'socket'
require 'time'
require 'timeout'
# Colors don't work on Appveyor
String.disable_colorization = true if Gem.win_platform?
require './ci/resources/cache'
def sleep_for(secs)
puts "Sleeping for #{secs}s".blue
sleep(secs)
end
def section(name)
timestamp = Time.now.utc.iso8601
puts ''
puts "[#{timestamp}] >>>>>>>>>>>>>> #{name} STAGE".black.on_white
puts ''
end
def install_requirements(req_file, pip_options = nil, output = nil, use_venv = nil)
pip_command = use_venv ? 'venv/bin/pip' : 'pip'
redirect_output = output ? "2>&1 >> #{output}" : ''
pip_options = '' if pip_options.nil?
File.open(req_file, 'r') do |f|
f.each_line do |line|
line.strip!
unless line.empty? || line.start_with?('#')
sh %(#{pip_command} install #{line} #{pip_options} #{redirect_output}\
|| echo 'Unable to install #{line}' #{redirect_output})
end
end
end
end
# helper class to wait for TCP/HTTP services to boot
class Wait
DEFAULT_TIMEOUT = 10
def self.check_port(port)
Timeout.timeout(0.5) do
begin
s = TCPSocket.new('localhost', port)
s.close
return true
rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH
return false
end
end
rescue Timeout::Error
return false
end
def self.check_url(url)
Timeout.timeout(0.5) do
begin
r = HTTParty.get(url)
return (200...300).include? r.code
rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH
return false
end
end
rescue Timeout::Error
return false
end
def self.check_file(file_path)
File.exist?(file_path)
end
def self.check(smth)
if smth.is_a? Integer
check_port smth
elsif smth.include? 'http'
check_url smth
else
check_file smth
end
end
def self.for(smth, max_timeout = DEFAULT_TIMEOUT)
start_time = Time.now
status = false
n = 1
puts "Trying #{smth}"
loop do
puts n.to_s
status = check(smth)
break if status || Time.now > start_time + max_timeout
n += 1
sleep 0.25
end
if status
puts 'Found!'
else
fail "Still not up after #{max_timeout}s"
end
status
end
end
# Initialize cache if in travis and in our repository
# (no cache for external contributors)
if ENV['TRAVIS'] && ENV['AWS_SECRET_ACCESS_KEY']
cache = Cache.new(debug: ENV['DEBUG_CACHE'],
s3: {
bucket: 'dd-agent-travis-cache',
access_key_id: ENV['AWS_ACCESS_KEY_ID'],
secret_access_key: ENV['AWS_SECRET_ACCESS_KEY']
})
end
namespace :ci do
namespace :common do
task :before_install do |t|
section('BEFORE_INSTALL')
# We use tempdir on Windows, no need to create it
sh %(mkdir -p #{ENV['VOLATILE_DIR']}) unless Gem.win_platform?
if ENV['TRAVIS'] && ENV['AWS_SECRET_ACCESS_KEY']
cache.directories = ["#{ENV['HOME']}/embedded"]
cache.setup
end
t.reenable
end
task :install do |t|
section('INSTALL')
sh %(#{'python -m ' if Gem.win_platform?}pip install --upgrade pip setuptools)
sh %(pip install\
-r requirements.txt\
--cache-dir #{ENV['PIP_CACHE']}\
2>&1 >> #{ENV['VOLATILE_DIR']}/ci.log)
install_requirements('requirements-opt.txt',
"--cache-dir #{ENV['PIP_CACHE']}",
"#{ENV['VOLATILE_DIR']}/ci.log")
sh %(pip install\
-r requirements-test.txt\
--cache-dir #{ENV['PIP_CACHE']}\
2>&1 >> #{ENV['VOLATILE_DIR']}/ci.log)
t.reenable
end
task :before_script do |t|
section('BEFORE_SCRIPT')
sh %(cp #{ENV['TRAVIS_BUILD_DIR']}/ci/resources/datadog.conf.example\
#{ENV['TRAVIS_BUILD_DIR']}/datadog.conf)
t.reenable
end
task :script do |t|
section('SCRIPT')
t.reenable
end
task :before_cache do |t|
if ENV['TRAVIS'] && ENV['AWS_SECRET_ACCESS_KEY']
section('BEFORE_CACHE')
sh %(find #{ENV['INTEGRATIONS_DIR']}/ -type f -name '*.log*' -delete)
end
t.reenable
end
task :cache do |t|
if ENV['TRAVIS'] && ENV['AWS_SECRET_ACCESS_KEY']
section('CACHE')
cache.push
end
t.reenable
end
task :cleanup do |t|
section('CLEANUP')
t.reenable
end
task :run_tests, :flavor do |t, attr|
flavors = attr[:flavor]
filter = ENV['NOSE_FILTER'] || '1'
if flavors.include?('default') || flavors.include?('checks_mock')
nose = "(not requires) and #{filter}"
else
nose = "(requires in ['#{flavors.join("','")}']) and #{filter}"
end
if flavors.include?('default') || flavors.include?('core_integration')
tests_directory = 'tests/core'
else
tests_directory = 'tests/checks'
end
# Rake on Windows doesn't support setting the var at the beginning of the
# command
path = ''
unless Gem.win_platform?
# FIXME: make the other filters than param configurable
# For integrations that cannot be easily installed in a
# separate dir we symlink stuff in the rootdir
path = %(PATH="#{ENV['INTEGRATIONS_DIR']}/bin:#{ENV['PATH']}" )
end
sh %(#{path}nosetests -v -A "#{nose}" #{tests_directory})
t.reenable
end
task execute: [:before_install, :install, :before_script, :script]
end
end
| bsd-3-clause |
CapeSepias/scala-js | library/src/main/scala/scala/scalajs/js/annotation/JSExportDescendentObjects.scala | 1258 | /* __ *\
** ________ ___ / / ___ __ ____ Scala.js API **
** / __/ __// _ | / / / _ | __ / // __/ (c) 2013, LAMP/EPFL **
** __\ \/ /__/ __ |/ /__/ __ |/_// /_\ \ http://scala-lang.org/ **
** /____/\___/_/ |_/____/_/ | |__/ /____/ **
** |/____/ **
\* */
package scala.scalajs.js.annotation
/** Specifies that all the objects extending the annotated class or trait
* should be exported for use in raw JS.
* Note that objects exported this way are exported under their fully
* qualified name.
*
* @param ignoreInvalidDescendants If true, descendants that cannot be exported
* are silently ignored.
* @see [[http://www.scala-js.org/doc/export-to-javascript.html Export Scala.js APIs to JavaScript]]
*/
class JSExportDescendentObjects(ignoreInvalidDescendants: Boolean)
extends scala.annotation.StaticAnnotation {
/** Constructor that makes invalid descendants fail.
*
* same as setting ingoreInvalidDescendants to false
*/
def this() = this(false)
}
| bsd-3-clause |
spreg-git/pysal | pysal/contrib/network/lincs.py | 13081 | #!/usr/bin/env python
"""
A library for computing local indicators of network-constrained clusters
Author:
Myunghwa Hwang [email protected]
"""
import unittest
import numpy as np
import scipy.stats as stats
import geodanet.network as pynet
import pysal, copy
import time
def unconditional_sim(event, base, s):
"""
Parameters:
event: n*1 numpy array with integer values
observed values for an event variable
base: n*1 numpy array with integer values
observed values for a population variable
s: integer
the number of simulations
Returns:
: n*s numpy array
"""
mean_risk = event.sum()*1.0/base.sum()
if base.dtype != int:
base = np.array([int(v) for v in base])
base_zeros = (base == 0.0)
base[base_zeros] += 1.0
sims = np.random.binomial(base, mean_risk, (s, len(event))).transpose()
sims[base_zeros, :] = 0.0
return sims
def unconditional_sim_poisson(event, base, s):
"""
Parameters:
event: n*1 numpy array with integer values
observed values for an event variable
base: n*1 numpy array with integer values
observed values for a population variable
s: integer
the number of simulations
Returns:
: n*s numpy array
"""
mean_risk = event.sum()*1.0/base.sum()
E = base*mean_risk
return np.random.poisson(E, (s, len(event))).transpose()
def conditional_multinomial(event, base, s):
"""
Parameters:
event: n*1 numpy array with integer values
observed values for an event variable
base: n*1 numpy array with integer values
observed values for a population variable
s: integer
the number of simulations
Returns:
: n*s numpy array
"""
m = int(event.sum())
props = base*1.0/base.sum()
return np.random.multinomial(m, props, s).transpose()
def pseudo_pvalues(obs, sims):
"""
Get pseudo p-values from a set of observed indices and their simulated ones.
Parameters:
obs: n*1 numpy array for observed values
sims: n*sims numpy array; sims is the number of simulations
Returns:
p_sim : n*1 numpy array for pseudo p-values
E_sim : mean of p_sim
SE_sim: standard deviation of p_sim
V_sim: variance of p_sim
z_sim: standardarized observed values
p_z_sim: p-value of z_sim based on normal distribution
"""
sims = np.transpose(sims)
permutations = sims.shape[0]
above = sims >= obs
larger = sum(above)
low_extreme = (permutations - larger) < larger
larger[low_extreme] = permutations - larger[low_extreme]
p_sim = (larger + 1.0)/(permutations + 1.0)
E_sim = sims.mean()
SE_sim = sims.std()
V_sim = SE_sim*SE_sim
z_sim = (obs - E_sim)/SE_sim
p_z_sim = 1 - stats.norm.cdf(np.abs(z_sim))
return p_sim, E_sim, SE_sim, V_sim, z_sim, p_z_sim
def node_weights(network, attribute=False):
"""
Obtains a spatial weights matrix of edges in a network
if two edges share a node, they are neighbors
Parameters:
network: a network with/without attributes
attribute: boolean
if true, attributes of edges are added to a dictionary of edges,
which is a return value
Returns:
w: a spatial weights instance
id2link: an associative dictionary that connects a sequential id to a unique
edge on the network
if attribute is true, each item in the dictionary includes the attributes
"""
link2id, id2link = {}, {}
counter = 0
neighbors, weights = {},{}
for n1 in network:
for n2 in network[n1]:
if (n1,n2) not in link2id or link2id[(n1,n2)] not in neighbors:
if (n1,n2) not in link2id:
link2id[(n1,n2)] = counter
link2id[(n2,n1)] = counter
if not attribute:
id2link[counter] = (n1, n2)
else:
id2link[counter] = tuple([(n1,n2)] + list(network[n1][n2][1:]))
counter += 1
neighbors_from_n1 = [(n1, n) for n in network[n1] if n != n2]
neighbors_from_n2 = [(n2, n) for n in network[n2] if n != n1]
neighbors_all = neighbors_from_n1 + neighbors_from_n2
neighbor_ids = []
for edge in neighbors_all:
if edge not in link2id:
link2id[edge] = counter
link2id[(edge[-1], edge[0])] = counter
if not attribute:
id2link[counter] = edge
else:
id2link[counter] = tuple([edge] + list(network[edge[0]][edge[1]][1:]))
neighbor_ids.append(counter)
counter += 1
else:
neighbor_ids.append(link2id[edge])
neighbors[link2id[(n1,n2)]] = neighbor_ids
weights[link2id[(n1,n2)]] = [1.0]*(len(neighbors_from_n1) + len(neighbors_from_n2))
return pysal.weights.W(neighbors, weights), id2link
def edgepoints_from_network(network, attribute=False):
"""
Obtains a list of projected points which are midpoints of edges
Parameters:
network: a network with/without attributes
attribute: boolean
if true, one of return values includes attributes for each edge
Returns:
id2linkpoints: a dictionary that associates a sequential id to a projected, midpoint of each edge
id2attr: a dictionary that associates a sequential id to the attributes of each edge
link2id: a dictionary that associates each edge to its id
"""
link2id, id2linkpoints, id2attr = {}, {}, {}
counter = 0
for n1 in network:
for n2 in network[n1]:
if (n1,n2) not in link2id or (n2,n1) not in link2id:
link2id[(n1,n2)] = counter
link2id[(n2,n1)] = counter
if type(network[n1][n2]) != list:
half_dist = network[n1][n2]/2
else:
half_dist = network[n1][n2][0]/2
if n1[0] < n2[0] or (n1[0] == n2[0] and n1[1] < n2[1]):
id2linkpoints[counter] = (n1,n2,half_dist,half_dist)
else:
id2linkpoints[counter] = (n2,n1,half_dist,half_dist)
if attribute:
id2attr[counter] = network[n1][n2][1:]
counter += 1
return id2linkpoints, id2attr, link2id
def dist_weights(network, id2linkpoints, link2id, bandwidth):
"""
Obtains a distance-based spatial weights matrix using network distance
Parameters:
network: an undirected network without additional attributes
id2linkpoints: a dictionary that includes a list of network-projected, midpoints of edges in the network
link2id: a dictionary that associates each edge to a unique id
bandwidth: a threshold distance for creating a spatial weights matrix
Returns:
w : a distance-based, binary spatial weights matrix
id2link: a dictionary that associates a unique id to each edge of the network
"""
linkpoints = id2linkpoints.values()
neighbors, id2link = {}, {}
net_distances = {}
for linkpoint in id2linkpoints:
if linkpoints[linkpoint] not in net_distances:
net_distances[linkpoints[linkpoint][0]] = pynet.dijkstras(network, linkpoints[linkpoint][0], r=bandwidth)
net_distances[linkpoints[linkpoint][1]] = pynet.dijkstras(network, linkpoints[linkpoint][1], r=bandwidth)
ngh = pynet.proj_distances_undirected(network, linkpoints[linkpoint], linkpoints, r=bandwidth, cache=net_distances)
#ngh = pynet.proj_distances_undirected(network, linkpoints[linkpoint], linkpoints, r=bandwidth)
if linkpoints[linkpoint] in ngh:
del ngh[linkpoints[linkpoint]]
if linkpoint not in neighbors:
neighbors[linkpoint] = []
for k in ngh.keys():
neighbor = link2id[k[:2]]
if neighbor not in neighbors[linkpoint]:
neighbors[linkpoint].append(neighbor)
if neighbor not in neighbors:
neighbors[neighbor] = []
if linkpoint not in neighbors[neighbor]:
neighbors[neighbor].append(linkpoint)
id2link[linkpoint] = id2linkpoints[linkpoint][:2]
weights = copy.copy(neighbors)
for ngh in weights:
weights[ngh] = [1.0]*len(weights[ngh])
return pysal.weights.W(neighbors, weights), id2link
def lincs(network, event, base, weight, dist=None, lisa_func='moran', sim_method="permutations", sim_num=99):
"""
Compute local Moran's I for edges in the network
Parameters:
network: a clean network where each edge has up to three attributes:
Its length, an event variable, and a base variable
event: integer
an index for the event variable
base: integer
an index for the base variable
weight: string
type of binary spatial weights
two options are allowed: Node-based, Distance-based
dist: float
threshold distance value for the distance-based weight
lisa_func: string
type of LISA functions
three options allowed: moran, g, and g_star
sim_method: string
type of simulation methods
four options allowed: permutations, binomial (unconditional),
poisson (unconditional), multinomial (conditional)
sim_num: integer
the number of simulations
Returns:
: a dictionary of edges
an edge and its moran's I are the key and item
: a Weights object
PySAL spatial weights object
"""
if lisa_func in ['g', 'g_star'] and weight == 'Node-based':
print 'Local G statistics can work only with distance-based weights matrix'
raise
if lisa_func == 'moran':
lisa_func = pysal.esda.moran.Moran_Local
else:
lisa_func = pysal.esda.getisord.G_Local
star = False
if lisa_func == 'g_star':
star = True
if base:
def getBase(edges, edge, base):
return edges[edge][base]
else:
def getBase(edges, edge, base):
return 1.0
w, edges, e, b, edges_geom = None, None, None, None, []
if weight == 'Node-based':
w, edges = node_weights(network, attribute=True)
n = len(edges)
e, b = np.zeros(n), np.zeros(n)
for edge in edges:
edges_geom.append(edges[edge][0])
e[edge] = edges[edge][event]
b[edge] = getBase(edges, edge, base)
w.id_order = edges.keys()
elif dist is not None:
id2edgepoints, id2attr, edge2id = edgepoints_from_network(network, attribute=True)
for n1 in network:
for n2 in network[n1]:
network[n1][n2] = network[n1][n2][0]
w, edges = dist_weights(network, id2edgepoints, edge2id, dist)
n = len(id2attr)
e, b = np.zeros(n), np.zeros(n)
if base:
base -= 1
for edge in id2attr:
edges_geom.append(edges[edge])
e[edge] = id2attr[edge][event - 1]
b[edge] = getBase(id2attr, edge, base)
w.id_order = id2attr.keys()
Is, p_sim, Zs = None,None, None
if sim_method == 'permutation':
if lisa_func == pysal.esda.moran.Moran_Local:
lisa_i = lisa_func(e*1.0/b,w,transformation="r",permutations=sim_num)
Is = lisa_i.Is
Zs = lisa_i.q
else:
lisa_i = lisa_func(e*1.0/b,w,transform="R",permutations=sim_num,star=star)
Is = lisa_i.Gs
Zs = lisa_i.Zs
p_sim = lisa_i.p_sim
else:
sims = None
if lisa_func == pysal.esda.moran.Moran_Local:
lisa_i = lisa_func(e*1.0/b,w,transformation="r",permutations=0)
Is = lisa_i.Is
Zs = lisa_i.q
else:
lisa_i = lisa_func(e*1.0/b,w,transform="R",permutations=0,star=star)
Is = lisa_i.Gs
Zs = lisa_i.Zs
if sim_method == 'binomial':
sims = unconditional_sim(e, b, sim_num)
elif sim_method == 'poisson':
sims = unconditional_sim_poisson(e, b, sim_num)
else:
sims = conditional_multinomial(e, b, sim_num)
if lisa_func == pysal.esda.moran.Moran_Local:
for i in range(sim_num):
sims[:,i] = lisa_func(sims[:,i]*1.0/b,w,transformation="r",permutations=0).Is
else:
for i in range(sim_num):
sims[:,i] = lisa_func(sims[:,i]*1.0/b,w,permutations=0,star=star).Gs
sim_res = pseudo_pvalues(Is, sims)
p_sim = sim_res[0]
w.transform = 'O'
return zip(edges_geom, e, b, Is, Zs, p_sim), w
| bsd-3-clause |
joone/chromium-crosswalk | third_party/WebKit/Source/core/page/WindowFeaturesTest.cpp | 969 | // Copyright 2015 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 "core/page/WindowFeatures.h"
#include "wtf/text/WTFString.h"
#include <gtest/gtest.h>
namespace blink {
using WindowFeaturesTest = ::testing::Test;
TEST_F(WindowFeaturesTest, NoOpener)
{
static const struct {
const char* featureString;
bool noopener;
} cases[] = {
{ "", false },
{ "something", false },
{ "something, something", false },
{ "notnoopener", false },
{ "noopener", true },
{ "something, noopener", true },
{ "noopener, something", true },
{ "NoOpEnEr", true },
};
for (const auto& test : cases) {
WindowFeatures features(test.featureString);
EXPECT_EQ(test.noopener, features.noopener) << "Testing '" << test.featureString << "'";
}
}
} // namespace blink
| bsd-3-clause |
phupn1510/ELK | kibana/kibana/node_modules/regexpu/regexpu.js | 278 | module.exports = {
'rewritePattern': require('./rewrite-pattern.js'),
'transformTree': require('./transform-tree.js'),
'transpileCode': require('./transpile-code.js'),
'version': require('./package.json').version
};
module.exports.transform = module.exports.transformTree;
| mit |
StudioBOZ/thirdClass | app/code/core/Mage/Shipping/Model/Carrier/Flatrate.php | 3793 | <?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* 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 [email protected] so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magentocommerce.com for more information.
*
* @category Mage
* @package Mage_Shipping
* @copyright Copyright (c) 2013 Magento Inc. (http://www.magentocommerce.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Flat rate shipping model
*
* @category Mage
* @package Mage_Shipping
* @author Magento Core Team <[email protected]>
*/
class Mage_Shipping_Model_Carrier_Flatrate
extends Mage_Shipping_Model_Carrier_Abstract
implements Mage_Shipping_Model_Carrier_Interface
{
protected $_code = 'flatrate';
protected $_isFixed = true;
/**
* Enter description here...
*
* @param Mage_Shipping_Model_Rate_Request $data
* @return Mage_Shipping_Model_Rate_Result
*/
public function collectRates(Mage_Shipping_Model_Rate_Request $request)
{
if (!$this->getConfigFlag('active')) {
return false;
}
$freeBoxes = 0;
if ($request->getAllItems()) {
foreach ($request->getAllItems() as $item) {
if ($item->getProduct()->isVirtual() || $item->getParentItem()) {
continue;
}
if ($item->getHasChildren() && $item->isShipSeparately()) {
foreach ($item->getChildren() as $child) {
if ($child->getFreeShipping() && !$child->getProduct()->isVirtual()) {
$freeBoxes += $item->getQty() * $child->getQty();
}
}
} elseif ($item->getFreeShipping()) {
$freeBoxes += $item->getQty();
}
}
}
$this->setFreeBoxes($freeBoxes);
$result = Mage::getModel('shipping/rate_result');
if ($this->getConfigData('type') == 'O') { // per order
$shippingPrice = $this->getConfigData('price');
} elseif ($this->getConfigData('type') == 'I') { // per item
$shippingPrice = ($request->getPackageQty() * $this->getConfigData('price')) - ($this->getFreeBoxes() * $this->getConfigData('price'));
} else {
$shippingPrice = false;
}
$shippingPrice = $this->getFinalPriceWithHandlingFee($shippingPrice);
if ($shippingPrice !== false) {
$method = Mage::getModel('shipping/rate_result_method');
$method->setCarrier('flatrate');
$method->setCarrierTitle($this->getConfigData('title'));
$method->setMethod('flatrate');
$method->setMethodTitle($this->getConfigData('name'));
if ($request->getFreeShipping() === true || $request->getPackageQty() == $this->getFreeBoxes()) {
$shippingPrice = '0.00';
}
$method->setPrice($shippingPrice);
$method->setCost($shippingPrice);
$result->append($method);
}
return $result;
}
public function getAllowedMethods()
{
return array('flatrate'=>$this->getConfigData('name'));
}
}
| mit |
clienthax/SpongeCommon | src/main/java/org/spongepowered/common/item/package-info.java | 1343 | /*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* 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.
*/
@org.spongepowered.api.util.annotation.NonnullByDefault package org.spongepowered.common.item;
| mit |
zecke/old-pharo-vm-sctp | processors/IA32/bochs/iodev/eth_vnet.cc | 40457 | /////////////////////////////////////////////////////////////////////////
// $Id: eth_vnet.cc,v 1.22 2008/01/26 22:24:01 sshwarts Exp $
/////////////////////////////////////////////////////////////////////////
//
// virtual Ethernet locator
//
// An implementation of ARP, ping(ICMP-echo), DHCP and read/write TFTP.
// Virtual host acts as a DHCP server for guest.
// There are no connections between the virtual host and real ethernets.
//
// Virtual host name: vnet
// Virtual host IP: 192.168.10.1
// Guest IP: 192.168.10.2
// Guest netmask: 255.255.255.0
// Guest broadcast: 192.168.10.255
// TFTP server uses ethdev value for the root directory and doesn't overwrite files
#define BX_PLUGGABLE
#define NO_DEVICE_INCLUDES
#include "iodev.h"
#if BX_NETWORKING
#include "eth.h"
#define LOG_THIS bx_devices.pluginNE2kDevice->
#define BX_ETH_VNET_LOGGING 1
#define BX_ETH_VNET_PCAP_LOGGING 0
#if BX_ETH_VNET_PCAP_LOGGING
#include <pcap.h>
#endif
/////////////////////////////////////////////////////////////////////////
// handler to send/receive packets
/////////////////////////////////////////////////////////////////////////
static const Bit8u default_host_ipv4addr[4] = {192,168,10,1};
static const Bit8u subnetmask_ipv4addr[4] = {0xff,0xff,0xff,0x00};
static const Bit8u default_guest_ipv4addr[4] = {192,168,10,2};
static const Bit8u broadcast_ipv4addr[3][4] =
{
{ 0, 0, 0, 0},
{255,255,255,255},
{192,168, 10,255},
};
#define ICMP_ECHO_PACKET_MAX 128
#define LAYER4_LISTEN_MAX 128
#define DEFAULT_LEASE_TIME 28800
static Bit8u packet_buffer[BX_PACKET_BUFSIZE];
static unsigned packet_len;
typedef void (*layer4_handler_t)(
void *this_ptr,
const Bit8u *ipheader,
unsigned ipheader_len,
unsigned sourceport,
unsigned targetport,
const Bit8u *data,
unsigned data_len
);
#define INET_PORT_FTPDATA 20
#define INET_PORT_FTP 21
#define INET_PORT_TIME 37
#define INET_PORT_NAME 42
#define INET_PORT_DOMAIN 53
#define INET_PORT_BOOTP_SERVER 67
#define INET_PORT_BOOTP_CLIENT 68
#define INET_PORT_HTTP 80
#define INET_PORT_NTP 123
// TFTP server support by EaseWay <[email protected]>
#define INET_PORT_TFTP_SERVER 69
#define TFTP_RRQ 1
#define TFTP_WRQ 2
#define TFTP_DATA 3
#define TFTP_ACK 4
#define TFTP_ERROR 5
#define TFTP_OPTACK 6
#define TFTP_BUFFER_SIZE 512
#define BOOTREQUEST 1
#define BOOTREPLY 2
#define BOOTPOPT_PADDING 0
#define BOOTPOPT_END 255
#define BOOTPOPT_SUBNETMASK 1
#define BOOTPOPT_TIMEOFFSET 2
#define BOOTPOPT_ROUTER_OPTION 3
#define BOOTPOPT_DOMAIN_NAMESERVER 6
#define BOOTPOPT_HOST_NAME 12
#define BOOTPOPT_DOMAIN_NAME 15
#define BOOTPOPT_MAX_DATAGRAM_SIZE 22
#define BOOTPOPT_DEFAULT_IP_TTL 23
#define BOOTPOPT_BROADCAST_ADDRESS 28
#define BOOTPOPT_ARPCACHE_TIMEOUT 35
#define BOOTPOPT_DEFAULT_TCP_TTL 37
#define BOOTPOPT_NTP_SERVER 42
#define BOOTPOPT_NETBIOS_NAMESERVER 44
#define BOOTPOPT_X_FONTSERVER 48
#define BOOTPOPT_REQUESTED_IP_ADDRESS 50
#define BOOTPOPT_IP_ADDRESS_LEASE_TIME 51
#define BOOTPOPT_OPTION_OVRLOAD 52
#define BOOTPOPT_DHCP_MESSAGETYPE 53
#define BOOTPOPT_SERVER_IDENTIFIER 54
#define BOOTPOPT_PARAMETER_REQUEST_LIST 55
#define BOOTPOPT_MAX_DHCP_MESSAGE_SIZE 57
#define BOOTPOPT_RENEWAL_TIME 58
#define BOOTPOPT_REBINDING_TIME 59
#define BOOTPOPT_CLASS_IDENTIFIER 60
#define BOOTPOPT_CLIENT_IDENTIFIER 61
#define DHCPDISCOVER 1
#define DHCPOFFER 2
#define DHCPREQUEST 3
#define DHCPDECLINE 4
#define DHCPACK 5
#define DHCPNAK 6
#define DHCPRELEASE 7
#define DHCPINFORM 8
class bx_vnet_pktmover_c : public eth_pktmover_c {
public:
bx_vnet_pktmover_c();
void pktmover_init(
const char *netif, const char *macaddr,
eth_rx_handler_t rxh, void *rxarg, char *script);
void sendpkt(void *buf, unsigned io_len);
private:
void guest_to_host(const Bit8u *buf, unsigned io_len);
void host_to_guest(Bit8u *buf, unsigned io_len);
void process_arp(const Bit8u *buf, unsigned io_len);
void host_to_guest_arp(Bit8u *buf, unsigned io_len);
void process_ipv4(const Bit8u *buf, unsigned io_len);
void host_to_guest_ipv4(Bit8u *buf, unsigned io_len);
layer4_handler_t get_layer4_handler(
unsigned ipprotocol, unsigned port);
bx_bool register_layer4_handler(
unsigned ipprotocol, unsigned port,layer4_handler_t func);
bx_bool unregister_layer4_handler(
unsigned ipprotocol, unsigned port);
void process_icmpipv4(
const Bit8u *ipheader, unsigned ipheader_len,
const Bit8u *l4pkt, unsigned l4pkt_len);
void process_tcpipv4(
const Bit8u *ipheader, unsigned ipheader_len,
const Bit8u *l4pkt, unsigned l4pkt_len);
void process_udpipv4(
const Bit8u *ipheader, unsigned ipheader_len,
const Bit8u *l4pkt, unsigned l4pkt_len);
void host_to_guest_udpipv4_packet(
unsigned target_port, unsigned source_port,
const Bit8u *udpdata, unsigned udpdata_len);
void process_icmpipv4_echo(
const Bit8u *ipheader, unsigned ipheader_len,
const Bit8u *l4pkt, unsigned l4pkt_len);
static void udpipv4_dhcp_handler(
void *this_ptr,
const Bit8u *ipheader, unsigned ipheader_len,
unsigned sourceport, unsigned targetport,
const Bit8u *data, unsigned data_len);
void udpipv4_dhcp_handler_ns(
const Bit8u *ipheader, unsigned ipheader_len,
unsigned sourceport, unsigned targetport,
const Bit8u *data, unsigned data_len);
static void udpipv4_tftp_handler(
void *this_ptr,
const Bit8u *ipheader, unsigned ipheader_len,
unsigned sourceport, unsigned targetport,
const Bit8u *data, unsigned data_len);
void udpipv4_tftp_handler_ns(
const Bit8u *ipheader, unsigned ipheader_len,
unsigned sourceport, unsigned targetport,
const Bit8u *data, unsigned data_len);
void tftp_send_error(
Bit8u *buffer,
unsigned sourceport, unsigned targetport,
unsigned code, const char *msg);
void tftp_send_data(
Bit8u *buffer,
unsigned sourceport, unsigned targetport,
unsigned block_nr);
void tftp_send_ack(
Bit8u *buffer,
unsigned sourceport, unsigned targetport,
unsigned block_nr);
void tftp_send_optack(
Bit8u *buffer,
unsigned sourceport, unsigned targetport,
size_t tsize_option, unsigned blksize_option);
char tftp_filename[BX_PATHNAME_LEN];
char tftp_rootdir[BX_PATHNAME_LEN];
bx_bool tftp_write;
Bit16u tftp_tid;
Bit8u host_macaddr[6];
Bit8u guest_macaddr[6];
Bit8u host_ipv4addr[4];
Bit8u guest_ipv4addr[4];
struct {
unsigned ipprotocol;
unsigned port;
layer4_handler_t func;
} l4data[LAYER4_LISTEN_MAX];
unsigned l4data_used;
static void rx_timer_handler(void *);
void rx_timer(void);
int rx_timer_index;
unsigned tx_time;
#if BX_ETH_VNET_LOGGING
FILE *pktlog_txt;
#endif // BX_ETH_VNET_LOGGING
#if BX_ETH_VNET_PCAP_LOGGING
pcap_t *pcapp;
pcap_dumper_t *pktlog_pcap;
struct pcap_pkthdr pcaphdr;
#endif // BX_ETH_VNET_PCAP_LOGGING
};
class bx_vnet_locator_c : public eth_locator_c {
public:
bx_vnet_locator_c(void) : eth_locator_c("vnet") {}
protected:
eth_pktmover_c *allocate(
const char *netif, const char *macaddr,
eth_rx_handler_t rxh,
void *rxarg, char *script) {
bx_vnet_pktmover_c *pktmover;
pktmover = new bx_vnet_pktmover_c();
pktmover->pktmover_init(netif, macaddr, rxh, rxarg, script);
return pktmover;
}
} bx_vnet_match;
static void put_net2(Bit8u *buf,Bit16u data)
{
*buf = (Bit8u)(data >> 8);
*(buf+1) = (Bit8u)(data & 0xff);
}
static void put_net4(Bit8u *buf,Bit32u data)
{
*buf = (Bit8u)((data >> 24) & 0xff);
*(buf+1) = (Bit8u)((data >> 16) & 0xff);
*(buf+2) = (Bit8u)((data >> 8) & 0xff);
*(buf+3) = (Bit8u)(data & 0xff);
}
static Bit16u get_net2(const Bit8u *buf)
{
return (((Bit16u)*buf) << 8) |
((Bit16u)*(buf+1));
}
static Bit32u get_net4(const Bit8u *buf)
{
return (((Bit32u)*buf) << 24) |
(((Bit32u)*(buf+1)) << 16) |
(((Bit32u)*(buf+2)) << 8) |
((Bit32u)*(buf+3));
}
static Bit16u ip_checksum(const Bit8u *buf, unsigned buf_len)
{
Bit32u sum = 0;
unsigned n;
for (n = 0; n < buf_len; n++) {
if (n & 1) {
sum += (Bit32u)(*buf++);
} else {
sum += (Bit32u)(*buf++) << 8;
}
}
while (sum > 0xffff) {
sum = (sum >> 16) + (sum & 0xffff);
}
return (Bit16u)sum;
}
// duplicate the part of tftp_send_data() that constructs the filename
// but ignore errors since tftp_send_data() will respond for us
static size_t get_file_size(const char *tpath, const char *tname)
{
struct stat stbuf;
char path[BX_PATHNAME_LEN];
if (strlen(tname) == 0)
return 0;
if ((strlen(tpath) + strlen(tname)) > BX_PATHNAME_LEN)
return 0;
sprintf(path, "%s/%s", tpath, tname);
if (stat(path, &stbuf) < 0)
return 0;
BX_INFO(("tftp filesize: %lu", (unsigned long)stbuf.st_size));
return stbuf.st_size;
}
bx_vnet_pktmover_c::bx_vnet_pktmover_c()
{
}
void bx_vnet_pktmover_c::pktmover_init(
const char *netif, const char *macaddr,
eth_rx_handler_t rxh, void *rxarg, char *script)
{
BX_INFO(("ne2k vnet driver"));
this->rxh = rxh;
this->rxarg = rxarg;
strcpy(this->tftp_rootdir, netif);
this->tftp_tid = 0;
this->tftp_write = 0;
memcpy(&host_macaddr[0], macaddr, 6);
memcpy(&guest_macaddr[0], macaddr, 6);
host_macaddr[5] = (host_macaddr[5] & (~0x01)) ^ 0x02;
memcpy(&host_ipv4addr[0], &default_host_ipv4addr[0], 4);
memcpy(&guest_ipv4addr[0], &broadcast_ipv4addr[0][0], 4);
l4data_used = 0;
register_layer4_handler(0x11,INET_PORT_BOOTP_SERVER,udpipv4_dhcp_handler);
register_layer4_handler(0x11,INET_PORT_TFTP_SERVER,udpipv4_tftp_handler);
this->rx_timer_index =
bx_pc_system.register_timer(this, this->rx_timer_handler, 1000,
0, 0, "eth_vnet");
#if BX_ETH_VNET_LOGGING
pktlog_txt = fopen ("ne2k-pktlog.txt", "wb");
if (!pktlog_txt) BX_PANIC (("ne2k-pktlog.txt failed"));
fprintf (pktlog_txt, "vnet packetmover readable log file\n");
fprintf (pktlog_txt, "TFTP root = %s\n", netif);
fprintf (pktlog_txt, "host MAC address = ");
int i;
for (i=0; i<6; i++)
fprintf (pktlog_txt, "%02x%s", 0xff & host_macaddr[i], i<5?":" : "\n");
fprintf (pktlog_txt, "guest MAC address = ");
for (i=0; i<6; i++)
fprintf (pktlog_txt, "%02x%s", 0xff & guest_macaddr[i], i<5?":" : "\n");
fprintf (pktlog_txt, "--\n");
fflush (pktlog_txt);
#endif
#if BX_ETH_VNET_PCAP_LOGGING
pcapp = pcap_open_dead (DLT_EN10MB, BX_PACKET_BUFSIZE);
pktlog_pcap = pcap_dump_open (pcapp, "ne2k-pktlog.pcap");
if (pktlog_pcap == NULL) BX_PANIC (("ne2k-pktlog.pcap failed"));
#endif
}
void bx_vnet_pktmover_c::sendpkt(void *buf, unsigned io_len)
{
guest_to_host((const Bit8u *)buf,io_len);
}
void bx_vnet_pktmover_c::guest_to_host(const Bit8u *buf, unsigned io_len)
{
#if BX_ETH_VNET_LOGGING
fprintf (pktlog_txt, "a packet from guest to host, length %u\n", io_len);
Bit8u *charbuf = (Bit8u *)buf;
unsigned n;
for (n=0; n<io_len; n++) {
if (((n % 16) == 0) && n>0)
fprintf (pktlog_txt, "\n");
fprintf (pktlog_txt, "%02x ", (unsigned)charbuf[n]);
}
fprintf (pktlog_txt, "\n--\n");
fflush (pktlog_txt);
#endif
#if BX_ETH_VNET_PCAP_LOGGING
if (pktlog_pcap && !ferror((FILE *)pktlog_pcap)) {
Bit64u time = bx_pc_system.time_usec();
pcaphdr.ts.tv_usec = time % 1000000;
pcaphdr.ts.tv_sec = time / 1000000;
pcaphdr.caplen = io_len;
pcaphdr.len = io_len;
pcap_dump((u_char *)pktlog_pcap, &pcaphdr, buf);
fflush((FILE *)pktlog_pcap);
}
#endif
this->tx_time = (64 + 96 + 4 * 8 + io_len * 8) / 10;
if ((io_len >= 14) &&
(!memcmp(&buf[6],&this->guest_macaddr[0],6)) &&
(!memcmp(&buf[0],&this->host_macaddr[0],6) ||
!memcmp(&buf[0],&broadcast_macaddr[0],6))) {
switch (get_net2(&buf[12])) {
case 0x0800: // IPv4.
process_ipv4(buf, io_len);
break;
case 0x0806: // ARP.
process_arp(buf, io_len);
break;
default: // unknown packet type.
break;
}
}
}
// The receive poll process
void bx_vnet_pktmover_c::rx_timer_handler(void *this_ptr)
{
bx_vnet_pktmover_c *class_ptr = (bx_vnet_pktmover_c *) this_ptr;
class_ptr->rx_timer();
}
void bx_vnet_pktmover_c::rx_timer(void)
{
this->rxh(this->rxarg, (void *)packet_buffer, packet_len);
#if BX_ETH_VNET_LOGGING
fprintf (pktlog_txt, "a packet from host to guest, length %u\n", packet_len);
Bit8u *charbuf = (Bit8u *)packet_buffer;
unsigned n;
for (n=0; n<packet_len; n++) {
if (((n % 16) == 0) && n>0)
fprintf (pktlog_txt, "\n");
fprintf (pktlog_txt, "%02x ", (unsigned)charbuf[n]);
}
fprintf (pktlog_txt, "\n--\n");
fflush (pktlog_txt);
#endif
#if BX_ETH_VNET_PCAP_LOGGING
if (pktlog_pcap && !ferror((FILE *)pktlog_pcap)) {
Bit64u time = bx_pc_system.time_usec();
pcaphdr.ts.tv_usec = time % 1000000;
pcaphdr.ts.tv_sec = time / 1000000;
pcaphdr.caplen = packet_len;
pcaphdr.len = packet_len;
pcap_dump((u_char *)pktlog_pcap, &pcaphdr, packet_buffer);
fflush((FILE *)pktlog_pcap);
}
#endif
}
void bx_vnet_pktmover_c::host_to_guest(Bit8u *buf, unsigned io_len)
{
Bit8u localbuf[60];
if (io_len < 14) {
BX_PANIC(("host_to_guest: io_len < 14!"));
return;
}
if (io_len < 60) {
memcpy(&localbuf[0],&buf[0],io_len);
memset(&localbuf[io_len],0,60-io_len);
buf=localbuf;
io_len=60;
}
packet_len = io_len;
memcpy(&packet_buffer, &buf[0], io_len);
unsigned rx_time = (64 + 96 + 4 * 8 + io_len * 8) / 10;
bx_pc_system.activate_timer(this->rx_timer_index, this->tx_time + rx_time + 100, 0);
}
/////////////////////////////////////////////////////////////////////////
// ARP
/////////////////////////////////////////////////////////////////////////
void bx_vnet_pktmover_c::process_arp(const Bit8u *buf, unsigned io_len)
{
unsigned opcode;
unsigned protocol;
Bit8u replybuf[60];
if (io_len < 22) return;
if (io_len < (unsigned)(22+buf[18]*2+buf[19]*2)) return;
// hardware:Ethernet
if (buf[14] != 0x00 || buf[15] != 0x01 || buf[18] != 0x06) return;
opcode = get_net2(&buf[20]);
protocol = get_net2(&buf[16]);
memset(&replybuf[0],0,60);
// protocol
switch (protocol) {
case 0x0800: // IPv4
if (buf[19] == 0x04) {
switch (opcode) {
case 0x0001: // ARP REQUEST
if (!memcmp(&buf[22],&this->guest_macaddr[0],6)) {
memcpy(&this->guest_ipv4addr[0],&buf[28],4);
if (!memcmp(&buf[38],&this->host_ipv4addr[0],4)) {
memcpy(&replybuf[14],&buf[14],6);
replybuf[20]=0x00;
replybuf[21]=0x02;
memcpy(&replybuf[22],&this->host_macaddr[0],6);
memcpy(&replybuf[28],&this->host_ipv4addr[0],4);
memcpy(&replybuf[32],&this->guest_macaddr[0],6);
memcpy(&replybuf[38],&this->guest_ipv4addr[0],4);
host_to_guest_arp(replybuf,60);
}
}
break;
case 0x0002: // ARP REPLY
BX_INFO(("unexpected ARP REPLY"));
break;
case 0x0003: // RARP REQUEST
BX_ERROR(("RARP is not implemented"));
break;
case 0x0004: // RARP REPLY
BX_INFO(("unexpected RARP REPLY"));
break;
default:
BX_INFO(("arp: unknown ARP opcode %04x",opcode));
break;
}
}
else
{
BX_INFO(("arp: unknown address length %u",(unsigned)buf[19]));
}
break;
default:
BX_INFO(("arp: unknown protocol 0x%04x",protocol));
break;
}
}
void bx_vnet_pktmover_c::host_to_guest_arp(Bit8u *buf, unsigned io_len)
{
memcpy(&buf[0],&this->guest_macaddr[0],6);
memcpy(&buf[6],&this->host_macaddr[0],6);
buf[12]=0x08;
buf[13]=0x06;
host_to_guest(buf,io_len);
}
/////////////////////////////////////////////////////////////////////////
// IPv4
/////////////////////////////////////////////////////////////////////////
void bx_vnet_pktmover_c::process_ipv4(const Bit8u *buf, unsigned io_len)
{
unsigned total_len;
unsigned packet_id;
unsigned fragment_flags;
unsigned fragment_offset;
unsigned ipproto;
unsigned l3header_len;
const Bit8u *l4pkt;
unsigned l4pkt_len;
if (io_len < (14U+20U)) {
BX_INFO(("ip packet - too small packet"));
return;
}
if ((buf[14+0] & 0xf0) != 0x40) {
BX_INFO(("ipv%u packet - not implemented",((unsigned)buf[14+0] >> 4)));
return;
}
l3header_len = ((unsigned)(buf[14+0] & 0x0f) << 2);
if (l3header_len != 20) {
BX_ERROR(("ip: option header is not implemented"));
return;
}
if (io_len < (14U+l3header_len)) return;
if (ip_checksum(&buf[14],l3header_len) != (Bit16u)0xffff) {
BX_INFO(("ip: invalid checksum"));
return;
}
total_len = get_net2(&buf[14+2]);
// FIXED By EaseWay
// Ignore this check to tolerant some cases
//if (io_len > (14U+total_len)) return;
if (memcmp(&buf[14+16],host_ipv4addr,4) &&
memcmp(&buf[14+16],broadcast_ipv4addr[0],4) &&
memcmp(&buf[14+16],broadcast_ipv4addr[1],4) &&
memcmp(&buf[14+16],broadcast_ipv4addr[2],4))
{
BX_INFO(("target IP address %u.%u.%u.%u is unknown",
(unsigned)buf[14+16],(unsigned)buf[14+17],
(unsigned)buf[14+18],(unsigned)buf[14+19]));
return;
}
packet_id = get_net2(&buf[14+4]);
fragment_flags = (unsigned)buf[14+6] >> 5;
fragment_offset = ((unsigned)get_net2(&buf[14+6]) & 0x1fff) << 3;
ipproto = buf[14+9];
if ((fragment_flags & 0x1) || (fragment_offset != 0)) {
BX_INFO(("ignore fragmented packet!"));
return;
} else {
l4pkt = &buf[14 + l3header_len];
l4pkt_len = total_len - l3header_len;
}
switch (ipproto) {
case 0x01: // ICMP
process_icmpipv4(&buf[14],l3header_len,l4pkt,l4pkt_len);
break;
case 0x06: // TCP
process_tcpipv4(&buf[14],l3header_len,l4pkt,l4pkt_len);
break;
case 0x11: // UDP
process_udpipv4(&buf[14],l3header_len,l4pkt,l4pkt_len);
break;
default:
BX_INFO(("unknown IP protocol %02x",ipproto));
break;
}
}
void bx_vnet_pktmover_c::host_to_guest_ipv4(Bit8u *buf, unsigned io_len)
{
unsigned l3header_len;
memcpy(&buf[0],&this->guest_macaddr[0],6);
memcpy(&buf[6],&this->host_macaddr[0],6);
buf[12]=0x08;
buf[13]=0x00;
buf[14+0] = (buf[14+0] & 0x0f) | 0x40;
l3header_len = ((unsigned)(buf[14+0] & 0x0f) << 2);
memcpy(&buf[14+12],&this->host_ipv4addr[0],4);
memcpy(&buf[14+16],&this->guest_ipv4addr[0],4);
put_net2(&buf[14+10], 0);
put_net2(&buf[14+10], ip_checksum(&buf[14],l3header_len) ^ (Bit16u)0xffff);
host_to_guest(buf,io_len);
}
layer4_handler_t bx_vnet_pktmover_c::get_layer4_handler(
unsigned ipprotocol, unsigned port)
{
unsigned n;
for (n = 0; n < l4data_used; n++) {
if (l4data[n].ipprotocol == ipprotocol && l4data[n].port == port)
return l4data[n].func;
}
return (layer4_handler_t)NULL;
}
bx_bool bx_vnet_pktmover_c::register_layer4_handler(
unsigned ipprotocol, unsigned port,layer4_handler_t func)
{
if (get_layer4_handler(ipprotocol,port) != (layer4_handler_t)NULL) {
BX_INFO(("IP protocol 0x%02x port %u is already in use",
ipprotocol,port));
return false;
}
unsigned n;
for (n = 0; n < l4data_used; n++) {
if (l4data[n].func == (layer4_handler_t)NULL) {
break;
}
}
if (n == l4data_used) {
if (n >= LAYER4_LISTEN_MAX) {
BX_ERROR(("vnet: LAYER4_LISTEN_MAX is too small"));
return false;
}
l4data_used++;
}
l4data[n].ipprotocol = ipprotocol;
l4data[n].port = port;
l4data[n].func = func;
return true;
}
bx_bool bx_vnet_pktmover_c::unregister_layer4_handler(
unsigned ipprotocol, unsigned port)
{
unsigned n;
for (n = 0; n < l4data_used; n++) {
if (l4data[n].ipprotocol == ipprotocol && l4data[n].port == port) {
l4data[n].func = (layer4_handler_t)NULL;
return true;
}
}
BX_ERROR(("IP protocol 0x%02x port %u is not registered",
ipprotocol,port));
return false;
}
void bx_vnet_pktmover_c::process_icmpipv4(
const Bit8u *ipheader, unsigned ipheader_len,
const Bit8u *l4pkt, unsigned l4pkt_len)
{
unsigned icmptype;
unsigned icmpcode;
if (l4pkt_len < 8) return;
icmptype = l4pkt[0];
icmpcode = l4pkt[1];
if (ip_checksum(l4pkt,l4pkt_len) != (Bit16u)0xffff) {
BX_INFO(("icmp: invalid checksum"));
return;
}
switch (icmptype) {
case 0x08: // ECHO
if (icmpcode == 0) {
process_icmpipv4_echo(ipheader,ipheader_len,l4pkt,l4pkt_len);
}
break;
default:
BX_INFO(("unhandled icmp packet: type=%u code=%u",
icmptype, icmpcode));
break;
}
}
void bx_vnet_pktmover_c::process_tcpipv4(
const Bit8u *ipheader, unsigned ipheader_len,
const Bit8u *l4pkt, unsigned l4pkt_len)
{
if (l4pkt_len < 20) return;
BX_INFO(("tcp packet - not implemented"));
}
void bx_vnet_pktmover_c::process_udpipv4(
const Bit8u *ipheader, unsigned ipheader_len,
const Bit8u *l4pkt, unsigned l4pkt_len)
{
unsigned udp_targetport;
unsigned udp_sourceport;
unsigned udp_len;
layer4_handler_t func;
if (l4pkt_len < 8) return;
udp_sourceport = get_net2(&l4pkt[0]);
udp_targetport = get_net2(&l4pkt[2]);
udp_len = get_net2(&l4pkt[4]);
func = get_layer4_handler(0x11,udp_targetport);
if (func != (layer4_handler_t)NULL) {
(*func)((void *)this,ipheader,ipheader_len,
udp_sourceport,udp_targetport,&l4pkt[8],l4pkt_len-8);
} else {
BX_INFO(("udp - unhandled port %u",udp_targetport));
}
}
void bx_vnet_pktmover_c::host_to_guest_udpipv4_packet(
unsigned target_port, unsigned source_port,
const Bit8u *udpdata, unsigned udpdata_len)
{
Bit8u ipbuf[BX_PACKET_BUFSIZE];
if ((udpdata_len + 42U) > BX_PACKET_BUFSIZE) {
BX_PANIC(("generated udp data is too long"));
return;
}
// udp pseudo-header
ipbuf[34U-12U]=0;
ipbuf[34U-11U]=0x11; // UDP
put_net2(&ipbuf[34U-10U],8U+udpdata_len);
memcpy(&ipbuf[34U-8U],host_ipv4addr,4);
memcpy(&ipbuf[34U-4U],guest_ipv4addr,4);
// udp header
put_net2(&ipbuf[34U+0],source_port);
put_net2(&ipbuf[34U+2],target_port);
put_net2(&ipbuf[34U+4],8U+udpdata_len);
put_net2(&ipbuf[34U+6],0);
memcpy(&ipbuf[42U],udpdata,udpdata_len);
put_net2(&ipbuf[34U+6], ip_checksum(&ipbuf[34U-12U],12U+8U+udpdata_len) ^ (Bit16u)0xffff);
// ip header
memset(&ipbuf[14U],0,20U);
ipbuf[14U+0] = 0x45;
ipbuf[14U+1] = 0x00;
put_net2(&ipbuf[14U+2],20U+8U+udpdata_len);
put_net2(&ipbuf[14U+4],1);
ipbuf[14U+6] = 0x00;
ipbuf[14U+7] = 0x00;
ipbuf[14U+8] = 0x07; // TTL
ipbuf[14U+9] = 0x11; // UDP
host_to_guest_ipv4(ipbuf,udpdata_len + 42U);
}
/////////////////////////////////////////////////////////////////////////
// ICMP/IPv4
/////////////////////////////////////////////////////////////////////////
void bx_vnet_pktmover_c::process_icmpipv4_echo(
const Bit8u *ipheader, unsigned ipheader_len,
const Bit8u *l4pkt, unsigned l4pkt_len)
{
Bit8u replybuf[ICMP_ECHO_PACKET_MAX];
if ((14U+ipheader_len+l4pkt_len) > ICMP_ECHO_PACKET_MAX) {
BX_ERROR(("icmp echo: size of an echo packet is too long"));
return;
}
memcpy(&replybuf[14],ipheader,ipheader_len);
memcpy(&replybuf[14+ipheader_len],l4pkt,l4pkt_len);
replybuf[14+ipheader_len+0] = 0x00; // echo reply
put_net2(&replybuf[14+ipheader_len+2],0);
put_net2(&replybuf[14+ipheader_len+2],
ip_checksum(&replybuf[14+ipheader_len],l4pkt_len) ^ (Bit16u)0xffff);
host_to_guest_ipv4(replybuf,14U+ipheader_len+l4pkt_len);
}
/////////////////////////////////////////////////////////////////////////
// DHCP/UDP/IPv4
/////////////////////////////////////////////////////////////////////////
void bx_vnet_pktmover_c::udpipv4_dhcp_handler(
void *this_ptr,
const Bit8u *ipheader, unsigned ipheader_len,
unsigned sourceport, unsigned targetport,
const Bit8u *data, unsigned data_len)
{
((bx_vnet_pktmover_c *)this_ptr)->udpipv4_dhcp_handler_ns(
ipheader,ipheader_len,sourceport,targetport,data,data_len);
}
void bx_vnet_pktmover_c::udpipv4_dhcp_handler_ns(
const Bit8u *ipheader, unsigned ipheader_len,
unsigned sourceport, unsigned targetport,
const Bit8u *data, unsigned data_len)
{
const Bit8u *opts;
unsigned opts_len;
unsigned extcode;
unsigned extlen;
const Bit8u *extdata;
unsigned dhcpmsgtype = 0;
bx_bool found_serverid = false;
bx_bool found_leasetime = false;
bx_bool found_guest_ipaddr = false;
Bit32u leasetime = BX_MAX_BIT32U;
const Bit8u *dhcpreqparams = NULL;
unsigned dhcpreqparams_len = 0;
Bit8u dhcpreqparam_default[8];
bx_bool dhcpreqparam_default_validflag = false;
unsigned dhcpreqparams_default_len = 0;
Bit8u *replyopts;
Bit8u replybuf[576];
if (data_len < (236U+64U)) return;
if (data[0] != BOOTREQUEST) return;
if (data[1] != 1 || data[2] != 6) return;
if (memcmp(&data[28U],guest_macaddr,6)) return;
if (data[236] != 0x63 || data[237] != 0x82 ||
data[238] != 0x53 || data[239] != 0x63) return;
opts = &data[240];
opts_len = data_len - 240U;
while (1) {
if (opts_len < 1) {
BX_ERROR(("dhcp: invalid request"));
return;
}
extcode = *opts++;
opts_len--;
if (extcode == BOOTPOPT_PADDING) continue;
if (extcode == BOOTPOPT_END) break;
if (opts_len < 1) {
BX_ERROR(("dhcp: invalid request"));
return;
}
extlen = *opts++;
opts_len--;
if (opts_len < extlen) {
BX_ERROR(("dhcp: invalid request"));
return;
}
extdata = opts;
opts += extlen;
opts_len -= extlen;
switch (extcode)
{
case BOOTPOPT_DHCP_MESSAGETYPE:
if (extlen != 1)
break;
dhcpmsgtype = *extdata;
break;
case BOOTPOPT_PARAMETER_REQUEST_LIST:
if (extlen < 1)
break;
dhcpreqparams = extdata;
dhcpreqparams_len = extlen;
break;
case BOOTPOPT_SERVER_IDENTIFIER:
if (extlen != 4)
break;
if (memcmp(extdata,host_ipv4addr,4)) {
BX_INFO(("dhcp: request to another server"));
return;
}
found_serverid = true;
break;
case BOOTPOPT_IP_ADDRESS_LEASE_TIME:
if (extlen != 4)
break;
leasetime = get_net4(&extdata[0]);
found_leasetime = true;
break;
case BOOTPOPT_REQUESTED_IP_ADDRESS:
if (extlen != 4)
break;
if (!memcmp(extdata,default_guest_ipv4addr,4)) {
found_guest_ipaddr = true;
memcpy(guest_ipv4addr,default_guest_ipv4addr,4);
}
break;
default:
BX_ERROR(("extcode %d not supported yet", extcode));
break;
}
}
memset(&dhcpreqparam_default,0,sizeof(dhcpreqparam_default));
memset(&replybuf[0],0,sizeof(replybuf));
replybuf[0] = BOOTREPLY;
replybuf[1] = 1;
replybuf[2] = 6;
memcpy(&replybuf[4],&data[4],4);
memcpy(&replybuf[16],default_guest_ipv4addr,4);
memcpy(&replybuf[20],host_ipv4addr,4);
memcpy(&replybuf[28],&data[28],6);
memcpy(&replybuf[44],"vnet",4);
memcpy(&replybuf[108],"pxelinux.0",10);
replybuf[236] = 0x63;
replybuf[237] = 0x82;
replybuf[238] = 0x53;
replybuf[239] = 0x63;
replyopts = &replybuf[240];
opts_len = sizeof(replybuf)/sizeof(replybuf[0])-240;
switch (dhcpmsgtype) {
case DHCPDISCOVER:
BX_INFO(("dhcp server: DHCPDISCOVER"));
*replyopts ++ = BOOTPOPT_DHCP_MESSAGETYPE;
*replyopts ++ = 1;
*replyopts ++ = DHCPOFFER;
opts_len -= 3;
dhcpreqparam_default[0] = BOOTPOPT_IP_ADDRESS_LEASE_TIME;
dhcpreqparam_default[1] = BOOTPOPT_SERVER_IDENTIFIER;
dhcpreqparam_default_validflag = true;
break;
case DHCPREQUEST:
BX_INFO(("dhcp server: DHCPREQUEST"));
// check ciaddr.
if (found_serverid || found_guest_ipaddr || (!memcmp(&data[12],default_guest_ipv4addr,4))) {
*replyopts ++ = BOOTPOPT_DHCP_MESSAGETYPE;
*replyopts ++ = 1;
*replyopts ++ = DHCPACK;
opts_len -= 3;
dhcpreqparam_default[0] = BOOTPOPT_IP_ADDRESS_LEASE_TIME;
if (!found_serverid) {
dhcpreqparam_default[1] = BOOTPOPT_SERVER_IDENTIFIER;
}
dhcpreqparam_default_validflag = true;
} else {
*replyopts ++ = BOOTPOPT_DHCP_MESSAGETYPE;
*replyopts ++ = 1;
*replyopts ++ = DHCPNAK;
opts_len -= 3;
if (found_leasetime) {
dhcpreqparam_default[dhcpreqparams_default_len++] = BOOTPOPT_IP_ADDRESS_LEASE_TIME;
dhcpreqparam_default_validflag = true;
}
if (!found_serverid) {
dhcpreqparam_default[dhcpreqparams_default_len++] = BOOTPOPT_SERVER_IDENTIFIER;
dhcpreqparam_default_validflag = true;
}
}
break;
default:
BX_ERROR(("dhcp server: unsupported message type %u",dhcpmsgtype));
return;
}
while (1) {
while (dhcpreqparams_len-- > 0) {
switch (*dhcpreqparams++) {
case BOOTPOPT_SUBNETMASK:
BX_INFO(("provide BOOTPOPT_SUBNETMASK"));
if (opts_len < 6) {
BX_ERROR(("option buffer is insufficient"));
return;
}
opts_len -= 6;
*replyopts ++ = BOOTPOPT_SUBNETMASK;
*replyopts ++ = 4;
memcpy(replyopts,subnetmask_ipv4addr,4);
replyopts += 4;
break;
case BOOTPOPT_ROUTER_OPTION:
BX_INFO(("provide BOOTPOPT_ROUTER_OPTION"));
if (opts_len < 6) {
BX_ERROR(("option buffer is insufficient"));
return;
}
opts_len -= 6;
*replyopts ++ = BOOTPOPT_ROUTER_OPTION;
*replyopts ++ = 4;
memcpy(replyopts,host_ipv4addr,4);
replyopts += 4;
break;
#if 0 // DNS is not implemented.
case BOOTPOPT_DOMAIN_NAMESERVER:
BX_INFO(("provide BOOTPOPT_DOMAIN_NAMESERVER"));
if (opts_len < 6) {
BX_ERROR(("option buffer is insufficient"));
return;
}
opts_len -= 6;
*replyopts ++ = BOOTPOPT_DOMAIN_NAMESERVER;
*replyopts ++ = 4;
memcpy(replyopts,host_ipv4addr,4);
replyopts += 4;
break;
#endif
case BOOTPOPT_BROADCAST_ADDRESS:
BX_INFO(("provide BOOTPOPT_BROADCAST_ADDRESS"));
if (opts_len < 6) {
BX_ERROR(("option buffer is insufficient"));
return;
}
opts_len -= 6;
*replyopts ++ = BOOTPOPT_BROADCAST_ADDRESS;
*replyopts ++ = 4;
memcpy(replyopts,broadcast_ipv4addr[2],4);
replyopts += 4;
break;
case BOOTPOPT_IP_ADDRESS_LEASE_TIME:
BX_INFO(("provide BOOTPOPT_IP_ADDRESS_LEASE_TIME"));
if (opts_len < 6) {
BX_ERROR(("option buffer is insufficient"));
return;
}
opts_len -= 6;
*replyopts ++ = BOOTPOPT_IP_ADDRESS_LEASE_TIME;
*replyopts ++ = 4;
if (leasetime < DEFAULT_LEASE_TIME) {
put_net4(replyopts, leasetime);
} else {
put_net4(replyopts, DEFAULT_LEASE_TIME);
}
replyopts += 4;
break;
case BOOTPOPT_SERVER_IDENTIFIER:
BX_INFO(("provide BOOTPOPT_SERVER_IDENTIFIER"));
if (opts_len < 6) {
BX_ERROR(("option buffer is insufficient"));
return;
}
opts_len -= 6;
*replyopts ++ = BOOTPOPT_SERVER_IDENTIFIER;
*replyopts ++ = 4;
memcpy(replyopts,host_ipv4addr,4);
replyopts += 4;
break;
case BOOTPOPT_RENEWAL_TIME:
BX_INFO(("provide BOOTPOPT_RENEWAL_TIME"));
if (opts_len < 6) {
BX_ERROR(("option buffer is insufficient"));
return;
}
opts_len -= 6;
*replyopts ++ = BOOTPOPT_RENEWAL_TIME;
*replyopts ++ = 4;
put_net4(replyopts, 600);
replyopts += 4;
break;
case BOOTPOPT_REBINDING_TIME:
BX_INFO(("provide BOOTPOPT_REBINDING_TIME"));
if (opts_len < 6) {
BX_ERROR(("option buffer is insufficient"));
return;
}
opts_len -= 6;
*replyopts ++ = BOOTPOPT_REBINDING_TIME;
*replyopts ++ = 4;
put_net4(replyopts, 1800);
replyopts += 4;
break;
default:
if (*(dhcpreqparams-1) != 0) {
BX_ERROR(("dhcp server: requested parameter %u not supported yet",*(dhcpreqparams-1)));
}
break;
}
}
if (!dhcpreqparam_default_validflag) break;
dhcpreqparams = &dhcpreqparam_default[0];
dhcpreqparams_len = sizeof(dhcpreqparam_default);
dhcpreqparam_default_validflag = false;
}
if (opts_len < 1) {
BX_ERROR(("option buffer is insufficient"));
return;
}
opts_len -= 2;
*replyopts ++ = BOOTPOPT_END;
opts_len = replyopts - &replybuf[0];
if (opts_len < (236U+64U)) {
opts_len = (236U+64U); // BOOTP
}
if (opts_len < (548U)) {
opts_len = 548U; // DHCP
}
host_to_guest_udpipv4_packet(
sourceport, targetport,
replybuf, opts_len);
}
void bx_vnet_pktmover_c::udpipv4_tftp_handler(
void *this_ptr,
const Bit8u *ipheader, unsigned ipheader_len,
unsigned sourceport, unsigned targetport,
const Bit8u *data, unsigned data_len)
{
((bx_vnet_pktmover_c *)this_ptr)->udpipv4_tftp_handler_ns(
ipheader,ipheader_len,sourceport,targetport,data,data_len);
}
void bx_vnet_pktmover_c::udpipv4_tftp_handler_ns(
const Bit8u *ipheader, unsigned ipheader_len,
unsigned sourceport, unsigned targetport,
const Bit8u *data, unsigned data_len)
{
Bit8u buffer[TFTP_BUFFER_SIZE + 4];
char path[BX_PATHNAME_LEN];
FILE *fp;
unsigned block_nr;
unsigned tftp_len;
switch (get_net2(data)) {
case TFTP_RRQ:
if (tftp_tid == 0) {
strncpy((char*)buffer, (const char*)data + 2, data_len - 2);
buffer[data_len - 4] = 0;
// options
size_t tsize_option = 0;
int blksize_option = 0;
if (strlen((char*)buffer) < data_len - 2) {
const char *mode = (const char*)data + 2 + strlen((char*)buffer) + 1;
int octet_option = 0;
while (mode < (const char*)data + data_len) {
if (memcmp(mode, "octet\0", 6) == 0) {
mode += 6;
octet_option = 1;
} else if (memcmp(mode, "tsize\0", 6) == 0) {
mode += 6;
tsize_option = 1; // size needed
mode += strlen(mode)+1;
} else if (memcmp(mode, "blksize\0", 8) == 0) {
mode += 8;
blksize_option = atoi(mode);
mode += strlen(mode)+1;
} else {
BX_INFO(("tftp req: unknown option %s", mode));
break;
}
}
if (!octet_option) {
tftp_send_error(buffer, sourceport, targetport, 4, "Unsupported transfer mode");
return;
}
}
strcpy(tftp_filename, (char*)buffer);
BX_INFO(("tftp req: %s", tftp_filename));
if (tsize_option) {
tsize_option = get_file_size(tftp_rootdir, tftp_filename);
if (tsize_option > 0) {
// if tsize requested and file exists, send optack and return
// optack ack will pick up where we leave off here.
// if blksize_option is less than TFTP_BUFFER_SIZE should
// probably use blksize_option...
tftp_send_optack(buffer, sourceport, targetport, tsize_option, TFTP_BUFFER_SIZE);
return;
}
}
tftp_tid = sourceport;
tftp_write = 0;
tftp_send_data(buffer, sourceport, targetport, 1);
} else {
tftp_send_error(buffer, sourceport, targetport, 4, "Illegal request");
}
break;
case TFTP_WRQ:
if (tftp_tid == 0) {
strncpy((char*)buffer, (const char*)data + 2, data_len - 2);
buffer[data_len - 4] = 0;
// transfer mode
if (strlen((char*)buffer) < data_len - 2) {
const char *mode = (const char*)data + 2 + strlen((char*)buffer) + 1;
if (memcmp(mode, "octet\0", 6) != 0) {
tftp_send_error(buffer, sourceport, targetport, 4, "Unsupported transfer mode");
return;
}
}
strcpy(tftp_filename, (char*)buffer);
sprintf(path, "%s/%s", tftp_rootdir, tftp_filename);
fp = fopen(path, "rb");
if (fp) {
tftp_send_error(buffer, sourceport, targetport, 6, "File exists");
fclose(fp);
return;
}
fp = fopen(path, "wb");
if (!fp) {
tftp_send_error(buffer, sourceport, targetport, 2, "Access violation");
return;
}
fclose(fp);
tftp_tid = sourceport;
tftp_write = 1;
tftp_send_ack(buffer, sourceport, targetport, 0);
} else {
tftp_send_error(buffer, sourceport, targetport, 4, "Illegal request");
}
break;
case TFTP_DATA:
if ((tftp_tid == sourceport) && (tftp_write == 1)) {
block_nr = get_net2(data + 2);
strncpy((char*)buffer, (const char*)data + 4, data_len - 4);
tftp_len = data_len - 4;
buffer[tftp_len] = 0;
if (tftp_len <= 512) {
sprintf(path, "%s/%s", tftp_rootdir, tftp_filename);
fp = fopen(path, "ab");
if (!fp) {
tftp_send_error(buffer, sourceport, targetport, 2, "Access violation");
return;
}
if (fseek(fp, (block_nr - 1) * TFTP_BUFFER_SIZE, SEEK_SET) < 0) {
tftp_send_error(buffer, sourceport, targetport, 3, "Block not seekable");
return;
}
fwrite(buffer, 1, tftp_len, fp);
fclose(fp);
tftp_send_ack(buffer, sourceport, targetport, block_nr);
if (tftp_len < 512) {
tftp_tid = 0;
}
} else {
tftp_send_error(buffer, sourceport, targetport, 4, "Illegal request");
}
} else {
tftp_send_error(buffer, sourceport, targetport, 4, "Illegal request");
}
break;
case TFTP_ACK:
tftp_send_data(buffer, sourceport, targetport, get_net2(data + 2) + 1);
break;
case TFTP_ERROR:
// silently ignore error packets
break;
default:
BX_ERROR(("TFTP unknown opt %d", get_net2(data)));
}
}
void bx_vnet_pktmover_c::tftp_send_error(
Bit8u *buffer,
unsigned sourceport, unsigned targetport,
unsigned code, const char *msg)
{
put_net2(buffer, TFTP_ERROR);
put_net2(buffer + 2, code);
strcpy((char*)buffer + 4, msg);
host_to_guest_udpipv4_packet(sourceport, targetport, buffer, strlen(msg) + 5);
tftp_tid = 0;
}
void bx_vnet_pktmover_c::tftp_send_data(
Bit8u *buffer,
unsigned sourceport, unsigned targetport,
unsigned block_nr)
{
char path[BX_PATHNAME_LEN];
char msg[BX_PATHNAME_LEN];
int rd;
if (strlen(tftp_filename) == 0) {
tftp_send_error(buffer, sourceport, targetport, 1, "File not found");
return;
}
if ((strlen(tftp_rootdir) + strlen(tftp_filename)) > BX_PATHNAME_LEN) {
tftp_send_error(buffer, sourceport, targetport, 1, "Path name too long");
return;
}
sprintf(path, "%s/%s", tftp_rootdir, tftp_filename);
FILE *fp = fopen(path, "rb");
if (!fp) {
sprintf(msg, "File not found: %s", tftp_filename);
tftp_send_error(buffer, sourceport, targetport, 1, msg);
return;
}
if (fseek(fp, (block_nr - 1) * TFTP_BUFFER_SIZE, SEEK_SET) < 0) {
tftp_send_error(buffer, sourceport, targetport, 3, "Block not seekable");
return;
}
rd = fread(buffer + 4, 1, TFTP_BUFFER_SIZE, fp);
fclose(fp);
if (rd < 0) {
tftp_send_error(buffer, sourceport, targetport, 3, "Block not readable");
return;
}
put_net2(buffer, TFTP_DATA);
put_net2(buffer + 2, block_nr);
host_to_guest_udpipv4_packet(sourceport, targetport, buffer, rd + 4);
if (rd < TFTP_BUFFER_SIZE) {
tftp_tid = 0;
}
}
void bx_vnet_pktmover_c::tftp_send_ack(
Bit8u *buffer,
unsigned sourceport, unsigned targetport,
unsigned block_nr)
{
put_net2(buffer, TFTP_ACK);
put_net2(buffer + 2, block_nr);
host_to_guest_udpipv4_packet(sourceport, targetport, buffer, 4);
}
void bx_vnet_pktmover_c::tftp_send_optack(
Bit8u *buffer,
unsigned sourceport, unsigned targetport,
size_t tsize_option, unsigned blksize_option)
{
Bit8u *p = buffer;
put_net2(p, TFTP_OPTACK);
p += 2;
if (tsize_option > 0) {
*p++='t'; *p++='s'; *p++='i'; *p++='z'; *p++='e'; *p++='\0';
sprintf((char *)p, "%lu", (unsigned long)tsize_option);
p += strlen((const char *)p) + 1;
}
if (blksize_option > 0) {
*p++='b'; *p++='l'; *p++='k'; *p++='s'; *p++='i'; *p++='z'; *p++='e'; *p++='\0';
sprintf((char *)p, "%d", blksize_option); p += strlen((const char *)p) + 1;
}
host_to_guest_udpipv4_packet(sourceport, targetport, buffer, p - buffer);
}
#endif /* if BX_NETWORKING */
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.