repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
minekrexx/mccVS
mccVS/mccVS/ProjectType/obj/Debug/projectreference.cs
18291
//------------------------------------------------------------------------------ // <auto-generated> // Dieser Code wurde von einem Tool generiert. // Laufzeitversion:4.0.30319.42000 // // Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn // der Code erneut generiert wird. // </auto-generated> //------------------------------------------------------------------------------ namespace ProjectType { internal partial class ProjectReference { /// <summary>Backing field for deserialized rule.<see cref='Microsoft.Build.Framework.XamlTypes.Rule'/>.</summary> private static Microsoft.Build.Framework.XamlTypes.Rule deserializedFallbackRule; /// <summary>The name of the schema to look for at runtime to fulfill property access.</summary> internal const string SchemaName = "ProjectReference"; /// <summary>The ItemType given in the Rule.DataSource property. May not apply to every Property's individual DataSource.</summary> internal const string PrimaryDataSourceItemType = "ProjectReference"; /// <summary>The Label given in the Rule.DataSource property. May not apply to every Property's individual DataSource.</summary> internal const string PrimaryDataSourceLabel = ""; /// <summary>A value indicating whether the compiler should include a reference to the target project's primary output assembly. (The "ReferenceOutputAssembly" property).</summary> internal const string ReferenceOutputAssemblyProperty = "ReferenceOutputAssembly"; /// <summary>Indicates whether the primary output of the reference target should be copied into this project's output directory, when that metadata is set on an unresolved reference. (The "Private" property).</summary> internal const string PrivateProperty = "Private"; /// <summary>Indicates whether the satellite assemblies of the reference target should be copied into this project's output directory. (The "CopyLocalSatelliteAssemblies" property).</summary> internal const string CopyLocalSatelliteAssembliesProperty = "CopyLocalSatelliteAssemblies"; /// <summary> (The "LinkLibraryDependencies" property).</summary> internal const string LinkLibraryDependenciesProperty = "LinkLibraryDependencies"; /// <summary> (The "UseLibraryDependencyInputs" property).</summary> internal const string UseLibraryDependencyInputsProperty = "UseLibraryDependencyInputs"; /// <summary>the Guid the solution tracks an individual project reference target with (The "Project" property).</summary> internal const string ProjectProperty = "Project"; /// <summary>The old (VS2010 beta) way to store the Guid the solution tracks an individual project reference target with (The "ReferencedProjectIdentifier" property).</summary> internal const string ReferencedProjectIdentifierProperty = "ReferencedProjectIdentifier"; /// <summary>Backing field for the <see cref='Microsoft.Build.Framework.XamlTypes.Rule'/> property.</summary> private Microsoft.VisualStudio.ProjectSystem.Properties.IRule rule; /// <summary>Backing field for the file name of the rule property.</summary> private string file; /// <summary>Backing field for the ItemType property.</summary> private string itemType; /// <summary>Backing field for the ItemName property.</summary> private string itemName; /// <summary>Configured Project</summary> private Microsoft.VisualStudio.ProjectSystem.ConfiguredProject configuredProject; /// <summary>The dictionary of named catalogs.</summary> private System.Collections.Immutable.IImmutableDictionary<string, Microsoft.VisualStudio.ProjectSystem.Properties.IPropertyPagesCatalog> catalogs; /// <summary>Backing field for the <see cref='Microsoft.VisualStudio.ProjectSystem.Properties.IRule'/> property.</summary> private Microsoft.VisualStudio.ProjectSystem.Properties.IRule fallbackRule; /// <summary>Thread locking object</summary> private object locker = new object(); /// <summary>Initializes a new instance of the ProjectReference class.</summary> internal ProjectReference(Microsoft.VisualStudio.ProjectSystem.Properties.IRule rule) { this.rule = rule; } /// <summary>Initializes a new instance of the ProjectReference class.</summary> internal ProjectReference(Microsoft.VisualStudio.ProjectSystem.ConfiguredProject configuredProject, System.Collections.Immutable.IImmutableDictionary<string, Microsoft.VisualStudio.ProjectSystem.Properties.IPropertyPagesCatalog> catalogs, string context, string file, string itemType, string itemName) : this(GetRule(System.Collections.Immutable.ImmutableDictionary.GetValueOrDefault(catalogs, context), file, itemType, itemName)) { if ((configuredProject == null)) { throw new System.ArgumentNullException("configuredProject"); } this.configuredProject = configuredProject; this.catalogs = catalogs; this.file = file; this.itemType = itemType; this.itemName = itemName; } /// <summary>Initializes a new instance of the ProjectReference class.</summary> internal ProjectReference(Microsoft.VisualStudio.ProjectSystem.Properties.IRule rule, Microsoft.VisualStudio.ProjectSystem.ConfiguredProject configuredProject) : this(rule) { if ((rule == null)) { throw new System.ArgumentNullException("rule"); } if ((configuredProject == null)) { throw new System.ArgumentNullException("configuredProject"); } this.configuredProject = configuredProject; this.rule = rule; this.file = this.rule.File; this.itemType = this.rule.ItemType; this.itemName = this.rule.ItemName; } /// <summary>Initializes a new instance of the ProjectReference class.</summary> internal ProjectReference(Microsoft.VisualStudio.ProjectSystem.ConfiguredProject configuredProject, System.Collections.Immutable.IImmutableDictionary<string, Microsoft.VisualStudio.ProjectSystem.Properties.IPropertyPagesCatalog> catalogs, string context, Microsoft.VisualStudio.ProjectSystem.Properties.IProjectPropertiesContext propertyContext) : this(configuredProject, catalogs, context, GetContextFile(propertyContext), propertyContext.ItemType, propertyContext.ItemName) { } /// <summary>Initializes a new instance of the ProjectReference class that assumes a project context (neither property sheet nor items).</summary> internal ProjectReference(Microsoft.VisualStudio.ProjectSystem.ConfiguredProject configuredProject, System.Collections.Immutable.IImmutableDictionary<string, Microsoft.VisualStudio.ProjectSystem.Properties.IPropertyPagesCatalog> catalogs) : this(configuredProject, catalogs, "Project", null, null, null) { } /// <summary>Gets the IRule used to get and set properties.</summary> public Microsoft.VisualStudio.ProjectSystem.Properties.IRule Rule { get { return this.rule; } } /// <summary>A value indicating whether the compiler should include a reference to the target project&apos;s primary output assembly.</summary> internal Microsoft.VisualStudio.ProjectSystem.Properties.IEvaluatedProperty ReferenceOutputAssembly { get { Microsoft.VisualStudio.ProjectSystem.Properties.IRule localRule = this.rule; if ((localRule == null)) { localRule = this.GeneratedFallbackRule; } if ((localRule == null)) { return null; } Microsoft.VisualStudio.ProjectSystem.Properties.IEvaluatedProperty property = ((Microsoft.VisualStudio.ProjectSystem.Properties.IEvaluatedProperty)(localRule.GetProperty(ReferenceOutputAssemblyProperty))); if (((property == null) && (this.GeneratedFallbackRule != null))) { localRule = this.GeneratedFallbackRule; property = ((Microsoft.VisualStudio.ProjectSystem.Properties.IEvaluatedProperty)(localRule.GetProperty(ReferenceOutputAssemblyProperty))); } return property; } } /// <summary>Indicates whether the primary output of the reference target should be copied into this project&apos;s output directory, when that metadata is set on an unresolved reference.</summary> internal Microsoft.VisualStudio.ProjectSystem.Properties.IEvaluatedProperty Private { get { Microsoft.VisualStudio.ProjectSystem.Properties.IRule localRule = this.rule; if ((localRule == null)) { localRule = this.GeneratedFallbackRule; } if ((localRule == null)) { return null; } Microsoft.VisualStudio.ProjectSystem.Properties.IEvaluatedProperty property = ((Microsoft.VisualStudio.ProjectSystem.Properties.IEvaluatedProperty)(localRule.GetProperty(PrivateProperty))); if (((property == null) && (this.GeneratedFallbackRule != null))) { localRule = this.GeneratedFallbackRule; property = ((Microsoft.VisualStudio.ProjectSystem.Properties.IEvaluatedProperty)(localRule.GetProperty(PrivateProperty))); } return property; } } /// <summary>Indicates whether the satellite assemblies of the reference target should be copied into this project&apos;s output directory.</summary> internal Microsoft.VisualStudio.ProjectSystem.Properties.IEvaluatedProperty CopyLocalSatelliteAssemblies { get { Microsoft.VisualStudio.ProjectSystem.Properties.IRule localRule = this.rule; if ((localRule == null)) { localRule = this.GeneratedFallbackRule; } if ((localRule == null)) { return null; } Microsoft.VisualStudio.ProjectSystem.Properties.IEvaluatedProperty property = ((Microsoft.VisualStudio.ProjectSystem.Properties.IEvaluatedProperty)(localRule.GetProperty(CopyLocalSatelliteAssembliesProperty))); if (((property == null) && (this.GeneratedFallbackRule != null))) { localRule = this.GeneratedFallbackRule; property = ((Microsoft.VisualStudio.ProjectSystem.Properties.IEvaluatedProperty)(localRule.GetProperty(CopyLocalSatelliteAssembliesProperty))); } return property; } } /// <summary>LinkLibraryDependencies</summary> internal Microsoft.VisualStudio.ProjectSystem.Properties.IEvaluatedProperty LinkLibraryDependencies { get { Microsoft.VisualStudio.ProjectSystem.Properties.IRule localRule = this.rule; if ((localRule == null)) { localRule = this.GeneratedFallbackRule; } if ((localRule == null)) { return null; } Microsoft.VisualStudio.ProjectSystem.Properties.IEvaluatedProperty property = ((Microsoft.VisualStudio.ProjectSystem.Properties.IEvaluatedProperty)(localRule.GetProperty(LinkLibraryDependenciesProperty))); if (((property == null) && (this.GeneratedFallbackRule != null))) { localRule = this.GeneratedFallbackRule; property = ((Microsoft.VisualStudio.ProjectSystem.Properties.IEvaluatedProperty)(localRule.GetProperty(LinkLibraryDependenciesProperty))); } return property; } } /// <summary>UseLibraryDependencyInputs</summary> internal Microsoft.VisualStudio.ProjectSystem.Properties.IEvaluatedProperty UseLibraryDependencyInputs { get { Microsoft.VisualStudio.ProjectSystem.Properties.IRule localRule = this.rule; if ((localRule == null)) { localRule = this.GeneratedFallbackRule; } if ((localRule == null)) { return null; } Microsoft.VisualStudio.ProjectSystem.Properties.IEvaluatedProperty property = ((Microsoft.VisualStudio.ProjectSystem.Properties.IEvaluatedProperty)(localRule.GetProperty(UseLibraryDependencyInputsProperty))); if (((property == null) && (this.GeneratedFallbackRule != null))) { localRule = this.GeneratedFallbackRule; property = ((Microsoft.VisualStudio.ProjectSystem.Properties.IEvaluatedProperty)(localRule.GetProperty(UseLibraryDependencyInputsProperty))); } return property; } } /// <summary>the Guid the solution tracks an individual project reference target with</summary> internal Microsoft.VisualStudio.ProjectSystem.Properties.IEvaluatedProperty Project { get { Microsoft.VisualStudio.ProjectSystem.Properties.IRule localRule = this.rule; if ((localRule == null)) { localRule = this.GeneratedFallbackRule; } if ((localRule == null)) { return null; } Microsoft.VisualStudio.ProjectSystem.Properties.IEvaluatedProperty property = ((Microsoft.VisualStudio.ProjectSystem.Properties.IEvaluatedProperty)(localRule.GetProperty(ProjectProperty))); if (((property == null) && (this.GeneratedFallbackRule != null))) { localRule = this.GeneratedFallbackRule; property = ((Microsoft.VisualStudio.ProjectSystem.Properties.IEvaluatedProperty)(localRule.GetProperty(ProjectProperty))); } return property; } } /// <summary>The old (VS2010 beta) way to store the Guid the solution tracks an individual project reference target with</summary> internal Microsoft.VisualStudio.ProjectSystem.Properties.IEvaluatedProperty ReferencedProjectIdentifier { get { Microsoft.VisualStudio.ProjectSystem.Properties.IRule localRule = this.rule; if ((localRule == null)) { localRule = this.GeneratedFallbackRule; } if ((localRule == null)) { return null; } Microsoft.VisualStudio.ProjectSystem.Properties.IEvaluatedProperty property = ((Microsoft.VisualStudio.ProjectSystem.Properties.IEvaluatedProperty)(localRule.GetProperty(ReferencedProjectIdentifierProperty))); if (((property == null) && (this.GeneratedFallbackRule != null))) { localRule = this.GeneratedFallbackRule; property = ((Microsoft.VisualStudio.ProjectSystem.Properties.IEvaluatedProperty)(localRule.GetProperty(ReferencedProjectIdentifierProperty))); } return property; } } /// <summary>Get the fallback rule if the current rule on disk is missing or a property in the rule on disk is missing</summary> private Microsoft.VisualStudio.ProjectSystem.Properties.IRule GeneratedFallbackRule { get { if (((this.fallbackRule == null) && (this.configuredProject != null))) { System.Threading.Monitor.Enter(this.locker); try { if ((this.fallbackRule == null)) { this.InitializeFallbackRule(); } } finally { System.Threading.Monitor.Exit(this.locker); } } return this.fallbackRule; } } private static Microsoft.VisualStudio.ProjectSystem.Properties.IRule GetRule(Microsoft.VisualStudio.ProjectSystem.Properties.IPropertyPagesCatalog catalog, string file, string itemType, string itemName) { if ((catalog == null)) { return null; } return catalog.BindToContext(SchemaName, file, itemType, itemName); } private static string GetContextFile(Microsoft.VisualStudio.ProjectSystem.Properties.IProjectPropertiesContext propertiesContext) { if ((propertiesContext.IsProjectFile == true)) { return null; } else { return propertiesContext.File; } } private void InitializeFallbackRule() { if ((this.configuredProject == null)) { return; } Microsoft.Build.Framework.XamlTypes.Rule unboundRule = ProjectReference.deserializedFallbackRule; if ((unboundRule == null)) { System.IO.Stream xamlStream = null; System.Reflection.Assembly thisAssembly = System.Reflection.Assembly.GetExecutingAssembly(); try { xamlStream = thisAssembly.GetManifestResourceStream("XamlRuleToCode:projectreference.xaml"); Microsoft.Build.Framework.XamlTypes.IProjectSchemaNode root = ((Microsoft.Build.Framework.XamlTypes.IProjectSchemaNode)(System.Xaml.XamlServices.Load(xamlStream))); System.Collections.Generic.IEnumerator<System.Object> ruleEnumerator = root.GetSchemaObjects(typeof(Microsoft.Build.Framework.XamlTypes.Rule)).GetEnumerator(); for ( ; ((unboundRule == null) && ruleEnumerator.MoveNext()); ) { Microsoft.Build.Framework.XamlTypes.Rule t = ((Microsoft.Build.Framework.XamlTypes.Rule)(ruleEnumerator.Current)); if (System.StringComparer.OrdinalIgnoreCase.Equals(t.Name, SchemaName)) { unboundRule = t; unboundRule.Name = "006a86bd-8070-4b2a-bba4-66183b0d3b67"; ProjectReference.deserializedFallbackRule = unboundRule; } } } finally { if ((xamlStream != null)) { ((System.IDisposable)(xamlStream)).Dispose(); } } } this.configuredProject.Services.AdditionalRuleDefinitions.AddRuleDefinition(unboundRule, "FallbackRuleCodeGenerationContext"); Microsoft.VisualStudio.ProjectSystem.Properties.IPropertyPagesCatalog catalog = this.configuredProject.Services.PropertyPagesCatalog.GetMemoryOnlyCatalog("FallbackRuleCodeGenerationContext"); this.fallbackRule = catalog.BindToContext(unboundRule.Name, this.file, this.itemType, this.itemName); } } internal partial class ProjectProperties { private static System.Func<System.Threading.Tasks.Task<System.Collections.Immutable.IImmutableDictionary<string, Microsoft.VisualStudio.ProjectSystem.Properties.IPropertyPagesCatalog>>, object, ProjectReference> CreateProjectReferencePropertiesDelegate = new System.Func<System.Threading.Tasks.Task<System.Collections.Immutable.IImmutableDictionary<string, Microsoft.VisualStudio.ProjectSystem.Properties.IPropertyPagesCatalog>>, object, ProjectReference>(CreateProjectReferenceProperties); private static ProjectReference CreateProjectReferenceProperties(System.Threading.Tasks.Task<System.Collections.Immutable.IImmutableDictionary<string, Microsoft.VisualStudio.ProjectSystem.Properties.IPropertyPagesCatalog>> namedCatalogs, object state) { ProjectProperties that = ((ProjectProperties)(state)); return new ProjectReference(that.ConfiguredProject, namedCatalogs.Result, "Project", that.File, that.ItemType, that.ItemName); } /// <summary>Gets the strongly-typed property accessor used to get and set Project reference properties properties.</summary> internal System.Threading.Tasks.Task<ProjectReference> GetProjectReferencePropertiesAsync() { System.Threading.Tasks.Task<System.Collections.Immutable.IImmutableDictionary<string, Microsoft.VisualStudio.ProjectSystem.Properties.IPropertyPagesCatalog>> namedCatalogsTask = this.GetNamedCatalogsAsync(); return namedCatalogsTask.ContinueWith(CreateProjectReferencePropertiesDelegate, this, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskContinuationOptions.ExecuteSynchronously, System.Threading.Tasks.TaskScheduler.Default); } } }
apache-2.0
duantonghai1984/Research
src/main/java/com/hp/hpl/hibernate/hbm/Person.java
1478
package com.hp.hpl.hibernate.hbm; import java.util.*; public class Person { private Long id; private int age; private String firstname; private String lastname; public Person() {} public Long getId() { return id; } public void setId(Long id) { this.id = id; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } private Set emailAddresses = new HashSet(); public Set getEmailAddresses() { return emailAddresses; } public void setEmailAddresses(Set emailAddresses) { this.emailAddresses = emailAddresses; } private Set events = new HashSet(); // Defensive, convenience methods protected Set getEvents() { return events; } protected void setEvents(Set events) { this.events = events; } public void addToEvent(Event event) { this.getEvents().add(event); event.getParticipants().add(this); } public void removeFromEvent(Event event) { this.getEvents().remove(event); event.getParticipants().remove(this); } }
apache-2.0
lunisolar/magma
magma-func/src/test/java/eu/lunisolar/magma/func/function/to/LToIntFunctionTest.java
16720
/* * This file is part of "lunisolar-magma". * * (C) Copyright 2014-2019 Lunisolar (http://lunisolar.eu/). * * 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 eu.lunisolar.magma.func.function.to; import eu.lunisolar.magma.func.*; // NOSONAR import javax.annotation.Nonnull; // NOSONAR import javax.annotation.Nullable; // NOSONAR import java.util.Objects;// NOSONAR import eu.lunisolar.magma.basics.meta.*; // NOSONAR import eu.lunisolar.magma.basics.meta.functional.*; // NOSONAR import eu.lunisolar.magma.basics.meta.functional.type.*; // NOSONAR import eu.lunisolar.magma.basics.meta.functional.domain.*; // NOSONAR import eu.lunisolar.magma.func.action.*; // NOSONAR import eu.lunisolar.magma.func.consumer.*; // NOSONAR import eu.lunisolar.magma.func.consumer.primitives.*; // NOSONAR import eu.lunisolar.magma.func.consumer.primitives.bi.*; // NOSONAR import eu.lunisolar.magma.func.consumer.primitives.obj.*; // NOSONAR import eu.lunisolar.magma.func.consumer.primitives.tri.*; // NOSONAR import eu.lunisolar.magma.func.function.*; // NOSONAR import eu.lunisolar.magma.func.function.conversion.*; // NOSONAR import eu.lunisolar.magma.func.function.from.*; // NOSONAR import eu.lunisolar.magma.func.function.to.*; // NOSONAR import eu.lunisolar.magma.func.operator.binary.*; // NOSONAR import eu.lunisolar.magma.func.operator.ternary.*; // NOSONAR import eu.lunisolar.magma.func.operator.unary.*; // NOSONAR import eu.lunisolar.magma.func.predicate.*; // NOSONAR import eu.lunisolar.magma.func.supplier.*; // NOSONAR import org.assertj.core.api.Assertions; //NOSONAR import org.testng.annotations.*; //NOSONAR import java.util.regex.Pattern; //NOSONAR import java.text.ParseException; //NOSONAR import eu.lunisolar.magma.basics.*; //NOSONAR import eu.lunisolar.magma.basics.exceptions.*; //NOSONAR import java.util.concurrent.atomic.AtomicInteger; //NOSONAR import eu.lunisolar.magma.func.tuple.*; // NOSONAR import static org.assertj.core.api.Assertions.*; //NOSONAR import java.util.function.*; // NOSONAR /** The test obviously concentrate on the interface methods the function it self is very simple. */ public class LToIntFunctionTest<T> { private static final String ORIGINAL_MESSAGE = "Original message"; private static final String EXCEPTION_WAS_WRAPPED = "Exception was wrapped."; private static final String NO_EXCEPTION_WERE_THROWN = "No exception were thrown."; private int testValue = 100; private LToIntFunction<Integer> sut = new LToIntFunction<Integer>(){ public int applyAsIntX(Integer a) { return testValue; } }; private ToIntFunction<Integer> jre = a -> testValue; private LToIntFunction<Integer> sutAlwaysThrowing = LToIntFunction.toIntFunc(a -> { throw new ParseException(ORIGINAL_MESSAGE, 0); }); private LToIntFunction<Integer> sutAlwaysThrowingUnchecked = LToIntFunction.toIntFunc(a -> { throw new IndexOutOfBoundsException(ORIGINAL_MESSAGE); }); @Test public void testTheResult() throws Throwable { assertThat(sut.applyAsInt(100)) .isEqualTo(testValue); } @Test public void testTupleCall() throws Throwable { LSingle<Integer> domainObject = Tuple4U.single(100); Object result = sut.tupleApplyAsInt(domainObject); assertThat(result) .isEqualTo(testValue); } @Test public void testNonNullApplyAsInt() throws Throwable { assertThat(sut.nonNullApplyAsInt(100)) .isEqualTo(testValue); } @Test public void testNestingApplyAsIntUnchecked() throws Throwable { // then try { sutAlwaysThrowingUnchecked.nestingApplyAsInt(100); fail(NO_EXCEPTION_WERE_THROWN); } catch (Exception e) { assertThat(e) .isExactlyInstanceOf(IndexOutOfBoundsException.class) .hasNoCause() .hasMessage(ORIGINAL_MESSAGE); } } @Test public void testShovingApplyAsIntUnchecked() throws Throwable { // then try { sutAlwaysThrowingUnchecked.shovingApplyAsInt(100); fail(NO_EXCEPTION_WERE_THROWN); } catch (Exception e) { assertThat(e) .isExactlyInstanceOf(IndexOutOfBoundsException.class) .hasNoCause() .hasMessage(ORIGINAL_MESSAGE); } } @Test public void testFunctionalInterfaceDescription() throws Throwable { assertThat(sut.functionalInterfaceDescription()) .isEqualTo("LToIntFunction: int applyAsInt(T a)"); } @Test public void testToIntFuncMethod() throws Throwable { assertThat(LToIntFunction.toIntFunc(a -> testValue )) .isInstanceOf(LToIntFunction.class); } @Test public void testWrapStdMethod() throws Throwable { assertThat(LToIntFunction.wrap(jre)) .isInstanceOf(LToIntFunction.class); } // <editor-fold desc="compose (functional)"> @Test public void testCompose() throws Throwable { final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false); final AtomicInteger beforeCalls = new AtomicInteger(0); //given (+ some assertions) LToIntFunction<Integer> sutO = a -> { mainFunctionCalled.set(true); assertThat(a).isEqualTo(90); return 100; }; LFunction<Integer,Integer> before = p0 -> { assertThat(p0).isEqualTo(80); beforeCalls.incrementAndGet(); return 90; }; //when LToIntFunction<Integer> function = sutO.compose(before); function.applyAsInt(80); //then - finals assertThat(mainFunctionCalled.get()).isEqualTo(true); assertThat(beforeCalls.get()).isEqualTo(1); } // </editor-fold> // <editor-fold desc="then (functional)"> @Test public void testThen0() throws Throwable { final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false); final ThreadLocal<Boolean> thenFunctionCalled = ThreadLocal.withInitial(()-> false); //given (+ some assertions) LToIntFunction<Integer> sutO = a -> { mainFunctionCalled.set(true); assertThat(a).isEqualTo(80); return 90; }; LIntFunction<Integer> thenFunction = p -> { thenFunctionCalled.set(true); // int assertThat(p).isEqualTo(90); // Integer return 100; }; //when LFunction<Integer,Integer> function = sutO.then(thenFunction); Integer finalValue = function.apply(80); //then - finals assertThat(finalValue).isEqualTo(100); assertThat(mainFunctionCalled.get()).isEqualTo(true); assertThat(thenFunctionCalled.get()).isEqualTo(true); } @Test public void testThenToByte1() throws Throwable { final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false); final ThreadLocal<Boolean> thenFunctionCalled = ThreadLocal.withInitial(()-> false); //given (+ some assertions) LToIntFunction<Integer> sutO = a -> { mainFunctionCalled.set(true); assertThat(a).isEqualTo(80); return 90; }; LIntToByteFunction thenFunction = p -> { thenFunctionCalled.set(true); // int assertThat(p).isEqualTo(90); // byte return (byte)100; }; //when LToByteFunction<Integer> function = sutO.thenToByte(thenFunction); byte finalValue = function.applyAsByte(80); //then - finals assertThat(finalValue).isEqualTo((byte)100); assertThat(mainFunctionCalled.get()).isEqualTo(true); assertThat(thenFunctionCalled.get()).isEqualTo(true); } @Test public void testThenToSrt2() throws Throwable { final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false); final ThreadLocal<Boolean> thenFunctionCalled = ThreadLocal.withInitial(()-> false); //given (+ some assertions) LToIntFunction<Integer> sutO = a -> { mainFunctionCalled.set(true); assertThat(a).isEqualTo(80); return 90; }; LIntToSrtFunction thenFunction = p -> { thenFunctionCalled.set(true); // int assertThat(p).isEqualTo(90); // short return (short)100; }; //when LToSrtFunction<Integer> function = sutO.thenToSrt(thenFunction); short finalValue = function.applyAsSrt(80); //then - finals assertThat(finalValue).isEqualTo((short)100); assertThat(mainFunctionCalled.get()).isEqualTo(true); assertThat(thenFunctionCalled.get()).isEqualTo(true); } @Test public void testThenToInt3() throws Throwable { final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false); final ThreadLocal<Boolean> thenFunctionCalled = ThreadLocal.withInitial(()-> false); //given (+ some assertions) LToIntFunction<Integer> sutO = a -> { mainFunctionCalled.set(true); assertThat(a).isEqualTo(80); return 90; }; LIntUnaryOperator thenFunction = p -> { thenFunctionCalled.set(true); // int assertThat(p).isEqualTo(90); // int return 100; }; //when LToIntFunction<Integer> function = sutO.thenToInt(thenFunction); int finalValue = function.applyAsInt(80); //then - finals assertThat(finalValue).isEqualTo(100); assertThat(mainFunctionCalled.get()).isEqualTo(true); assertThat(thenFunctionCalled.get()).isEqualTo(true); } @Test public void testThenToLong4() throws Throwable { final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false); final ThreadLocal<Boolean> thenFunctionCalled = ThreadLocal.withInitial(()-> false); //given (+ some assertions) LToIntFunction<Integer> sutO = a -> { mainFunctionCalled.set(true); assertThat(a).isEqualTo(80); return 90; }; LIntToLongFunction thenFunction = p -> { thenFunctionCalled.set(true); // int assertThat(p).isEqualTo(90); // long return 100L; }; //when LToLongFunction<Integer> function = sutO.thenToLong(thenFunction); long finalValue = function.applyAsLong(80); //then - finals assertThat(finalValue).isEqualTo(100L); assertThat(mainFunctionCalled.get()).isEqualTo(true); assertThat(thenFunctionCalled.get()).isEqualTo(true); } @Test public void testThenToFlt5() throws Throwable { final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false); final ThreadLocal<Boolean> thenFunctionCalled = ThreadLocal.withInitial(()-> false); //given (+ some assertions) LToIntFunction<Integer> sutO = a -> { mainFunctionCalled.set(true); assertThat(a).isEqualTo(80); return 90; }; LIntToFltFunction thenFunction = p -> { thenFunctionCalled.set(true); // int assertThat(p).isEqualTo(90); // float return 100f; }; //when LToFltFunction<Integer> function = sutO.thenToFlt(thenFunction); float finalValue = function.applyAsFlt(80); //then - finals assertThat(finalValue).isEqualTo(100f); assertThat(mainFunctionCalled.get()).isEqualTo(true); assertThat(thenFunctionCalled.get()).isEqualTo(true); } @Test public void testThenToDbl6() throws Throwable { final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false); final ThreadLocal<Boolean> thenFunctionCalled = ThreadLocal.withInitial(()-> false); //given (+ some assertions) LToIntFunction<Integer> sutO = a -> { mainFunctionCalled.set(true); assertThat(a).isEqualTo(80); return 90; }; LIntToDblFunction thenFunction = p -> { thenFunctionCalled.set(true); // int assertThat(p).isEqualTo(90); // double return 100d; }; //when LToDblFunction<Integer> function = sutO.thenToDbl(thenFunction); double finalValue = function.applyAsDbl(80); //then - finals assertThat(finalValue).isEqualTo(100d); assertThat(mainFunctionCalled.get()).isEqualTo(true); assertThat(thenFunctionCalled.get()).isEqualTo(true); } @Test public void testThenToChar7() throws Throwable { final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false); final ThreadLocal<Boolean> thenFunctionCalled = ThreadLocal.withInitial(()-> false); //given (+ some assertions) LToIntFunction<Integer> sutO = a -> { mainFunctionCalled.set(true); assertThat(a).isEqualTo(80); return 90; }; LIntToCharFunction thenFunction = p -> { thenFunctionCalled.set(true); // int assertThat(p).isEqualTo(90); // char return '\u0100'; }; //when LToCharFunction<Integer> function = sutO.thenToChar(thenFunction); char finalValue = function.applyAsChar(80); //then - finals assertThat(finalValue).isEqualTo('\u0100'); assertThat(mainFunctionCalled.get()).isEqualTo(true); assertThat(thenFunctionCalled.get()).isEqualTo(true); } @Test public void testThenToBool8() throws Throwable { final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false); final ThreadLocal<Boolean> thenFunctionCalled = ThreadLocal.withInitial(()-> false); //given (+ some assertions) LToIntFunction<Integer> sutO = a -> { mainFunctionCalled.set(true); assertThat(a).isEqualTo(80); return 90; }; LIntPredicate thenFunction = p -> { thenFunctionCalled.set(true); // int assertThat(p).isEqualTo(90); // boolean return true; }; //when LPredicate<Integer> function = sutO.thenToBool(thenFunction); boolean finalValue = function.test(80); //then - finals assertThat(finalValue).isEqualTo(true); assertThat(mainFunctionCalled.get()).isEqualTo(true); assertThat(thenFunctionCalled.get()).isEqualTo(true); } // </editor-fold> @Test(expectedExceptions = RuntimeException.class) public void testShove() { // given LToIntFunction<Integer> sutThrowing = LToIntFunction.toIntFunc(a -> { throw new UnsupportedOperationException(); }); // when sutThrowing.shovingApplyAsInt(100); } @Test public void testToString() throws Throwable { assertThat(sut.toString()) .isInstanceOf(String.class) .startsWith(this.getClass().getName()+"$"); assertThat(String.format("%s", sut)) .isInstanceOf(String.class) .contains("LToIntFunction: int applyAsInt(T a)"); } @Test public void isThrowing() { assertThat(sut.isThrowing()) .isFalse(); } }
apache-2.0
GoogleCloudPlatform/prometheus-engine
third_party/prometheus_ui/base/web/ui/react-app/node_modules/promise-polyfill/src/polyfill.js
1082
import Promise from './index'; import promiseFinally from './finally'; import allSettled from './allSettled'; /** @suppress {undefinedVars} */ var globalNS = (function() { // the only reliable means to get the global object is // `Function('return this')()` // However, this causes CSP violations in Chrome apps. if (typeof self !== 'undefined') { return self; } if (typeof window !== 'undefined') { return window; } if (typeof global !== 'undefined') { return global; } throw new Error('unable to locate global object'); })(); // Expose the polyfill if Promise is undefined or set to a // non-function value. The latter can be due to a named HTMLElement // being exposed by browsers for legacy reasons. // https://github.com/taylorhakes/promise-polyfill/issues/114 if (typeof globalNS['Promise'] !== 'function') { globalNS['Promise'] = Promise; } else if (!globalNS.Promise.prototype['finally']) { globalNS.Promise.prototype['finally'] = promiseFinally; } else if (!globalNS.Promise.allSettled) { globalNS.Promise.allSettled = allSettled; }
apache-2.0
muczy/libjtodotxt
libjtodotxt/src_test/org/libjtodotxt/ParseExceptionTest.java
948
package org.libjtodotxt; import static org.junit.Assert.assertEquals; import org.junit.Test; public class ParseExceptionTest { @Test public void testParseException() { new ParseException(); } @Test public void testParseExceptionStringThrowable() { String cause = "testCause"; Throwable throwable = new ParseException(); ParseException testException = new ParseException(cause, throwable); assertEquals(cause, testException.getMessage()); assertEquals(throwable, testException.getCause()); } @Test public void testParseExceptionString() { String cause = "testCause"; ParseException testException = new ParseException(cause); assertEquals(cause, testException.getMessage()); } @Test public void testParseExceptionThrowable() { Throwable throwable = new ParseException(); ParseException testException = new ParseException(throwable); assertEquals(throwable, testException.getCause()); } }
apache-2.0
jentfoo/aws-sdk-java
aws-java-sdk-kinesis/src/main/java/com/amazonaws/services/kinesisanalytics/model/MappingParameters.java
7213
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.kinesisanalytics.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * When configuring application input at the time of creating or updating an application, provides additional mapping * information specific to the record format (such as JSON, CSV, or record fields delimited by some delimiter) on the * streaming source. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/kinesisanalytics-2015-08-14/MappingParameters" target="_top">AWS * API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class MappingParameters implements Serializable, Cloneable, StructuredPojo { /** * <p> * Provides additional mapping information when JSON is the record format on the streaming source. * </p> */ private JSONMappingParameters jSONMappingParameters; /** * <p> * Provides additional mapping information when the record format uses delimiters (for example, CSV). * </p> */ private CSVMappingParameters cSVMappingParameters; /** * <p> * Provides additional mapping information when JSON is the record format on the streaming source. * </p> * * @param jSONMappingParameters * Provides additional mapping information when JSON is the record format on the streaming source. */ public void setJSONMappingParameters(JSONMappingParameters jSONMappingParameters) { this.jSONMappingParameters = jSONMappingParameters; } /** * <p> * Provides additional mapping information when JSON is the record format on the streaming source. * </p> * * @return Provides additional mapping information when JSON is the record format on the streaming source. */ public JSONMappingParameters getJSONMappingParameters() { return this.jSONMappingParameters; } /** * <p> * Provides additional mapping information when JSON is the record format on the streaming source. * </p> * * @param jSONMappingParameters * Provides additional mapping information when JSON is the record format on the streaming source. * @return Returns a reference to this object so that method calls can be chained together. */ public MappingParameters withJSONMappingParameters(JSONMappingParameters jSONMappingParameters) { setJSONMappingParameters(jSONMappingParameters); return this; } /** * <p> * Provides additional mapping information when the record format uses delimiters (for example, CSV). * </p> * * @param cSVMappingParameters * Provides additional mapping information when the record format uses delimiters (for example, CSV). */ public void setCSVMappingParameters(CSVMappingParameters cSVMappingParameters) { this.cSVMappingParameters = cSVMappingParameters; } /** * <p> * Provides additional mapping information when the record format uses delimiters (for example, CSV). * </p> * * @return Provides additional mapping information when the record format uses delimiters (for example, CSV). */ public CSVMappingParameters getCSVMappingParameters() { return this.cSVMappingParameters; } /** * <p> * Provides additional mapping information when the record format uses delimiters (for example, CSV). * </p> * * @param cSVMappingParameters * Provides additional mapping information when the record format uses delimiters (for example, CSV). * @return Returns a reference to this object so that method calls can be chained together. */ public MappingParameters withCSVMappingParameters(CSVMappingParameters cSVMappingParameters) { setCSVMappingParameters(cSVMappingParameters); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getJSONMappingParameters() != null) sb.append("JSONMappingParameters: ").append(getJSONMappingParameters()).append(","); if (getCSVMappingParameters() != null) sb.append("CSVMappingParameters: ").append(getCSVMappingParameters()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof MappingParameters == false) return false; MappingParameters other = (MappingParameters) obj; if (other.getJSONMappingParameters() == null ^ this.getJSONMappingParameters() == null) return false; if (other.getJSONMappingParameters() != null && other.getJSONMappingParameters().equals(this.getJSONMappingParameters()) == false) return false; if (other.getCSVMappingParameters() == null ^ this.getCSVMappingParameters() == null) return false; if (other.getCSVMappingParameters() != null && other.getCSVMappingParameters().equals(this.getCSVMappingParameters()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getJSONMappingParameters() == null) ? 0 : getJSONMappingParameters().hashCode()); hashCode = prime * hashCode + ((getCSVMappingParameters() == null) ? 0 : getCSVMappingParameters().hashCode()); return hashCode; } @Override public MappingParameters clone() { try { return (MappingParameters) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.kinesisanalytics.model.transform.MappingParametersMarshaller.getInstance().marshall(this, protocolMarshaller); } }
apache-2.0
stephane-bastian/vertx-web-mvc
src/main/java/com/thesoftwarefactory/vertx/web/mvc/impl/LayoutImpl.java
1492
package com.thesoftwarefactory.vertx.web.mvc.impl; import java.util.Objects; import com.thesoftwarefactory.vertx.web.mvc.Layout; import io.vertx.core.Handler; import io.vertx.ext.web.RoutingContext; public class LayoutImpl implements Layout { private String path; private String parentPath; private Handler<RoutingContext> handler; public LayoutImpl(String path, Handler<RoutingContext> handler) { Objects.requireNonNull(path); Objects.requireNonNull(handler); this.path = path; this.handler = handler; } public LayoutImpl(String path, String parentPath, Handler<RoutingContext> handler) { Objects.requireNonNull(path); Objects.requireNonNull(parentPath); Objects.requireNonNull(handler); this.path = path; this.parentPath = parentPath; this.handler = handler; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; LayoutImpl other = (LayoutImpl) obj; if (path == null) { if (other.path != null) return false; } else if (!path.equals(other.path)) return false; return true; } public Handler<RoutingContext> handler() { return handler; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((path == null) ? 0 : path.hashCode()); return result; } public String parentPath() { return parentPath; } public String path() { return path; } }
apache-2.0
colewang/twu-biblioteca-yuwang
src/com/twu/biblioteca/lists/ListObject.java
536
package com.twu.biblioteca.lists; import com.twu.biblioteca.output.Output; import java.util.List; public abstract class ListObject<E> { protected List<E> list; public List<E> getList() { return list; } public E get(int index) { if (index < list.size() && index >= 0) return list.get(index); throw new ArrayIndexOutOfBoundsException(); } public boolean remove(E e) { return list.remove(e); } public boolean add(E e) { return list.add(e); } }
apache-2.0
WillleePang/java
Practice/src/com/willlee/algorithms/shellsort/ShellSortApp.java
493
package com.willlee.algorithms.shellsort; public class ShellSortApp { public static void main(String[] args) { int maxSize = 10000; ArraySh arr; arr = new ArraySh(maxSize); for (int j = 0; j < maxSize; j++) { long n = (int) (java.lang.Math.random() * 999999); arr.insert(n); } arr.display(); long start = System.currentTimeMillis(); arr.shellSort(); long end = System.currentTimeMillis(); System.out.println("use time is :" + (end - start)); arr.display(); } }
apache-2.0
nicolaferraro/camel
components/camel-kubernetes/src/generated/java/org/apache/camel/component/kubernetes/customresources/KubernetesCustomResourcesEndpointConfigurer.java
13427
/* Generated by camel build tools - do NOT edit this file! */ package org.apache.camel.component.kubernetes.customresources; import java.util.Map; import org.apache.camel.CamelContext; import org.apache.camel.spi.ExtendedPropertyConfigurerGetter; import org.apache.camel.spi.PropertyConfigurerGetter; import org.apache.camel.spi.ConfigurerStrategy; import org.apache.camel.spi.GeneratedPropertyConfigurer; import org.apache.camel.util.CaseInsensitiveMap; import org.apache.camel.support.component.PropertyConfigurerSupport; /** * Generated by camel build tools - do NOT edit this file! */ @SuppressWarnings("unchecked") public class KubernetesCustomResourcesEndpointConfigurer extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { KubernetesCustomResourcesEndpoint target = (KubernetesCustomResourcesEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "apiversion": case "apiVersion": target.getConfiguration().setApiVersion(property(camelContext, java.lang.String.class, value)); return true; case "bridgeerrorhandler": case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true; case "cacertdata": case "caCertData": target.getConfiguration().setCaCertData(property(camelContext, java.lang.String.class, value)); return true; case "cacertfile": case "caCertFile": target.getConfiguration().setCaCertFile(property(camelContext, java.lang.String.class, value)); return true; case "clientcertdata": case "clientCertData": target.getConfiguration().setClientCertData(property(camelContext, java.lang.String.class, value)); return true; case "clientcertfile": case "clientCertFile": target.getConfiguration().setClientCertFile(property(camelContext, java.lang.String.class, value)); return true; case "clientkeyalgo": case "clientKeyAlgo": target.getConfiguration().setClientKeyAlgo(property(camelContext, java.lang.String.class, value)); return true; case "clientkeydata": case "clientKeyData": target.getConfiguration().setClientKeyData(property(camelContext, java.lang.String.class, value)); return true; case "clientkeyfile": case "clientKeyFile": target.getConfiguration().setClientKeyFile(property(camelContext, java.lang.String.class, value)); return true; case "clientkeypassphrase": case "clientKeyPassphrase": target.getConfiguration().setClientKeyPassphrase(property(camelContext, java.lang.String.class, value)); return true; case "connectiontimeout": case "connectionTimeout": target.getConfiguration().setConnectionTimeout(property(camelContext, java.lang.Integer.class, value)); return true; case "crdgroup": case "crdGroup": target.getConfiguration().setCrdGroup(property(camelContext, java.lang.String.class, value)); return true; case "crdname": case "crdName": target.getConfiguration().setCrdName(property(camelContext, java.lang.String.class, value)); return true; case "crdplural": case "crdPlural": target.getConfiguration().setCrdPlural(property(camelContext, java.lang.String.class, value)); return true; case "crdscope": case "crdScope": target.getConfiguration().setCrdScope(property(camelContext, java.lang.String.class, value)); return true; case "crdversion": case "crdVersion": target.getConfiguration().setCrdVersion(property(camelContext, java.lang.String.class, value)); return true; case "dnsdomain": case "dnsDomain": target.getConfiguration().setDnsDomain(property(camelContext, java.lang.String.class, value)); return true; case "exceptionhandler": case "exceptionHandler": target.setExceptionHandler(property(camelContext, org.apache.camel.spi.ExceptionHandler.class, value)); return true; case "exchangepattern": case "exchangePattern": target.setExchangePattern(property(camelContext, org.apache.camel.ExchangePattern.class, value)); return true; case "kubernetesclient": case "kubernetesClient": target.getConfiguration().setKubernetesClient(property(camelContext, io.fabric8.kubernetes.client.KubernetesClient.class, value)); return true; case "labelkey": case "labelKey": target.getConfiguration().setLabelKey(property(camelContext, java.lang.String.class, value)); return true; case "labelvalue": case "labelValue": target.getConfiguration().setLabelValue(property(camelContext, java.lang.String.class, value)); return true; case "lazystartproducer": case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true; case "namespace": target.getConfiguration().setNamespace(property(camelContext, java.lang.String.class, value)); return true; case "oauthtoken": case "oauthToken": target.getConfiguration().setOauthToken(property(camelContext, java.lang.String.class, value)); return true; case "operation": target.getConfiguration().setOperation(property(camelContext, java.lang.String.class, value)); return true; case "password": target.getConfiguration().setPassword(property(camelContext, java.lang.String.class, value)); return true; case "poolsize": case "poolSize": target.getConfiguration().setPoolSize(property(camelContext, int.class, value)); return true; case "portname": case "portName": target.getConfiguration().setPortName(property(camelContext, java.lang.String.class, value)); return true; case "portprotocol": case "portProtocol": target.getConfiguration().setPortProtocol(property(camelContext, java.lang.String.class, value)); return true; case "resourcename": case "resourceName": target.getConfiguration().setResourceName(property(camelContext, java.lang.String.class, value)); return true; case "synchronous": target.setSynchronous(property(camelContext, boolean.class, value)); return true; case "trustcerts": case "trustCerts": target.getConfiguration().setTrustCerts(property(camelContext, java.lang.Boolean.class, value)); return true; case "username": target.getConfiguration().setUsername(property(camelContext, java.lang.String.class, value)); return true; default: return false; } } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "apiversion": case "apiVersion": return java.lang.String.class; case "bridgeerrorhandler": case "bridgeErrorHandler": return boolean.class; case "cacertdata": case "caCertData": return java.lang.String.class; case "cacertfile": case "caCertFile": return java.lang.String.class; case "clientcertdata": case "clientCertData": return java.lang.String.class; case "clientcertfile": case "clientCertFile": return java.lang.String.class; case "clientkeyalgo": case "clientKeyAlgo": return java.lang.String.class; case "clientkeydata": case "clientKeyData": return java.lang.String.class; case "clientkeyfile": case "clientKeyFile": return java.lang.String.class; case "clientkeypassphrase": case "clientKeyPassphrase": return java.lang.String.class; case "connectiontimeout": case "connectionTimeout": return java.lang.Integer.class; case "crdgroup": case "crdGroup": return java.lang.String.class; case "crdname": case "crdName": return java.lang.String.class; case "crdplural": case "crdPlural": return java.lang.String.class; case "crdscope": case "crdScope": return java.lang.String.class; case "crdversion": case "crdVersion": return java.lang.String.class; case "dnsdomain": case "dnsDomain": return java.lang.String.class; case "exceptionhandler": case "exceptionHandler": return org.apache.camel.spi.ExceptionHandler.class; case "exchangepattern": case "exchangePattern": return org.apache.camel.ExchangePattern.class; case "kubernetesclient": case "kubernetesClient": return io.fabric8.kubernetes.client.KubernetesClient.class; case "labelkey": case "labelKey": return java.lang.String.class; case "labelvalue": case "labelValue": return java.lang.String.class; case "lazystartproducer": case "lazyStartProducer": return boolean.class; case "namespace": return java.lang.String.class; case "oauthtoken": case "oauthToken": return java.lang.String.class; case "operation": return java.lang.String.class; case "password": return java.lang.String.class; case "poolsize": case "poolSize": return int.class; case "portname": case "portName": return java.lang.String.class; case "portprotocol": case "portProtocol": return java.lang.String.class; case "resourcename": case "resourceName": return java.lang.String.class; case "synchronous": return boolean.class; case "trustcerts": case "trustCerts": return java.lang.Boolean.class; case "username": return java.lang.String.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { KubernetesCustomResourcesEndpoint target = (KubernetesCustomResourcesEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "apiversion": case "apiVersion": return target.getConfiguration().getApiVersion(); case "bridgeerrorhandler": case "bridgeErrorHandler": return target.isBridgeErrorHandler(); case "cacertdata": case "caCertData": return target.getConfiguration().getCaCertData(); case "cacertfile": case "caCertFile": return target.getConfiguration().getCaCertFile(); case "clientcertdata": case "clientCertData": return target.getConfiguration().getClientCertData(); case "clientcertfile": case "clientCertFile": return target.getConfiguration().getClientCertFile(); case "clientkeyalgo": case "clientKeyAlgo": return target.getConfiguration().getClientKeyAlgo(); case "clientkeydata": case "clientKeyData": return target.getConfiguration().getClientKeyData(); case "clientkeyfile": case "clientKeyFile": return target.getConfiguration().getClientKeyFile(); case "clientkeypassphrase": case "clientKeyPassphrase": return target.getConfiguration().getClientKeyPassphrase(); case "connectiontimeout": case "connectionTimeout": return target.getConfiguration().getConnectionTimeout(); case "crdgroup": case "crdGroup": return target.getConfiguration().getCrdGroup(); case "crdname": case "crdName": return target.getConfiguration().getCrdName(); case "crdplural": case "crdPlural": return target.getConfiguration().getCrdPlural(); case "crdscope": case "crdScope": return target.getConfiguration().getCrdScope(); case "crdversion": case "crdVersion": return target.getConfiguration().getCrdVersion(); case "dnsdomain": case "dnsDomain": return target.getConfiguration().getDnsDomain(); case "exceptionhandler": case "exceptionHandler": return target.getExceptionHandler(); case "exchangepattern": case "exchangePattern": return target.getExchangePattern(); case "kubernetesclient": case "kubernetesClient": return target.getConfiguration().getKubernetesClient(); case "labelkey": case "labelKey": return target.getConfiguration().getLabelKey(); case "labelvalue": case "labelValue": return target.getConfiguration().getLabelValue(); case "lazystartproducer": case "lazyStartProducer": return target.isLazyStartProducer(); case "namespace": return target.getConfiguration().getNamespace(); case "oauthtoken": case "oauthToken": return target.getConfiguration().getOauthToken(); case "operation": return target.getConfiguration().getOperation(); case "password": return target.getConfiguration().getPassword(); case "poolsize": case "poolSize": return target.getConfiguration().getPoolSize(); case "portname": case "portName": return target.getConfiguration().getPortName(); case "portprotocol": case "portProtocol": return target.getConfiguration().getPortProtocol(); case "resourcename": case "resourceName": return target.getConfiguration().getResourceName(); case "synchronous": return target.isSynchronous(); case "trustcerts": case "trustCerts": return target.getConfiguration().getTrustCerts(); case "username": return target.getConfiguration().getUsername(); default: return null; } } }
apache-2.0
aosp-mirror/platform_frameworks_support
v7/recyclerview/src/androidTest/java/androidx/recyclerview/widget/DummyItemAnimator.java
8230
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.recyclerview.widget; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.LOCAL_VARIABLE; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.CLASS; import java.lang.annotation.Retention; import java.lang.annotation.Target; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /** * This is a dummy ItemAnimator class that does not depends on Duration, Tests would use this class * to control whenever they want the Animator to finish. * 1. Test MUST call endAnimation(ViewHolder) on UI thread to finish animation of a given ViewHolder * Or Test calls endAnimations() on UI thread to end animations for all. * 2. Test can call getAddAnimations() etc. to get ViewHolders that currently running animation. * 3. Test can call {@link #expect(int, int)} and {@link #waitFor(int)} to wait given * Events are fired. */ public class DummyItemAnimator extends SimpleItemAnimator { static final long TIMEOUT_SECOND = 10; ArrayList<RecyclerView.ViewHolder> mAdds = new ArrayList(); ArrayList<RecyclerView.ViewHolder> mRemoves = new ArrayList(); ArrayList<RecyclerView.ViewHolder> mMoves = new ArrayList(); ArrayList<RecyclerView.ViewHolder> mChangesOld = new ArrayList(); ArrayList<RecyclerView.ViewHolder> mChangesNew = new ArrayList(); @Retention(CLASS) @Target({PARAMETER, METHOD, LOCAL_VARIABLE, FIELD}) public @interface CountDownLatchIndex { } @CountDownLatchIndex public static final int ADD_START = 0; @CountDownLatchIndex public static final int ADD_FINISHED = 1; @CountDownLatchIndex public static final int REMOVE_START = 2; @CountDownLatchIndex public static final int REMOVE_FINISHED = 3; @CountDownLatchIndex public static final int MOVE_START = 4; @CountDownLatchIndex public static final int MOVE_FINISHED = 5; @CountDownLatchIndex public static final int CHANGE_OLD_START = 6; @CountDownLatchIndex public static final int CHANGE_OLD_FINISHED = 7; @CountDownLatchIndex public static final int CHANGE_NEW_START = 8; @CountDownLatchIndex public static final int CHANGE_NEW_FINISHED = 9; static final int NUM_COUNT_DOWN_LATCH = 10; CountDownLatch[] mCountDownLatches = new CountDownLatch[NUM_COUNT_DOWN_LATCH]; public List<RecyclerView.ViewHolder> getAddAnimations() { return mAdds; } public List<RecyclerView.ViewHolder> getRemoveAnimations() { return mRemoves; } public List<RecyclerView.ViewHolder> getMovesAnimations() { return mMoves; } public List<RecyclerView.ViewHolder> getChangesOldAnimations() { return mChangesOld; } public List<RecyclerView.ViewHolder> getChangesNewAnimations() { return mChangesNew; } @Override public boolean animateRemove(RecyclerView.ViewHolder holder) { mRemoves.add(holder); dispatchRemoveStarting(holder); return false; } @Override public boolean animateAdd(RecyclerView.ViewHolder holder) { mAdds.add(holder); dispatchAddStarting(holder); return false; } @Override public boolean animateMove(RecyclerView.ViewHolder holder, int fromX, int fromY, int toX, int toY) { mMoves.add(holder); dispatchMoveStarting(holder); return false; } @Override public boolean animateChange(RecyclerView.ViewHolder oldHolder, RecyclerView.ViewHolder newHolder, int fromLeft, int fromTop, int toLeft, int toTop) { mChangesOld.add(oldHolder); mChangesNew.add(newHolder); dispatchChangeStarting(oldHolder, true); dispatchChangeStarting(newHolder, false); return false; } public void expect(@CountDownLatchIndex int index, int count) { mCountDownLatches[index] = new CountDownLatch(count); } public void waitFor(@CountDownLatchIndex int index) throws InterruptedException { mCountDownLatches[index].await(TIMEOUT_SECOND, TimeUnit.SECONDS); } @Override public void onChangeStarting(RecyclerView.ViewHolder item, boolean oldItem) { CountDownLatch latch = mCountDownLatches[oldItem ? CHANGE_OLD_START : CHANGE_NEW_START]; if (latch != null) { latch.countDown(); } } @Override public void onMoveStarting(RecyclerView.ViewHolder item) { CountDownLatch latch = mCountDownLatches[MOVE_START]; if (latch != null) { latch.countDown(); } } @Override public void onAddStarting(RecyclerView.ViewHolder item) { CountDownLatch latch = mCountDownLatches[ADD_START]; if (latch != null) { latch.countDown(); } } @Override public void onRemoveStarting(RecyclerView.ViewHolder item) { CountDownLatch latch = mCountDownLatches[REMOVE_START]; if (latch != null) { latch.countDown(); } } @Override public void onChangeFinished(RecyclerView.ViewHolder item, boolean oldItem) { CountDownLatch latch = mCountDownLatches[oldItem ? CHANGE_OLD_FINISHED : CHANGE_NEW_FINISHED]; if (latch != null) { latch.countDown(); } } @Override public void onMoveFinished(RecyclerView.ViewHolder item) { CountDownLatch latch = mCountDownLatches[MOVE_FINISHED]; if (latch != null) { latch.countDown(); } } @Override public void onAddFinished(RecyclerView.ViewHolder item) { CountDownLatch latch = mCountDownLatches[ADD_FINISHED]; if (latch != null) { latch.countDown(); } } @Override public void onRemoveFinished(RecyclerView.ViewHolder item) { CountDownLatch latch = mCountDownLatches[REMOVE_FINISHED]; if (latch != null) { latch.countDown(); } } @Override public void runPendingAnimations() { } @Override public void endAnimation(RecyclerView.ViewHolder item) { if (mAdds.remove(item)) { dispatchAddFinished(item); } else if (mRemoves.remove(item)) { dispatchRemoveFinished(item); } else if (mMoves.remove(item)) { dispatchMoveFinished(item); } else if (mChangesOld.remove(item)) { dispatchChangeFinished(item, true); } else if (mChangesNew.remove(item)) { dispatchChangeFinished(item, false); } } @Override public void endAnimations() { for (int i = mAdds.size() - 1; i >= 0; i--) { endAnimation(mAdds.get(i)); } for (int i = mRemoves.size() - 1; i >= 0; i--) { endAnimation(mRemoves.get(i)); } for (int i = mMoves.size() - 1; i >= 0; i--) { endAnimation(mMoves.get(i)); } for (int i = mChangesOld.size() - 1; i >= 0; i--) { endAnimation(mChangesOld.get(i)); } for (int i = mChangesNew.size() - 1; i >= 0; i--) { endAnimation(mChangesNew.get(i)); } } @Override public boolean isRunning() { return mAdds.size() != 0 || mRemoves.size() != 0 || mMoves.size() != 0 || mChangesOld.size() != 0 || mChangesNew.size() != 0; } }
apache-2.0
monkeysquare/katana
src/Microsoft.Owin.Security.OAuth/Provider/OAuthTokenEndpointContext.cs
1703
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Security.Claims; using Microsoft.Owin.Security.OAuth.Messages; using Microsoft.Owin.Security.Provider; namespace Microsoft.Owin.Security.OAuth { public class OAuthTokenEndpointContext : EndpointContext<OAuthAuthorizationServerOptions> { public OAuthTokenEndpointContext( IOwinContext context, OAuthAuthorizationServerOptions options, AuthenticationTicket ticket, TokenEndpointRequest tokenEndpointRequest) : base(context, options) { if (ticket == null) { throw new ArgumentNullException("ticket"); } Identity = ticket.Identity; Properties = ticket.Properties; TokenEndpointRequest = tokenEndpointRequest; AdditionalResponseParameters = new Dictionary<string, object>(StringComparer.Ordinal); TokenIssued = Identity != null; } public ClaimsIdentity Identity { get; private set; } public AuthenticationProperties Properties { get; private set; } public TokenEndpointRequest TokenEndpointRequest { get; set; } public bool TokenIssued { get; private set; } public IDictionary<string, object> AdditionalResponseParameters { get; private set; } public void Issue(ClaimsIdentity identity, AuthenticationProperties properties) { Identity = identity; Properties = properties; TokenIssued = true; } } }
apache-2.0
rmadapur/networking-brocade
networking_brocade/vyatta/common/l3_agent.py
4083
# Copyright 2015 Brocade Communications System, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from novaclient.v1_1 import client as novaclient from neutron.agent.l3 import agent as l3_agent from neutron.agent.l3 import router_info from neutron.agent import l3_agent as entry from neutron.common import constants as l3_constants from networking_brocade.vyatta.common import config as vyatta_config from networking_brocade.vyatta.common import exceptions as v_exc from networking_brocade.vyatta.vrouter import client as vyatta_client _KEY_VYATTA_EXTRA_DATA = '_vyatta' _KEY_MANAGEMENT_IP_ADDRESS = 'management_ip_address' class RouterInfo(router_info.RouterInfo): def add_floating_ip(self, fip, interface_name, device): pass def initialize(self, process_monitor): pass def process(self, agent): pass def delete(self, agent): self.router['gw_port'] = None self.router[l3_constants.INTERFACE_KEY] = [] self.router[l3_constants.FLOATINGIP_KEY] = [] self.process(agent) class L3AgentMiddleware(l3_agent.L3NATAgentWithStateReport): def __init__(self, host, conf=None): super(L3AgentMiddleware, self).__init__(host, conf) compute_client = novaclient.Client( vyatta_config.VROUTER.tenant_admin_name, vyatta_config.VROUTER.tenant_admin_password, auth_url=vyatta_config.CONF.nova_admin_auth_url, service_type="compute", tenant_id=vyatta_config.VROUTER.tenant_id) self._vyatta_clients_pool = vyatta_client.ClientsPool(compute_client) def get_router(self, router_id): try: router = self.router_info[router_id] except KeyError: raise v_exc.InvalidL3AgentStateError(description=_( 'L3 agent have no info about reouter id={0}').format( router_id)) return router.router def get_router_client(self, router_id): router = self.get_router(router_id) try: address = router[_KEY_VYATTA_EXTRA_DATA] address = address[_KEY_MANAGEMENT_IP_ADDRESS] except KeyError: raise v_exc.CorruptedSystemError( description=('router {0} does not contain vyatta vrouter ' 'management ip address').format(router_id)) return self._vyatta_clients_pool.get_by_address(router_id, address) def _create_router(self, router_id, router): if router.get('distributed') or router.get('ha'): raise v_exc.DvrOrHaRouterNotSupported(router_id=router_id) kwargs = { 'router_id': router_id, 'router': router, 'use_ipv6': self.use_ipv6, 'agent_conf': self.conf, 'interface_driver': self.driver, } return RouterInfo(**kwargs) def _get_router_info_list_for_tenant(self, router_ids, tenant_id): """Returns the list of router info objects on which to apply the fw.""" router_info_list = [] # Pick up namespaces for Tenant Routers for rid in router_ids: # for routers without an interface - get_routers returns # the router - but this is not yet populated in router_info if rid not in self.router_info: continue router_info_list.append(self.router_info[rid]) return router_info_list def main(): entry.main( manager='networking_brocade.vyatta.common.l3_agent.L3AgentMiddleware')
apache-2.0
johanek/johanek-puppet
mcollective/files/mcollective-plugins/puppetlabs/audit/logstash/logstash.rb
1457
module MCollective module RPC # An audit plugin that just logs to a logstash queue # # You can configure which queue it emits events to with the setting # # plugin.logstash.target # class Logstash<Audit require 'json' def audit_request(request, connection) now = Time.now.utc now_tz = tz = now.utc? ? "Z" : now.strftime("%z") now_iso8601 = "%s.%06d%s" % [now.strftime("%Y-%m-%dT%H:%M:%S"), now.tv_usec, now_tz] audit_entry = {"@source_host" => Config.instance.identity, "@tags" => [], "@type" => "mcollective-audit", "@source" => "mcollective-audit", "@timestamp" => now_iso8601, "@fields" => {"uniqid" => request.uniqid, "request_time" => request.time, "caller" => request.caller, "callerhost" => request.sender, "agent" => request.agent, "action" => request.action, "data" => request.data.pretty_print_inspect}, "@message" => "#{Config.instance.identity}: #{request.caller}@#{request.sender} invoked agent #{request.agent}##{request.action}"} target = Config.instance.pluginconf["logstash.target"] || "/queue/mcollective.audit" if connection.respond_to?(:publish) connection.publish(target, req) else connection.send(target, req) end end end end end # vi:tabstop=2:expandtab:ai
apache-2.0
Thingee/cinder
cinder/volume/drivers/san/hp/hp_3par_common.py
52446
# (c) Copyright 2012-2014 Hewlett-Packard Development Company, L.P. # 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. # """ Volume driver common utilities for HP 3PAR Storage array The 3PAR drivers requires 3.1.3 firmware on the 3PAR array. You will need to install the python hp3parclient. sudo pip install hp3parclient The drivers uses both the REST service and the SSH command line to correctly operate. Since the ssh credentials and the REST credentials can be different we need to have settings for both. The drivers requires the use of the san_ip, san_login, san_password settings for ssh connections into the 3PAR array. It also requires the setting of hp3par_api_url, hp3par_username, hp3par_password for credentials to talk to the REST service on the 3PAR array. """ import ast import base64 import json import pprint import re import uuid from cinder.openstack.common import importutils hp3parclient = importutils.try_import("hp3parclient") if hp3parclient: from hp3parclient import client from hp3parclient import exceptions as hpexceptions from oslo.config import cfg from cinder import context from cinder import exception from cinder.openstack.common import excutils from cinder.openstack.common import log as logging from cinder.openstack.common import loopingcall from cinder import units from cinder.volume import qos_specs from cinder.volume import volume_types LOG = logging.getLogger(__name__) MIN_CLIENT_VERSION = '3.0.0' hp3par_opts = [ cfg.StrOpt('hp3par_api_url', default='', help="3PAR WSAPI Server Url like " "https://<3par ip>:8080/api/v1"), cfg.StrOpt('hp3par_username', default='', help="3PAR Super user username"), cfg.StrOpt('hp3par_password', default='', help="3PAR Super user password", secret=True), cfg.StrOpt('hp3par_cpg', default="OpenStack", help="The CPG to use for volume creation"), cfg.StrOpt('hp3par_cpg_snap', default="", help="The CPG to use for Snapshots for volumes. " "If empty hp3par_cpg will be used"), cfg.StrOpt('hp3par_snapshot_retention', default="", help="The time in hours to retain a snapshot. " "You can't delete it before this expires."), cfg.StrOpt('hp3par_snapshot_expiration', default="", help="The time in hours when a snapshot expires " " and is deleted. This must be larger than expiration"), cfg.BoolOpt('hp3par_debug', default=False, help="Enable HTTP debugging to 3PAR"), cfg.ListOpt('hp3par_iscsi_ips', default=[], help="List of target iSCSI addresses to use.") ] CONF = cfg.CONF CONF.register_opts(hp3par_opts) class HP3PARCommon(object): """Class that contains common code for the 3PAR drivers. Version history: 1.2.0 - Updated hp3parclient API use to 2.0.x 1.2.1 - Check that the VVS exists 1.2.2 - log prior to raising exceptions 1.2.3 - Methods to update key/value pair bug #1258033 1.2.4 - Remove deprecated config option hp3par_domain 1.2.5 - Raise Ex when deleting snapshot with dependencies bug #1250249 1.2.6 - Allow optional specifying n:s:p for vlun creation bug #1269515 This update now requires 3.1.2 MU3 firmware 1.3.0 - Removed all SSH code. We rely on the hp3parclient now. 2.0.0 - Update hp3parclient API uses 3.0.x 2.0.1 - Updated to use qos_specs, added new qos settings and personas 2.0.2 - Add back-end assisted volume migrate 2.0.3 - Allow deleting missing snapshots bug #1283233 2.0.4 - Allow volumes created from snapshots to be larger bug #1279478 2.0.5 - Fix extend volume units bug #1284368 2.0.6 - use loopingcall.wait instead of time.sleep 2.0.7 - Allow extend volume based on snapshot bug #1285906 2.0.8 - Fix detach issue for multiple hosts bug #1288927 2.0.9 - Remove unused 3PAR driver method bug #1310807 2.0.10 - Fixed an issue with 3PAR vlun location bug #1315542 2.0.11 - Remove hp3parclient requirement from unit tests #1315195 """ VERSION = "2.0.11" stats = {} # TODO(Ramy): move these to the 3PAR Client VLUN_TYPE_EMPTY = 1 VLUN_TYPE_PORT = 2 VLUN_TYPE_HOST = 3 VLUN_TYPE_MATCHED_SET = 4 VLUN_TYPE_HOST_SET = 5 # Valid values for volume type extra specs # The first value in the list is the default value valid_prov_values = ['thin', 'full'] valid_persona_values = ['1 - Generic', '2 - Generic-ALUA', '6 - Generic-legacy', '7 - HPUX-legacy', '8 - AIX-legacy', '9 - EGENERA', '10 - ONTAP-legacy', '11 - VMware', '12 - OpenVMS', '13 - HPUX', '15 - WindowsServer'] hp_qos_keys = ['minIOPS', 'maxIOPS', 'minBWS', 'maxBWS', 'latency', 'priority'] qos_priority_level = {'low': 1, 'normal': 2, 'high': 3} hp3par_valid_keys = ['cpg', 'snap_cpg', 'provisioning', 'persona', 'vvs'] def __init__(self, config): self.config = config self.hosts_naming_dict = dict() self.client = None def get_version(self): return self.VERSION def check_flags(self, options, required_flags): for flag in required_flags: if not getattr(options, flag, None): msg = _('%s is not set') % flag LOG.error(msg) raise exception.InvalidInput(reason=msg) def _create_client(self): cl = client.HP3ParClient(self.config.hp3par_api_url) client_version = hp3parclient.version if (client_version < MIN_CLIENT_VERSION): ex_msg = (_('Invalid hp3parclient version found (%(found)s). ' 'Version %(minimum)s or greater required.') % {'found': client_version, 'minimum': MIN_CLIENT_VERSION}) LOG.error(ex_msg) raise exception.InvalidInput(reason=ex_msg) cl.setSSHOptions(self.config.san_ip, self.config.san_login, self.config.san_password, port=self.config.san_ssh_port, conn_timeout=self.config.ssh_conn_timeout, privatekey=self.config.san_private_key) return cl def client_login(self): try: LOG.debug("Connecting to 3PAR") self.client.login(self.config.hp3par_username, self.config.hp3par_password) except hpexceptions.HTTPUnauthorized as ex: msg = (_("Failed to Login to 3PAR (%(url)s) because %(err)s") % {'url': self.config.hp3par_api_url, 'err': ex}) LOG.error(msg) raise exception.InvalidInput(reason=msg) def client_logout(self): self.client.logout() LOG.debug("Disconnect from 3PAR") def do_setup(self, context): if hp3parclient is None: msg = _('You must install hp3parclient before using 3PAR drivers.') raise exception.VolumeBackendAPIException(data=msg) try: self.client = self._create_client() except hpexceptions.UnsupportedVersion as ex: raise exception.InvalidInput(ex) LOG.info(_("HP3PARCommon %(common_ver)s, hp3parclient %(rest_ver)s") % {"common_ver": self.VERSION, "rest_ver": hp3parclient.get_version_string()}) if self.config.hp3par_debug: self.client.debug_rest(True) self.client_login() try: # make sure the default CPG exists self.validate_cpg(self.config.hp3par_cpg) finally: self.client_logout() def validate_cpg(self, cpg_name): try: self.client.getCPG(cpg_name) except hpexceptions.HTTPNotFound: err = (_("CPG (%s) doesn't exist on array") % cpg_name) LOG.error(err) raise exception.InvalidInput(reason=err) def get_domain(self, cpg_name): try: cpg = self.client.getCPG(cpg_name) except hpexceptions.HTTPNotFound: err = (_("Failed to get domain because CPG (%s) doesn't " "exist on array.") % cpg_name) LOG.error(err) raise exception.InvalidInput(reason=err) if 'domain' in cpg: return cpg['domain'] return None def extend_volume(self, volume, new_size): volume_name = self._get_3par_vol_name(volume['id']) old_size = volume['size'] growth_size = int(new_size) - old_size LOG.debug(_("Extending Volume %(vol)s from %(old)s to %(new)s, " " by %(diff)s GB.") % {'vol': volume_name, 'old': old_size, 'new': new_size, 'diff': growth_size}) growth_size_mib = growth_size * units.KiB self._extend_volume(volume, volume_name, growth_size_mib) def _extend_volume(self, volume, volume_name, growth_size_mib, _convert_to_base=False): try: if _convert_to_base: LOG.debug(_("Converting to base volume prior to growing.")) self._convert_to_base_volume(volume) self.client.growVolume(volume_name, growth_size_mib) except Exception as ex: with excutils.save_and_reraise_exception() as ex_ctxt: if (not _convert_to_base and isinstance(ex, hpexceptions.HTTPForbidden) and ex.get_code() == 150): # Error code 150 means 'invalid operation: Cannot grow # this type of volume'. # Suppress raising this exception because we can # resolve it by converting it into a base volume. # Afterwards, extending the volume should succeed, or # fail with a different exception/error code. ex_ctxt.reraise = False self._extend_volume(volume, volume_name, growth_size_mib, _convert_to_base=True) else: LOG.error(_("Error extending volume: %(vol)s. " "Exception: %(ex)s") % {'vol': volume_name, 'ex': ex}) def _get_3par_vol_name(self, volume_id): """Get converted 3PAR volume name. Converts the openstack volume id from ecffc30f-98cb-4cf5-85ee-d7309cc17cd2 to osv-7P.DD5jLTPWF7tcwnMF80g We convert the 128 bits of the uuid into a 24character long base64 encoded string to ensure we don't exceed the maximum allowed 31 character name limit on 3Par We strip the padding '=' and replace + with . and / with - """ volume_name = self._encode_name(volume_id) return "osv-%s" % volume_name def _get_3par_snap_name(self, snapshot_id): snapshot_name = self._encode_name(snapshot_id) return "oss-%s" % snapshot_name def _get_3par_vvs_name(self, volume_id): vvs_name = self._encode_name(volume_id) return "vvs-%s" % vvs_name def _encode_name(self, name): uuid_str = name.replace("-", "") vol_uuid = uuid.UUID('urn:uuid:%s' % uuid_str) vol_encoded = base64.b64encode(vol_uuid.bytes) # 3par doesn't allow +, nor / vol_encoded = vol_encoded.replace('+', '.') vol_encoded = vol_encoded.replace('/', '-') # strip off the == as 3par doesn't like those. vol_encoded = vol_encoded.replace('=', '') return vol_encoded def _capacity_from_size(self, vol_size): # because 3PAR volume sizes are in # Mebibytes, Gigibytes, not Megabytes. MB = 1000L MiB = 1.048576 if int(vol_size) == 0: capacity = MB # default: 1GB else: capacity = vol_size * MB capacity = int(round(capacity / MiB)) return capacity def _delete_3par_host(self, hostname): self.client.deleteHost(hostname) def _create_3par_vlun(self, volume, hostname, nsp): try: location = None if nsp is None: location = self.client.createVLUN(volume, hostname=hostname, auto=True) else: port = self.build_portPos(nsp) location = self.client.createVLUN(volume, hostname=hostname, auto=True, portPos=port) vlun_info = None if location: # The LUN id is returned as part of the location URI vlun = location.split(',') vlun_info = {'volume_name': vlun[0], 'lun_id': int(vlun[1]), 'host_name': vlun[2], } if len(vlun) > 3: vlun_info['nsp'] = vlun[3] return vlun_info except hpexceptions.HTTPBadRequest as e: if 'must be in the same domain' in e.get_description(): LOG.error(e.get_description()) raise exception.Invalid3PARDomain(err=e.get_description()) def _safe_hostname(self, hostname): """We have to use a safe hostname length for 3PAR host names.""" try: index = hostname.index('.') except ValueError: # couldn't find it index = len(hostname) # we'll just chop this off for now. if index > 23: index = 23 return hostname[:index] def _get_3par_host(self, hostname): return self.client.getHost(hostname) def get_ports(self): return self.client.getPorts() def get_active_target_ports(self): ports = self.get_ports() target_ports = [] for port in ports['members']: if ( port['mode'] == self.client.PORT_MODE_TARGET and port['linkState'] == self.client.PORT_STATE_READY ): port['nsp'] = self.build_nsp(port['portPos']) target_ports.append(port) return target_ports def get_active_fc_target_ports(self): ports = self.get_active_target_ports() fc_ports = [] for port in ports: if port['protocol'] == self.client.PORT_PROTO_FC: fc_ports.append(port) return fc_ports def get_active_iscsi_target_ports(self): ports = self.get_active_target_ports() iscsi_ports = [] for port in ports: if port['protocol'] == self.client.PORT_PROTO_ISCSI: iscsi_ports.append(port) return iscsi_ports def get_volume_stats(self, refresh): if refresh: self._update_volume_stats() return self.stats def _update_volume_stats(self): # const to convert MiB to GB const = 0.0009765625 # storage_protocol and volume_backend_name are # set in the child classes stats = {'driver_version': '1.0', 'free_capacity_gb': 'unknown', 'reserved_percentage': 0, 'storage_protocol': None, 'total_capacity_gb': 'unknown', 'QoS_support': True, 'vendor_name': 'Hewlett-Packard', 'volume_backend_name': None} try: cpg = self.client.getCPG(self.config.hp3par_cpg) if 'limitMiB' not in cpg['SDGrowth']: total_capacity = 'infinite' free_capacity = 'infinite' else: total_capacity = int(cpg['SDGrowth']['limitMiB'] * const) free_capacity = int((cpg['SDGrowth']['limitMiB'] - cpg['UsrUsage']['usedMiB']) * const) stats['total_capacity_gb'] = total_capacity stats['free_capacity_gb'] = free_capacity except hpexceptions.HTTPNotFound: err = (_("CPG (%s) doesn't exist on array") % self.config.hp3par_cpg) LOG.error(err) raise exception.InvalidInput(reason=err) info = self.client.getStorageSystemInfo() stats['location_info'] = ('HP3PARDriver:%(sys_id)s:%(dest_cpg)s' % {'sys_id': info['serialNumber'], 'dest_cpg': self.config.safe_get( 'hp3par_cpg')}) self.stats = stats def _get_vlun(self, volume_name, hostname, lun_id=None): """find a VLUN on a 3PAR host.""" vluns = self.client.getHostVLUNs(hostname) found_vlun = None for vlun in vluns: if volume_name in vlun['volumeName']: if lun_id: if vlun['lun'] == lun_id: found_vlun = vlun break else: found_vlun = vlun break if found_vlun is None: msg = (_("3PAR vlun %(name)s not found on host %(host)s") % {'name': volume_name, 'host': hostname}) LOG.warn(msg) return found_vlun def create_vlun(self, volume, host, nsp=None): """Create a VLUN. In order to export a volume on a 3PAR box, we have to create a VLUN. """ volume_name = self._get_3par_vol_name(volume['id']) vlun_info = self._create_3par_vlun(volume_name, host['name'], nsp) return self._get_vlun(volume_name, host['name'], vlun_info['lun_id']) def delete_vlun(self, volume, hostname): volume_name = self._get_3par_vol_name(volume['id']) vlun = self._get_vlun(volume_name, hostname) if vlun is not None: # VLUN Type of MATCHED_SET 4 requires the port to be provided if self.VLUN_TYPE_MATCHED_SET == vlun['type']: self.client.deleteVLUN(volume_name, vlun['lun'], hostname, vlun['portPos']) else: self.client.deleteVLUN(volume_name, vlun['lun'], hostname) try: self._delete_3par_host(hostname) self._remove_hosts_naming_dict_host(hostname) except hpexceptions.HTTPConflict as ex: # host will only be removed after all vluns # have been removed if 'has exported VLUN' in ex.get_description(): pass else: raise def _remove_hosts_naming_dict_host(self, hostname): items = self.hosts_naming_dict.items() lkey = None for key, value in items: if value == hostname: lkey = key if lkey is not None: del self.hosts_naming_dict[lkey] def _get_volume_type(self, type_id): ctxt = context.get_admin_context() return volume_types.get_volume_type(ctxt, type_id) def _get_key_value(self, hp3par_keys, key, default=None): if hp3par_keys is not None and key in hp3par_keys: return hp3par_keys[key] else: return default def _get_qos_value(self, qos, key, default=None): if key in qos: return qos[key] else: return default def _get_qos_by_volume_type(self, volume_type): qos = {} qos_specs_id = volume_type.get('qos_specs_id') specs = volume_type.get('extra_specs') #NOTE(kmartin): We prefer the qos_specs association # and override any existing extra-specs settings # if present. if qos_specs_id is not None: kvs = qos_specs.get_qos_specs(context.get_admin_context(), qos_specs_id)['specs'] else: kvs = specs for key, value in kvs.iteritems(): if 'qos:' in key: fields = key.split(':') key = fields[1] if key in self.hp_qos_keys: qos[key] = value return qos def _get_keys_by_volume_type(self, volume_type): hp3par_keys = {} specs = volume_type.get('extra_specs') for key, value in specs.iteritems(): if ':' in key: fields = key.split(':') key = fields[1] if key in self.hp3par_valid_keys: hp3par_keys[key] = value return hp3par_keys def _set_qos_rule(self, qos, vvs_name): min_io = self._get_qos_value(qos, 'minIOPS') max_io = self._get_qos_value(qos, 'maxIOPS') min_bw = self._get_qos_value(qos, 'minBWS') max_bw = self._get_qos_value(qos, 'maxBWS') latency = self._get_qos_value(qos, 'latency') priority = self._get_qos_value(qos, 'priority', 'normal') qosRule = {} if min_io: qosRule['ioMinGoal'] = int(min_io) if max_io is None: qosRule['ioMaxLimit'] = int(min_io) if max_io: qosRule['ioMaxLimit'] = int(max_io) if min_io is None: qosRule['ioMinGoal'] = int(max_io) if min_bw: qosRule['bwMinGoalKB'] = int(min_bw) * units.KiB if max_bw is None: qosRule['bwMaxLimitKB'] = int(min_bw) * units.KiB if max_bw: qosRule['bwMaxLimitKB'] = int(max_bw) * units.KiB if min_bw is None: qosRule['bwMinGoalKB'] = int(max_bw) * units.KiB if latency: qosRule['latencyGoal'] = int(latency) if priority: qosRule['priority'] = self.qos_priority_level.get(priority.lower()) try: self.client.createQoSRules(vvs_name, qosRule) except Exception: with excutils.save_and_reraise_exception(): LOG.error(_("Error creating QOS rule %s") % qosRule) def _add_volume_to_volume_set(self, volume, volume_name, cpg, vvs_name, qos): if vvs_name is not None: # Admin has set a volume set name to add the volume to try: self.client.addVolumeToVolumeSet(vvs_name, volume_name) except hpexceptions.HTTPNotFound: msg = _('VV Set %s does not exist.') % vvs_name LOG.error(msg) raise exception.InvalidInput(reason=msg) else: vvs_name = self._get_3par_vvs_name(volume['id']) domain = self.get_domain(cpg) self.client.createVolumeSet(vvs_name, domain) try: self._set_qos_rule(qos, vvs_name) self.client.addVolumeToVolumeSet(vvs_name, volume_name) except Exception as ex: # Cleanup the volume set if unable to create the qos rule # or add the volume to the volume set self.client.deleteVolumeSet(vvs_name) raise exception.CinderException(ex) def get_cpg(self, volume, allowSnap=False): volume_name = self._get_3par_vol_name(volume['id']) vol = self.client.getVolume(volume_name) if 'userCPG' in vol: return vol['userCPG'] elif allowSnap: return vol['snapCPG'] return None def _get_3par_vol_comment(self, volume_name): vol = self.client.getVolume(volume_name) if 'comment' in vol: return vol['comment'] return None def get_persona_type(self, volume, hp3par_keys=None): default_persona = self.valid_persona_values[0] type_id = volume.get('volume_type_id', None) volume_type = None if type_id is not None: volume_type = self._get_volume_type(type_id) if hp3par_keys is None: hp3par_keys = self._get_keys_by_volume_type(volume_type) persona_value = self._get_key_value(hp3par_keys, 'persona', default_persona) if persona_value not in self.valid_persona_values: err = _("Must specify a valid persona %(valid)s, " "value '%(persona)s' is invalid.") % \ ({'valid': self.valid_persona_values, 'persona': persona_value}) LOG.error(err) raise exception.InvalidInput(reason=err) # persona is set by the id so remove the text and return the id # i.e for persona '1 - Generic' returns 1 persona_id = persona_value.split(' ') return persona_id[0] def get_volume_settings_from_type(self, volume): cpg = None snap_cpg = None volume_type = None vvs_name = None hp3par_keys = {} qos = {} type_id = volume.get('volume_type_id', None) if type_id is not None: volume_type = self._get_volume_type(type_id) hp3par_keys = self._get_keys_by_volume_type(volume_type) vvs_name = self._get_key_value(hp3par_keys, 'vvs') if vvs_name is None: qos = self._get_qos_by_volume_type(volume_type) cpg = self._get_key_value(hp3par_keys, 'cpg', self.config.hp3par_cpg) if cpg is not self.config.hp3par_cpg: # The cpg was specified in a volume type extra spec so it # needs to be validated that it's in the correct domain. self.validate_cpg(cpg) # Also, look to see if the snap_cpg was specified in volume # type extra spec, if not use the extra spec cpg as the # default. snap_cpg = self._get_key_value(hp3par_keys, 'snap_cpg', cpg) else: # default snap_cpg to hp3par_cpg_snap if it's not specified # in the volume type extra specs. snap_cpg = self.config.hp3par_cpg_snap # if it's still not set or empty then set it to the cpg # specified in the cinder.conf file. if not self.config.hp3par_cpg_snap: snap_cpg = cpg # if provisioning is not set use thin default_prov = self.valid_prov_values[0] prov_value = self._get_key_value(hp3par_keys, 'provisioning', default_prov) # check for valid provisioning type if prov_value not in self.valid_prov_values: err = _("Must specify a valid provisioning type %(valid)s, " "value '%(prov)s' is invalid.") % \ ({'valid': self.valid_prov_values, 'prov': prov_value}) LOG.error(err) raise exception.InvalidInput(reason=err) tpvv = True if prov_value == "full": tpvv = False # check for valid persona even if we don't use it until # attach time, this will give the end user notice that the # persona type is invalid at volume creation time self.get_persona_type(volume, hp3par_keys) return {'cpg': cpg, 'snap_cpg': snap_cpg, 'vvs_name': vvs_name, 'qos': qos, 'tpvv': tpvv, 'volume_type': volume_type} def create_volume(self, volume): LOG.debug("CREATE VOLUME (%s : %s %s)" % (volume['display_name'], volume['name'], self._get_3par_vol_name(volume['id']))) try: comments = {'volume_id': volume['id'], 'name': volume['name'], 'type': 'OpenStack'} name = volume.get('display_name', None) if name: comments['display_name'] = name # get the options supported by volume types type_info = self.get_volume_settings_from_type(volume) volume_type = type_info['volume_type'] vvs_name = type_info['vvs_name'] qos = type_info['qos'] cpg = type_info['cpg'] snap_cpg = type_info['snap_cpg'] tpvv = type_info['tpvv'] type_id = volume.get('volume_type_id', None) if type_id is not None: comments['volume_type_name'] = volume_type.get('name') comments['volume_type_id'] = type_id if vvs_name is not None: comments['vvs'] = vvs_name else: comments['qos'] = qos extras = {'comment': json.dumps(comments), 'snapCPG': snap_cpg, 'tpvv': tpvv} capacity = self._capacity_from_size(volume['size']) volume_name = self._get_3par_vol_name(volume['id']) self.client.createVolume(volume_name, cpg, capacity, extras) if qos or vvs_name is not None: try: self._add_volume_to_volume_set(volume, volume_name, cpg, vvs_name, qos) except exception.InvalidInput as ex: # Delete the volume if unable to add it to the volume set self.client.deleteVolume(volume_name) LOG.error(ex) raise exception.CinderException(ex) except hpexceptions.HTTPConflict: msg = _("Volume (%s) already exists on array") % volume_name LOG.error(msg) raise exception.Duplicate(msg) except hpexceptions.HTTPBadRequest as ex: LOG.error(ex) raise exception.Invalid(ex.get_description()) except exception.InvalidInput as ex: LOG.error(ex) raise ex except exception.CinderException as ex: LOG.error(ex) raise ex except Exception as ex: LOG.error(ex) raise exception.CinderException(ex) def _copy_volume(self, src_name, dest_name, cpg, snap_cpg=None, tpvv=True): # Virtual volume sets are not supported with the -online option LOG.debug(_('Creating clone of a volume %(src)s to %(dest)s.') % {'src': src_name, 'dest': dest_name}) optional = {'tpvv': tpvv, 'online': True} if snap_cpg is not None: optional['snapCPG'] = snap_cpg body = self.client.copyVolume(src_name, dest_name, cpg, optional) return body['taskid'] def get_next_word(self, s, search_string): """Return the next word. Search 's' for 'search_string', if found return the word preceding 'search_string' from 's'. """ word = re.search(search_string.strip(' ') + ' ([^ ]*)', s) return word.groups()[0].strip(' ') def _get_3par_vol_comment_value(self, vol_comment, key): comment_dict = dict(ast.literal_eval(vol_comment)) if key in comment_dict: return comment_dict[key] return None def create_cloned_volume(self, volume, src_vref): try: orig_name = self._get_3par_vol_name(volume['source_volid']) vol_name = self._get_3par_vol_name(volume['id']) type_info = self.get_volume_settings_from_type(volume) # make the 3PAR copy the contents. # can't delete the original until the copy is done. self._copy_volume(orig_name, vol_name, cpg=type_info['cpg'], snap_cpg=type_info['snap_cpg'], tpvv=type_info['tpvv']) return None except hpexceptions.HTTPForbidden: raise exception.NotAuthorized() except hpexceptions.HTTPNotFound: raise exception.NotFound() except Exception as ex: LOG.error(ex) raise exception.CinderException(ex) def delete_volume(self, volume): try: volume_name = self._get_3par_vol_name(volume['id']) # Try and delete the volume, it might fail here because # the volume is part of a volume set which will have the # volume set name in the error. try: self.client.deleteVolume(volume_name) except hpexceptions.HTTPBadRequest as ex: if ex.get_code() == 29: if self.client.isOnlinePhysicalCopy(volume_name): LOG.debug(_("Found an online copy for %(volume)s") % {'volume': volume_name}) # the volume is in process of being cloned. # stopOnlinePhysicalCopy will also delete # the volume once it stops the copy. self.client.stopOnlinePhysicalCopy(volume_name) else: LOG.error(ex) raise ex else: LOG.error(ex) raise ex except hpexceptions.HTTPConflict as ex: if ex.get_code() == 34: # This is a special case which means the # volume is part of a volume set. vvset_name = self.client.findVolumeSet(volume_name) LOG.debug("Returned vvset_name = %s" % vvset_name) if vvset_name is not None and \ vvset_name.startswith('vvs-'): # We have a single volume per volume set, so # remove the volume set. self.client.deleteVolumeSet( self._get_3par_vvs_name(volume['id'])) elif vvset_name is not None: # We have a pre-defined volume set just remove the # volume and leave the volume set. self.client.removeVolumeFromVolumeSet(vvset_name, volume_name) self.client.deleteVolume(volume_name) else: LOG.error(ex) raise ex except hpexceptions.HTTPNotFound as ex: # We'll let this act as if it worked # it helps clean up the cinder entries. msg = _("Delete volume id not found. Removing from cinder: " "%(id)s Ex: %(msg)s") % {'id': volume['id'], 'msg': ex} LOG.warning(msg) except hpexceptions.HTTPForbidden as ex: LOG.error(ex) raise exception.NotAuthorized(ex.get_description()) except hpexceptions.HTTPConflict as ex: LOG.error(ex) raise exception.VolumeIsBusy(ex.get_description()) except Exception as ex: LOG.error(ex) raise exception.CinderException(ex) def create_volume_from_snapshot(self, volume, snapshot): """Creates a volume from a snapshot. """ LOG.debug("Create Volume from Snapshot\n%s\n%s" % (pprint.pformat(volume['display_name']), pprint.pformat(snapshot['display_name']))) if volume['size'] < snapshot['volume_size']: err = ("You cannot reduce size of the volume. It must " "be greater than or equal to the snapshot.") LOG.error(err) raise exception.InvalidInput(reason=err) try: snap_name = self._get_3par_snap_name(snapshot['id']) volume_name = self._get_3par_vol_name(volume['id']) extra = {'volume_id': volume['id'], 'snapshot_id': snapshot['id']} volume_type = None type_id = volume.get('volume_type_id', None) vvs_name = None qos = {} hp3par_keys = {} if type_id is not None: volume_type = self._get_volume_type(type_id) hp3par_keys = self._get_keys_by_volume_type(volume_type) vvs_name = self._get_key_value(hp3par_keys, 'vvs') if vvs_name is None: qos = self._get_qos_by_volume_type(volume_type) name = volume.get('display_name', None) if name: extra['display_name'] = name description = volume.get('display_description', None) if description: extra['description'] = description optional = {'comment': json.dumps(extra), 'readOnly': False} self.client.createSnapshot(volume_name, snap_name, optional) # Grow the snapshot if needed growth_size = volume['size'] - snapshot['volume_size'] if growth_size > 0: try: LOG.debug(_('Converting to base volume type: %s.') % volume['id']) self._convert_to_base_volume(volume) growth_size_mib = growth_size * units.GiB / units.MiB LOG.debug(_('Growing volume: %(id)s by %(size)s GiB.') % {'id': volume['id'], 'size': growth_size}) self.client.growVolume(volume_name, growth_size_mib) except Exception as ex: LOG.error(_("Error extending volume %(id)s. Ex: %(ex)s") % {'id': volume['id'], 'ex': ex}) # Delete the volume if unable to grow it self.client.deleteVolume(volume_name) raise exception.CinderException(ex) if qos or vvs_name is not None: cpg = self._get_key_value(hp3par_keys, 'cpg', self.config.hp3par_cpg) try: self._add_volume_to_volume_set(volume, volume_name, cpg, vvs_name, qos) except Exception as ex: # Delete the volume if unable to add it to the volume set self.client.deleteVolume(volume_name) LOG.error(ex) raise exception.CinderException(ex) except hpexceptions.HTTPForbidden as ex: LOG.error(ex) raise exception.NotAuthorized() except hpexceptions.HTTPNotFound as ex: LOG.error(ex) raise exception.NotFound() except Exception as ex: LOG.error(ex) raise exception.CinderException(ex) def create_snapshot(self, snapshot): LOG.debug("Create Snapshot\n%s" % pprint.pformat(snapshot)) try: snap_name = self._get_3par_snap_name(snapshot['id']) vol_name = self._get_3par_vol_name(snapshot['volume_id']) extra = {'volume_name': snapshot['volume_name']} vol_id = snapshot.get('volume_id', None) if vol_id: extra['volume_id'] = vol_id try: extra['display_name'] = snapshot['display_name'] except AttributeError: pass try: extra['description'] = snapshot['display_description'] except AttributeError: pass optional = {'comment': json.dumps(extra), 'readOnly': True} if self.config.hp3par_snapshot_expiration: optional['expirationHours'] = ( self.config.hp3par_snapshot_expiration) if self.config.hp3par_snapshot_retention: optional['retentionHours'] = ( self.config.hp3par_snapshot_retention) self.client.createSnapshot(snap_name, vol_name, optional) except hpexceptions.HTTPForbidden as ex: LOG.error(ex) raise exception.NotAuthorized() except hpexceptions.HTTPNotFound as ex: LOG.error(ex) raise exception.NotFound() def update_volume_key_value_pair(self, volume, key, value): """Updates key,value pair as metadata onto virtual volume. If key already exists, the value will be replaced. """ LOG.debug("VOLUME (%s : %s %s) Updating KEY-VALUE pair: (%s : %s)" % (volume['display_name'], volume['name'], self._get_3par_vol_name(volume['id']), key, value)) try: volume_name = self._get_3par_vol_name(volume['id']) if value is None: value = '' self.client.setVolumeMetaData(volume_name, key, value) except Exception as ex: msg = _('Failure in update_volume_key_value_pair:%s') % ex LOG.error(msg) raise exception.VolumeBackendAPIException(data=msg) def clear_volume_key_value_pair(self, volume, key): """Clears key,value pairs metadata from virtual volume.""" LOG.debug("VOLUME (%s : %s %s) Clearing Key : %s)" % (volume['display_name'], volume['name'], self._get_3par_vol_name(volume['id']), key)) try: volume_name = self._get_3par_vol_name(volume['id']) self.client.removeVolumeMetaData(volume_name, key) except Exception as ex: msg = _('Failure in clear_volume_key_value_pair:%s') % ex LOG.error(msg) raise exception.VolumeBackendAPIException(data=msg) def attach_volume(self, volume, instance_uuid): LOG.debug("Attach Volume\n%s" % pprint.pformat(volume)) try: self.update_volume_key_value_pair(volume, 'HPQ-CS-instance_uuid', instance_uuid) except Exception: with excutils.save_and_reraise_exception(): LOG.error(_("Error attaching volume %s") % volume) def detach_volume(self, volume): LOG.debug("Detach Volume\n%s" % pprint.pformat(volume)) try: self.clear_volume_key_value_pair(volume, 'HPQ-CS-instance_uuid') except Exception: with excutils.save_and_reraise_exception(): LOG.error(_("Error detaching volume %s") % volume) def migrate_volume(self, volume, host): """Migrate directly if source and dest are managed by same storage. :param volume: A dictionary describing the volume to migrate :param host: A dictionary describing the host to migrate to, where host['host'] is its name, and host['capabilities'] is a dictionary of its reported capabilities. :returns (False, None) if the driver does not support migration, (True, None) if sucessful """ dbg = {'id': volume['id'], 'host': host['host']} LOG.debug(_('enter: migrate_volume: id=%(id)s, host=%(host)s.') % dbg) false_ret = (False, None) # Make sure volume is not attached if volume['status'] != 'available': LOG.debug(_('Volume is attached: migrate_volume: ' 'id=%(id)s, host=%(host)s.') % dbg) return false_ret if 'location_info' not in host['capabilities']: return false_ret info = host['capabilities']['location_info'] try: (dest_type, dest_id, dest_cpg) = info.split(':') except ValueError: return false_ret sys_info = self.client.getStorageSystemInfo() if not (dest_type == 'HP3PARDriver' and dest_id == sys_info['serialNumber']): LOG.debug(_('Dest does not match: migrate_volume: ' 'id=%(id)s, host=%(host)s.') % dbg) return false_ret type_info = self.get_volume_settings_from_type(volume) if dest_cpg == type_info['cpg']: LOG.debug(_('CPGs are the same: migrate_volume: ' 'id=%(id)s, host=%(host)s.') % dbg) return false_ret # Check to make sure CPGs are in the same domain src_domain = self.get_domain(type_info['cpg']) dst_domain = self.get_domain(dest_cpg) if src_domain != dst_domain: LOG.debug(_('CPGs in different domains: migrate_volume: ' 'id=%(id)s, host=%(host)s.') % dbg) return false_ret self._convert_to_base_volume(volume, new_cpg=dest_cpg) # TODO(Ramy) When volume retype is available, # use that to change the type LOG.debug(_('leave: migrate_volume: id=%(id)s, host=%(host)s.') % dbg) return (True, None) def _convert_to_base_volume(self, volume, new_cpg=None): try: type_info = self.get_volume_settings_from_type(volume) if new_cpg: cpg = new_cpg else: cpg = type_info['cpg'] # Change the name such that it is unique since 3PAR # names must be unique across all CPGs volume_name = self._get_3par_vol_name(volume['id']) temp_vol_name = volume_name.replace("osv-", "omv-") # Create a physical copy of the volume task_id = self._copy_volume(volume_name, temp_vol_name, cpg, cpg, type_info['tpvv']) LOG.debug(_('Copy volume scheduled: convert_to_base_volume: ' 'id=%s.') % volume['id']) # Wait for the physical copy task to complete def _wait_for_task(task_id): status = self.client.getTask(task_id) LOG.debug("3PAR Task id %(id)s status = %(status)s" % {'id': task_id, 'status': status['status']}) if status['status'] is not self.client.TASK_ACTIVE: self._task_status = status raise loopingcall.LoopingCallDone() self._task_status = None timer = loopingcall.FixedIntervalLoopingCall( _wait_for_task, task_id) timer.start(interval=1).wait() if self._task_status['status'] is not self.client.TASK_DONE: dbg = {'status': self._task_status, 'id': volume['id']} msg = _('Copy volume task failed: convert_to_base_volume: ' 'id=%(id)s, status=%(status)s.') % dbg raise exception.CinderException(msg) else: LOG.debug(_('Copy volume completed: convert_to_base_volume: ' 'id=%s.') % volume['id']) comment = self._get_3par_vol_comment(volume_name) if comment: self.client.modifyVolume(temp_vol_name, {'comment': comment}) LOG.debug(_('Volume rename completed: convert_to_base_volume: ' 'id=%s.') % volume['id']) # Delete source volume after the copy is complete self.client.deleteVolume(volume_name) LOG.debug(_('Delete src volume completed: convert_to_base_volume: ' 'id=%s.') % volume['id']) # Rename the new volume to the original name self.client.modifyVolume(temp_vol_name, {'newName': volume_name}) LOG.info(_('Completed: convert_to_base_volume: ' 'id=%s.') % volume['id']) except hpexceptions.HTTPConflict: msg = _("Volume (%s) already exists on array.") % volume_name LOG.error(msg) raise exception.Duplicate(msg) except hpexceptions.HTTPBadRequest as ex: LOG.error(ex) raise exception.Invalid(ex.get_description()) except exception.InvalidInput as ex: LOG.error(ex) raise ex except exception.CinderException as ex: LOG.error(ex) raise ex except Exception as ex: LOG.error(ex) raise exception.CinderException(ex) def delete_snapshot(self, snapshot): LOG.debug("Delete Snapshot id %s %s" % (snapshot['id'], pprint.pformat(snapshot))) try: snap_name = self._get_3par_snap_name(snapshot['id']) self.client.deleteVolume(snap_name) except hpexceptions.HTTPForbidden as ex: LOG.error(ex) raise exception.NotAuthorized() except hpexceptions.HTTPNotFound as ex: # We'll let this act as if it worked # it helps clean up the cinder entries. msg = _("Delete Snapshot id not found. Removing from cinder: " "%(id)s Ex: %(msg)s") % {'id': snapshot['id'], 'msg': ex} LOG.warning(msg) except hpexceptions.HTTPConflict as ex: LOG.error(ex) raise exception.SnapshotIsBusy(snapshot_name=snapshot['id']) def _get_3par_hostname_from_wwn_iqn(self, wwns, iqns): if wwns is not None and not isinstance(wwns, list): wwns = [wwns] if iqns is not None and not isinstance(iqns, list): iqns = [iqns] out = self.client.getHosts() hosts = out['members'] for host in hosts: if 'iSCSIPaths' in host and iqns is not None: iscsi_paths = host['iSCSIPaths'] for iscsi in iscsi_paths: for iqn in iqns: if iqn == iscsi['name']: return host['name'] if 'FCPaths' in host and wwns is not None: fc_paths = host['FCPaths'] for fc in fc_paths: for wwn in wwns: if wwn == fc['wwn']: return host['name'] def terminate_connection(self, volume, hostname, wwn=None, iqn=None): """Driver entry point to unattach a volume from an instance.""" try: # does 3par know this host by a different name? if hostname in self.hosts_naming_dict: hostname = self.hosts_naming_dict.get(hostname) self.delete_vlun(volume, hostname) return except hpexceptions.HTTPNotFound as e: if 'host does not exist' in e.get_description(): # use the wwn to see if we can find the hostname hostname = self._get_3par_hostname_from_wwn_iqn(wwn, iqn) # no 3par host, re-throw if (hostname is None): LOG.error(e) raise else: # not a 'host does not exist' HTTPNotFound exception, re-throw LOG.error(e) raise # try again with name retrieved from 3par self.delete_vlun(volume, hostname) def build_nsp(self, portPos): return '%s:%s:%s' % (portPos['node'], portPos['slot'], portPos['cardPort']) def build_portPos(self, nsp): split = nsp.split(":") portPos = {} portPos['node'] = int(split[0]) portPos['slot'] = int(split[1]) portPos['cardPort'] = int(split[2]) return portPos
apache-2.0
naveedaz/azure-powershell
src/ResourceManager/Profile/Commands.Profile/Account/AddAzureRmAccount.cs
14562
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.Azure.Commands.Common.Authentication; using Microsoft.Azure.Commands.Common.Authentication.Abstractions; using Microsoft.Azure.Commands.Common.Authentication.Models; using Microsoft.Azure.Commands.Profile.Models; using Microsoft.Azure.Commands.ResourceManager.Common; using Microsoft.WindowsAzure.Commands.Common; using Microsoft.WindowsAzure.Commands.Utilities.Common; using System; using System.IO; using System.Management.Automation; using System.Reflection; using System.Security; using Microsoft.Azure.Commands.Profile.Properties; using Microsoft.Azure.Commands.Profile.Common; namespace Microsoft.Azure.Commands.Profile { /// <summary> /// Cmdlet to log into an environment and download the subscriptions /// </summary> [Cmdlet("Add", "AzureRmAccount", DefaultParameterSetName = "UserWithSubscriptionId", SupportsShouldProcess=true)] [Alias("Login-AzureRmAccount", "Login-AzAccount")] [OutputType(typeof(PSAzureProfile))] public class AddAzureRMAccountCommand : AzureContextModificationCmdlet, IModuleAssemblyInitializer { public const string UserParameterSet = "UserWithSubscriptionId"; public const string ServicePrincipalParameterSet = "ServicePrincipalWithSubscriptionId"; public const string ServicePrincipalCertificateParameterSet= "ServicePrincipalCertificateWithSubscriptionId"; public const string AccessTokenParameterSet = "AccessTokenWithSubscriptionId"; public const string ManagedServiceParameterSet = "ManagedServiceLogin"; protected IAzureEnvironment _environment =AzureEnvironment.PublicEnvironments[EnvironmentName.AzureCloud]; [Parameter(Mandatory = false, HelpMessage = "Name of the environment containing the account to log into")] [Alias("EnvironmentName")] [ValidateNotNullOrEmpty] public string Environment { get; set; } [Parameter(ParameterSetName = UserParameterSet, Mandatory = false, HelpMessage = "Optional credential", Position = 0)] [Parameter(ParameterSetName = ServicePrincipalParameterSet, Mandatory = true, HelpMessage = "Credential")] public PSCredential Credential { get; set; } [Parameter(ParameterSetName = ServicePrincipalCertificateParameterSet, Mandatory = true, HelpMessage = "Certificate Hash (Thumbprint)")] public string CertificateThumbprint { get; set; } [Parameter(ParameterSetName = ServicePrincipalCertificateParameterSet, Mandatory = true, HelpMessage = "SPN")] public string ApplicationId { get; set; } [Parameter(ParameterSetName = ServicePrincipalParameterSet, Mandatory = true)] [Parameter(ParameterSetName = ServicePrincipalCertificateParameterSet, Mandatory = true)] public SwitchParameter ServicePrincipal { get; set; } [Parameter(ParameterSetName = UserParameterSet, Mandatory = false, HelpMessage = "Optional tenant name or ID")] [Parameter(ParameterSetName = ServicePrincipalParameterSet, Mandatory = true, HelpMessage = "Tenant name or ID")] [Parameter(ParameterSetName = AccessTokenParameterSet, Mandatory = false, HelpMessage = "Tenant name or ID")] [Parameter(ParameterSetName = ServicePrincipalCertificateParameterSet, Mandatory = true, HelpMessage = "Tenant name or ID")] [Parameter(ParameterSetName = ManagedServiceParameterSet, Mandatory = false, HelpMessage = "Optional tenant name or ID")] [Alias("Domain")] [ValidateNotNullOrEmpty] public string TenantId { get; set; } [Parameter(ParameterSetName = AccessTokenParameterSet, Mandatory = true, HelpMessage = "AccessToken for Azure Resource Manager")] [ValidateNotNullOrEmpty] public string AccessToken { get; set; } [Parameter(ParameterSetName = AccessTokenParameterSet, Mandatory = false, HelpMessage = "AccessToken for Graph Service")] [ValidateNotNullOrEmpty] public string GraphAccessToken { get; set; } [Parameter(ParameterSetName = AccessTokenParameterSet, Mandatory = false, HelpMessage = "AccessToken for KeyVault Service")] [ValidateNotNullOrEmpty] public string KeyVaultAccessToken { get; set; } [Parameter(ParameterSetName = AccessTokenParameterSet, Mandatory = true, HelpMessage = "Account Id for access token")] [Parameter(ParameterSetName = ManagedServiceParameterSet, Mandatory = false, HelpMessage = "Account Id for managed service")] [ValidateNotNullOrEmpty] public string AccountId { get; set; } [Parameter(ParameterSetName = ManagedServiceParameterSet, Mandatory =true, HelpMessage = "Login using managed service identity in the current environment.")] [Alias("MSI")] public SwitchParameter ManagedService { get; set; } [Parameter(ParameterSetName = ManagedServiceParameterSet, Mandatory = false, HelpMessage = "Port number for managed service login.")] [PSDefaultValue(Help = "50342", Value = 50342)] public int ManagedServicePort { get; set; } = 50342; [Parameter(ParameterSetName = ManagedServiceParameterSet, Mandatory = false, HelpMessage = "Host name for managed service login.")] [PSDefaultValue(Help = "localhost", Value = "localhost")] public string ManagedServiceHostName { get; set; } = "localhost"; [Alias("SubscriptionName", "SubscriptionId")] [Parameter(ParameterSetName = UserParameterSet, Mandatory = false, HelpMessage = "Subscription Name or ID", ValueFromPipeline = true)] [Parameter(ParameterSetName = ServicePrincipalParameterSet, Mandatory = false, HelpMessage = "Subscription Name or ID", ValueFromPipeline = true)] [Parameter(ParameterSetName = ServicePrincipalCertificateParameterSet, Mandatory = false, HelpMessage = "Subscription Name or ID", ValueFromPipeline = true)] [Parameter(ParameterSetName = AccessTokenParameterSet, Mandatory = false, HelpMessage = "Subscription Name or ID", ValueFromPipeline = true)] [Parameter(ParameterSetName = ManagedServiceParameterSet, Mandatory = false, HelpMessage = "Subscription Name or ID", ValueFromPipeline = true)] [ValidateNotNullOrEmpty] public string Subscription { get; set; } [Parameter(Mandatory = false, HelpMessage = "Name of the default context from this login")] [ValidateNotNullOrEmpty] public string ContextName { get; set; } [Parameter(ParameterSetName = AccessTokenParameterSet, Mandatory = false, HelpMessage = "Skip validation for access token")] public SwitchParameter SkipValidation { get; set; } [Parameter(Mandatory = false, HelpMessage = "Overwrite the existing context with the same name, if any.")] public SwitchParameter Force { get; set; } protected override IAzureContext DefaultContext { get { return null; } } protected override void BeginProcessing() { base.BeginProcessing(); if (MyInvocation.BoundParameters.ContainsKey(nameof(Environment))) { var profile = GetDefaultProfile(); if (!profile.TryGetEnvironment(Environment, out _environment)) { throw new PSInvalidOperationException( string.Format(Resources.UnknownEnvironment, Environment)); } } } public override void ExecuteCmdlet() { Guid subscrptionIdGuid; string subscriptionName = null; string subscriptionId = null; if (MyInvocation.BoundParameters.ContainsKey(nameof(Subscription))) { if (Guid.TryParse(Subscription, out subscrptionIdGuid)) { subscriptionId = Subscription; } else { subscriptionName = Subscription; } } AzureAccount azureAccount = new AzureAccount(); switch (ParameterSetName) { case AccessTokenParameterSet: azureAccount.Type = AzureAccount.AccountType.AccessToken; azureAccount.Id = AccountId; azureAccount.SetProperty(AzureAccount.Property.AccessToken, AccessToken); azureAccount.SetProperty(AzureAccount.Property.GraphAccessToken, GraphAccessToken); azureAccount.SetProperty(AzureAccount.Property.KeyVaultAccessToken, KeyVaultAccessToken); break; case ServicePrincipalCertificateParameterSet: case ServicePrincipalParameterSet: azureAccount.Type = AzureAccount.AccountType.ServicePrincipal; break; case ManagedServiceParameterSet: azureAccount.Type = AzureAccount.AccountType.ManagedService; azureAccount.Id = MyInvocation.BoundParameters.ContainsKey(nameof(AccountId))? AccountId : string.Format("MSI@{0}", ManagedServicePort); var builder = new UriBuilder(); builder.Scheme = "http"; builder.Host = ManagedServiceHostName; builder.Port = ManagedServicePort; builder.Path = "/oauth2/token"; azureAccount.SetProperty(AzureAccount.Property.MSILoginUri, builder.Uri.ToString()); break; default: azureAccount.Type = AzureAccount.AccountType.User; break; } SecureString password = null; if (Credential != null) { azureAccount.Id = Credential.UserName; password = Credential.Password; } if (!string.IsNullOrEmpty(ApplicationId)) { azureAccount.Id = ApplicationId; } if (!string.IsNullOrWhiteSpace(CertificateThumbprint)) { azureAccount.SetThumbprint(CertificateThumbprint); } if (!string.IsNullOrEmpty(TenantId)) { azureAccount.SetProperty(AzureAccount.Property.Tenants, new[] { TenantId }); } if (ShouldProcess(string.Format(Resources.LoginTarget, azureAccount.Type, _environment.Name), "log in")) { if (AzureRmProfileProvider.Instance.Profile == null) { InitializeProfileProvider(); } SetContextWithOverwritePrompt((localProfile, profileClient, name) => { WriteObject((PSAzureProfile)profileClient.Login( azureAccount, _environment, TenantId, subscriptionId, subscriptionName, password, SkipValidation, (s) => WriteWarning(s), name)); }); } } bool CheckForExistingContext(AzureRmProfile profile, string name) { return name != null && profile != null && profile.Contexts != null && profile.Contexts.ContainsKey(name); } void SetContextWithOverwritePrompt(Action<AzureRmProfile, RMProfileClient, string> setContextAction) { string name = null; if (MyInvocation.BoundParameters.ContainsKey(nameof(ContextName))) { name = ContextName; } AzureRmProfile profile = DefaultProfile as AzureRmProfile; if (!CheckForExistingContext(profile, name) || Force.IsPresent || ShouldContinue(string.Format(Resources.ReplaceContextQuery, name), string.Format(Resources.ReplaceContextCaption, name))) { ModifyContext((prof, client) => setContextAction(prof, client, name)); } } /// <summary> /// Load global aliases for ARM /// </summary> public void OnImport() { #if DEBUG try { #endif AzureSessionInitializer.InitializeAzureSession(); #if DEBUG if (!TestMockSupport.RunningMocked) { #endif AzureSession.Instance.DataStore = new DiskDataStore(); #if DEBUG } #endif bool autoSaveEnabled = AzureSession.Instance.ARMContextSaveMode == ContextSaveMode.CurrentUser; var autosaveVariable = System.Environment.GetEnvironmentVariable(AzureProfileConstants.AzureAutosaveVariable); bool localAutosave; if(bool.TryParse(autosaveVariable, out localAutosave)) { autoSaveEnabled = localAutosave; } InitializeProfileProvider(autoSaveEnabled); #if DEBUG } catch (Exception) when (TestMockSupport.RunningMocked) { // This will throw exception for tests, ignore. } #endif } } }
apache-2.0
doheekim/chuizonetest
app/views.py
3133
#-*-coding:utf-8-*- import sys reload(sys) sys.setdefaultencoding('UTF8') from flask import render_template, request, redirect, url_for, Flask, session, jsonify, make_response, request from app import app, db from app.forms import AcademyForm from app.models import Academy from flask.ext.sqlalchemy import SQLAlchemy from sqlalchemy import desc @app.route('/') @app.route('/main') def main(): return render_template('main.html') @app.route('/map') def map(): return render_template('map.html') @app.route('/mapnlist') def mapnlist(): return render_template('mapnlist.html') @app.route('/mapdata') def mapdata(): # mapdata = Academy.query.filter(Academy.location == 'kng').first() location = str(request.args.get('searcher_1')) mapdata = db.session.query(Academy).filter(Academy.academy_latlng == "kng").order_by(desc(Academy.id)) resp = {} resp["data"] = [] temp = {} for academy in mapdata: temp['id'] = academy.id temp['name'] = academy.academy_name temp['latlang'] = academy.academy_latlng resp["data"].append(temp) temp = {} return jsonify(resp) @app.route('/academy') def academy(): return render_template('academy.html') @app.route('/academy/create', methods=['GET', 'POST']) def academy_create(): form=AcademyForm() if request.method == 'GET': return render_template('create.html', form=form) elif request.method == 'POST': if form.validate_on_submit(): academy = Academy( academy_name=form.academy_name.data, teacher_name=form.teacher_name.data, academy_introduce=form.academy_introduce.data, teacher_introduce=form.teacher_introduce.data, curriculum_introduce=form.curriculum_introduce.data, academy_address=form.academy_address.data, welcome_line=form.welcome_line.data, phone_number=form.phone_number.data, class_time=form.class_time.data, class_fee=form.class_fee.data, homepage=form.homepage.data, location=form.location.data, category=form.category.data, academy_latlng=form.academy_latlng.data, image_1=form.image_1.data, image_2=form.image_2.data, image_3=form.image_3.data, image_4=form.image_4.data, image_5=form.image_5.data ) db.session.add(academy) db.session.commit() return render_template('main.html') return render_template('create.html', form=form) return render_template('create.html', form=form) @app.route('/academy/<int:id>', methods=['GET']) def academy_detail(id): academy = Academy.query.get(id) return render_template('academy_test.html', academy=academy) @app.route('/academy_test_2') def academy_test_2(): return render_template('academy_test_2.html') # @app.route('/academy/update/<int:id>', methods=['GET', 'POST']) # def academy_update(): # academy = Academy.query.get(id) # form = AcademyForm(request.form, obj=academy) # if request.method == 'GET': # return render_template('update.html', form=form) # elif request.method == 'POST': # if form.validate_on_submit(): # form.populate_obj(academy) # db.session.commit() # return redirect(url_for('academy_detail', id=id)) # return render_template('update.html', form=form)
apache-2.0
bedatadriven/renjin-statet
org.renjin.core/src-gen/org/renjin/primitives/R$primitive$dim.java
2826
package org.renjin.primitives; import org.renjin.eval.Context; import org.renjin.eval.EvalException; import org.renjin.primitives.annotations.processor.ArgumentException; import org.renjin.primitives.annotations.processor.ArgumentIterator; import org.renjin.sexp.AbstractSEXP; import org.renjin.sexp.BuiltinFunction; import org.renjin.sexp.Environment; import org.renjin.sexp.FunctionCall; import org.renjin.sexp.PairList; import org.renjin.sexp.SEXP; public class R$primitive$dim extends BuiltinFunction { public R$primitive$dim() { super("dim"); } public SEXP apply(Context context, Environment environment, FunctionCall call, PairList args) { try { ArgumentIterator argIt = new ArgumentIterator(context, environment, args); SEXP s0 = argIt.evalNext(); if (((AbstractSEXP) s0).isObject()) { SEXP genericResult = S3 .tryDispatchFromPrimitive(context, environment, call, "dim", s0, args); if (genericResult!= null) { return genericResult; } } if (!argIt.hasNext()) { return this.doApply(context, environment, s0); } throw new EvalException("dim: too many arguments, expected at most 1."); } catch (ArgumentException e) { throw new EvalException(context, "Invalid argument: %s. Expected:\n\tdim(any)", e.getMessage()); } catch (EvalException e) { e.initContext(context); throw e; } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new EvalException(e); } } public static SEXP doApply(Context context, Environment environment, FunctionCall call, String[] argNames, SEXP[] args) { try { if ((args.length) == 1) { return doApply(context, environment, args[ 0 ]); } } catch (EvalException e) { e.initContext(context); throw e; } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new EvalException(e); } throw new EvalException("dim: max arity is 1"); } public SEXP apply(Context context, Environment environment, FunctionCall call, String[] argNames, SEXP[] args) { return R$primitive$dim.doApply(context, environment, call, argNames, args); } public static SEXP doApply(Context context, Environment environment, SEXP arg0) throws Exception { if (arg0 instanceof SEXP) { return Attributes.getDimensions(((SEXP) arg0)); } else { throw new EvalException(String.format("Invalid argument:\n\tdim(%s)\n\tExpected:\n\tdim(any)", arg0 .getTypeName())); } } }
apache-2.0
m-lab/etl
parser/tcpinfo_test.go
11010
package parser_test import ( "archive/tar" "compress/gzip" "context" "encoding/json" "errors" "io" "os" "path/filepath" "strings" "testing" "time" "github.com/go-test/deep" v2 "github.com/m-lab/annotation-service/api/v2" "cloud.google.com/go/bigquery" "cloud.google.com/go/civil" "github.com/m-lab/annotation-service/api" "github.com/m-lab/etl/etl" "github.com/m-lab/etl/parser" "github.com/m-lab/etl/schema" "github.com/m-lab/etl/storage" "github.com/m-lab/etl/task" ) func assertTCPInfoParser(in *parser.TCPInfoParser) { func(p etl.Parser) {}(in) } func fileSource(fn string) (etl.TestSource, error) { if !(strings.HasSuffix(fn, ".tgz") || strings.HasSuffix(fn, ".tar") || strings.HasSuffix(fn, ".tar.gz")) { return nil, errors.New("not tar or tgz: " + fn) } var rdr io.ReadCloser var raw io.ReadCloser raw, err := os.Open(fn) if err != nil { return nil, err } // Handle .tar.gz, .tgz files. if strings.HasSuffix(strings.ToLower(fn), "gz") { rdr, err = gzip.NewReader(raw) if err != nil { raw.Close() return nil, err } } else { rdr = raw } tarReader := tar.NewReader(rdr) timeout := 16 * time.Millisecond return &storage.GCSSource{TarReader: tarReader, Closer: raw, RetryBaseTime: timeout, TableBase: "test", PathDate: civil.Date{Year: 2020, Month: 6, Day: 11}}, nil } var tcpInfoAnno = map[string]*api.Annotations{ // client ip. "35.225.75.192": &api.Annotations{ Geo: &api.GeolocationIP{ ContinentCode: "NA", CountryCode: "US", Latitude: 1.0, Longitude: 2.0, }, Network: &api.ASData{ ASNumber: 1234, Systems: []api.System{ {ASNs: []uint32{1234}}, }, }, }, // server ip. "195.89.146.242": &api.Annotations{ Geo: &api.GeolocationIP{ ContinentCode: "NA", CountryCode: "US", Latitude: 1.0, Longitude: 2.0, }, Network: &api.ASData{ ASNumber: 1234, Systems: []api.System{ {ASNs: []uint32{1234}}, }, }, }, } type inMemorySink struct { data []interface{} committed int failed int token chan struct{} } func newInMemorySink() *inMemorySink { data := make([]interface{}, 0) token := make(chan struct{}, 1) token <- struct{}{} return &inMemorySink{data, 0, 0, token} } // acquire and release handle the single token that protects the FlushSlice and // access to the metrics. func (in *inMemorySink) acquire() { <-in.token } func (in *inMemorySink) release() { in.token <- struct{}{} // return the token. } func (in *inMemorySink) Commit(data []interface{}, label string) (int, error) { in.acquire() defer in.release() in.data = append(in.data, data...) in.committed = len(in.data) return len(data), nil } func (in *inMemorySink) Close() error { return nil } func (in *inMemorySink) Flush() error { in.committed = len(in.data) return nil } func (in *inMemorySink) Committed() int { return in.committed } type nullCloser struct{} func (nc nullCloser) Close() error { return nil } // NOTE: This uses a fake annotator which returns no annotations. // TODO: This test seems to be flakey in travis - sometimes only 357 tests instead of 362 func TestTCPParser(t *testing.T) { parserVersion := parser.InitParserVersionForTest() taskfilename := "testdata/20190516T013026.744845Z-tcpinfo-mlab4-arn02-ndt.tgz" url := "gs://fake-archive/ndt/tcpinfo/2019/05/16/" + filepath.Base(taskfilename) src, err := fileSource(taskfilename) if err != nil { t.Fatal("Failed reading testdata from", taskfilename) } // Inject fake inserter and annotator ins := newInMemorySink() p := parser.NewTCPInfoParser(ins, "test", "_suffix", newFakeAnnotator(tcpInfoAnno)) task := task.NewTask(url, src, p, nullCloser{}) startDecode := time.Now() n, err := task.ProcessAllTests(false) decodeTime := time.Since(startDecode) if err != nil { t.Fatal(err) } // This taskfile has 364 tcpinfo files in it. // tar -tf parser/testdata/20190516T013026.744845Z-tcpinfo-mlab4-arn02-ndt.tgz | wc if n != 364 { t.Errorf("Expected ProcessAllTests to handle %d files, but it handled %d.\n", 364, n) } // Two tests (Cookies 2E1E and 2DEE) and have no snapshots, so there are only 362 rows committed. if ins.Committed() != 362 { t.Errorf("Expected %d, Got %d.", 362, ins.Committed()) } if len(ins.data) < 1 { t.Fatal("Should have at least one inserted row") } // Examine rows in some detail... for i, rawRow := range ins.data { row, ok := rawRow.(*schema.TCPRow) if !ok { t.Fatal("not a TCPRow") } if row.ParseInfo.ParseTime.After(time.Now()) { t.Error("Should have inserted parse_time") } if row.ParseInfo.TaskFileName != url { t.Error("Should have correct taskfilename", taskfilename, "!=", row.ParseInfo.TaskFileName) } if !strings.Contains(row.ParseInfo.Filename, row.UUID) { t.Errorf("Should have non empty filename containing UUID: %s not found in :%s:\n", row.UUID, row.ParseInfo.Filename) } if row.ParseInfo.ParserVersion != parserVersion { t.Error("ParserVersion not properly set", row.ParseInfo.ParserVersion) } // Spot check the SockID.SPort. First 5 rows have SPort = 3010 if i < 5 && row.SockID.SPort != 3010 { t.Error("SPort should be 3010", row.SockID, i) } // Check that source (server) IPs are correct. if row.SockID.SrcIP != "195.89.146.242" && row.SockID.SrcIP != "2001:5012:100:24::242" { t.Error("Wrong SrcIP", row.SockID.SrcIP) } if row.Client == nil { t.Error("Client annotations should not be nil", row.SockID, row.FinalSnapshot) } if row.Server == nil { t.Error("Server annotations should not be nil") } else if row.Server.IATA == "" { t.Error("Server IATA should not be empty") } } // This section is just for understanding how big these objects typically are, and what kind of compression // rates we see. Not fundamental to the test. // Find the row with the largest json representation, and estimate the Marshalling time per snapshot. startMarshal := time.Now() var largestRow *schema.TCPRow var largestJson []byte totalSnaps := int64(0) for _, r := range ins.data { row, _ := r.(*schema.TCPRow) jsonBytes, _ := json.Marshal(r) totalSnaps += int64(len(row.Snapshots)) if len(jsonBytes) > len(largestJson) { largestRow = row largestJson = jsonBytes } } marshalTime := time.Since(startMarshal) duration := largestRow.FinalSnapshot.Timestamp.Sub(largestRow.Snapshots[0].Timestamp) t.Log("Largest json is", len(largestJson), "bytes in", len(largestRow.Snapshots), "snapshots, over", duration, "with", len(largestJson)/len(largestRow.Snapshots), "json bytes/snap") t.Log("Total of", totalSnaps, "snapshots decoded and marshalled") t.Log("Average", decodeTime.Nanoseconds()/totalSnaps, "nsec/snap to decode", marshalTime.Nanoseconds()/totalSnaps, "nsec/snap to marshal") // Log one snapshot for debugging snapJson, _ := json.Marshal(largestRow.FinalSnapshot) t.Log(string(snapJson)) if duration > 20*time.Second { t.Error("Incorrect duration calculation", duration) } if totalSnaps != 1588 { t.Error("expected 1588 (thinned) snapshots, got", totalSnaps) } // Verify the client and server annotations match. cx := v2.ConvertAnnotationsToClientAnnotations(tcpInfoAnno["35.225.75.192"]) if diff := deep.Equal(&largestRow.ClientX, cx); diff != nil { t.Errorf("ClientX annotation does not match; %#v", diff) } sx := v2.ConvertAnnotationsToServerAnnotations(tcpInfoAnno["195.89.146.242"]) sx.Site = "arn02" sx.Machine = "mlab4" if diff := deep.Equal(&largestRow.ServerX, sx); diff != nil { t.Errorf("ServerX annotation does not match; %#v", diff) } } // This is a subset of TestTCPParser, but simpler, so might be useful. func TestTCPTask(t *testing.T) { // Inject fake inserter and annotator ins := newInMemorySink() p := parser.NewTCPInfoParser(ins, "test", "_suffix", newFakeAnnotator(tcpInfoAnno)) filename := "testdata/20190516T013026.744845Z-tcpinfo-mlab4-arn02-ndt.tgz" url := "gs://fake-archive/ndt/tcpinfo/2019/05/16/" + filepath.Base(filename) src, err := fileSource(filename) if err != nil { t.Fatal("Failed reading testdata from", filename) } task := task.NewTask(url, src, p, &nullCloser{}) n, err := task.ProcessAllTests(false) if err != nil { t.Fatal(err) } if n != 364 { t.Errorf("Expected ProcessAllTests to handle %d files, but it handled %d.\n", 364, n) } } func TestBQSaver(t *testing.T) { // Inject fake inserter and annotator ins := newInMemorySink() p := parser.NewTCPInfoParser(ins, "test", "_suffix", newFakeAnnotator(tcpInfoAnno)) filename := "testdata/20190516T013026.744845Z-tcpinfo-mlab4-arn02-ndt.tgz" url := "gs://fake-archive/ndt/tcpinfo/2019/05/16/" + filepath.Base(filename) src, err := fileSource(filename) if err != nil { t.Fatal("Failed reading testdata from", filename) } task := task.NewTask(url, src, p, &nullCloser{}) _, err = task.ProcessAllTests(false) if err != nil { t.Fatal(err) } row, _ := ins.data[0].(*schema.TCPRow) rowMap, _, _ := row.Save() sid, ok := rowMap["SockID"] if !ok { t.Fatal("Should have SockID") } id := sid.(map[string]bigquery.Value) if id["SPort"].(uint16) != 3010 { t.Error(id) } } // This test writes 364 rows to a json file in GCS. // The rows can then be loaded into a BQ table, using the schema in testdata, like: // bq load --source_format=NEWLINE_DELIMITED_JSON \ // mlab-sandbox:gfr.small_tcpinfo gs://archive-mlab-testing/gfr/tcpinfo.json ./schema.json // Recommend commenting out snapshots in tcpinfo.go. func TestTaskToGCS(t *testing.T) { t.Skip("Skipping test intended for manual experimentation") c, err := storage.GetStorageClient(true) if err != nil { t.Fatal(err) } rw, err := storage.NewRowWriter(context.Background(), c, "archive-mlab-testing", "gfr/tcpinfo2.json") if err != nil { t.Fatal(err) } // Inject fake inserter and annotator p := parser.NewTCPInfoParser(rw, "test", "_suffix", newFakeAnnotator(tcpInfoAnno)) filename := "testdata/20190516T013026.744845Z-tcpinfo-mlab4-arn02-ndt.tgz" url := "gs://fake-archive/ndt/tcpinfo/2019/05/16/" + filepath.Base(filename) src, err := fileSource(filename) if err != nil { t.Fatal("Failed reading testdata from", filename) } task := task.NewTask(url, src, p, &nullCloser{}) n, err := task.ProcessAllTests(false) if err != nil { t.Fatal(err) } err = rw.Close() if err != nil { t.Fatal(err) } if n != 364 { t.Errorf("Expected ProcessAllTests to handle %d files, but it handled %d.\n", 364, n) } } func BenchmarkTCPParser(b *testing.B) { // Inject fake inserter and annotator ins := newInMemorySink() p := parser.NewTCPInfoParser(ins, "test", "_suffix", newFakeAnnotator(tcpInfoAnno)) filename := "testdata/20190516T013026.744845Z-tcpinfo-mlab4-arn02-ndt.tgz" n := 0 for i := 0; i < b.N; i += n { src, err := fileSource(filename) if err != nil { b.Fatalf("cannot read testdata.") } task := task.NewTask(filename, src, p, &nullCloser{}) n, err = task.ProcessAllTests(false) if err != nil { b.Fatal(err) } } }
apache-2.0
juttle/juttle-viz
src/lib/generators/axis-label.js
3162
var d3 = require('d3'); var _ = require('underscore'); var defaults = require('../utils/default-options')(); /** * Axis label component that can be used for x or y axis * @param {Object} el - the HTML element * @param {string} options.labelText - the label text * @param {string} options.orientation - supported values 'left', 'right', 'bottom' */ var AxisLabel = function(el, options) { if (typeof options === 'undefined') { options = {}; } // apply defaults options = _.defaults(options, defaults, { orientation : 'left', labelText: '', // true to position the axis-label // when chart uses layout positioning of axis-labels is handled by layout position: true }); this._labelText = options.labelText; this._animDuration = options.duration; this._orientation = options.orientation; this._margin = options.margin; this._width = options.width; this._height = options.height; this._isPositioned = options.position; this._container = d3.select(el); this._g = null; this._text = null; }; AxisLabel.prototype.draw = function() { var cls; if (this._g === null) { switch(this._orientation) { case 'left': cls = 'y left'; break; case 'right': cls = 'y right'; break; case 'bottom': cls = 'x'; break; } this._g = this._container .append('g') .attr('class', 'axis-label ' + cls); this._text = this._g.append('text') .attr('text-anchor', 'middle') .text(this._labelText); } }; AxisLabel.prototype.setLabelText = function(labelText) { this._labelText = labelText; this._updateLabelText(); }; AxisLabel.prototype.setDuration = function(duration) { this._animDuration = duration; }; AxisLabel.prototype.resize = function(boxmodel) { this._width = boxmodel.width; this._height = boxmodel.height; if (boxmodel.margin) { this._margin = boxmodel.margin; } if (this._g !== null && this._isPositioned) { this._position(); } }; AxisLabel.prototype._position = function() { var x, y, rotate; if (this._orientation === 'left') { x = -this._margin.left + 25; // 25 is the distance in px from the outer chart area border y = (this._height-this._margin.bottom-this._margin.top)/2; rotate = -90; } if (this._orientation === 'right') { x = this._width - this._margin.left - 25; y = (this._height-this._margin.top-this._margin.bottom)/2; rotate = 90; } if (this._orientation === 'bottom') { x = (this._width - this._margin.left - this._margin.right)/2; y = this._height - 30; rotate = 0; } this._g .attr('transform','translate(' + x + ',' + y + ')rotate(' + rotate + ')'); }; AxisLabel.prototype._updateLabelText = function() { if (this._text !== null) { this._text .text(this._labelText); } }; module.exports = AxisLabel;
apache-2.0
Spieldichein/ShoprX
Android/ShoprX/src/main/java/de/tum/in/schlichter/shoprx/Explanations/Algorithm/ValueConverter.java
2852
package de.tum.in.schlichter.shoprx.Explanations.Algorithm; import android.content.Context; import java.util.HashMap; import de.tum.in.schlichter.shoprx.R; /** * Created by Nicksteal on 29.03.2015. */ public class ValueConverter { static HashMap<String, Integer> sDescriptorMap; static { sDescriptorMap = Maps.newHashMap(); sDescriptorMap.put("Swim suit", R.string.swim_suit); sDescriptorMap.put("Trunks", R.string.trunks); sDescriptorMap.put("Blouse", R.string.blouse); sDescriptorMap.put("Shirt", R.string.shirt); sDescriptorMap.put("Trousers", R.string.trousers); sDescriptorMap.put("Jeans", R.string.jeans); sDescriptorMap.put("Dress", R.string.dress); sDescriptorMap.put("Poloshirt", R.string.poloshirt); sDescriptorMap.put("Sweater", R.string.sweater); sDescriptorMap.put("Skirt", R.string.skirt); sDescriptorMap.put("Shorts", R.string.shorts); sDescriptorMap.put("Cardigan", R.string.cardigan); // sDescriptorMap.put("Top/T-Shirt", R.string.top_t_shirt); sDescriptorMap.put("Female", R.string.female); sDescriptorMap.put("Male", R.string.male); sDescriptorMap.put("Unisex", R.string.unisex); sDescriptorMap.put("Blue", R.string.blue); sDescriptorMap.put("Red", R.string.red); sDescriptorMap.put("Pink", R.string.pink); // sDescriptorMap.put("Purple", R.string.purple); sDescriptorMap.put("Yellow", R.string.yellow); sDescriptorMap.put("Brown", R.string.brown); sDescriptorMap.put("Colored", R.string.colored); //sDescriptorMap.put("Mixed", R.string.); sDescriptorMap.put("Grey", R.string.grey); sDescriptorMap.put("Green", R.string.green); sDescriptorMap.put("Orange", R.string.orange); sDescriptorMap.put("Black", R.string.black); sDescriptorMap.put("Turquoise", R.string.turquoise); sDescriptorMap.put("White", R.string.white); sDescriptorMap.put("Beige", R.string.beige); sDescriptorMap.put("less than 25 €", R.string.less_than_25); sDescriptorMap.put("25 to 50 €", R.string._25_to_50); sDescriptorMap.put("50 to 75 €", R.string._50_to_75); sDescriptorMap.put("75 to 100 €", R.string._75_to_100); sDescriptorMap.put("100 to 150 €", R.string._100_to_150); sDescriptorMap.put("150 to 200 €", R.string._150_to_200); sDescriptorMap.put("200 € or more", R.string._200_or_more); } public static String getLocalizedStringForValue(Context context, String descriptor) { Integer integer = sDescriptorMap.get(descriptor); if (integer != null) { return context.getString(integer); } else { return descriptor; } } }
apache-2.0
liuxing521a/itas-core
core/src/main/java/org/itas/core/dbpool/PreparedStatementHandle.java
27479
/* Copyright 2009 Wallace Wadge This file is part of BoneCP. BoneCP 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 (at your option) any later version. BoneCP 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 BoneCP. If not, see <http://www.gnu.org/licenses/>. */ package org.itas.core.dbpool; import java.io.InputStream; import java.io.Reader; import java.math.BigDecimal; import java.net.URL; import java.sql.Array; import java.sql.Blob; import java.sql.Clob; import java.sql.Date; import java.sql.ParameterMetaData; import java.sql.PreparedStatement; import java.sql.Ref; import java.sql.ResultSet; import java.sql.ResultSetMetaData; // #ifdef JDK6 import java.sql.NClob; import java.sql.RowId; import java.sql.SQLXML; // #endif JDK6 import java.sql.SQLException; import java.sql.Time; import java.sql.Timestamp; import java.util.Calendar; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Wrapper around JDBC PreparedStatement. * * @author wallacew */ public class PreparedStatementHandle extends StatementHandle implements PreparedStatement { /** Handle to the real prepared statement. */ private PreparedStatement internalPreparedStatement; /** Class logger. */ private static final Logger logger = LoggerFactory.getLogger(PreparedStatementHandle.class); /** * PreparedStatement Wrapper constructor. * * @param internalPreparedStatement * @param sql * sql statement * @param cache * cache handle. * @param connectionHandle * Handle to the connection this is tied to. * @param cacheKey */ public PreparedStatementHandle(PreparedStatement internalPreparedStatement, String sql, ConnectionHandle connectionHandle, String cacheKey, IStatementCache cache) { super(internalPreparedStatement, sql, cache, connectionHandle, cacheKey, connectionHandle.isLogStatementsEnabled()); this.internalPreparedStatement = internalPreparedStatement; this.connectionHandle = connectionHandle; this.sql = sql; this.cache = cache; } /** * {@inheritDoc} * * @see java.sql.PreparedStatement#addBatch() */ // @Override public void addBatch() throws SQLException { checkClosed(); try { if (this.logStatementsEnabled){ this.batchSQL.append(this.sql); } this.internalPreparedStatement.addBatch(); } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } /** * {@inheritDoc} * * @see java.sql.PreparedStatement#clearParameters() */ // @Override public void clearParameters() throws SQLException { checkClosed(); try { this.internalPreparedStatement.clearParameters(); if (this.logStatementsEnabled){ this.logParams.clear(); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } /** * {@inheritDoc} * * @see java.sql.PreparedStatement#execute() */ // @Override public boolean execute() throws SQLException { checkClosed(); try { if (this.logStatementsEnabled){ logger.debug(PoolUtil.fillLogParams(this.sql, this.logParams)); } long queryStartTime = queryTimerStart(); boolean result = this.internalPreparedStatement.execute(); queryTimerEnd(this.sql, queryStartTime); return result; } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } /** * {@inheritDoc} * * @see java.sql.PreparedStatement#executeQuery() */ // @Override public ResultSet executeQuery() throws SQLException { checkClosed(); try { if (this.logStatementsEnabled){ logger.debug(PoolUtil.fillLogParams(this.sql, this.logParams)); } long queryStartTime = queryTimerStart(); ResultSet result = this.internalPreparedStatement.executeQuery(); queryTimerEnd(this.sql, queryStartTime); return result; } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } /** * {@inheritDoc} * * @see java.sql.PreparedStatement#executeUpdate() */ // @Override public int executeUpdate() throws SQLException { checkClosed(); try { if (this.logStatementsEnabled){ logger.debug(PoolUtil.fillLogParams(this.sql, this.logParams)); } long queryStartTime = queryTimerStart(); int result = this.internalPreparedStatement.executeUpdate(); queryTimerEnd(this.sql, queryStartTime); return result; } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } /** * {@inheritDoc} * * @see java.sql.PreparedStatement#getMetaData() */ // @Override public ResultSetMetaData getMetaData() throws SQLException { checkClosed(); try { return this.internalPreparedStatement.getMetaData(); } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } /** * {@inheritDoc} * * @see java.sql.PreparedStatement#getParameterMetaData() */ // @Override public ParameterMetaData getParameterMetaData() throws SQLException { checkClosed(); try { return this.internalPreparedStatement.getParameterMetaData(); } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } /** * {@inheritDoc} * * @see java.sql.PreparedStatement#setArray(int, java.sql.Array) */ // @Override public void setArray(int parameterIndex, Array x) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setArray(parameterIndex, x); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, x); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } // #ifdef JDK6 @Override public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setBinaryStream(parameterIndex, x); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, x); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } @Override public void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setBinaryStream(parameterIndex, x, length); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, x); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } @Override public void setBlob(int parameterIndex, InputStream inputStream) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setBlob(parameterIndex, inputStream); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, inputStream); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } @Override public void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setAsciiStream(parameterIndex, x, length); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, x); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } @Override public void setClob(int parameterIndex, Reader reader) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setClob(parameterIndex, reader); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, reader); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } @Override public void setRowId(int parameterIndex, RowId x) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setRowId(parameterIndex, x); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, x); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } @Override public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setSQLXML(parameterIndex, xmlObject); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, xmlObject); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } @Override public void setClob(int parameterIndex, Reader reader, long length) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setClob(parameterIndex, reader, length); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, reader); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } @Override public void setNCharacterStream(int parameterIndex, Reader value) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setNCharacterStream(parameterIndex, value); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, value); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } @Override public void setNCharacterStream(int parameterIndex, Reader value, long length) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setNCharacterStream(parameterIndex, value, length); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, value); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } @Override public void setNClob(int parameterIndex, NClob value) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setNClob(parameterIndex, value); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, value); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } @Override public void setNClob(int parameterIndex, Reader reader) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setNClob(parameterIndex, reader); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, reader); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } @Override public void setNClob(int parameterIndex, Reader reader, long length) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setNClob(parameterIndex, reader, length); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, reader); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } @Override public void setNString(int parameterIndex, String value) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setNString(parameterIndex, value); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, value); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } @Override public void setAsciiStream(int parameterIndex, InputStream x) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setAsciiStream(parameterIndex, x); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, x); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } @Override public void setCharacterStream(int parameterIndex, Reader reader, long length) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setCharacterStream(parameterIndex, reader, length); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, reader); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } @Override public void setBlob(int parameterIndex, InputStream inputStream, long length) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setBlob(parameterIndex, inputStream, length); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, inputStream); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } @Override public void setCharacterStream(int parameterIndex, Reader reader) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setCharacterStream(parameterIndex, reader); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, reader); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } // #endif JDK6 /** * {@inheritDoc} * * @see java.sql.PreparedStatement#setAsciiStream(int, java.io.InputStream, * int) */ // @Override public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setAsciiStream(parameterIndex, x, length); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, x); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } /** * {@inheritDoc} * * @see java.sql.PreparedStatement#setBigDecimal(int, java.math.BigDecimal) */ // @Override public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setBigDecimal(parameterIndex, x); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, x); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } /** * {@inheritDoc} * * @see java.sql.PreparedStatement#setBinaryStream(int, java.io.InputStream, * int) */ // @Override public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setBinaryStream(parameterIndex, x, length); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, x); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } /** * {@inheritDoc} * * @see java.sql.PreparedStatement#setBlob(int, java.sql.Blob) */ // @Override public void setBlob(int parameterIndex, Blob x) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setBlob(parameterIndex, x); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, x); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } /** * {@inheritDoc} * * @see java.sql.PreparedStatement#setBoolean(int, boolean) */ // @Override public void setBoolean(int parameterIndex, boolean x) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setBoolean(parameterIndex, x); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, x); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } /** * {@inheritDoc} * * @see java.sql.PreparedStatement#setByte(int, byte) */ // @Override public void setByte(int parameterIndex, byte x) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setByte(parameterIndex, x); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, x); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } /** * {@inheritDoc} * * @see java.sql.PreparedStatement#setBytes(int, byte[]) */ // @Override public void setBytes(int parameterIndex, byte[] x) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setBytes(parameterIndex, x); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, x); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } /** * {@inheritDoc} * * @see java.sql.PreparedStatement#setCharacterStream(int, java.io.Reader, * int) */ // @Override public void setCharacterStream(int parameterIndex, Reader reader, int length) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setCharacterStream(parameterIndex, reader, length); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, reader); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } /** * {@inheritDoc} * * @see java.sql.PreparedStatement#setClob(int, java.sql.Clob) */ // @Override public void setClob(int parameterIndex, Clob x) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setClob(parameterIndex, x); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, x); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } /** * {@inheritDoc} * * @see java.sql.PreparedStatement#setDate(int, java.sql.Date) */ // @Override public void setDate(int parameterIndex, Date x) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setDate(parameterIndex, x); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, x); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } /** * {@inheritDoc} * * @see java.sql.PreparedStatement#setDate(int, java.sql.Date, * java.util.Calendar) */ // @Override public void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setDate(parameterIndex, x, cal); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, PoolUtil.safePrint(x, ", cal=", cal)); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } /** * {@inheritDoc} * * @see java.sql.PreparedStatement#setDouble(int, double) */ // @Override public void setDouble(int parameterIndex, double x) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setDouble(parameterIndex, x); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, x); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } /** * {@inheritDoc} * * @see java.sql.PreparedStatement#setFloat(int, float) */ // @Override public void setFloat(int parameterIndex, float x) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setFloat(parameterIndex, x); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, x); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } /** * {@inheritDoc} * * @see java.sql.PreparedStatement#setInt(int, int) */ // @Override public void setInt(int parameterIndex, int x) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setInt(parameterIndex, x); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, x); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } /** * {@inheritDoc} * * @see java.sql.PreparedStatement#setLong(int, long) */ // @Override public void setLong(int parameterIndex, long x) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setLong(parameterIndex, x); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, x); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } /** * {@inheritDoc} * * @see java.sql.PreparedStatement#setNull(int, int) */ // @Override public void setNull(int parameterIndex, int sqlType) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setNull(parameterIndex, sqlType); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, "[SQL NULL of type "+sqlType+"]"); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } /** * {@inheritDoc} * * @see java.sql.PreparedStatement#setNull(int, int, java.lang.String) */ // @Override public void setNull(int parameterIndex, int sqlType, String typeName) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setNull(parameterIndex, sqlType, typeName); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, PoolUtil.safePrint("[SQL NULL of type ", sqlType, ", type = ", typeName, "]")); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } /** * {@inheritDoc} * * @see java.sql.PreparedStatement#setObject(int, java.lang.Object) */ // @Override public void setObject(int parameterIndex, Object x) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setObject(parameterIndex, x); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, x); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } /** * {@inheritDoc} * * @see java.sql.PreparedStatement#setObject(int, java.lang.Object, int) */ // @Override public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setObject(parameterIndex, x, targetSqlType); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, x); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } /** * {@inheritDoc} * * @see java.sql.PreparedStatement#setObject(int, java.lang.Object, int, * int) */ // @Override public void setObject(int parameterIndex, Object x, int targetSqlType, int scaleOrLength) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setObject(parameterIndex, x, targetSqlType, scaleOrLength); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, x); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } /** * {@inheritDoc} * * @see java.sql.PreparedStatement#setRef(int, java.sql.Ref) */ // @Override public void setRef(int parameterIndex, Ref x) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setRef(parameterIndex, x); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, x); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } /** * {@inheritDoc} * * @see java.sql.PreparedStatement#setShort(int, short) */ // @Override public void setShort(int parameterIndex, short x) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setShort(parameterIndex, x); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, x); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } /** * {@inheritDoc} * * @see java.sql.PreparedStatement#setString(int, java.lang.String) */ // @Override public void setString(int parameterIndex, String x) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setString(parameterIndex, x); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, x); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } /** * {@inheritDoc} * * @see java.sql.PreparedStatement#setTime(int, java.sql.Time) */ // @Override public void setTime(int parameterIndex, Time x) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setTime(parameterIndex, x); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, x); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } /** * {@inheritDoc} * * @see java.sql.PreparedStatement#setTime(int, java.sql.Time, * java.util.Calendar) */ // @Override public void setTime(int parameterIndex, Time x, Calendar cal) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setTime(parameterIndex, x, cal); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, PoolUtil.safePrint(x, ", cal=", cal)); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } /** * {@inheritDoc} * * @see java.sql.PreparedStatement#setTimestamp(int, java.sql.Timestamp) */ // @Override public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setTimestamp(parameterIndex, x); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, x); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } /** * {@inheritDoc} * * @see java.sql.PreparedStatement#setTimestamp(int, java.sql.Timestamp, * java.util.Calendar) */ // @Override public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setTimestamp(parameterIndex, x, cal); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, PoolUtil.safePrint(x, ", cal=", cal)); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } /** * {@inheritDoc} * * @see java.sql.PreparedStatement#setURL(int, java.net.URL) */ // @Override public void setURL(int parameterIndex, URL x) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setURL(parameterIndex, x); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, x); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } /** * {@inheritDoc} * * @see java.sql.PreparedStatement#setUnicodeStream(int, * java.io.InputStream, int) */ // @Override @Deprecated public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException { checkClosed(); try { this.internalPreparedStatement.setUnicodeStream(parameterIndex, x, length); if (this.logStatementsEnabled){ this.logParams.put(parameterIndex, x); } } catch (Throwable t) { throw this.connectionHandle.markPossiblyBroken(t); } } /** Returns the wrapped internal statement. * @return the internalPreparedStatement that this wrapper is using. */ public PreparedStatement getInternalPreparedStatement() { return this.internalPreparedStatement; } /** Sets the internal statement that this wrapper wraps. * @param internalPreparedStatement the internalPreparedStatement to set */ public void setInternalPreparedStatement(PreparedStatement internalPreparedStatement) { this.internalPreparedStatement = internalPreparedStatement; } /** {@inheritDoc} * @see java.lang.Object#finalize() * // @Override protected void finalize() throws Throwable { super.finalize(); if (!isClosed()){ close(); logger.warn("BoneCP detected an unclosed statement and has closed it for you. You should be closing this statement in your application - enable connectionWatch config setting for additional debugging assistance."); } } */ }
apache-2.0
dresl/python_web
gettingstarted/views.py
13531
from django.shortcuts import get_object_or_404, render, render_to_response from django.http import HttpResponseRedirect, HttpResponse from django.core.urlresolvers import reverse from django.template import * from django.views import generic from django.utils import timezone from polls.models import Choice, Question, Greeting, Sidebar from books.models import Publisher, Author, Book from django import forms from django.contrib import auth from django.core.context_processors import csrf from django.contrib.auth.forms import UserCreationForm import datetime from django.core.mail import send_mail,BadHeaderError from forms import ContactForm from django.conf import settings from django.contrib.auth.models import User def contact_thanks(request): args = {} if request.user.is_authenticated(): args['username'] = request.user.username args['sidebar'] = Sidebar.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date') args['full_name'] = request.user.first_name + ' ' + request.user.last_name return render(request, 'apps/contact_thanks.html', args) else: args['sidebar'] = Sidebar.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date') return render(request, 'apps/contact_thanks.html', args) def send_email(request): subject = request.POST.get('subject', '') message = request.POST.get('message', '') from_email = request.POST.get('from_email', '') if request.user.is_authenticated(): if subject and message and from_email: try: send_mail(subject, message, from_email, ['resldominik@gymnachod.cz']) except BadHeaderError: return HttpResponse('Invalid header found.') return HttpResponseRedirect('/contact/thanks/') else: # In reality we'd use a form class # to get proper validation errors. return render(request,'apps/new_contact_form.html',{'username': request.user.username, 'full_name': request.user.first_name + ' ' + request.user.last_name}) else: if subject and message and from_email: try: send_mail(subject, message, from_email, ['resldominik@gymnachod.cz']) except BadHeaderError: return HttpResponse('Invalid header found.') return HttpResponseRedirect('/contact/thanks/') else: # In reality we'd use a form class # to get proper validation errors. return render(request,'apps/new_contact_form.html',) def contact(request): if request.user.is_authenticated(): if request.method == 'POST': if not request.POST.get('subject', '') and not request.POST.get('message', '') or request.POST.get('email') and '@' not in request.POST['email']: subject_error = 'Enter a subject.' message_error = 'Enter a message.' email_error = 'Enter a valid e-mail address.' return render(request, 'apps/contact_form.html', {'subject_error': subject_error, 'message_error': message_error, 'email_error': email_error, 'username': request.user.username, 'full_name': request.user.first_name + ' ' + request.user.last_name, 'sidebar': Sidebar.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')}) if not request.POST.get('subject', ''): subject_error = 'Enter a subject.' return render(request, 'apps/contact_form.html', {'subject_error': subject_error,'username': request.user.username, 'full_name': request.user.first_name + ' ' + request.user.last_name, 'sidebar': Sidebar.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')}) if not request.POST.get('message', ''): message_error = 'Enter a message.' return render(request, 'apps/contact_form.html', {'message_error': message_error,'username': request.user.username, 'full_name': request.user.first_name + ' ' + request.user.last_name, 'sidebar': Sidebar.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')}) if request.POST.get('email') and '@' not in request.POST['email']: email_error = 'Enter a valid e-mail address.' return render(request, 'apps/contact_form.html', {'email_error': email_error,'username': request.user.username, 'full_name': request.user.first_name + ' ' + request.user.last_name, 'sidebar': Sidebar.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')}) else: send_mail( request.POST['subject'], request.POST['message'], request.POST.get('email', ''), ['resldominik@gymnachod.cz'], fail_silently=False ) return HttpResponseRedirect('/contact/thanks/') return render(request,'apps/contact_form.html', { 'subject': request.POST.get('subject', ''), 'message': request.POST.get('message', ''), 'email': request.POST.get('email', ''), 'username': request.user.username, 'sidebar': Sidebar.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date'), 'full_name': request.user.first_name + ' ' + request.user.last_name }) else: if request.method == 'POST': if not request.POST.get('subject', '') and not request.POST.get('message', '') or request.POST.get('email') and '@' not in request.POST['email']: subject_error = 'Enter a subject.' message_error = 'Enter a message.' email_error = 'Enter a valid e-mail address.' return render(request, 'apps/contact_form.html', {'subject_error': subject_error, 'message_error': message_error, 'email_error': email_error, 'sidebar': Sidebar.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')}) if not request.POST.get('subject', ''): subject_error = 'Enter a subject.' return render(request, 'apps/contact_form.html', {'subject_error': subject_error, 'sidebar': Sidebar.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')}) if not request.POST.get('message', ''): message_error = 'Enter a message.' return render(request, 'apps/contact_form.html', {'message_error': message_error, 'sidebar': Sidebar.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')}) if request.POST.get('email') and '@' not in request.POST['email']: email_error = 'Enter a valid e-mail address.' return render(request, 'apps/contact_form.html', {'email_error': email_error, 'sidebar': Sidebar.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')}) else: send_mail( request.POST['subject'], request.POST['message'], request.POST.get('email', ''), ['resldominik@gymnachod.cz'], fail_silently=False ) return HttpResponseRedirect('/contact/thanks/') return render(request,'apps/contact_form.html', { 'subject': request.POST.get('subject', ''), 'message': request.POST.get('message', ''), 'email': request.POST.get('email', ''), 'sidebar': Sidebar.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date') }) def home(request): now = datetime.datetime.now() path = request.path your_browser = request.META.get('HTTP_USER_AGENT', 'unknown') if request.user.is_authenticated(): return render(request, 'apps/current.html', {'current_date': now, 'path': path, 'your_browser': your_browser, 'username': request.user.username, 'sidebar': Sidebar.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date'), 'full_name': request.user.first_name + ' ' + request.user.last_name}) else: return render(request, 'apps/current.html', {'current_date': now, 'path': path, 'your_browser': your_browser, 'sidebar': Sidebar.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')}) def search_form(request): args = {} if request.user.is_authenticated(): args['username'] = request.user.username args['sidebar'] = Sidebar.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date') args['full_name'] = request.user.first_name + ' ' + request.user.last_name return render(request, 'apps/search_form.html', args) else: args['sidebar'] = Sidebar.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date') return render(request, 'apps/search_form.html', args) def search(request): errors = [] if request.user.is_authenticated(): if 'q' in request.GET: q = request.GET['q'] if not q: errors.append('Enter a search term.') elif len(q) > 20: errors.append('Please enter at most 20 characters.') else: books = Book.objects.filter(title__icontains=q) return render(request, 'apps/search_results.html', {'books': books, 'query': q, 'username': request.user.username, 'full_name': request.user.first_name + ' ' + request.user.last_name, 'sidebar': Sidebar.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:50]}) return render(request, 'apps/search_form.html', {'errors': errors, 'username': request.user.username, 'sidebar': Sidebar.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date'), 'full_name': request.user.first_name + ' ' + request.user.last_name}) else: if 'q' in request.GET: q = request.GET['q'] args = {} if not q: errors.append('Enter a search term.') elif len(q) > 20: errors.append('Please enter at most 20 characters.') else: args['books'] = Book.objects.filter(title__icontains=q) args['query'] = q args['sidebar'] = Sidebar.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date') return render(request, 'apps/search_results.html', args) return render(request, 'apps/search_form.html', {'errors': errors, 'username': request.user.username, 'sidebar': Sidebar.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')}) def hours_ahead(request, offset): try: offset = int(offset) except ValueError: raise Http404() futuretime = datetime.datetime.now() + datetime.timedelta(hours=offset) path = request.path if request.user.is_authenticated(): return render(request, 'apps/future.html', {'next_time': futuretime, 'hour_offset': offset, 'path': path, 'username': request.user.username, 'sidebar': Sidebar.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date'), 'full_name': request.user.first_name + ' ' + request.user.last_name}) else: return render(request, 'apps/future.html', {'next_time': futuretime, 'hour_offset': offset, 'path': path, 'sidebar': Sidebar.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')})
apache-2.0
Tangyingqi/Jiemian
app/src/androidTest/java/com/tyq/jiemian/ApplicationTest.java
346
package com.tyq.jiemian; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
apache-2.0
jamesdbloom/mockserver
mockserver-examples/src/main/java/org/mockserver/examples/mockserver/MockServerClientExamples.java
4972
package org.mockserver.examples.mockserver; import org.mockserver.client.MockServerClient; import org.mockserver.integration.ClientAndServer; import org.mockserver.model.ClearType; import org.mockserver.model.HttpRequest; import org.mockserver.model.HttpRequestAndHttpResponse; import org.mockserver.verify.VerificationTimes; import java.util.List; import static org.mockserver.model.Cookie.cookie; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.response; import static org.mockserver.model.Parameter.param; public class MockServerClientExamples { public void createExpectationMockServerClient() { new MockServerClient("localhost", 1080) .when( request() .withMethod("GET") .withPath("/view/cart") .withCookies( cookie("session", "4930456C-C718-476F-971F-CB8E047AB349") ) .withQueryStringParameters( param("cartId", "055CA455-1DF7-45BB-8535-4F83E7266092") ) ) .respond( response() .withBody("some_response_body") ); } public void createExpectationOverTLSMockServerClient() { new MockServerClient("localhost", 1080) .withSecure(true) .when( request() .withMethod("GET") .withPath("/view/cart") .withCookies( cookie("session", "4930456C-C718-476F-971F-CB8E047AB349") ) .withQueryStringParameters( param("cartId", "055CA455-1DF7-45BB-8535-4F83E7266092") ) ) .respond( response() .withBody("some_response_body") ); } public void createExpectationClientAndServer() { new ClientAndServer(1080) .when( request() .withMethod("GET") .withPath("/view/cart") .withCookies( cookie("session", "4930456C-C718-476F-971F-CB8E047AB349") ) .withQueryStringParameters( param("cartId", "055CA455-1DF7-45BB-8535-4F83E7266092") ) ) .respond( response() .withBody("some_response_body") ); } public void verifyRequests() { new MockServerClient("localhost", 1080) .verify( request() .withPath("/some/path"), VerificationTimes.atLeast(2) ); } public void verifyRequestSequence() { new MockServerClient("localhost", 1080) .verify( request() .withPath("/some/path/one"), request() .withPath("/some/path/two"), request() .withPath("/some/path/three") ); } public void retrieveRecordedRequests() { HttpRequest[] recordedRequests = new MockServerClient("localhost", 1080) .retrieveRecordedRequests( request() .withPath("/some/path") .withMethod("POST") ); } public void retrieveRecordedRequestResponses() { HttpRequestAndHttpResponse[] httpRequestAndHttpResponse = new MockServerClient("localhost", 1080) .retrieveRecordedRequestsAndResponses( request() .withPath("/some/path") .withMethod("POST") ); } public void retrieveRecordedLogMessages() { String[] logMessages = new MockServerClient("localhost", 1080) .retrieveLogMessagesArray( request() .withPath("/some/path") .withMethod("POST") ); } public void clear() { new MockServerClient("localhost", 1080).clear( request() .withPath("/some/path") .withMethod("POST") ); } public void clearLogs() { new MockServerClient("localhost", 1080).clear( request() .withPath("/some/path") .withMethod("POST"), ClearType.LOG ); } public void reset() { new MockServerClient("localhost", 1080).reset(); } public void bindToAdditionFreePort() { List<Integer> boundPorts = new MockServerClient("localhost", 1080).bind( 0 ); } public void bindToAdditionalSpecifiedPort() { List<Integer> boundPorts = new MockServerClient("localhost", 1080).bind( 1081, 1082 ); } }
apache-2.0
gmanev/queue-actions
queueactions-subscriber-jms/src/main/java/com/jjinterna/queueactions/subscriber/jms/impl/HttpActionRoute.java
3073
package com.jjinterna.queueactions.subscriber.jms.impl; import java.util.Collection; import java.util.Dictionary; import org.apache.camel.Exchange; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.model.dataformat.JaxbDataFormat; import com.jjinterna.queueactions.model.QueueActionsEvent; public class HttpActionRoute extends RouteBuilder { private String routeId; private String endpoint; private Collection<String> eventSelector; private String queueSelector; private String endpointProtocol; public HttpActionRoute(String routeId, Dictionary properties) { this.routeId = routeId; this.endpoint = (String) properties.get("EndpointURI"); this.eventSelector = (Collection<String>) properties.get("EventSelector"); this.queueSelector = (String) properties.get("QueueSelector"); this.endpointProtocol = (String) properties.get("EndpointProtocol"); if (endpointProtocol == null) { endpointProtocol = "GET"; } } public String getRouteId() { return HttpActionRoute.class.getSimpleName() + "-" + routeId; } @Override public void configure() throws Exception { JaxbDataFormat jaxb = new JaxbDataFormat(); jaxb.setContextPath(QueueActionsEvent.class.getPackage().getName()); fromF("activemq:topic:QueueActions?username={{jmsUsername}}&password={{jmsPassword}}%s", getSelectorString()).id(getRouteId()) .choice() .when(constant(endpointProtocol).isEqualTo("HTTP GET")) .process(new QueueEvent2HttpQuery()) .setProperty("Endpoint", constant("http4://uri")) .setHeader(Exchange.HTTP_URI, constant(endpoint)) .setHeader(Exchange.HTTP_METHOD, constant("GET")) .setBody(constant("")) .endChoice() .when(constant(endpointProtocol).isEqualTo("HTTP POST")) .process(new JAXBElementWrap()) .marshal(jaxb) .setProperty("Endpoint", constant("http4://uri")) .setHeader(Exchange.HTTP_URI, constant(endpoint)) .setHeader(Exchange.HTTP_METHOD, constant("POST")) .setHeader(Exchange.CONTENT_TYPE, constant("application/xml")) .endChoice() .when(constant(endpointProtocol).isEqualTo("SOAP")) .setProperty("Endpoint", constant("cxf://" + endpoint + "?serviceClass=com.jjinterna.queueactions.service.QueueActionsService&loggingFeatureEnabled=false")) .setHeader("SOAPAction", constant("updateEvent")) .endChoice() .end() .removeHeaders("JMS*") .removeHeaders("QActions*") .recipientList(simple("${property.Endpoint}")); } private String getSelectorString() { String selector = null; if (eventSelector != null) { for (String ev : eventSelector) { if (selector == null) { selector = ""; } else { selector += ","; } selector += "'" + ev + "'"; } selector = "QActionsEvent IN(" + selector + ")"; } if (queueSelector != null && queueSelector.length() > 0) { if (selector == null) { selector = ""; } else { selector += " AND "; } selector += "QActionsQueue='" + queueSelector + "'"; } if (selector == null) return ""; return "&selector=" + selector; } }
apache-2.0
ederign/kie-wb-common
kie-wb-common-stunner/kie-wb-common-stunner-extensions/kie-wb-common-stunner-lienzo-extensions/src/main/java/org/kie/workbench/common/stunner/lienzo/toolbox/items/impl/ItemGridImpl.java
8513
/* * Copyright 2017 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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.kie.workbench.common.stunner.lienzo.toolbox.items.impl; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.function.BiConsumer; import java.util.function.Supplier; import com.ait.lienzo.client.core.shape.Group; import com.ait.lienzo.client.core.types.BoundingBox; import com.ait.lienzo.client.core.types.Point2D; import org.kie.workbench.common.stunner.lienzo.toolbox.ItemGrid; import org.kie.workbench.common.stunner.lienzo.toolbox.grid.Point2DGrid; import org.kie.workbench.common.stunner.lienzo.toolbox.items.AbstractDecoratedItem; import org.kie.workbench.common.stunner.lienzo.toolbox.items.AbstractPrimitiveItem; import org.kie.workbench.common.stunner.lienzo.toolbox.items.DecoratedItem; import org.uberfire.mvp.Command; public class ItemGridImpl extends WrappedItem<ItemGridImpl> implements ItemGrid<ItemGridImpl, Point2DGrid, DecoratedItem> { private final AbstractGroupItem groupPrimitiveItem; private final List<AbstractDecoratedItem> items = new LinkedList<>(); private Point2DGrid grid; private Command refreshCallback; private BoundingBox boundingBox; private Supplier<BoundingBox> boundingBoxSupplier = new Supplier<BoundingBox>() { @Override public BoundingBox get() { return boundingBox; } }; public ItemGridImpl() { this(new GroupImpl(new Group())); } ItemGridImpl(final AbstractGroupItem groupPrimitiveItem) { this.groupPrimitiveItem = groupPrimitiveItem .setBoundingBox(boundingBoxSupplier); this.boundingBox = new BoundingBox(0, 0, 1, 1); this.refreshCallback = () -> { if (null != groupPrimitiveItem.asPrimitive().getLayer()) { groupPrimitiveItem.asPrimitive().getLayer().batch(); } }; } @Override public ItemGridImpl grid(final Point2DGrid grid) { this.grid = grid; return checkReposition(); } @Override public ItemGridImpl add(final DecoratedItem... items) { for (final DecoratedItem item : items) { try { addItem((AbstractDecoratedItem) item); } catch (final ClassCastException e) { throw new UnsupportedOperationException("This item only supports subtypes " + "of " + AbstractDecoratedItem.class.getName()); } } return itemsUpdated(); } @Override public Iterator<DecoratedItem> iterator() { return new ListItemsIterator<AbstractDecoratedItem>(items) { @Override protected void remove(final AbstractDecoratedItem item) { items.remove(item); itemsUpdated(); } }; } @Override public ItemGridImpl show(final Command before, final Command after) { return super.show(() -> { repositionItems(); for (final DecoratedItem button : items) { button.show(); } before.execute(); }, after); } @Override public ItemGridImpl hide(final Command before, final Command after) { return super.hide(before, () -> { for (final DecoratedItem button : items) { button.hide(); } after.execute(); fireRefresh(); }); } public ItemGridImpl onRefresh(final Command refreshCallback) { this.refreshCallback = refreshCallback; return this; } public ItemGridImpl refresh() { return checkReposition(); } public int size() { return items.size(); } public ItemGridImpl useShowExecutor(final BiConsumer<Group, Command> executor) { this.getWrapped().useShowExecutor(executor); return this; } public ItemGridImpl useHideExecutor(final BiConsumer<Group, Command> executor) { this.getWrapped().useHideExecutor(executor); return this; } @Override public void destroy() { getWrapped().destroy(); items.clear(); refreshCallback = null; boundingBoxSupplier = null; boundingBox = null; } public Point2DGrid getGrid() { return grid; } void addItem(final AbstractDecoratedItem button) { this.items.add(button); if (isVisible()) { button.show(); } else { button.hide(); } getWrapped().getGroupItem().add(button.asPrimitive()); } private ItemGridImpl itemsUpdated() { // Reposition items as for the given grid. repositionItems(); // Calculate BB. double maxw = 0; double maxh = 0; for (final AbstractDecoratedItem item : items) { final Point2D location = item.asPrimitive().getLocation(); final BoundingBox itemBB = (BoundingBox) item.getBoundingBox().get(); final double itemw = itemBB.getWidth() + location.getX(); final double itemh = itemBB.getHeight() + location.getY(); if (itemw > maxw) { maxw = itemw; } if (itemh > maxh) { maxh = itemh; } } boundingBox = new BoundingBox(0, 0, maxw, maxh); // Update decorator. if (null != getWrapped().getDecorator()) { getWrapped().getDecorator().setBoundingBox(getBoundingBox().get()); if (getWrapped().getDecorator() instanceof AbstractPrimitiveItem) { ((AbstractPrimitiveItem) getWrapped().getDecorator()).asPrimitive().moveToBottom(); } } return this; } @Override public Supplier<BoundingBox> getBoundingBox() { return boundingBoxSupplier; } private ItemGridImpl checkReposition() { if (isVisible()) { return repositionItems(); } return this; } private ItemGridImpl repositionItems() { final Iterator<Point2D> gridIterator = grid.iterator(); for (final AbstractDecoratedItem button : items) { final Point2D point = gridIterator.next(); button.asPrimitive().setLocation(point); } fireRefresh(); return this; } private void fireRefresh() { if (null != refreshCallback) { refreshCallback.execute(); } } @Override protected AbstractGroupItem<?> getWrapped() { return groupPrimitiveItem; } private abstract static class ListItemsIterator<I extends AbstractDecoratedItem> implements Iterator<DecoratedItem> { private final List<I> items; private int index; private ListItemsIterator(final List<I> items) { this.items = new LinkedList<>(items); this.index = 0; } protected abstract void remove(I item); @Override public boolean hasNext() { return index < items.size(); } @Override public I next() { return items.get(index++ - 1); } @Override public void remove() { I item = items.get(index); remove(item); } } }
apache-2.0
VahidN/DNTIdentity
src/ASPNETCoreIdentitySample/Areas/Identity/Controllers/UserCardController.cs
2299
using ASPNETCoreIdentitySample.Services.Contracts.Identity; using ASPNETCoreIdentitySample.Services.Identity; using ASPNETCoreIdentitySample.ViewModels.Identity; using DNTBreadCrumb.Core; using DNTCommon.Web.Core; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace ASPNETCoreIdentitySample.Areas.Identity.Controllers; [AllowAnonymous, Area(AreaConstants.IdentityArea), BreadCrumb(Title = "برگه‌ی کاربری", UseDefaultRouteUrl = true, Order = 0)] public class UserCardController : Controller { private readonly IApplicationRoleManager _roleManager; private readonly IApplicationUserManager _userManager; public UserCardController( IApplicationUserManager userManager, IApplicationRoleManager roleManager) { _userManager = userManager ?? throw new ArgumentNullException(nameof(userManager)); _roleManager = roleManager ?? throw new ArgumentNullException(nameof(roleManager)); } [BreadCrumb(Title = "ایندکس", Order = 1)] public async Task<IActionResult> Index(int? id) { if (!id.HasValue && User.Identity is { IsAuthenticated: true }) { id = User.Identity.GetUserId<int>(); } if (!id.HasValue) { return View("Error"); } var user = await _userManager.FindByIdIncludeUserRolesAsync(id.Value); if (user == null) { return View("NotFound"); } var model = new UserCardItemViewModel { User = user, ShowAdminParts = User.IsInRole(ConstantRoles.Admin), Roles = await _roleManager.GetAllCustomRolesAsync(), ActiveTab = UserCardItemActiveTab.UserInfo }; return View(model); } [ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)] public async Task<IActionResult> EmailToImage(int? id) { if (!id.HasValue) { return NotFound(); } var fileContents = await _userManager.GetEmailImageAsync(id); return new FileContentResult(fileContents, "image/png"); } [BreadCrumb(Title = "لیست کاربران آنلاین", Order = 1)] public IActionResult OnlineUsers() { return View(); } }
apache-2.0
opencirclesolutions/dynamo
dynamo-api/src/main/java/com/ocs/dynamo/exception/OCSRuntimeException.java
1154
/* 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.ocs.dynamo.exception; /** * Base class for any runtime exceptions. Must always be used instead of a plain * java.lang.RuntimeException. Subclass when appropriate * * @author bas.rutten */ public class OCSRuntimeException extends RuntimeException { private static final long serialVersionUID = -6263372299801009820L; public OCSRuntimeException() { // default constructor } public OCSRuntimeException(String message) { super(message); } public OCSRuntimeException(String message, Throwable cause) { super(message, cause); } }
apache-2.0
ronniemara/android-UniversalMusicPlayer
mobile/src/main/java/net/africahomepage/mp3africa/ui/tv/TvVerticalGridActivity.java
3952
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.africahomepage.mp3africa.ui.tv; import android.content.ComponentName; import android.os.Bundle; import android.os.RemoteException; import android.support.v4.app.FragmentActivity; import android.support.v4.media.MediaBrowserCompat; import android.support.v4.media.session.MediaControllerCompat; import net.africahomepage.mp3africa.MusicService; import net.africahomepage.mp3africa.R; import net.africahomepage.mp3africa.utils.LogHelper; public class TvVerticalGridActivity extends FragmentActivity implements TvVerticalGridFragment.MediaFragmentListener { private static final String TAG = LogHelper.makeLogTag(TvVerticalGridActivity.class); public static final String SHARED_ELEMENT_NAME = "hero"; private MediaBrowserCompat mMediaBrowser; private String mMediaId; private String mTitle; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.tv_vertical_grid); mMediaId = getIntent().getStringExtra(TvBrowseActivity.SAVED_MEDIA_ID); mTitle = getIntent().getStringExtra(TvBrowseActivity.BROWSE_TITLE); getWindow().setBackgroundDrawableResource(R.drawable.bg); mMediaBrowser = new MediaBrowserCompat(this, new ComponentName(this, MusicService.class), mConnectionCallback, null); } @Override protected void onStart() { super.onStart(); LogHelper.d(TAG, "Activity onStart: mMediaBrowser connect"); mMediaBrowser.connect(); } @Override protected void onStop() { super.onStop(); mMediaBrowser.disconnect(); } protected void browse() { LogHelper.d(TAG, "navigateToBrowser, mediaId=" + mMediaId); TvVerticalGridFragment fragment = (TvVerticalGridFragment) getSupportFragmentManager() .findFragmentById(R.id.vertical_grid_fragment); fragment.setMediaId(mMediaId); fragment.setTitle(mTitle); } @Override public MediaBrowserCompat getMediaBrowser() { return mMediaBrowser; } private final MediaBrowserCompat.ConnectionCallback mConnectionCallback = new MediaBrowserCompat.ConnectionCallback() { @Override public void onConnected() { LogHelper.d(TAG, "onConnected: session token ", mMediaBrowser.getSessionToken()); try { MediaControllerCompat mediaController = new MediaControllerCompat( TvVerticalGridActivity.this, mMediaBrowser.getSessionToken()); setSupportMediaController(mediaController); browse(); } catch (RemoteException e) { LogHelper.e(TAG, e, "could not connect media controller"); } } @Override public void onConnectionFailed() { LogHelper.d(TAG, "onConnectionFailed"); } @Override public void onConnectionSuspended() { LogHelper.d(TAG, "onConnectionSuspended"); setSupportMediaController(null); } }; }
apache-2.0
thankpoint/thanks4java
security/src/main/java/io/github/thankpoint/security/impl/sign/SecuritySignatureGeneratorImplWithHash.java
1671
package io.github.thankpoint.security.impl.sign; import io.github.thankpoint.security.api.algorithm.SecurityAlgorithm; import io.github.thankpoint.security.api.hash.SecurityHashCreator; import io.github.thankpoint.security.api.sign.SecuritySignatureCreator; import io.github.thankpoint.security.api.sign.SecuritySignatureSigner; import io.github.thankpoint.security.impl.AbstractSecurityAlgorithm; /** * Implementation of {@link SecuritySignatureCreator} combining a {@link SecuritySignatureSigner} with a * {@link SecurityHashCreator}. * * @author thks */ public abstract class SecuritySignatureGeneratorImplWithHash extends AbstractSecurityAlgorithm implements SecuritySignatureCreator { private final SecurityHashCreator hashGenerator; /** * The constructor. * * @param hashGenerator the {@link SecurityHashCreator} to apply as extension. */ public SecuritySignatureGeneratorImplWithHash(SecurityHashCreator hashGenerator) { super(); this.hashGenerator = hashGenerator; } /** * @return the {@link SecurityAlgorithm} to extend. */ protected abstract SecurityAlgorithm getSignatureAlgorithm(); /** * @return the {@link SecurityHashCreator} to apply as extension. */ protected SecurityHashCreator getHashGenerator() { return this.hashGenerator; } @Override public String getAlgorithm() { return this.hashGenerator.getAlgorithm() + "+" + getSignatureAlgorithm().getAlgorithm(); } @Override public void update(byte[] input, int offset, int length) { this.hashGenerator.update(input, offset, length); } @Override public void reset() { this.hashGenerator.reset(); } }
apache-2.0
embree/embree
common/tasking/taskschedulertbb.cpp
2285
// Copyright 2009-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 #include "taskschedulertbb.h" namespace embree { static bool g_tbb_threads_initialized = false; #if TBB_INTERFACE_VERSION >= 11005 static tbb::global_control* g_tbb_thread_control = nullptr; #else static tbb::task_scheduler_init g_tbb_threads(tbb::task_scheduler_init::deferred); #endif class TBBAffinity: public tbb::task_scheduler_observer { public: void on_scheduler_entry( bool ) { setAffinity(TaskScheduler::threadIndex()); } } tbb_affinity; void TaskScheduler::create(size_t numThreads, bool set_affinity, bool start_threads) { assert(numThreads); /* first terminate threads in case we configured them */ if (g_tbb_threads_initialized) { #if TBB_INTERFACE_VERSION >= 11005 delete g_tbb_thread_control; g_tbb_thread_control = nullptr; #else g_tbb_threads.terminate(); #endif g_tbb_threads_initialized = false; } /* only set affinity if requested by the user */ #if TBB_INTERFACE_VERSION >= 9000 // affinity not properly supported by older TBB versions if (set_affinity) tbb_affinity.observe(true); #endif /* now either keep default settings or configure number of threads */ if (numThreads == std::numeric_limits<size_t>::max()) { numThreads = threadCount(); } else { g_tbb_threads_initialized = true; const size_t max_concurrency = threadCount(); if (numThreads > max_concurrency) numThreads = max_concurrency; #if TBB_INTERFACE_VERSION >= 11005 g_tbb_thread_control = new tbb::global_control(tbb::global_control::max_allowed_parallelism,numThreads); #else g_tbb_threads.initialize(int(numThreads)); #endif } /* start worker threads */ if (start_threads) { BarrierSys barrier(numThreads); tbb::parallel_for(size_t(0), size_t(numThreads), size_t(1), [&] ( size_t i ) { barrier.wait(); }); } } void TaskScheduler::destroy() { if (g_tbb_threads_initialized) { #if TBB_INTERFACE_VERSION >= 11005 delete g_tbb_thread_control; g_tbb_thread_control = nullptr; #else g_tbb_threads.terminate(); #endif g_tbb_threads_initialized = false; } } }
apache-2.0
Liuzhiyang94/ComponentProjectDemo
ModuleDevelopDemo/modulea/src/main/java/com/lzy/demo/modulea/OrderInfoUtil2_0.java
4884
package com.lzy.demo.modulea; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Random; public class OrderInfoUtil2_0 { /** * 构造授权参数列表 * * @param pid * @param app_id * @param target_id * @return */ public static Map<String, String> buildAuthInfoMap(String pid, String app_id, String target_id, boolean rsa2) { Map<String, String> keyValues = new HashMap<String, String>(); // 商户签约拿到的app_id,如:2013081700024223 keyValues.put("app_id", app_id); // 商户签约拿到的pid,如:2088102123816631 keyValues.put("pid", pid); // 服务接口名称, 固定值 keyValues.put("apiname", "com.alipay.account.auth"); // 商户类型标识, 固定值 keyValues.put("app_name", "mc"); // 业务类型, 固定值 keyValues.put("biz_type", "openservice"); // 产品码, 固定值 keyValues.put("product_id", "APP_FAST_LOGIN"); // 授权范围, 固定值 keyValues.put("scope", "kuaijie"); // 商户唯一标识,如:kkkkk091125 keyValues.put("target_id", target_id); // 授权类型, 固定值 keyValues.put("auth_type", "AUTHACCOUNT"); // 签名类型 keyValues.put("sign_type", rsa2 ? "RSA2" : "RSA"); return keyValues; } /** * 构造支付订单参数列表 * @param pid * @param app_id * @param target_id * @return */ public static Map<String, String> buildOrderParamMap(String app_id, boolean rsa2) { Map<String, String> keyValues = new HashMap<String, String>(); keyValues.put("app_id", app_id); keyValues.put("biz_content", "{\"timeout_express\":\"30m\",\"product_code\":\"QUICK_MSECURITY_PAY\",\"total_amount\":\"0.01\",\"subject\":\"1\",\"body\":\"我是测试数据\",\"out_trade_no\":\"" + getOutTradeNo() + "\"}"); keyValues.put("charset", "utf-8"); keyValues.put("method", "alipay.trade.app.pay"); keyValues.put("sign_type", rsa2 ? "RSA2" : "RSA"); keyValues.put("timestamp", "2016-07-29 16:55:53"); keyValues.put("version", "1.0"); return keyValues; } /** * 构造支付订单参数信息 * * @param map * 支付订单参数 * @return */ public static String buildOrderParam(Map<String, String> map) { List<String> keys = new ArrayList<String>(map.keySet()); StringBuilder sb = new StringBuilder(); for (int i = 0; i < keys.size() - 1; i++) { String key = keys.get(i); String value = map.get(key); sb.append(buildKeyValue(key, value, true)); sb.append("&"); } String tailKey = keys.get(keys.size() - 1); String tailValue = map.get(tailKey); sb.append(buildKeyValue(tailKey, tailValue, true)); return sb.toString(); } /** * 拼接键值对 * * @param key * @param value * @param isEncode * @return */ private static String buildKeyValue(String key, String value, boolean isEncode) { StringBuilder sb = new StringBuilder(); sb.append(key); sb.append("="); if (isEncode) { try { sb.append(URLEncoder.encode(value, "UTF-8")); } catch (UnsupportedEncodingException e) { sb.append(value); } } else { sb.append(value); } return sb.toString(); } /** * 对支付参数信息进行签名 * * @param map * 待签名授权信息 * * @return */ public static String getSign(Map<String, String> map, String rsaKey, boolean rsa2) { List<String> keys = new ArrayList<String>(map.keySet()); // key排序 Collections.sort(keys); StringBuilder authInfo = new StringBuilder(); for (int i = 0; i < keys.size() - 1; i++) { String key = keys.get(i); String value = map.get(key); authInfo.append(buildKeyValue(key, value, false)); authInfo.append("&"); } String tailKey = keys.get(keys.size() - 1); String tailValue = map.get(tailKey); authInfo.append(buildKeyValue(tailKey, tailValue, false)); String oriSign = SignUtils.sign(authInfo.toString(), rsaKey, rsa2); String encodedSign = ""; try { encodedSign = URLEncoder.encode(oriSign, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return "sign=" + encodedSign; } /** * 要求外部订单号必须唯一。 * @return */ private static String getOutTradeNo() { SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss", Locale.getDefault()); Date date = new Date(); String key = format.format(date); Random r = new Random(); key = key + r.nextInt(); key = key.substring(0, 15); return key; } }
apache-2.0
googleads/google-ads-java
google-ads-stubs-v9/src/main/java/com/google/ads/googleads/v9/services/MutateCampaignCustomizersResponse.java
42532
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v9/services/campaign_customizer_service.proto package com.google.ads.googleads.v9.services; /** * <pre> * Response message for an campaign customizer mutate. * </pre> * * Protobuf type {@code google.ads.googleads.v9.services.MutateCampaignCustomizersResponse} */ public final class MutateCampaignCustomizersResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v9.services.MutateCampaignCustomizersResponse) MutateCampaignCustomizersResponseOrBuilder { private static final long serialVersionUID = 0L; // Use MutateCampaignCustomizersResponse.newBuilder() to construct. private MutateCampaignCustomizersResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private MutateCampaignCustomizersResponse() { results_ = java.util.Collections.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new MutateCampaignCustomizersResponse(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private MutateCampaignCustomizersResponse( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { if (!((mutable_bitField0_ & 0x00000001) != 0)) { results_ = new java.util.ArrayList<com.google.ads.googleads.v9.services.MutateCampaignCustomizerResult>(); mutable_bitField0_ |= 0x00000001; } results_.add( input.readMessage(com.google.ads.googleads.v9.services.MutateCampaignCustomizerResult.parser(), extensionRegistry)); break; } case 18: { com.google.rpc.Status.Builder subBuilder = null; if (partialFailureError_ != null) { subBuilder = partialFailureError_.toBuilder(); } partialFailureError_ = input.readMessage(com.google.rpc.Status.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(partialFailureError_); partialFailureError_ = subBuilder.buildPartial(); } break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000001) != 0)) { results_ = java.util.Collections.unmodifiableList(results_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v9.services.CampaignCustomizerServiceProto.internal_static_google_ads_googleads_v9_services_MutateCampaignCustomizersResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v9.services.CampaignCustomizerServiceProto.internal_static_google_ads_googleads_v9_services_MutateCampaignCustomizersResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v9.services.MutateCampaignCustomizersResponse.class, com.google.ads.googleads.v9.services.MutateCampaignCustomizersResponse.Builder.class); } public static final int RESULTS_FIELD_NUMBER = 1; private java.util.List<com.google.ads.googleads.v9.services.MutateCampaignCustomizerResult> results_; /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCustomizerResult results = 1;</code> */ @java.lang.Override public java.util.List<com.google.ads.googleads.v9.services.MutateCampaignCustomizerResult> getResultsList() { return results_; } /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCustomizerResult results = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.ads.googleads.v9.services.MutateCampaignCustomizerResultOrBuilder> getResultsOrBuilderList() { return results_; } /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCustomizerResult results = 1;</code> */ @java.lang.Override public int getResultsCount() { return results_.size(); } /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCustomizerResult results = 1;</code> */ @java.lang.Override public com.google.ads.googleads.v9.services.MutateCampaignCustomizerResult getResults(int index) { return results_.get(index); } /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCustomizerResult results = 1;</code> */ @java.lang.Override public com.google.ads.googleads.v9.services.MutateCampaignCustomizerResultOrBuilder getResultsOrBuilder( int index) { return results_.get(index); } public static final int PARTIAL_FAILURE_ERROR_FIELD_NUMBER = 2; private com.google.rpc.Status partialFailureError_; /** * <pre> * Errors that pertain to operation failures in the partial failure mode. * Returned only when partial_failure = true and all errors occur inside the * operations. If any errors occur outside the operations (e.g. auth errors), * we return an RPC level error. * </pre> * * <code>.google.rpc.Status partial_failure_error = 2;</code> * @return Whether the partialFailureError field is set. */ @java.lang.Override public boolean hasPartialFailureError() { return partialFailureError_ != null; } /** * <pre> * Errors that pertain to operation failures in the partial failure mode. * Returned only when partial_failure = true and all errors occur inside the * operations. If any errors occur outside the operations (e.g. auth errors), * we return an RPC level error. * </pre> * * <code>.google.rpc.Status partial_failure_error = 2;</code> * @return The partialFailureError. */ @java.lang.Override public com.google.rpc.Status getPartialFailureError() { return partialFailureError_ == null ? com.google.rpc.Status.getDefaultInstance() : partialFailureError_; } /** * <pre> * Errors that pertain to operation failures in the partial failure mode. * Returned only when partial_failure = true and all errors occur inside the * operations. If any errors occur outside the operations (e.g. auth errors), * we return an RPC level error. * </pre> * * <code>.google.rpc.Status partial_failure_error = 2;</code> */ @java.lang.Override public com.google.rpc.StatusOrBuilder getPartialFailureErrorOrBuilder() { return getPartialFailureError(); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < results_.size(); i++) { output.writeMessage(1, results_.get(i)); } if (partialFailureError_ != null) { output.writeMessage(2, getPartialFailureError()); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < results_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, results_.get(i)); } if (partialFailureError_ != null) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(2, getPartialFailureError()); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.ads.googleads.v9.services.MutateCampaignCustomizersResponse)) { return super.equals(obj); } com.google.ads.googleads.v9.services.MutateCampaignCustomizersResponse other = (com.google.ads.googleads.v9.services.MutateCampaignCustomizersResponse) obj; if (!getResultsList() .equals(other.getResultsList())) return false; if (hasPartialFailureError() != other.hasPartialFailureError()) return false; if (hasPartialFailureError()) { if (!getPartialFailureError() .equals(other.getPartialFailureError())) return false; } if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (getResultsCount() > 0) { hash = (37 * hash) + RESULTS_FIELD_NUMBER; hash = (53 * hash) + getResultsList().hashCode(); } if (hasPartialFailureError()) { hash = (37 * hash) + PARTIAL_FAILURE_ERROR_FIELD_NUMBER; hash = (53 * hash) + getPartialFailureError().hashCode(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v9.services.MutateCampaignCustomizersResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v9.services.MutateCampaignCustomizersResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v9.services.MutateCampaignCustomizersResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v9.services.MutateCampaignCustomizersResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v9.services.MutateCampaignCustomizersResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v9.services.MutateCampaignCustomizersResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v9.services.MutateCampaignCustomizersResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v9.services.MutateCampaignCustomizersResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.google.ads.googleads.v9.services.MutateCampaignCustomizersResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.google.ads.googleads.v9.services.MutateCampaignCustomizersResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.google.ads.googleads.v9.services.MutateCampaignCustomizersResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v9.services.MutateCampaignCustomizersResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.ads.googleads.v9.services.MutateCampaignCustomizersResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * Response message for an campaign customizer mutate. * </pre> * * Protobuf type {@code google.ads.googleads.v9.services.MutateCampaignCustomizersResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v9.services.MutateCampaignCustomizersResponse) com.google.ads.googleads.v9.services.MutateCampaignCustomizersResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v9.services.CampaignCustomizerServiceProto.internal_static_google_ads_googleads_v9_services_MutateCampaignCustomizersResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v9.services.CampaignCustomizerServiceProto.internal_static_google_ads_googleads_v9_services_MutateCampaignCustomizersResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v9.services.MutateCampaignCustomizersResponse.class, com.google.ads.googleads.v9.services.MutateCampaignCustomizersResponse.Builder.class); } // Construct using com.google.ads.googleads.v9.services.MutateCampaignCustomizersResponse.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { getResultsFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); if (resultsBuilder_ == null) { results_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); } else { resultsBuilder_.clear(); } if (partialFailureErrorBuilder_ == null) { partialFailureError_ = null; } else { partialFailureError_ = null; partialFailureErrorBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v9.services.CampaignCustomizerServiceProto.internal_static_google_ads_googleads_v9_services_MutateCampaignCustomizersResponse_descriptor; } @java.lang.Override public com.google.ads.googleads.v9.services.MutateCampaignCustomizersResponse getDefaultInstanceForType() { return com.google.ads.googleads.v9.services.MutateCampaignCustomizersResponse.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v9.services.MutateCampaignCustomizersResponse build() { com.google.ads.googleads.v9.services.MutateCampaignCustomizersResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v9.services.MutateCampaignCustomizersResponse buildPartial() { com.google.ads.googleads.v9.services.MutateCampaignCustomizersResponse result = new com.google.ads.googleads.v9.services.MutateCampaignCustomizersResponse(this); int from_bitField0_ = bitField0_; if (resultsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { results_ = java.util.Collections.unmodifiableList(results_); bitField0_ = (bitField0_ & ~0x00000001); } result.results_ = results_; } else { result.results_ = resultsBuilder_.build(); } if (partialFailureErrorBuilder_ == null) { result.partialFailureError_ = partialFailureError_; } else { result.partialFailureError_ = partialFailureErrorBuilder_.build(); } onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.ads.googleads.v9.services.MutateCampaignCustomizersResponse) { return mergeFrom((com.google.ads.googleads.v9.services.MutateCampaignCustomizersResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v9.services.MutateCampaignCustomizersResponse other) { if (other == com.google.ads.googleads.v9.services.MutateCampaignCustomizersResponse.getDefaultInstance()) return this; if (resultsBuilder_ == null) { if (!other.results_.isEmpty()) { if (results_.isEmpty()) { results_ = other.results_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureResultsIsMutable(); results_.addAll(other.results_); } onChanged(); } } else { if (!other.results_.isEmpty()) { if (resultsBuilder_.isEmpty()) { resultsBuilder_.dispose(); resultsBuilder_ = null; results_ = other.results_; bitField0_ = (bitField0_ & ~0x00000001); resultsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getResultsFieldBuilder() : null; } else { resultsBuilder_.addAllMessages(other.results_); } } } if (other.hasPartialFailureError()) { mergePartialFailureError(other.getPartialFailureError()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.ads.googleads.v9.services.MutateCampaignCustomizersResponse parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.ads.googleads.v9.services.MutateCampaignCustomizersResponse) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.util.List<com.google.ads.googleads.v9.services.MutateCampaignCustomizerResult> results_ = java.util.Collections.emptyList(); private void ensureResultsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { results_ = new java.util.ArrayList<com.google.ads.googleads.v9.services.MutateCampaignCustomizerResult>(results_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v9.services.MutateCampaignCustomizerResult, com.google.ads.googleads.v9.services.MutateCampaignCustomizerResult.Builder, com.google.ads.googleads.v9.services.MutateCampaignCustomizerResultOrBuilder> resultsBuilder_; /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCustomizerResult results = 1;</code> */ public java.util.List<com.google.ads.googleads.v9.services.MutateCampaignCustomizerResult> getResultsList() { if (resultsBuilder_ == null) { return java.util.Collections.unmodifiableList(results_); } else { return resultsBuilder_.getMessageList(); } } /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCustomizerResult results = 1;</code> */ public int getResultsCount() { if (resultsBuilder_ == null) { return results_.size(); } else { return resultsBuilder_.getCount(); } } /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCustomizerResult results = 1;</code> */ public com.google.ads.googleads.v9.services.MutateCampaignCustomizerResult getResults(int index) { if (resultsBuilder_ == null) { return results_.get(index); } else { return resultsBuilder_.getMessage(index); } } /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCustomizerResult results = 1;</code> */ public Builder setResults( int index, com.google.ads.googleads.v9.services.MutateCampaignCustomizerResult value) { if (resultsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureResultsIsMutable(); results_.set(index, value); onChanged(); } else { resultsBuilder_.setMessage(index, value); } return this; } /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCustomizerResult results = 1;</code> */ public Builder setResults( int index, com.google.ads.googleads.v9.services.MutateCampaignCustomizerResult.Builder builderForValue) { if (resultsBuilder_ == null) { ensureResultsIsMutable(); results_.set(index, builderForValue.build()); onChanged(); } else { resultsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCustomizerResult results = 1;</code> */ public Builder addResults(com.google.ads.googleads.v9.services.MutateCampaignCustomizerResult value) { if (resultsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureResultsIsMutable(); results_.add(value); onChanged(); } else { resultsBuilder_.addMessage(value); } return this; } /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCustomizerResult results = 1;</code> */ public Builder addResults( int index, com.google.ads.googleads.v9.services.MutateCampaignCustomizerResult value) { if (resultsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureResultsIsMutable(); results_.add(index, value); onChanged(); } else { resultsBuilder_.addMessage(index, value); } return this; } /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCustomizerResult results = 1;</code> */ public Builder addResults( com.google.ads.googleads.v9.services.MutateCampaignCustomizerResult.Builder builderForValue) { if (resultsBuilder_ == null) { ensureResultsIsMutable(); results_.add(builderForValue.build()); onChanged(); } else { resultsBuilder_.addMessage(builderForValue.build()); } return this; } /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCustomizerResult results = 1;</code> */ public Builder addResults( int index, com.google.ads.googleads.v9.services.MutateCampaignCustomizerResult.Builder builderForValue) { if (resultsBuilder_ == null) { ensureResultsIsMutable(); results_.add(index, builderForValue.build()); onChanged(); } else { resultsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCustomizerResult results = 1;</code> */ public Builder addAllResults( java.lang.Iterable<? extends com.google.ads.googleads.v9.services.MutateCampaignCustomizerResult> values) { if (resultsBuilder_ == null) { ensureResultsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, results_); onChanged(); } else { resultsBuilder_.addAllMessages(values); } return this; } /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCustomizerResult results = 1;</code> */ public Builder clearResults() { if (resultsBuilder_ == null) { results_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { resultsBuilder_.clear(); } return this; } /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCustomizerResult results = 1;</code> */ public Builder removeResults(int index) { if (resultsBuilder_ == null) { ensureResultsIsMutable(); results_.remove(index); onChanged(); } else { resultsBuilder_.remove(index); } return this; } /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCustomizerResult results = 1;</code> */ public com.google.ads.googleads.v9.services.MutateCampaignCustomizerResult.Builder getResultsBuilder( int index) { return getResultsFieldBuilder().getBuilder(index); } /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCustomizerResult results = 1;</code> */ public com.google.ads.googleads.v9.services.MutateCampaignCustomizerResultOrBuilder getResultsOrBuilder( int index) { if (resultsBuilder_ == null) { return results_.get(index); } else { return resultsBuilder_.getMessageOrBuilder(index); } } /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCustomizerResult results = 1;</code> */ public java.util.List<? extends com.google.ads.googleads.v9.services.MutateCampaignCustomizerResultOrBuilder> getResultsOrBuilderList() { if (resultsBuilder_ != null) { return resultsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(results_); } } /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCustomizerResult results = 1;</code> */ public com.google.ads.googleads.v9.services.MutateCampaignCustomizerResult.Builder addResultsBuilder() { return getResultsFieldBuilder().addBuilder( com.google.ads.googleads.v9.services.MutateCampaignCustomizerResult.getDefaultInstance()); } /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCustomizerResult results = 1;</code> */ public com.google.ads.googleads.v9.services.MutateCampaignCustomizerResult.Builder addResultsBuilder( int index) { return getResultsFieldBuilder().addBuilder( index, com.google.ads.googleads.v9.services.MutateCampaignCustomizerResult.getDefaultInstance()); } /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v9.services.MutateCampaignCustomizerResult results = 1;</code> */ public java.util.List<com.google.ads.googleads.v9.services.MutateCampaignCustomizerResult.Builder> getResultsBuilderList() { return getResultsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v9.services.MutateCampaignCustomizerResult, com.google.ads.googleads.v9.services.MutateCampaignCustomizerResult.Builder, com.google.ads.googleads.v9.services.MutateCampaignCustomizerResultOrBuilder> getResultsFieldBuilder() { if (resultsBuilder_ == null) { resultsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v9.services.MutateCampaignCustomizerResult, com.google.ads.googleads.v9.services.MutateCampaignCustomizerResult.Builder, com.google.ads.googleads.v9.services.MutateCampaignCustomizerResultOrBuilder>( results_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); results_ = null; } return resultsBuilder_; } private com.google.rpc.Status partialFailureError_; private com.google.protobuf.SingleFieldBuilderV3< com.google.rpc.Status, com.google.rpc.Status.Builder, com.google.rpc.StatusOrBuilder> partialFailureErrorBuilder_; /** * <pre> * Errors that pertain to operation failures in the partial failure mode. * Returned only when partial_failure = true and all errors occur inside the * operations. If any errors occur outside the operations (e.g. auth errors), * we return an RPC level error. * </pre> * * <code>.google.rpc.Status partial_failure_error = 2;</code> * @return Whether the partialFailureError field is set. */ public boolean hasPartialFailureError() { return partialFailureErrorBuilder_ != null || partialFailureError_ != null; } /** * <pre> * Errors that pertain to operation failures in the partial failure mode. * Returned only when partial_failure = true and all errors occur inside the * operations. If any errors occur outside the operations (e.g. auth errors), * we return an RPC level error. * </pre> * * <code>.google.rpc.Status partial_failure_error = 2;</code> * @return The partialFailureError. */ public com.google.rpc.Status getPartialFailureError() { if (partialFailureErrorBuilder_ == null) { return partialFailureError_ == null ? com.google.rpc.Status.getDefaultInstance() : partialFailureError_; } else { return partialFailureErrorBuilder_.getMessage(); } } /** * <pre> * Errors that pertain to operation failures in the partial failure mode. * Returned only when partial_failure = true and all errors occur inside the * operations. If any errors occur outside the operations (e.g. auth errors), * we return an RPC level error. * </pre> * * <code>.google.rpc.Status partial_failure_error = 2;</code> */ public Builder setPartialFailureError(com.google.rpc.Status value) { if (partialFailureErrorBuilder_ == null) { if (value == null) { throw new NullPointerException(); } partialFailureError_ = value; onChanged(); } else { partialFailureErrorBuilder_.setMessage(value); } return this; } /** * <pre> * Errors that pertain to operation failures in the partial failure mode. * Returned only when partial_failure = true and all errors occur inside the * operations. If any errors occur outside the operations (e.g. auth errors), * we return an RPC level error. * </pre> * * <code>.google.rpc.Status partial_failure_error = 2;</code> */ public Builder setPartialFailureError( com.google.rpc.Status.Builder builderForValue) { if (partialFailureErrorBuilder_ == null) { partialFailureError_ = builderForValue.build(); onChanged(); } else { partialFailureErrorBuilder_.setMessage(builderForValue.build()); } return this; } /** * <pre> * Errors that pertain to operation failures in the partial failure mode. * Returned only when partial_failure = true and all errors occur inside the * operations. If any errors occur outside the operations (e.g. auth errors), * we return an RPC level error. * </pre> * * <code>.google.rpc.Status partial_failure_error = 2;</code> */ public Builder mergePartialFailureError(com.google.rpc.Status value) { if (partialFailureErrorBuilder_ == null) { if (partialFailureError_ != null) { partialFailureError_ = com.google.rpc.Status.newBuilder(partialFailureError_).mergeFrom(value).buildPartial(); } else { partialFailureError_ = value; } onChanged(); } else { partialFailureErrorBuilder_.mergeFrom(value); } return this; } /** * <pre> * Errors that pertain to operation failures in the partial failure mode. * Returned only when partial_failure = true and all errors occur inside the * operations. If any errors occur outside the operations (e.g. auth errors), * we return an RPC level error. * </pre> * * <code>.google.rpc.Status partial_failure_error = 2;</code> */ public Builder clearPartialFailureError() { if (partialFailureErrorBuilder_ == null) { partialFailureError_ = null; onChanged(); } else { partialFailureError_ = null; partialFailureErrorBuilder_ = null; } return this; } /** * <pre> * Errors that pertain to operation failures in the partial failure mode. * Returned only when partial_failure = true and all errors occur inside the * operations. If any errors occur outside the operations (e.g. auth errors), * we return an RPC level error. * </pre> * * <code>.google.rpc.Status partial_failure_error = 2;</code> */ public com.google.rpc.Status.Builder getPartialFailureErrorBuilder() { onChanged(); return getPartialFailureErrorFieldBuilder().getBuilder(); } /** * <pre> * Errors that pertain to operation failures in the partial failure mode. * Returned only when partial_failure = true and all errors occur inside the * operations. If any errors occur outside the operations (e.g. auth errors), * we return an RPC level error. * </pre> * * <code>.google.rpc.Status partial_failure_error = 2;</code> */ public com.google.rpc.StatusOrBuilder getPartialFailureErrorOrBuilder() { if (partialFailureErrorBuilder_ != null) { return partialFailureErrorBuilder_.getMessageOrBuilder(); } else { return partialFailureError_ == null ? com.google.rpc.Status.getDefaultInstance() : partialFailureError_; } } /** * <pre> * Errors that pertain to operation failures in the partial failure mode. * Returned only when partial_failure = true and all errors occur inside the * operations. If any errors occur outside the operations (e.g. auth errors), * we return an RPC level error. * </pre> * * <code>.google.rpc.Status partial_failure_error = 2;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.rpc.Status, com.google.rpc.Status.Builder, com.google.rpc.StatusOrBuilder> getPartialFailureErrorFieldBuilder() { if (partialFailureErrorBuilder_ == null) { partialFailureErrorBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.rpc.Status, com.google.rpc.Status.Builder, com.google.rpc.StatusOrBuilder>( getPartialFailureError(), getParentForChildren(), isClean()); partialFailureError_ = null; } return partialFailureErrorBuilder_; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.ads.googleads.v9.services.MutateCampaignCustomizersResponse) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v9.services.MutateCampaignCustomizersResponse) private static final com.google.ads.googleads.v9.services.MutateCampaignCustomizersResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v9.services.MutateCampaignCustomizersResponse(); } public static com.google.ads.googleads.v9.services.MutateCampaignCustomizersResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<MutateCampaignCustomizersResponse> PARSER = new com.google.protobuf.AbstractParser<MutateCampaignCustomizersResponse>() { @java.lang.Override public MutateCampaignCustomizersResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new MutateCampaignCustomizersResponse(input, extensionRegistry); } }; public static com.google.protobuf.Parser<MutateCampaignCustomizersResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<MutateCampaignCustomizersResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v9.services.MutateCampaignCustomizersResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache-2.0
mdejong/GvmCpp
src/GvmVectorSpace.hpp
4836
// // GvmVectorSpace.hpp // GvmCpp // // Created by Mo DeJong on 8/14/15. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // #import "GvmCommon.hpp" #import <tgmath.h> namespace Gvm { // FP // // Floating point type that store the results of calculations // based on points. This floating point type could be float // or double. // V // // Vector of points type, a point is typically 2 or 3 // values that represent (X,Y) or (X,Y,Z) coordinates // in 2D or 3D space. The type passed as V should // extend the GvmVector interface. template<typename V, typename FP, int D> class GvmVectorSpace { public: // The computed variance of the cluster int getDimensions() { return D; } // constructor GvmVectorSpace<FP,D>() { assert(D >= 1); } // space factory methods V newOrigin() { // Invoke default constructor return V(); } V newCopy(V &pt) { // Invoke copy constructor return V(pt); } // space point operations FP magnitudeSqr(V &pt) { FP sum = FP(0.0); for (int i = 0; i < D; i++) { // sum += (pt[i] * pt[i]); sum += pt.iSquared(i); } return sum; } FP sum(V &pt) { FP sum = FP(0.0); for (int i = 0; i < D; i++) { FP c = pt[i]; sum += c; } return sum; } void setToOrigin(V &pt) { for (int i = 0; i < D; i++) { pt[i] = FP(0.0); } } void setTo(V &dstPt, V &srcPt) { for (int i = 0; i < D; i++) { dstPt[i] = srcPt[i]; } } void setToScaled(V &dstPt, FP m, V &srcPt) { for (int i = 0; i < D; i++) { dstPt[i] = m * srcPt[i]; } } void setToScaledSqr(V &dstPt, FP m, V &srcPt) { for (int i = 0; i < D; i++) { // dstPt[i] = (srcPt[i] * srcPt[i]); dstPt[i] = m * srcPt.iSquared(i); } } void add(V &dstPt, V &srcPt) { for (int i = 0; i < D; i++) { dstPt[i] += srcPt[i]; } } void addScaled(V &dstPt, FP m, V &srcPt) { for (int i = 0; i < D; i++) { dstPt[i] += m * srcPt[i]; } } void addScaledSqr(V &dstPt, FP m, V &srcPt) { for (int i = 0; i < D; i++) { // dstPt[i] += m * (srcPt[i] * srcPt[i]); dstPt[i] += m * srcPt.iSquared(i); } } void subtract(V &dstPt, V &srcPt) { for (int i = 0; i < D; i++) { dstPt[i] -= srcPt[i]; } } void subtractScaled(V &dstPt, FP m, V &srcPt) { for (int i = 0; i < D; i++) { dstPt[i] -= m * srcPt[i]; } } void subtractScaledSqr(V &dstPt, FP m, V &srcPt) { for (int i = 0; i < D; i++) { // dstPt[i] -= m * (srcPt[i] * srcPt[i]); dstPt[i] -= m * srcPt.iSquared(i); } } void scale(V &pt, FP m) { for (int i = 0; i < D; i++) { pt[i] *= m; } } void square(V &pt) { for (int i = 0; i < D; i++) { pt[i] *= pt[i]; } } // Note that this distance method is not used in the implementation // since it is much more effective to use delta squared directly. FP distance(V &pt1, V &pt2) { FP sum = FP(0.0); for (int i = 0; i < D; i++) { FP d = pt1[i] - pt2[i]; sum += d * d; } return sqrt(sum); } // optimizations // FIXME: make optimized versions of functions below FP variance(const FP m, const V &pt, const V &ptSqr) { FP sum = FP(0.0); const FP mMult = FP(1.0) / m; for (int i = 0; i < D; i++) { FP c = pt[i]; sum += ptSqr[i] - ((c * c) * mMult); } return sum; } FP variance(const FP m1, const V &pt1, const V &ptSqr1, const FP m2, const V &pt2) { const FP m0 = m1 + m2; const FP m0Mult = FP(1.0) / m0; FP sum = FP(0.0); for (int i = 0; i < D; i++) { FP c2 = pt2[i]; FP c = pt1[i] + (m2 * c2); FP cSqr = ptSqr1[i] + (m2 * (c2 * c2)); sum += cSqr - ((c * c) * m0Mult); } return sum; } FP variance(const FP m1, const V &pt1, const V &ptSqr1, const FP m2, const V &pt2, const V &ptSqr2) { const FP m0 = m1 + m2; const FP m0Mult = FP(1.0) / m0; FP sum = FP(0.0); for (int i = 0; i < D; i++) { FP c = pt1[i] + pt2[i]; FP cSqr = ptSqr1[i] + ptSqr2[i]; sum += cSqr - ((c * c) * m0Mult); } return sum; } std::string toString(V &pt) { return pt.toString(); } }; // end class GvmVectorSpace }
apache-2.0
pmuetschard/gwt-debug-panel
src/main/test/com/google/gwt/debugpanel/common/GwtStatisticsEventSystemTest.java
4928
/* * Copyright 2009 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.gwt.debugpanel.common; import java.util.Iterator; /** * Tests the {@link GwtStatisticsEventSystem}. */ public class GwtStatisticsEventSystemTest extends AbstractDebugPanelGwtTestCase { private GwtStatisticsEventSystem system; @Override protected void gwtSetUp() throws Exception { super.gwtSetUp(); setup(); system = new GwtStatisticsEventSystem(); system.enable(true); } // This is necessary as the tests are not run in isolation. private native void setup() /*-{ $wnd.__stats = new Array(); $wnd.__stats_listener = null; }-*/; public void testRegisterAndDispatch() { final int[] invokeCount = new int[1]; system.addListener(new StatisticsEventListener() { //@Override public void onStatisticsEvent(StatisticsEvent event) { assertEquals("event1", event.getModuleName()); invokeCount[0]++; } }, false); dispatch(event("event1")); assertEquals(1, invokeCount[0]); } public void testReplay() { dispatch(event("event1")); dispatch(event("event2")); final int[] invokeCount = new int[1]; system.addListener(new StatisticsEventListener() { //@Override public void onStatisticsEvent(StatisticsEvent event) { if (invokeCount[0] == 0) { assertEquals("event1", event.getModuleName()); } else if (invokeCount[0] == 1) { assertEquals("event2", event.getModuleName()); } invokeCount[0]++; } }, true); assertEquals(2, invokeCount[0]); } public void testNoReplay() { dispatch(event("event1")); dispatch(event("event2")); system.addListener(new StatisticsEventListener() { //@Override public void onStatisticsEvent(StatisticsEvent event) { fail("No invocation expected when replay is false."); } }, false); } public void testClearHistory() { dispatch(event("event1")); assertTrue(system.pastEvents().hasNext()); system.clearEventHistory(); assertFalse(system.pastEvents().hasNext()); } public void testEventIterator() { Object event1 = event("event1"), event2 = event("event2"); dispatch(event1); dispatch(event2); Iterator<StatisticsEvent> iterator = system.pastEvents(); assertTrue(iterator.hasNext()); assertEquals("event1", iterator.next().getModuleName()); assertTrue(iterator.hasNext()); assertEquals("event2", iterator.next().getModuleName()); assertFalse(iterator.hasNext()); } public void testHooksIntoGwtStatsSystem() { final int[] invokeCount = new int[1]; system.addListener(new StatisticsEventListener() { //@Override public void onStatisticsEvent(StatisticsEvent event) { invokeCount[0]++; } }, false); assertEquals(0, invokeCount[0]); // Simulate an event sent by the GWT system via JavaScript. dispatch(null); assertEquals(1, invokeCount[0]); } public void testEventsAreIgnoredWhenDisabled() { system = new GwtStatisticsEventSystem(); system.addListener(new StatisticsEventListener() { //@Override public void onStatisticsEvent(StatisticsEvent event) { fail("system is disabled, not expecting any events"); } }, false); dispatch(null); } public void testIteratorIsReadOnly() { dispatch(event("event")); Iterator<StatisticsEvent> iterator = system.pastEvents(); assertTrue(iterator.hasNext()); iterator.next(); try { iterator.remove(); fail("Iterator should not all remove"); } catch (RuntimeException e) { // Expected. } } public void testNoEventsAreReceivedAfterRemovingListener() { StatisticsEventListener listener = new StatisticsEventListener() { //@Override public void onStatisticsEvent(StatisticsEvent event) { fail("did not expect any events"); } }; system.addListener(listener, false); system.removeListener(listener); dispatch(event("event")); } private native void dispatch(Object evt) /*-{ var stats = $wnd.__stats; if (stats) { stats[stats.length] = evt; } var listener = $wnd.__stats_listener; if (listener) { listener(evt); } }-*/; private native Object event(String module) /*-{ return { moduleName: module }; }-*/; }
apache-2.0
Deyuan/qmsim
Python/qos_scheduler.py
5032
# QoS Scheduler # Schedule for a spec, return scheduled containers # Author: Deyuan Guo, Chunkun Bo # Date: Dec 10, 2015 # some factors: # - task: # "new" - just looking for available containers for a spec # "update" - update qos spec, and consider actual_file_size # "reschedule" - consider actual_file_size # #update and reschedule are similar. # - bandwidth_factor: when searching higher level of location, bandwidth gets lower # - latency_factor: when searching higher level of location, latency gets higher # - actual_file_size: How much space the client is using. Large size will significantly slow down rescheduling. For update and reschedule, we need to consider this factor, e.g. prefer to reschedule small size import itertools import itf_database import qos_checker # Schedule heuristic 0: only check the storage size requirement, and pick one def schedule_0(spec): scheduled_containers = [] info = '' container_id_list = itf_database.get_container_id_list() container_id_list = [x for x in container_id_list if \ qos_checker.check_space(spec, [itf_database.get_status(x)])] if len(container_id_list) > 0: container_id = container_id_list[0] status = itf_database.get_status(container_id) scheduled_containers.append(container_id) cost = status.CostPerGBMonth / 1024.0 * spec.ReservedSize info = '$%.2f/month' % cost return scheduled_containers, info # Schedule heuristic 1: check storage, availability and reliability def schedule_1(spec): scheduled_containers = [] info = '' container_id_list_all = itf_database.get_container_id_list() # filter out some containers container_id_list = [] for cid in container_id_list_all: status = itf_database.get_status(cid) if qos_checker.check_space(spec, [status]) and \ status.StorageReliability > 0 and \ status.ContainerAvailability > 0: container_id_list.append(cid) # check if k containers together can satisfy the spec for k in range(min(5, len(container_id_list))): cid_comb = list(itertools.combinations(container_id_list, k)) for comb in cid_comb: cid_list = list(comb) status_list = [itf_database.get_status(x) for x in cid_list] if qos_checker.check_availability(spec, status_list) and \ qos_checker.check_reliability(spec, status_list): scheduled_containers = cid_list costs = [x.CostPerGBMonth for x in status_list] cost = sum(costs) / 1024.0 * spec.ReservedSize info = '$%.2f/month' % cost return scheduled_containers, info return scheduled_containers, info # Chunkun: check storage, bandwidth, dataintegirty availability and reliability def schedule_2(spec): scheduled_containers = [] info = '' container_id_list_all = itf_database.get_container_id_list() # filter out some containers container_id_list = [] for cid in container_id_list_all: status = itf_database.get_status(cid) if qos_checker.check_space(spec, [status]) and \ qos_checker.check_dataintegrity(spec,[status]) and \ status.StorageReliability > 0 and \ status.ContainerAvailability > 0: container_id_list.append(cid) # check if k containers together can satisfy the spec for k in range(min(5, len(container_id_list))): cid_comb = list(itertools.combinations(container_id_list, k)) for comb in cid_comb: cid_list = list(comb) status_list = [itf_database.get_status(x) for x in cid_list] if qos_checker.check_availability(spec, status_list) and \ qos_checker.check_reliability(spec, status_list) and \ qos_checker.check_bandwidth(spec, status_list) and \ qos_checker.check_latency(spec, status_list): scheduled_containers = cid_list costs = [x.CostPerGBMonth for x in status_list] cost = sum(costs) / 1024.0 * spec.ReservedSize info = '$%.2f/month' % cost return scheduled_containers, info return scheduled_containers, info # Top level scheduler entry # Input a QosSpec class instance, return a list of containers def schedule (spec, task): print '[QoS Scheduler] Schedule spec {' + spec.SpecId + '} for task {' + \ task + '}' # Pick a schedule strategy if task == 'new' or task == 'update': scheduled_containers, info = schedule_2(spec) else: scheduled_containers = [] info = 'unsupported task' print '[QoS Scheduler] Schedule results: ' + str(scheduled_containers) \ + ' {' + info + '}' return scheduled_containers, info # Only for testing if __name__ == '__main__': print "[QoS Scheduler] Schedule a QoS spec to a set of containers."
apache-2.0
dotnetcurry/async-in-aspnet-vnext
AsyncWebApi/AsyncWebApi/About.aspx.designer.cs
432
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace AsyncWebApi { public partial class About { } }
apache-2.0
gesellix/docker-java
src/main/java/com/github/dockerjava/api/model/ContainerConfig.java
8785
package com.github.dockerjava.api.model; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import javax.annotation.CheckForNull; import java.io.Serializable; import java.util.Map; /** * Used as part of 'images/IMAGE/someimage' response. * * @author Konstantin Pelykh (kpelykh@gmail.com) */ @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(Include.NON_NULL) public class ContainerConfig implements Serializable { private static final long serialVersionUID = 1L; @JsonProperty("AttachStderr") private Boolean attachStderr; @JsonProperty("AttachStdin") private Boolean attachStdin; @JsonProperty("AttachStdout") private Boolean attachStdout; @JsonProperty("Cmd") private String[] cmd; @JsonProperty("Domainname") private String domainName; @JsonProperty("Entrypoint") private String[] entrypoint; @JsonProperty("Env") private String[] env; @JsonProperty("ExposedPorts") private ExposedPorts exposedPorts; @JsonProperty("Hostname") private String hostName; @JsonProperty("Image") private String image; @JsonProperty("Labels") private Map<String, String> labels; @JsonProperty("MacAddress") private String macAddress; @JsonProperty("NetworkDisabled") private Boolean networkDisabled; @JsonProperty("OnBuild") private String[] onBuild; @JsonProperty("OpenStdin") private Boolean stdinOpen; @JsonProperty("PortSpecs") private String[] portSpecs; @JsonProperty("StdinOnce") private Boolean stdInOnce; @JsonProperty("Tty") private Boolean tty; @JsonProperty("User") private String user; @JsonProperty("Volumes") private Map<String, ?> volumes; @JsonProperty("WorkingDir") private String workingDir; @JsonProperty("Healthcheck") private HealthCheck healthCheck; @JsonIgnore public ExposedPort[] getExposedPorts() { return exposedPorts != null ? exposedPorts.getExposedPorts() : null; } /** * @see #attachStderr */ @CheckForNull public Boolean getAttachStderr() { return attachStderr; } /** * @see #attachStderr */ public ContainerConfig withAttachStderr(Boolean attachStderr) { this.attachStderr = attachStderr; return this; } /** * @see #attachStdin */ @CheckForNull public Boolean getAttachStdin() { return attachStdin; } /** * @see #attachStdin */ public ContainerConfig withAttachStdin(Boolean attachStdin) { this.attachStdin = attachStdin; return this; } /** * @see #attachStdout */ @CheckForNull public Boolean getAttachStdout() { return attachStdout; } /** * @see #attachStdout */ public ContainerConfig withAttachStdout(Boolean attachStdout) { this.attachStdout = attachStdout; return this; } /** * @see #cmd */ @CheckForNull public String[] getCmd() { return cmd; } /** * @see #cmd */ public ContainerConfig withCmd(String[] cmd) { this.cmd = cmd; return this; } /** * @see #domainName */ @CheckForNull public String getDomainName() { return domainName; } /** * @see #domainName */ public ContainerConfig withDomainName(String domainName) { this.domainName = domainName; return this; } /** * @see #entrypoint */ @CheckForNull public String[] getEntrypoint() { return entrypoint; } /** * @see #entrypoint */ public ContainerConfig withEntrypoint(String[] entrypoint) { this.entrypoint = entrypoint; return this; } /** * @see #env */ @CheckForNull public String[] getEnv() { return env; } /** * @see #env */ public ContainerConfig withEnv(String[] env) { this.env = env; return this; } /** * @see #exposedPorts */ public ContainerConfig withExposedPorts(ExposedPorts exposedPorts) { this.exposedPorts = exposedPorts; return this; } /** * @see #hostName */ @CheckForNull public String getHostName() { return hostName; } /** * @see #hostName */ public ContainerConfig withHostName(String hostName) { this.hostName = hostName; return this; } /** * @see #image */ @CheckForNull public String getImage() { return image; } /** * @see #image */ public ContainerConfig withImage(String image) { this.image = image; return this; } /** * @see #labels */ @CheckForNull public Map<String, String> getLabels() { return labels; } /** * @see #labels */ public ContainerConfig withLabels(Map<String, String> labels) { this.labels = labels; return this; } /** * @see #macAddress */ @CheckForNull public String getMacAddress() { return macAddress; } /** * @see #macAddress */ public ContainerConfig withMacAddress(String macAddress) { this.macAddress = macAddress; return this; } /** * @see #networkDisabled */ @CheckForNull public Boolean getNetworkDisabled() { return networkDisabled; } /** * @see #networkDisabled */ public ContainerConfig withNetworkDisabled(Boolean networkDisabled) { this.networkDisabled = networkDisabled; return this; } /** * @see #onBuild */ @CheckForNull public String[] getOnBuild() { return onBuild; } /** * @see #onBuild */ public ContainerConfig withOnBuild(String[] onBuild) { this.onBuild = onBuild; return this; } /** * @see #portSpecs */ @CheckForNull public String[] getPortSpecs() { return portSpecs; } /** * @see #portSpecs */ public ContainerConfig withPortSpecs(String[] portSpecs) { this.portSpecs = portSpecs; return this; } /** * @see #stdInOnce */ @CheckForNull public Boolean getStdInOnce() { return stdInOnce; } /** * @see #stdInOnce */ public ContainerConfig withStdInOnce(Boolean stdInOnce) { this.stdInOnce = stdInOnce; return this; } /** * @see #stdinOpen */ @CheckForNull public Boolean getStdinOpen() { return stdinOpen; } /** * @see #stdinOpen */ public ContainerConfig withStdinOpen(Boolean stdinOpen) { this.stdinOpen = stdinOpen; return this; } /** * @see #tty */ @CheckForNull public Boolean getTty() { return tty; } /** * @see #tty */ public ContainerConfig withTty(Boolean tty) { this.tty = tty; return this; } /** * @see #user */ @CheckForNull public String getUser() { return user; } /** * @see #user */ public ContainerConfig withUser(String user) { this.user = user; return this; } /** * @see #volumes */ @CheckForNull public Map<String, ?> getVolumes() { return volumes; } /** * @see #volumes */ public ContainerConfig withVolumes(Map<String, ?> volumes) { this.volumes = volumes; return this; } /** * @see #workingDir */ @CheckForNull public String getWorkingDir() { return workingDir; } /** * @see #healthCheck */ @CheckForNull public HealthCheck getHealthcheck() { return healthCheck; } /** * @see #workingDir */ public ContainerConfig withWorkingDir(String workingDir) { this.workingDir = workingDir; return this; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } @Override public boolean equals(Object o) { return EqualsBuilder.reflectionEquals(this, o); } @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } }
apache-2.0
lyg123/sharding-jdbc
sharding-jdbc-core/src/main/java/com/dangdang/ddframe/rdb/sharding/executor/wrapper/PreparedStatementExecutorWrapper.java
2976
/* * Copyright 1999-2015 dangdang.com. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * </p> */ package com.dangdang.ddframe.rdb.sharding.executor.wrapper; import com.dangdang.ddframe.rdb.sharding.executor.event.DMLExecutionEvent; import com.dangdang.ddframe.rdb.sharding.executor.event.DQLExecutionEvent; import com.dangdang.ddframe.rdb.sharding.router.SQLExecutionUnit; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import lombok.Getter; import java.sql.PreparedStatement; import java.util.List; /** * 预编译语句对象的执行上下文. * * @author zhangliang */ public class PreparedStatementExecutorWrapper extends AbstractExecutorWrapper { @Getter private final PreparedStatement preparedStatement; private final Optional<DMLExecutionEvent> dmlExecutionEvent; private final Optional<DQLExecutionEvent> dqlExecutionEvent; public PreparedStatementExecutorWrapper(final PreparedStatement preparedStatement, final List<Object> parameters, final SQLExecutionUnit sqlExecutionUnit) { super(sqlExecutionUnit); this.preparedStatement = preparedStatement; if (isDML()) { dmlExecutionEvent = Optional.of(new DMLExecutionEvent(getSqlExecutionUnit().getDataSource(), getSqlExecutionUnit().getSql(), Lists.newArrayList(parameters))); dqlExecutionEvent = Optional.absent(); } else if (isDQL()) { dqlExecutionEvent = Optional.of(new DQLExecutionEvent(getSqlExecutionUnit().getDataSource(), getSqlExecutionUnit().getSql(), Lists.newArrayList(parameters))); dmlExecutionEvent = Optional.absent(); } else { dmlExecutionEvent = Optional.absent(); dqlExecutionEvent = Optional.absent(); } } @Override public Optional<DMLExecutionEvent> getDMLExecutionEvent() { return dmlExecutionEvent; } @Override public Optional<DQLExecutionEvent> getDQLExecutionEvent() { return dqlExecutionEvent; } /** * 增加批量参数. * * @param parameters 参数列表 */ public void addBatchParameters(final List<Object> parameters) { Preconditions.checkArgument(isDML() && dmlExecutionEvent.isPresent()); dmlExecutionEvent.get().addBatchParameters(Lists.newArrayList(parameters)); } }
apache-2.0
wqq686/keystone
keystone-core/src/main/java/com/keystone/server/KeystoneStoreManager.java
5350
package com.keystone.server; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; import com.keystone.server.admin.KeystoneAdminContext; import com.keystone.server.contexts.KeystoneAppContext; import com.keystone.server.contexts.services.MethodSkeleton; import com.keystone.server.contexts.services.ServiceSkeleton; import com.keystone.support.common.CommonUtils; import com.keystone.support.common.IOUtils; /** * 对于access.cache.txt,首先会写入access2.cache.txt中, 然后再重命名为access.cache.txt * * @author wuqq * */ public class KeystoneStoreManager { private static final String LINE_SEPARATOR = System.getProperty("line.separator"); /** */ private static String accessFilePath ; /** */ private static String accessFilePath2 ; /** */ private static Thread worker = null ; /** * */ public static synchronized void start() { initPath(); recover(); startWorker(); System.out.println("[KEYSTONE] The store manager started..."); } /** * */ @SuppressWarnings("deprecation") public static synchronized void stop() { if(worker!=null) { worker.stop(); } } /** * */ static synchronized void initPath() { String root = KeystoneResourcesManager.getServerConfig().getServerRoot() ; accessFilePath = IOUtils.mergePaths(root, "store", "access.cache.txt") ; accessFilePath2 = IOUtils.mergePaths(root, "store", "access.cache2.txt") ; } /** * */ static synchronized void recover() { String root = KeystoneResourcesManager.getServerConfig().getServerRoot() ; accessFilePath = IOUtils.mergePaths(root, "store", "access.cache.txt") ; File accessFile = IOUtils.getFile(accessFilePath) ; if(accessFile!=null) { BufferedReader reader = null ; try { reader = new BufferedReader(new FileReader(accessFile)) ; String line = null ; while((line=reader.readLine())!=null) { Map<String, Map<String, Long>> one = JSON.parseObject(line, new TypeReference<Map<String, Map<String, Long>>>(){}) ; for(String key : one.keySet()) { Map<String, Long> stat = one.get(key) ; String[] array = key.split("\\.") ; String contextName = array[0], serviceName = array[1], methodName = array[2] ; MethodSkeleton skeleton = KeystoneResourcesManager.getMethodSkeleton(contextName, serviceName, methodName, false) ; if(skeleton!=null) { long accessCount = CommonUtils.get(stat, "accessCount", 0L) ; long successCount = CommonUtils.get(stat, "successCount", 0L) ; long failedCount = CommonUtils.get(stat, "failedCount", 0L) ; long avgCost = CommonUtils.get(stat, "avgCost", 0L) ; skeleton.initStatCount(accessCount, successCount, failedCount, avgCost) ; } } } } catch(Exception ignore) {} finally { IOUtils.close(reader); } } } /** * */ static synchronized void startWorker() { worker = new Thread("ksserver-stat-worker") { @Override public void run() { for(;;) { //1. try{ TimeUnit.SECONDS.sleep(10); }catch(Exception ignore){} //2. stat(); } } } ; worker.setDaemon(true); worker.start(); } /** * */ static synchronized void stat() { boolean ok = writeAccessFile2() ; if(ok) { File accessFile2 = new File(accessFilePath2), accessFile = new File(accessFilePath) ; IOUtils.renameFile(accessFile2, accessFile); } } static boolean writeAccessFile2() { BufferedWriter writer = null ; boolean success = false ; try { File accessFile2 = IOUtils.getFile(accessFilePath2) ; writer = new BufferedWriter(new FileWriter(accessFile2)) ; ConcurrentMap<String, KeystoneAppContext> contexts = KeystoneResourcesManager.getAppcontexts() ; for(String name : contexts.keySet()) { KeystoneAppContext kac = contexts.get(name) ; if(kac instanceof KeystoneAdminContext) continue ; String contextName = kac.getContextName() ; for( String serviceName : kac.getRemotingContainer().skeletons().keySet() ) { ServiceSkeleton skeleton = KeystoneResourcesManager.getServiceSkeleton(contextName, serviceName, false) ; if(skeleton==null) continue ; for(MethodSkeleton mskeleton : skeleton.getMethodContainer().values()) { String methodName = mskeleton.getMethod().getName() ; String key = contextName + "." + serviceName + "." + methodName ; Map<String, Long> stat = new HashMap<>() ; stat.put("accessCount", mskeleton.getAccessCount()) ; stat.put("successCount", mskeleton.getSuccessCount()) ; stat.put("failedCount", mskeleton.getFailedCount()) ; stat.put("avgCost", mskeleton.getAvgCost()) ; Map<String, Map<String, Long>> stamp = new HashMap<>() ; stamp.put(key, stat) ; String line = JSON.toJSONString(stamp) ; writer.write(line); writer.write(LINE_SEPARATOR); } } } success = true ; } catch(Exception ignore){} finally{ IOUtils.close(writer); } return success ; } }
apache-2.0
alex9311/PredictionIO
examples/scala-parallel-similarproduct/recommended-user/src/main/scala/Serving.scala
284
package org.template.recommendeduser import org.apache.predictionio.controller.LServing class Serving extends LServing[Query, PredictedResult] { override def serve(query: Query, predictedResults: Seq[PredictedResult]): PredictedResult = { predictedResults.head } }
apache-2.0
mglukhikh/intellij-community
java/java-analysis-impl/src/com/intellij/codeInspection/AnonymousCanBeLambdaInspection.java
26182
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInspection; import com.intellij.codeInsight.AnnotationUtil; import com.intellij.codeInsight.ChangeContextUtil; import com.intellij.codeInsight.daemon.GroupNames; import com.intellij.codeInsight.daemon.impl.analysis.HighlightControlFlowUtil; import com.intellij.codeInsight.intention.HighPriorityAction; import com.intellij.codeInspection.ui.SingleCheckboxOptionsPanel; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.*; import com.intellij.psi.codeStyle.JavaCodeStyleManager; import com.intellij.psi.controlFlow.AnalysisCanceledException; import com.intellij.psi.controlFlow.ControlFlow; import com.intellij.psi.controlFlow.ControlFlowUtil; import com.intellij.psi.util.*; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.hash.LinkedHashMap; import com.intellij.util.text.UniqueNameGenerator; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.*; import java.util.function.UnaryOperator; import static com.intellij.codeInsight.AnnotationUtil.CHECK_EXTERNAL; public class AnonymousCanBeLambdaInspection extends AbstractBaseJavaLocalInspectionTool { public static final Logger LOG = Logger.getInstance(AnonymousCanBeLambdaInspection.class); public boolean reportNotAnnotatedInterfaces = true; @Nls @NotNull @Override public String getGroupDisplayName() { return GroupNames.LANGUAGE_LEVEL_SPECIFIC_GROUP_NAME; } @Nls @NotNull @Override public String getDisplayName() { return "Anonymous type can be replaced with lambda"; } @Override public boolean isEnabledByDefault() { return true; } @NotNull @Override public String getShortName() { return "Convert2Lambda"; } @Nullable @Override public JComponent createOptionsPanel() { return new SingleCheckboxOptionsPanel("Report when interface is not annotated with @FunctionalInterface", this, "reportNotAnnotatedInterfaces"); } @NotNull @Override public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) { return new JavaElementVisitor() { @Override public void visitAnonymousClass(final PsiAnonymousClass aClass) { super.visitAnonymousClass(aClass); final PsiElement parent = aClass.getParent(); if (canBeConvertedToLambda(aClass, false, isOnTheFly || reportNotAnnotatedInterfaces, Collections.emptySet())) { final PsiElement lBrace = aClass.getLBrace(); LOG.assertTrue(lBrace != null); final TextRange rangeInElement = new TextRange(0, aClass.getStartOffsetInParent() + lBrace.getStartOffsetInParent()); ProblemHighlightType type = ProblemHighlightType.LIKE_UNUSED_SYMBOL; if (isOnTheFly && !reportNotAnnotatedInterfaces) { final PsiClass baseClass = aClass.getBaseClassType().resolve(); LOG.assertTrue(baseClass != null); if (!AnnotationUtil.isAnnotated(baseClass, CommonClassNames.JAVA_LANG_FUNCTIONAL_INTERFACE, CHECK_EXTERNAL)) { type = ProblemHighlightType.INFORMATION; } } holder.registerProblem(parent, "Anonymous #ref #loc can be replaced with lambda", type, rangeInElement, new ReplaceWithLambdaFix()); } } }; } static boolean hasRuntimeAnnotations(PsiMethod method, @NotNull Set<String> runtimeAnnotationsToIgnore) { PsiAnnotation[] annotations = method.getModifierList().getAnnotations(); for (PsiAnnotation annotation : annotations) { PsiJavaCodeReferenceElement ref = annotation.getNameReferenceElement(); PsiElement target = ref != null ? ref.resolve() : null; if (target instanceof PsiClass) { if (runtimeAnnotationsToIgnore.contains(((PsiClass)target).getQualifiedName())) { continue; } final PsiAnnotation retentionAnno = AnnotationUtil.findAnnotation((PsiClass)target, Retention.class.getName()); if (retentionAnno != null) { PsiAnnotationMemberValue value = retentionAnno.findAttributeValue("value"); if (value instanceof PsiReferenceExpression) { final PsiElement resolved = ((PsiReferenceExpression)value).resolve(); if (resolved instanceof PsiField && RetentionPolicy.RUNTIME.name().equals(((PsiField)resolved).getName())) { final PsiClass containingClass = ((PsiField)resolved).getContainingClass(); if (containingClass != null && RetentionPolicy.class.getName().equals(containingClass.getQualifiedName())) { return true; } } } } } } return false; } public static boolean hasForbiddenRefsInsideBody(PsiMethod method, PsiAnonymousClass aClass) { final ForbiddenRefsChecker checker = new ForbiddenRefsChecker(method, aClass); final PsiCodeBlock body = method.getBody(); LOG.assertTrue(body != null); body.accept(checker); return checker.hasForbiddenRefs(); } private static PsiType getInferredType(PsiAnonymousClass aClass, PsiMethod method) { final PsiExpression expression = (PsiExpression)aClass.getParent(); final PsiType psiType = PsiTypesUtil.getExpectedTypeByParent(expression); if (psiType != null) { return psiType; } PsiExpression topExpr = expression; while (topExpr.getParent() instanceof PsiParenthesizedExpression) { topExpr = (PsiExpression)topExpr.getParent(); } final PsiCall call = LambdaUtil.treeWalkUp(topExpr); if (call != null && call.resolveMethod() != null) { Object marker = new Object(); PsiTreeUtil.mark(aClass, marker); PsiCall copyCall = LambdaUtil.copyTopLevelCall(call); if (copyCall == null) return null; final PsiElement classArg = PsiTreeUtil.releaseMark(copyCall, marker); if (classArg instanceof PsiAnonymousClass) { PsiExpression lambda = JavaPsiFacade.getElementFactory(aClass.getProject()) .createExpressionFromText(ReplaceWithLambdaFix.composeLambdaText(method), expression); lambda = (PsiExpression)classArg.getParent().replace(lambda); ((PsiLambdaExpression)lambda).getBody().replace(method.getBody()); final PsiType interfaceType; if (copyCall.resolveMethod() == null) { return PsiType.NULL; } else { interfaceType = ((PsiLambdaExpression)lambda).getFunctionalInterfaceType(); } return interfaceType; } } return PsiType.NULL; } public static boolean canBeConvertedToLambda(PsiAnonymousClass aClass, boolean acceptParameterizedFunctionTypes, @NotNull Set<String> ignoredRuntimeAnnotations) { return canBeConvertedToLambda(aClass, acceptParameterizedFunctionTypes, true, ignoredRuntimeAnnotations); } public static boolean isLambdaForm(PsiAnonymousClass aClass, Set<String> ignoredRuntimeAnnotations) { PsiMethod[] methods = aClass.getMethods(); if(methods.length != 1) return false; PsiMethod method = methods[0]; return aClass.getFields().length == 0 && aClass.getInnerClasses().length == 0 && aClass.getInitializers().length == 0 && method.getBody() != null && method.getDocComment() == null && !hasRuntimeAnnotations(method, ignoredRuntimeAnnotations) && !method.hasModifierProperty(PsiModifier.SYNCHRONIZED) && !method.hasModifierProperty(PsiModifier.STRICTFP) && !hasForbiddenRefsInsideBody(method, aClass); } public static boolean canBeConvertedToLambda(PsiAnonymousClass aClass, boolean acceptParameterizedFunctionTypes, boolean reportNotAnnotatedInterfaces, @NotNull Set<String> ignoredRuntimeAnnotations) { PsiElement parent = aClass.getParent(); final PsiElement lambdaContext = parent != null ? parent.getParent() : null; if (lambdaContext == null || !LambdaUtil.isValidLambdaContext(lambdaContext) && !(lambdaContext instanceof PsiReferenceExpression)) return false; if (PsiUtil.getLanguageLevel(aClass).isAtLeast(LanguageLevel.JDK_1_8)) { final PsiClassType baseClassType = aClass.getBaseClassType(); final PsiClassType.ClassResolveResult resolveResult = baseClassType.resolveGenerics(); final PsiClass baseClass = resolveResult.getElement(); if (baseClass == null || !reportNotAnnotatedInterfaces && !AnnotationUtil.isAnnotated(baseClass, CommonClassNames.JAVA_LANG_FUNCTIONAL_INTERFACE, CHECK_EXTERNAL)) { return false; } final PsiMethod interfaceMethod = LambdaUtil.getFunctionalInterfaceMethod(resolveResult); if (interfaceMethod != null && (acceptParameterizedFunctionTypes || !interfaceMethod.hasTypeParameters())) { if (isLambdaForm(aClass, ignoredRuntimeAnnotations)) { final PsiMethod method = aClass.getMethods()[0]; return getInferredType(aClass, method) != null; } } } return false; } public static PsiExpression replaceAnonymousWithLambda(@NotNull PsiElement anonymousClass, PsiType expectedType) { PsiNewExpression newArrayExpression = (PsiNewExpression)JavaPsiFacade.getElementFactory(anonymousClass.getProject()) .createExpressionFromText("new " + expectedType.getCanonicalText() + "[]{" + anonymousClass.getText() + "}", anonymousClass); PsiArrayInitializerExpression initializer = newArrayExpression.getArrayInitializer(); LOG.assertTrue(initializer != null); return replacePsiElementWithLambda(initializer.getInitializers()[0], true, false); } public static PsiExpression replacePsiElementWithLambda(@NotNull PsiElement element, final boolean ignoreEqualsMethod, boolean forceIgnoreTypeCast) { if (!(element instanceof PsiNewExpression)) { return null; } final PsiNewExpression newExpression = (PsiNewExpression)element; final PsiAnonymousClass anonymousClass = newExpression.getAnonymousClass(); if (anonymousClass == null) return null; final PsiMethod method; if (ignoreEqualsMethod) { final List<PsiMethod> methods = ContainerUtil.filter(anonymousClass.getMethods(), method1 -> !"equals".equals(method1.getName())); method = methods.get(0); } else { method = anonymousClass.getMethods()[0]; } if (method == null || method.getBody() == null) return null; return generateLambdaByMethod(anonymousClass, method, lambda -> (PsiLambdaExpression)newExpression.replace(lambda), forceIgnoreTypeCast); } /** * Try convert given method of given anonymous class into lambda and replace given element. * * @param anonymousClass physical anonymous class containing method * @param method physical method to convert with non-empty body * @param replacer an operator which actually inserts a lambda into the file (possibly removing anonymous class) * and returns an inserted physical lambda * @param forceIgnoreTypeCast if false, type cast might be added if necessary * @return newly-generated lambda expression (possibly with typecast) */ @NotNull static PsiExpression generateLambdaByMethod(PsiAnonymousClass anonymousClass, PsiMethod method, UnaryOperator<PsiLambdaExpression> replacer, boolean forceIgnoreTypeCast) { ChangeContextUtil.encodeContextInfo(anonymousClass, true); final String canonicalText = anonymousClass.getBaseClassType().getCanonicalText(); final PsiCodeBlock body = method.getBody(); LOG.assertTrue(body != null); final Collection<PsiComment> comments = collectCommentsOutsideMethodBody(anonymousClass.getParent(), body); final Project project = anonymousClass.getProject(); final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project); final String withoutTypesDeclared = ReplaceWithLambdaFix.composeLambdaText(method); PsiLambdaExpression lambdaExpression = (PsiLambdaExpression)elementFactory.createExpressionFromText(withoutTypesDeclared, anonymousClass); PsiElement lambdaBody = lambdaExpression.getBody(); LOG.assertTrue(lambdaBody != null); lambdaBody.replace(body); lambdaExpression = replacer.apply(lambdaExpression); final Set<PsiVariable> variables = new HashSet<>(); final Set<String> usedLocalNames = new HashSet<>(); collectLocalVariablesDefinedInsideLambda(lambdaExpression, variables, usedLocalNames); ReplaceWithLambdaFix .giveUniqueNames(project, elementFactory, lambdaExpression, usedLocalNames, variables.toArray(new PsiVariable[0])); final PsiExpression singleExpr = RedundantLambdaCodeBlockInspection.isCodeBlockRedundant(lambdaExpression.getBody()); if (singleExpr != null) { lambdaExpression.getBody().replace(singleExpr); } ChangeContextUtil.decodeContextInfo(lambdaExpression, null, null); restoreComments(comments, lambdaExpression); final JavaCodeStyleManager javaCodeStyleManager = JavaCodeStyleManager.getInstance(project); if (forceIgnoreTypeCast) { return (PsiExpression)javaCodeStyleManager.shortenClassReferences(lambdaExpression); } PsiTypeCastExpression typeCast = (PsiTypeCastExpression)elementFactory .createExpressionFromText("(" + canonicalText + ")" + withoutTypesDeclared, lambdaExpression); final PsiExpression typeCastOperand = typeCast.getOperand(); LOG.assertTrue(typeCastOperand instanceof PsiLambdaExpression); final PsiElement fromText = ((PsiLambdaExpression)typeCastOperand).getBody(); LOG.assertTrue(fromText != null); lambdaBody = lambdaExpression.getBody(); LOG.assertTrue(lambdaBody != null); fromText.replace(lambdaBody); ((PsiLambdaExpression)typeCastOperand).getParameterList().replace(lambdaExpression.getParameterList()); typeCast = (PsiTypeCastExpression)lambdaExpression.replace(typeCast); if (RedundantCastUtil.isCastRedundant(typeCast)) { final PsiExpression operand = typeCast.getOperand(); LOG.assertTrue(operand != null); return (PsiExpression)typeCast.replace(operand); } return (PsiExpression)javaCodeStyleManager.shortenClassReferences(typeCast); } @NotNull static Collection<PsiComment> collectCommentsOutsideMethodBody(PsiElement anonymousClass, PsiCodeBlock body) { final Collection<PsiComment> psiComments = PsiTreeUtil.findChildrenOfType(anonymousClass, PsiComment.class); psiComments.removeIf(comment -> PsiTreeUtil.isAncestor(body, comment, false)); return ContainerUtil.map(psiComments, (comment) -> (PsiComment)comment.copy()); } private static void collectLocalVariablesDefinedInsideLambda(PsiLambdaExpression lambdaExpression, final Set<PsiVariable> variables, Set<String> namesOfVariablesInTheBlock) { PsiElement block = PsiUtil.getTopLevelEnclosingCodeBlock(lambdaExpression, null); if (block == null) { block = lambdaExpression; } block.accept(new JavaRecursiveElementWalkingVisitor() { @Override public void visitVariable(PsiVariable variable) { super.visitVariable(variable); if (!(variable instanceof PsiField)) { variables.add(variable); } } }); final PsiResolveHelper helper = PsiResolveHelper.SERVICE.getInstance(lambdaExpression.getProject()); for (Iterator<PsiVariable> iterator = variables.iterator(); iterator.hasNext(); ) { PsiVariable local = iterator.next(); final String localName = local.getName(); if (localName == null || shadowingResolve(localName, lambdaExpression, helper) || !PsiTreeUtil.isAncestor(lambdaExpression, local, false)) { iterator.remove(); namesOfVariablesInTheBlock.add(localName); } } } private static boolean shadowingResolve(String localName, PsiLambdaExpression lambdaExpression, PsiResolveHelper helper) { final PsiVariable variable = helper.resolveReferencedVariable(localName, lambdaExpression); return variable == null || variable instanceof PsiField; } private static class ReplaceWithLambdaFix implements LocalQuickFix, HighPriorityAction { @NotNull @Override public String getFamilyName() { return "Replace with lambda"; } @Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { final PsiElement element = descriptor.getPsiElement(); if (element != null) { replacePsiElementWithLambda(element, false, false); } } private static void giveUniqueNames(Project project, final PsiElementFactory elementFactory, PsiElement body, Set<String> usedLocalNames, PsiVariable[] parameters) { final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project); final Map<PsiVariable, String> names = new HashMap<>(); for (PsiVariable parameter : parameters) { String parameterName = parameter.getName(); String uniqueVariableName = UniqueNameGenerator.generateUniqueName(codeStyleManager.suggestUniqueVariableName(parameterName, parameter.getParent(), false), usedLocalNames); if (!Comparing.equal(parameterName, uniqueVariableName)) { names.put(parameter, uniqueVariableName); } } if (names.isEmpty()) return; final LinkedHashMap<PsiElement, PsiElement> replacements = new LinkedHashMap<>(); body.accept(new JavaRecursiveElementWalkingVisitor() { @Override public void visitVariable(PsiVariable variable) { super.visitVariable(variable); final String newName = names.get(variable); if (newName != null) { replacements.put(variable.getNameIdentifier(), elementFactory.createIdentifier(newName)); } } @Override public void visitReferenceExpression(PsiReferenceExpression expression) { super.visitReferenceExpression(expression); final PsiElement resolve = expression.resolve(); if (resolve instanceof PsiVariable) { final String newName = names.get(resolve); if (newName != null) { replacements.put(expression, elementFactory.createExpressionFromText(newName, expression)); } } } }); for (PsiElement psiElement : replacements.keySet()) { psiElement.replace(replacements.get(psiElement)); } } private static String composeLambdaText(PsiMethod method) { final StringBuilder buf = new StringBuilder(); final PsiParameter[] parameters = method.getParameterList().getParameters(); if (parameters.length != 1) { buf.append("("); } buf.append(StringUtil.join(parameters, ReplaceWithLambdaFix::composeParameter, ",")); if (parameters.length != 1) { buf.append(")"); } buf.append("-> {}"); return buf.toString(); } private static String composeParameter(PsiParameter parameter) { String parameterName = parameter.getName(); if (parameterName == null) { parameterName = ""; } return parameterName; } } public static boolean functionalInterfaceMethodReferenced(PsiMethod psiMethod, PsiAnonymousClass anonymClass, PsiCallExpression callExpression) { if (psiMethod != null && !psiMethod.hasModifierProperty(PsiModifier.STATIC)) { final PsiClass containingClass = psiMethod.getContainingClass(); if (containingClass != null && CommonClassNames.JAVA_LANG_OBJECT.equals(containingClass.getQualifiedName())) { return false; } if (callExpression instanceof PsiMethodCallExpression && ((PsiMethodCallExpression)callExpression).getMethodExpression().isQualified()) { return false; } if (InheritanceUtil.isInheritorOrSelf(anonymClass, containingClass, true) && !InheritanceUtil.hasEnclosingInstanceInScope(containingClass, anonymClass.getParent(), true, true)) { return true; } } return false; } public static void restoreComments(Collection<PsiComment> comments, PsiElement lambda) { PsiElement anchor = PsiTreeUtil.getParentOfType(lambda, PsiStatement.class, PsiField.class); if (anchor == null) { anchor = lambda; } for (PsiComment comment : comments) { anchor.getParent().addBefore(comment, anchor); } } private static class ForbiddenRefsChecker extends JavaRecursiveElementWalkingVisitor { private boolean myBodyContainsForbiddenRefs; private final PsiMethod myMethod; private final PsiAnonymousClass myAnonymClass; public ForbiddenRefsChecker(PsiMethod method, PsiAnonymousClass aClass) { myMethod = method; myAnonymClass = aClass; } @Override public void visitMethodCallExpression(PsiMethodCallExpression methodCallExpression) { if (myBodyContainsForbiddenRefs) return; super.visitMethodCallExpression(methodCallExpression); final PsiMethod psiMethod = methodCallExpression.resolveMethod(); if (psiMethod == myMethod || functionalInterfaceMethodReferenced(psiMethod, myAnonymClass, methodCallExpression) || psiMethod != null && !methodCallExpression.getMethodExpression().isQualified() && "getClass".equals(psiMethod.getName()) && psiMethod.getParameterList().getParametersCount() == 0) { myBodyContainsForbiddenRefs = true; } } @Override public void visitThisExpression(PsiThisExpression expression) { if (myBodyContainsForbiddenRefs) return; if (expression.getQualifier() == null) { myBodyContainsForbiddenRefs = true; } } @Override public void visitSuperExpression(PsiSuperExpression expression) { if (myBodyContainsForbiddenRefs) return; if (expression.getQualifier() == null) { myBodyContainsForbiddenRefs = true; } } @Override public void visitVariable(PsiVariable variable) { if (myBodyContainsForbiddenRefs) return; super.visitVariable(variable); } @Override public void visitReferenceExpression(PsiReferenceExpression expression) { if (myBodyContainsForbiddenRefs) return; super.visitReferenceExpression(expression); if (!(expression.getParent() instanceof PsiMethodCallExpression)) { final PsiMember member = PsiTreeUtil.getParentOfType(myAnonymClass, PsiMember.class); if (member instanceof PsiField || member instanceof PsiClassInitializer) { final PsiElement resolved = expression.resolve(); final PsiClass memberContainingClass = member.getContainingClass(); if (resolved instanceof PsiField && memberContainingClass != null && PsiTreeUtil.isAncestor(((PsiField)resolved).getContainingClass(), memberContainingClass, false) && expression.getQualifierExpression() == null) { final PsiExpression initializer = ((PsiField)resolved).getInitializer(); if (initializer == null || resolved == member || initializer.getTextOffset() > myAnonymClass.getTextOffset() && ((PsiField)resolved).hasModifierProperty(PsiModifier.STATIC) == member.hasModifierProperty(PsiModifier.STATIC)) { myBodyContainsForbiddenRefs = true; } } } else { final PsiMethod method = PsiTreeUtil.getParentOfType(myAnonymClass, PsiMethod.class); if (method != null && method.isConstructor()) { final PsiElement resolved = expression.resolve(); if (resolved instanceof PsiField && ((PsiField)resolved).hasModifierProperty(PsiModifier.FINAL) && ((PsiField)resolved).getInitializer() == null && ((PsiField)resolved).getContainingClass() == method.getContainingClass()) { try { final PsiCodeBlock constructorBody = method.getBody(); if (constructorBody != null) { final ControlFlow flow = HighlightControlFlowUtil.getControlFlowNoConstantEvaluate(constructorBody); final int startOffset = flow.getStartOffset(myAnonymClass); final Collection<PsiVariable> writtenVariables = ControlFlowUtil.getWrittenVariables(flow, 0, startOffset, false); if (!writtenVariables.contains(resolved)) { myBodyContainsForbiddenRefs = true; } } } catch (AnalysisCanceledException e) { myBodyContainsForbiddenRefs = true; } } } } } } public boolean hasForbiddenRefs() { return myBodyContainsForbiddenRefs; } } }
apache-2.0
nvlled/storemi
resources/public/js/ui.js
11391
/** @jsx React.DOM */ var View = React.createClass({displayName: 'View', getInitialState: function() { var state = { data: this.props.data, bindings: this.props.bindings, activeChapterLabel: '', } var chapters = this.props.data.chapters; if (_.size(chapters) > 0) { state.activeChapterLabel = chapters[0].label; } state.visibility = _.reduce(chapters, function(v, chapter) { v[chapter.label] = false; return v; }, {}); return state; }, setBinding: function(key, val) { var bindings = this.state.bindings; bindings.set(key, val); this.setState({ bindings: bindings, }); }, update: function(data) { this.setState({ data: data, }); }, selectChapter: function(chapterLabel) { var visibility = _.clone(this.state.visibility); var activeChapterLabel = this.state.activeChapterLabel; visibility[chapterLabel] = true; if (chapterLabel != activeChapterLabel) visibility[activeChapterLabel] = false; this.setState({ visibility: visibility, activeChapterLabel: chapterLabel, }); return false; }, render: function() { var self = this; var data = this.state.data; var visibility = this.state.visibility; var chapters = data.chapters.map(function(chapter) { var visible = visibility[chapter.label]; return ( Chapter( {data:chapter, visible:visible, setBinding:self.setBinding, bindings:self.state.bindings, defaultBindings:data.defaultBindings, onChapterSelect:self.selectChapter} ) ); }); return ( React.DOM.div(null, React.DOM.h1(null, data.storyTitle), React.DOM.p(null, data.synopsis), React.DOM.hr(null ), ChapterList( {data:data.chapters, onChapterSelect:this.selectChapter} ), React.DOM.hr(null ), ChapterContainer( {ref:"chapters"}, chapters) ) ); } }); var ChapterContainer = React.createClass({displayName: 'ChapterContainer', render: function() { return ( React.DOM.div(null, this.props.children) ); } }); var ChapterList = React.createClass({displayName: 'ChapterList', render: function() { var self = this; var contents = self.props.data.map(function(chapter) { var handler = self.props.onChapterSelect.bind(null, chapter.label); return ( React.DOM.li(null, React.DOM.a( {href:"", onClick:handler}, chapter.title ) ) ) }); return ( React.DOM.ul(null, contents) ); } }); var Chapter = React.createClass({displayName: 'Chapter', getInitialState: function() { var scenes = this.props.data.scenes || []; var state = { activeScene: {}, }; if (_.size(scenes) > 0) { state.activeScene = scenes[0]; } state.visibility = _.reduce(scenes, function(v, scene) { v[scene.label] = false; return v; }, {}); return state; }, selectScene: function(scene) { var visibility = _.clone(this.state.visibility); var activeScene = this.state.activeScene; visibility[scene.label] = true; if (scene.label != activeScene.label) visibility[activeScene.label] = false; this.setState({ visibility: visibility, activeScene: scene, }); //return false; }, componentWillReceiveProps: function() { var scenes = this.props.data.scenes || []; var activeScene = this.state.activeScene; var updatedScene = _.find(scenes, function(scene) { if (scene.label == activeScene.label) return true; }); if (updatedScene) { this.selectScene(updatedScene); } }, render: function() { var self = this; var data = this.props.data; var visibility = this.state.visibility; var scenes = _.map(data.scenes, function(scene) { return ( Scene( {onChapterSelect:self.props.onChapterSelect, setBinding:self.props.setBinding, bindings:self.props.bindings, defaultBindings:self.props.defaultBindings, otherScenes:data.scenes, visible:visibility[scene.label], data:scene} ) ); }); var sceneLinks = _.map(data.scenes, function(scene) { return ( React.DOM.li(null, React.DOM.a( {href:"#"+scene.label, onClick:self.selectScene.bind(null, scene)}, scene.title ) ) ); }); var style = toDisplayStyle(this.props.visible); return ( React.DOM.div( {style:style}, React.DOM.h2(null, data.title), React.DOM.p(null, "Scenes:"), React.DOM.ul(null, sceneLinks), React.DOM.hr(null ), React.DOM.div( {ref:"scenes", className:"scenes"}, scenes) /*<Scene ref='scene' otherScenes={scenes} data={this.state.activeScene} /> */ ) ); } }); var Scene = React.createClass({displayName: 'Scene', getInitialState: function() { return { subsceneLabel: '', } }, componentWillReceiveProps: function() { var subscene = this.state.subscene; if (subscene && subscene.props.data) this.showSubScene(subscene.props.data.label); }, setSubscene: function(label) { this.setState({ subsceneLabel: label }); //return false; }, getSubscene: function() { var subsceneLabel = this.state.subsceneLabel; var data = _.find(this.props.otherScenes, function(scene) { return scene.label == subsceneLabel; }); var subscene; var key = this.props.data.label + "->" + subsceneLabel; if (data) { subscene = ( Scene( {setBinding:this.props.setBinding, bindings:this.props.bindings, defaultBindings:this.props.defaultBindings, onChapterSelect:this.props.onChapterSelect, key:key, visible:true, otherScenes:this.props.otherScenes, data:data} ) ); } else { subscene = React.DOM.p(null) } return subscene; }, createSceneLink: function(elem, mappings) { var label = elem.label; var toScene = mappings[label] || ""; return ( React.DOM.a( {className:"scene-link", href:"#"+toScene, onClick:this.setSubscene.bind(null, toScene)}, elem.text ) ); }, createChapterLink: function(elem, mappings) { var label = elem.label; var toChapter = mappings[label] || "nope"; var handler = this.props.onChapterSelect; return ( React.DOM.a( {className:"chapter-link", href:"#"+toChapter, onClick:handler.bind(null, toChapter)}, elem.text ) ); }, createImage: function(elem, mappings) { var label = elem.label; var url = mappings[label] || ""; return React.DOM.img( {src:url} ) }, createInput: function(elem, mappings) { var self = this; var label = elem.label; var toScene = mappings[label] || ""; var key = elem.text; return ( React.DOM.span( {className:"game-input"}, React.DOM.input( {ref:"input", defaultValue:self.props.bindings.get(key), onKeyUp:onKeyUp} ), React.DOM.a( {ref:"link", href:"#"+toScene, onClick:handler}, "[",elem.buttonVal,"]" ) ) ); function handler() { self.setSubscene(toScene); var input = self.refs.input.getDOMNode(); input.value = input.value || self.props.defaultBindings[key]; self.props.setBinding(key, input.value); } function onKeyUp(e) { if (e.keyCode == 13) { self.refs.link.getDOMNode().click(); } } }, br: function() { return React.DOM.br(null ); }, render: function() { var data = this.props.data; var mappings = data.mappings; var self = this; var contents = _.map(data.contents, function(elem) { if (typeof elem === "string") { return intercalate(elem.split("\n"), self.br); } switch (elem.name) { case "LINK": return self.createSceneLink(elem, mappings); case "CHAP": return self.createChapterLink(elem, mappings); case "IMG": return self.createImage(elem, mappings); case "INPUT": return self.createInput(elem, mappings); case "VAR": return ( React.DOM.b( {className:"game-var"}, self.props.bindings.get(elem.text) || self.props.defaultBindings[elem.text] ) ); } }); var style = toDisplayStyle(this.props.visible); var subscene = this.getSubscene(); return ( React.DOM.div( {style:style}, React.DOM.h3( {className:"scene-title"}, data.title, React.DOM.a( {href:"#"+data.label, name:data.label}, " # " ) ), React.DOM.p(null, contents), subscene ) ); } }); function toDisplayStyle(visible) { return { display: visible ? "inherit" : "none", } } function scrollViewTo(container, node, step) { var d = node.offsetTop - container.scrollTop; step = step || d; if (d != 0) { // normalize d = Math.abs(d)/d; } var x = 20, lastOffset; var timerId = setInterval(function() { container.scrollTop += d*(step - container.offsetTop); if (lastOffset == container.scrollTop || Math.abs(container.scrollTop - node.offsetTop) < x) clearInterval(timerId); lastOffset = container.scrollTop; }, 10); }
apache-2.0
hpgrahsl/kafka-connect-mongodb
src/main/java/at/grahsl/kafka/connect/mongodb/cdc/debezium/mongodb/MongoDbDelete.java
1737
/* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package at.grahsl.kafka.connect.mongodb.cdc.debezium.mongodb; import at.grahsl.kafka.connect.mongodb.cdc.CdcOperation; import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import com.mongodb.DBCollection; import com.mongodb.client.model.DeleteOneModel; import com.mongodb.client.model.WriteModel; import org.apache.kafka.connect.errors.DataException; import org.bson.BsonDocument; public class MongoDbDelete implements CdcOperation { @Override public WriteModel<BsonDocument> perform(SinkDocument doc) { BsonDocument keyDoc = doc.getKeyDoc().orElseThrow( () -> new DataException("error: key doc must not be missing for delete operation") ); try { BsonDocument filterDoc = BsonDocument.parse( "{"+DBCollection.ID_FIELD_NAME+ ":"+keyDoc.getString(MongoDbHandler.JSON_ID_FIELD_PATH) .getValue()+"}" ); return new DeleteOneModel<>(filterDoc); } catch(Exception exc) { throw new DataException(exc); } } }
apache-2.0
yecjl/AndroidStudyDemo
Day10/10_videoplayer_v2/src/test/java/com/study/videoplayer2/ExampleUnitTest.java
400
package com.study.videoplayer2; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
apache-2.0
Alacant/Rawr-RG
ItemButtonWithEnchant.cs
4566
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; namespace Rawr { public partial class ItemButtonWithEnchant : UserControl { public ItemButtonWithEnchant() { InitializeComponent(); buttonEnchant.MouseEnter += new EventHandler(buttonEnchant_MouseEnter); buttonEnchant.MouseLeave += new EventHandler(buttonEnchant_MouseLeave); ItemToolTip.Instance.SetToolTip(this, ""); } private IFormItemSelectionProvider _formItemSelection; public IFormItemSelectionProvider FormItemSelection { get { return _formItemSelection; } set { _formItemSelection = value; itemButtonItem.FormItemSelection = value; } } public override string Text { get { return itemButtonItem.Text; } set { itemButtonItem.Text = value; } } public CharacterSlot CharacterSlot { get { return itemButtonItem.CharacterSlot; } set { itemButtonItem.CharacterSlot = value; } } public ItemInstance SelectedItem { get { return itemButtonItem.SelectedItemInstance; } set { itemButtonItem.SelectedItemInstance = value; UpdateSelectedItem(); } } public int SelectedItemId { get { return itemButtonItem.SelectedItemId; } set { itemButtonItem.SelectedItemId = value; } } public Image ItemIcon { get { return itemButtonItem.ItemIcon; } set { itemButtonItem.ItemIcon = value; } } public bool UseVisualStyleBackColor { get { return itemButtonItem.UseVisualStyleBackColor; } set { itemButtonItem.UseVisualStyleBackColor = value; } } private Character _character; public Character Character { get { return _character; } set { if (_character != null) { _character.CalculationsInvalidated -= new EventHandler(_character_CalculationsInvalidated); } _character = itemButtonItem.Character = value; if (_character != null) { _character.CalculationsInvalidated += new EventHandler(_character_CalculationsInvalidated); //SelectedEnchant = _character.GetEnchantBySlot(CharacterSlot); } } } void _character_CalculationsInvalidated(object sender, EventArgs e) { UpdateSelectedItem(); } public int SelectedEnchantId { get { if (SelectedItem == null || SelectedItem.Enchant == null) return 0; else return SelectedItem.Enchant.Id; } } public Enchant SelectedEnchant { get { if (SelectedItem == null) return null; else return SelectedItem.Enchant; } } public bool ItemHidden { get { return itemButtonItem.ItemHidden; } set { itemButtonItem.ItemHidden = value; UpdateSelectedItem(); } } public void UpdateSelectedItem() { if (ItemHidden) { buttonEnchant.Text = ""; } else { if (Width < 50 || Height < 60) { if (SelectedEnchant == null) buttonEnchant.Text = ""; else buttonEnchant.Text = SelectedEnchant.ReallyShortName; } else if (SelectedEnchant == null) buttonEnchant.Text = ""; else buttonEnchant.Text = SelectedEnchant.ShortName; } itemButtonItem.UpdateSelectedItem(); } private void buttonEnchant_Click(object sender, EventArgs e) { IFormItemSelectionProvider form = (FormItemSelection ?? (this.FindForm() as IFormItemSelectionProvider)); if (form != null) form.FormItemSelection.Show(this, CharacterSlot); } void buttonEnchant_MouseLeave(object sender, EventArgs e) { ItemToolTip.Instance.Hide(this); } void buttonEnchant_MouseEnter(object sender, EventArgs e) { if (SelectedEnchant != null) { int tipX = this.Width; Item itemEnchant = new Item(SelectedEnchant.Name, ItemQuality.Temp, ItemType.None, -1 * (SelectedEnchant.Id + (10000 * (int)SelectedEnchant.Slot)), null, ItemSlot.None, null, false, SelectedEnchant.Stats, null, ItemSlot.None, ItemSlot.None, ItemSlot.None, 0, 0, ItemDamageType.Physical, 0, null); if (Parent.PointToScreen(Location).X + tipX + 249 > System.Windows.Forms.Screen.GetWorkingArea(this).Right) tipX = -249; ItemToolTip.Instance.Show(Character, itemEnchant, this, new Point(tipX, itemButtonItem.Height)); } } } }
apache-2.0
Nersent/Wexond
src/preloads/chrome-webstore.ts
2778
export const injectChromeWebstoreInstallButton = () => { const baseUrl = 'https://clients2.google.com/service/update2/crx?response=redirect&acceptformat=crx2,crx3&prodversion=%VERSION&x=id%3D%ID%26installsource%3Dondemand%26uc'; const ibText = 'Add to Wexond'; const ibTemplate = '<div role="button" class="dd-Va g-c-wb g-eg-ua-Uc-c-za g-c-Oc-td-jb-oa g-c" aria-label="' + ibText + '" tabindex="0" style="user-select: none;"><div class="g-c-Hf"><div class="g-c-x"><div class="g-c-R webstore-test-button-label">' + ibText + '</div></div></div></div>'; function waitForCreation(selector: any, callback: any) { const element = document.querySelector(selector); if (element != null) { callback(element); } else { setTimeout(() => { waitForCreation(selector, callback); }, 50); } } waitForCreation('.h-F-f-k.F-f-k', (element: any) => { element.addEventListener('DOMNodeInserted', (event: any) => { if (event.relatedNode != element) return; setTimeout(() => { // eslint-disable-next-line @typescript-eslint/no-use-before-define new (InstallButton as any)( event.target.querySelector('.h-e-f-Ra-c.e-f-oh-Md-zb-k'), ); }, 10); }); }); document.addEventListener('DOMNodeInserted', (event: any) => { setTimeout(() => { // eslint-disable-next-line @typescript-eslint/no-use-before-define Array.from(document.getElementsByClassName('a-na-d-K-ea')).forEach( (el) => { el.parentNode.removeChild(el); }, ); }, 10); }); function installPlugin( id: string, version = navigator.userAgent.match(/(?<=Chrom(e|ium)\/)\d+\.\d+/)[0], ) { window.location.href = baseUrl .replace('%VERSION', version) .replace('%ID', id); } function InstallButton( this: any, wrapper: any, id = document.URL.match(/(?<=\/)(\w+)(\?|$)/)[1], ) { if (wrapper == null) return; wrapper.innerHTML += ibTemplate; this.DOM = wrapper.children[0]; /* Styling */ this.DOM.addEventListener('mouseover', () => { this.DOM.className = 'dd-Va g-c-wb g-eg-ua-Uc-c-za g-c-0c-td-jb-oa g-c g-c-l'; }); this.DOM.addEventListener('mouseout', () => { this.DOM.className = 'dd-Va g-c-wb g-eg-ua-Uc-c-za g-c-Oc-td-jb-oa g-c'; }); this.DOM.addEventListener('mousedown', () => { this.DOM.className = 'dd-Va g-c-wb g-eg-ua-Uc-c-za g-c-Oc-td-jb-oa g-c g-c-Xc g-c-Sc-ci g-c-l g-c-Bd'; }); this.DOM.addEventListener('mouseup', () => { this.DOM.className = 'dd-Va g-c-wb g-eg-ua-Uc-c-za g-c-0c-td-jb-oa g-c g-c-l'; }); this.DOM.addEventListener('click', () => { installPlugin(id); }); } };
apache-2.0
tianfengjingjing/YOFC_Stage1_RightOracle
src/com/yofc/odn/contract/action/AddContractAttach.java
3937
package com.yofc.odn.contract.action; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import javax.annotation.Resource; import org.apache.struts2.ServletActionContext; import org.apache.struts2.components.ElseIf; import com.opensymphony.xwork2.ActionSupport; import com.yofc.odn.contract.service.ContractService; import com.yofc.odn.contract.service.impl.ContractServiceImpl; import com.yofc.odn.contract.util.ContractFileUnit; public class AddContractAttach extends ActionSupport { /* * (non-Javadoc) * * @该action主要是添加合同附件 */ private ContractService contractService; private String uploadFileType;//判断添加附件的类型 private Integer typeInteger = 0;//标志位是判断上传文件错误的原因 private String savepath; //文件保存的文件夹名字 private String contractNumber;//上传的合同号 private java.util.List<File> upload; private java.util.List<String> uploadFileName; private java.util.List<String> uploadContentType; public Integer getTypeInteger() { return typeInteger; } public java.util.List<File> getUpload() { return upload; } public void setUpload(java.util.List<File> upload) { this.upload = upload; } public java.util.List<String> getUploadFileName() { return uploadFileName; } public void setUploadFileName(java.util.List<String> uploadFileName) { this.uploadFileName = uploadFileName; } public java.util.List<String> getUploadContentType() { return uploadContentType; } public void setUploadContentType(java.util.List<String> uploadContentType) { this.uploadContentType = uploadContentType; } public void setTypeInteger(Integer typeInteger) { this.typeInteger = typeInteger; } public String getUploadFileType() { return uploadFileType; } public void setUploadFileType(String uploadFileType) { this.uploadFileType = uploadFileType; } public ContractService getContractService() { return contractService; } @Resource(name = "contractContractService") public void setContractService(ContractService contractService) { this.contractService = contractService; } public String getContractNumber() { return contractNumber; } public void setContractNumber(String contractNumber) { this.contractNumber = contractNumber; } public String getSavepath() throws Exception { return ServletActionContext.getServletContext().getRealPath(savepath); } public void setSavepath(String savepath) { this.savepath = savepath; } @Override public String execute(){ String filePath = ServletActionContext.getServletContext().getRealPath( "/" + savepath); if(upload!=null){ for(int i=0;i<upload.size();i++){ long size=getUpload().get(i).length(); int postion =getUploadFileName().get(i).lastIndexOf("."); String fileName=getUploadFileName().get(i).substring(postion+1); if (size > 409600 && !"txt".equals(fileName) && !"doc".equals(fileName) && !"docx".equals(fileName)) { typeInteger = 1; return "error"; }else if (size > 409600 && ("txt".equals(fileName) || "doc".equals(fileName) || "docx" .equals(fileName))) { typeInteger = 2; return "error"; } else if (size < 409600 && !"txt".equals(fileName) && !"doc".equals(fileName) && !"docx".equals(fileName)) { typeInteger = 3; return "error"; }else if(size < 409600 && ("txt".equals(fileName)) || "doc".equals(fileName) || "docx".equals(fileName)){ try { ContractFileUnit.AddContractAttach(getUpload().get(i), filePath+"\\"+getUploadFileName().get(i)); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //TODO file // contractService.upDataContract(contractNumber, filePath, uploadFileType); } } return "success"; }else{ return "error"; } //return "error"; } }
apache-2.0
cloudflare/unsee
assets/static/unsilence.js
3063
"use strict"; const $ = require("jquery"); const unsee = require("./unsee"); var selectors = { button: "button.silence-delete" }; function unsilenceButtonByID(alertmanagerURI, silenceID) { var amSelector = "[data-alertmanager-uri='" + alertmanagerURI + "']"; var silenceSelector = "[data-silence-id='" + silenceID + "']"; return $(selectors.button + amSelector + silenceSelector); } function markInProgress(alertmanagerURI, silenceID) { var elem = unsilenceButtonByID(alertmanagerURI, silenceID); elem.attr("title", "Silence is being deleted from Alertmanager"); elem.tooltip("fixTitle"); elem.find(".fa").removeClass("fa-trash-o").addClass("fa-refresh fa-spin"); } function markFailed(alertmanagerURI, silenceID, xhr) { var err = unsee.parseAJAXError(xhr, "Failed to delete this silence from Alertmanager"); var elem = unsilenceButtonByID(alertmanagerURI, silenceID); elem.attr("title", err); elem.tooltip("fixTitle"); elem.find(".fa").removeClass("fa-trash-o fa-refresh fa-spin").addClass("fa-exclamation-circle text-danger"); // Disable button, wait 5s and reset button to the original state elem.data("disabled", "true"); setTimeout(function() { elem.find(".fa").removeClass("fa-exclamation-circle text-danger").addClass("fa-trash-o"); elem.removeData("disabled"); elem.attr("title", "Delete this silence"); elem.tooltip("fixTitle"); }, 5000); } function markSuccess(alertmanagerURI, silenceID) { var elem = unsilenceButtonByID(alertmanagerURI, silenceID); elem.attr("title", "Silence deleted from Alertmanager"); elem.tooltip("fixTitle"); elem.find(".fa").removeClass("fa-trash-o fa-refresh fa-spin").addClass("fa-check-circle text-success"); // disable button so it's no longer clickable elem.data("disabled", "true"); } function deleteSilence(alertmanagerURI, silenceID) { $.ajax({ type: "DELETE", url: alertmanagerURI + "/api/v1/silence/" + silenceID, error: function(xhr) { markFailed(alertmanagerURI, silenceID, xhr); }, success: function() { markSuccess(alertmanagerURI, silenceID); }, dataType: "json" }); } function init() { $("body").on("click", selectors.button, function(event) { var elem = $(event.currentTarget); if (elem.data("disabled")) { // if we marked button as disabled then skip all actions // we use data attr to keep tooplips working on disabled buttons // setting attr(disabled) via jquery disables bootstrap tooltips return false; } // hide tooltip for button that triggers this action elem.tooltip("hide"); var amURI = elem.data("alertmanager-uri"); var silenceID = elem.data("silence-id"); // change icon to indicate progress markInProgress(amURI, silenceID); // send DELETE request to Alertmanager deleteSilence(amURI, silenceID); }); } exports.init = init;
apache-2.0
BUPTAnderson/apache-hive-2.1.1-src
ql/src/java/org/apache/hadoop/hive/ql/udf/generic/GenericUDFOPNumericPlus.java
3840
/** * 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.hadoop.hive.ql.udf.generic; import org.apache.hadoop.hive.common.type.HiveDecimal; import org.apache.hadoop.hive.ql.exec.Description; import org.apache.hadoop.hive.ql.exec.vector.VectorizedExpressions; import org.apache.hadoop.hive.ql.exec.vector.expressions.gen.*; import org.apache.hadoop.hive.serde2.io.ByteWritable; import org.apache.hadoop.hive.serde2.io.DoubleWritable; import org.apache.hadoop.hive.serde2.io.HiveDecimalWritable; import org.apache.hadoop.hive.serde2.io.ShortWritable; import org.apache.hadoop.hive.serde2.typeinfo.DecimalTypeInfo; import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory; import org.apache.hadoop.io.FloatWritable; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; /** * The reason that we list evaluate methods with all numeric types is for both * better performance and type checking (so we know int + int is still an int * instead of a double); otherwise a single method that takes (Number a, Number * b) and use a.doubleValue() == b.doubleValue() is enough. * * The case of int + double will be handled by implicit type casting using * UDFRegistry.implicitConvertable method. */ @Description(name = "+", value = "a _FUNC_ b - Returns a+b") public class GenericUDFOPNumericPlus extends GenericUDFBaseNumeric { public GenericUDFOPNumericPlus() { super(); this.opDisplayName = "+"; } @Override protected ByteWritable evaluate(ByteWritable left, ByteWritable right) { byteWritable.set((byte)(left.get() + right.get())); return byteWritable; } @Override protected ShortWritable evaluate(ShortWritable left, ShortWritable right) { shortWritable.set((short)(left.get() + right.get())); return shortWritable; } @Override protected IntWritable evaluate(IntWritable left, IntWritable right) { intWritable.set(left.get() + right.get()); return intWritable; } @Override protected LongWritable evaluate(LongWritable left, LongWritable right) { longWritable.set(left.get() + right.get()); return longWritable; } @Override protected FloatWritable evaluate(FloatWritable left, FloatWritable right) { floatWritable.set(left.get() + right.get()); return floatWritable; } @Override protected DoubleWritable evaluate(DoubleWritable left, DoubleWritable right) { doubleWritable.set(left.get() + right.get()); return doubleWritable; } @Override protected HiveDecimalWritable evaluate(HiveDecimal left, HiveDecimal right) { HiveDecimal dec = left.add(right); if (dec == null) { return null; } decimalWritable.set(dec); return decimalWritable; } @Override protected DecimalTypeInfo deriveResultDecimalTypeInfo(int prec1, int scale1, int prec2, int scale2) { int intPart = Math.max(prec1 - scale1, prec2 - scale2); int scale = Math.max(scale1, scale2); int prec = Math.min(intPart + scale + 1, HiveDecimal.MAX_PRECISION); return TypeInfoFactory.getDecimalTypeInfo(prec, scale); } }
apache-2.0
omacarena/only-short-poc
java.multiversion/v2dep/src/main/sample/multiversion/deps/CoreDependency.java
137
package sample.multiversion.deps; public class CoreDependency { public String getVersion() { return "core-dep-v2"; } }
apache-2.0
florianerhard/gedi
cglib/src/net/sf/cglib/beans/TestBeanMap.java
5695
/** * * Copyright 2017 Florian Erhard * * 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 2003,2004 The Apache Software 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. */ package net.sf.cglib.beans; import net.sf.cglib.proxy.*; import net.sf.cglib.core.Constants; import net.sf.cglib.core.ReflectUtils; import java.lang.reflect.Method; import java.util.*; import junit.framework.*; public class TestBeanMap extends net.sf.cglib.CodeGenTestCase { public static class TestBean { private String foo; private String bar = "x"; private String baz; private int quud; private int quick = 42; private int quip; public String getFoo() { return foo; } public void setFoo(String value) { foo = value; } public String getBar() { return bar; } public void setBaz(String value) { baz = value; } public int getQuud() { return quud; } public void setQuud(int value) { quud = value; } public int getQuick() { return quick; } public void setQuip(int value) { quip = value; } } public void testBeanMap() { TestBean bean = new TestBean(); BeanMap map = BeanMap.create(bean); assertTrue(map.size() == 6); assertTrue(map.get("foo") == null); map.put("foo", "FOO"); assertTrue("FOO".equals(map.get("foo"))); assertTrue(bean.getFoo().equals("FOO")); assertTrue("x".equals(map.get("bar"))); assertTrue(((Integer)map.get("quick")).intValue() == 42); map.put("quud", new Integer(13)); assertTrue(bean.getQuud() == 13); assertTrue(map.getPropertyType("foo").equals(String.class)); assertTrue(map.getPropertyType("quud").equals(Integer.TYPE)); assertTrue(map.getPropertyType("kdkkj") == null); } public void testEntrySet() { TestBean bean = new TestBean(); BeanMap map = BeanMap.create(bean); assertTrue(map.entrySet().size() == map.size()); } public void testNoUnderlyingBean() { BeanMap.Generator gen = new BeanMap.Generator(); gen.setBeanClass(TestBean.class); BeanMap map = gen.create(); TestBean bean = new TestBean(); assertTrue(bean.getFoo() == null); assertTrue(map.put(bean, "foo", "FOO") == null); assertTrue(bean.getFoo().equals("FOO")); assertTrue(map.get(bean, "foo").equals("FOO")); } public void testMixinMapIntoBean() { Object bean = new TestBean(); bean = mixinMapIntoBean(bean); ((TestBean)bean).setFoo("hello"); assertTrue(bean instanceof Map); assertTrue(((Map)bean).get("foo").equals("hello")); } public void testRequire() { BeanMap.Generator gen = new BeanMap.Generator(); gen.setBeanClass(TestBean.class); gen.setRequire(BeanMap.REQUIRE_GETTER); BeanMap map = gen.create(); assertTrue(map.containsKey("foo")); assertTrue(map.containsKey("bar")); assertTrue(!map.containsKey("baz")); } public static Object mixinMapIntoBean(final Object bean) { Enhancer e = new Enhancer(); e.setSuperclass(bean.getClass()); e.setInterfaces(new Class[]{ Map.class }); final Map map = BeanMap.create(bean); e.setCallbackFilter(new CallbackFilter() { public int accept(Method method) { return method.getDeclaringClass().equals(Map.class) ? 1 : 0; } }); e.setCallbacks(new Callback[]{ new Dispatcher() { public Object loadObject() { return bean; } }, new Dispatcher() { public Object loadObject() { return map; } } }); return e.create(); } // TODO: test different package // TODO: test change bean instance // TODO: test toString public TestBeanMap(String testName) { super(testName); } public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static Test suite() { return new TestSuite(TestBeanMap.class); } public void perform(ClassLoader loader) throws Throwable { //tested in enhancer test unit } public void testFailOnMemoryLeak() throws Throwable { } }
apache-2.0
hazendaz/assertj-core
src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_containsOnlyNulls_Test.java
1256
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * Copyright 2012-2021 the original author or authors. */ package org.assertj.core.api.objectarray; import org.assertj.core.api.ObjectArrayAssert; import org.assertj.core.api.ObjectArrayAssertBaseTest; import static org.mockito.Mockito.verify; /** * Tests for <code>{@link ObjectArrayAssert#containsOnlyNulls()}</code>. * * @author Billy Yuan */ class ObjectArrayAssert_containsOnlyNulls_Test extends ObjectArrayAssertBaseTest { @Override protected ObjectArrayAssert<Object> invoke_api_method() { return assertions.containsOnlyNulls(); } @Override protected void verify_internal_effects() { verify(arrays).assertContainsOnlyNulls(getInfo(assertions), getActual(assertions)); } }
apache-2.0
SixLabors/Fonts
tests/SixLabors.Fonts.Tests/Issues/Issues_47.cs
4033
// Copyright (c) Six Labors. // Licensed under the Apache License, Version 2.0. using System; using System.Collections.Generic; using System.Globalization; using SixLabors.Fonts.Tests.Fakes; using Xunit; namespace SixLabors.Fonts.Tests.Issues { public class Issues_47 { [Theory] [InlineData("hello world hello world hello world hello world")] public void LeftAlignedTextNewLineShouldNotStartWithWhiteSpace(string text) { Font font = CreateFont("\t x"); var r = new GlyphRenderer(); IReadOnlyList<GlyphLayout> layout = new TextLayout().GenerateLayout(text.AsSpan(), new TextOptions(new Font(font, 30)) { WrappingLength = 350, HorizontalAlignment = HorizontalAlignment.Left }); float lineYPos = layout[0].Location.Y; foreach (GlyphLayout glyph in layout) { if (lineYPos != glyph.Location.Y) { Assert.False(glyph.IsWhiteSpace()); lineYPos = glyph.Location.Y; } } } [Theory] [InlineData("hello world hello world hello world hello world", HorizontalAlignment.Left)] [InlineData("hello world hello world hello world hello world", HorizontalAlignment.Right)] [InlineData("hello world hello world hello world hello world", HorizontalAlignment.Center)] [InlineData("hello world hello world hello hello world", HorizontalAlignment.Left)] public void NewWrappedLinesShouldNotStartOrEndWithWhiteSpace(string text, HorizontalAlignment horizontalAlignment) { Font font = CreateFont("\t x"); var r = new GlyphRenderer(); IReadOnlyList<GlyphLayout> layout = new TextLayout().GenerateLayout(text.AsSpan(), new TextOptions(new Font(font, 30)) { WrappingLength = 350, HorizontalAlignment = horizontalAlignment }); float lineYPos = layout[0].Location.Y; for (int i = 0; i < layout.Count; i++) { GlyphLayout glyph = layout[i]; if (lineYPos != glyph.Location.Y) { Assert.False(glyph.IsWhiteSpace()); Assert.False(layout[i - 1].IsWhiteSpace()); lineYPos = glyph.Location.Y; } } } [Fact] public void WhiteSpaceAtStartOfTextShouldNotBeTrimmed() { Font font = CreateFont("\t x"); string text = " hello world hello world hello world"; var r = new GlyphRenderer(); IReadOnlyList<GlyphLayout> layout = new TextLayout().GenerateLayout(text.AsSpan(), new TextOptions(new Font(font, 30)) { WrappingLength = 350 }); Assert.True(layout[0].IsWhiteSpace()); Assert.True(layout[1].IsWhiteSpace()); Assert.True(layout[2].IsWhiteSpace()); } [Fact] public void WhiteSpaceAtTheEndOfTextShouldBeTrimmed() { Font font = CreateFont("\t x"); string text = "hello world hello world hello world "; var r = new GlyphRenderer(); IReadOnlyList<GlyphLayout> layout = new TextLayout().GenerateLayout(text.AsSpan(), new TextOptions(new Font(font, 30)) { WrappingLength = 350 }); Assert.False(layout[layout.Count - 1].IsWhiteSpace()); Assert.False(layout[layout.Count - 2].IsWhiteSpace()); Assert.False(layout[layout.Count - 3].IsWhiteSpace()); } public static Font CreateFont(string text) { var fc = (IFontMetricsCollection)new FontCollection(); Font d = fc.AddMetrics(new FakeFontInstance(text), CultureInfo.InvariantCulture).CreateFont(12); return new Font(d, 1); } } }
apache-2.0
sptz45/coeus
src/main/scala/com/tzavellas/coeus/core/HttpResponseGenerator.scala
1143
/* - Coeus web framework ------------------------- * * Licensed under the Apache License, Version 2.0. * * Author: Spiros Tzavellas */ package com.tzavellas.coeus.core import javax.servlet.http.HttpServletResponse import scala.collection.Set private object HttpResponseGenerator { /** * Writes an response for an HTTP OPTIONS request using the specified * allowed methods. */ def writeOptions(response: HttpServletResponse, methods: Set[String]) { response.setStatus(HttpServletResponse.SC_OK) response.setHeader("Allow", methods.mkString(", ")) response.setHeader("Cache-Control", "no-cache, no-store") response.setHeader("Content-Length", "0") response.flushBuffer() } /** * Writes a response for <em>405 Method Not Allowed</em> that includes * an <em>Allow</em> header with the allowed methods. */ def writeMethodNotAllowed(response: HttpServletResponse, methods: Set[String]) { response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED) response.setHeader("Allow", methods.mkString(", ")) response.setHeader("Content-Length", "0") response.flushBuffer() } }
apache-2.0
fhalim/NServiceBus.PostgreSQL
NServiceBus.PostgreSQL/Stats.cs
418
namespace NServiceBus.PostgreSQL { using System; public static class Stats { public static event EventHandler<MethodExecutionInfo> MethodExecuted; public static void Raise(Object sender, MethodExecutionInfo executionInfo) { if (MethodExecuted != null) { MethodExecuted(sender, executionInfo); } } } }
apache-2.0
hubme/WorkHelperApp
javalib/src/main/java/com/example/serializable/ExternalizableSample.java
1832
package com.example.serializable; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; /** * @author VanceKing * @since 2018/4/23. */ class ExternalizableSample { public static void main(String[] args) { testExternalizable(); } private static void testExternalizable() { String path = "c://user.txt"; Person person = new Person(100, "Vance"); System.out.println("序列化:" + person.toString()); Utils.serialize(person, path); Person person2 = (Person) Utils.unSerialize(path); System.out.println("反序列化:" + person2.toString()); System.out.println("前后对象相同(==)吗?: " + (person == person2)); } private static class Person implements Externalizable { private int id; //此时用 transient 修饰没有意义。因为自己控制序列化过程。 private transient String name; public Person() { } public Person(int id, String name) { this.id = id; this.name = name; } //实现序列化 @Override public void writeExternal(ObjectOutput objectOutput) throws IOException { objectOutput.writeObject(name); objectOutput.writeObject(id); } //实现反序列化 @Override public void readExternal(ObjectInput objectInput) throws IOException, ClassNotFoundException { name = (String) objectInput.readObject(); id = (Integer) objectInput.readObject(); } @Override public String toString() { return "Person{" + "id=" + id + ", name='" + name + '\'' + '}'; } } }
apache-2.0
equella/Equella
Source/Plugins/Core/com.equella.core/src/com/tle/core/harvester/oai/verb/ListMetadataFormats.java
1807
/* * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * The Apereo Foundation licenses this file to you under the Apache License, * Version 2.0, (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tle.core.harvester.oai.verb; import com.tle.core.harvester.oai.data.List; import com.tle.core.harvester.oai.data.Response; import com.tle.core.harvester.oai.data.ResumptionToken; import com.tle.core.harvester.oai.error.IdDoesNotExistException; import com.tle.core.harvester.oai.error.NoMetadataFormatsException; /** */ public class ListMetadataFormats extends Verb { private static final String VERB = "ListMetadataFormats"; public ListMetadataFormats() { super(); } public ListMetadataFormats(ResumptionToken token) { addParamater(RESUMPTION_TOKEN, token.getToken()); } public ListMetadataFormats(String identifier) { addParamater(IDENTIFIER, identifier); } @Override public String getVerb() { return VERB; } public List getResult() throws IdDoesNotExistException, NoMetadataFormatsException { Response response = call(); checkIdDoesNotExistError(response); checkNoMetadataFormats(response); return listFromXML(response); } }
apache-2.0
laimis/lucenenet
src/Lucene.Net.Tests.QueryParser/Classic/TestMultiAnalyzer.cs
11484
/* * * 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. * */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; using Lucene.Net.Analysis; using Lucene.Net.Analysis.TokenAttributes; using Lucene.Net.Search; using Lucene.Net.Util; namespace Lucene.Net.QueryParsers.Classic { [TestFixture] public class TestMultiAnalyzer_ : BaseTokenStreamTestCase { private static int multiToken = 0; [Test] public virtual void TestMultiAnalyzer() { QueryParser qp = new QueryParser(TEST_VERSION_CURRENT, "", new MultiAnalyzer()); // trivial, no multiple tokens: assertEquals("foo", qp.Parse("foo").toString()); assertEquals("foo", qp.Parse("\"foo\"").toString()); assertEquals("foo foobar", qp.Parse("foo foobar").toString()); assertEquals("\"foo foobar\"", qp.Parse("\"foo foobar\"").toString()); assertEquals("\"foo foobar blah\"", qp.Parse("\"foo foobar blah\"").toString()); // two tokens at the same position: assertEquals("(multi multi2) foo", qp.Parse("multi foo").toString()); assertEquals("foo (multi multi2)", qp.Parse("foo multi").toString()); assertEquals("(multi multi2) (multi multi2)", qp.Parse("multi multi").toString()); assertEquals("+(foo (multi multi2)) +(bar (multi multi2))", qp.Parse("+(foo multi) +(bar multi)").toString()); assertEquals("+(foo (multi multi2)) field:\"bar (multi multi2)\"", qp.Parse("+(foo multi) field:\"bar multi\"").toString()); // phrases: assertEquals("\"(multi multi2) foo\"", qp.Parse("\"multi foo\"").toString()); assertEquals("\"foo (multi multi2)\"", qp.Parse("\"foo multi\"").toString()); assertEquals("\"foo (multi multi2) foobar (multi multi2)\"", qp.Parse("\"foo multi foobar multi\"").toString()); // fields: assertEquals("(field:multi field:multi2) field:foo", qp.Parse("field:multi field:foo").toString()); assertEquals("field:\"(multi multi2) foo\"", qp.Parse("field:\"multi foo\"").toString()); // three tokens at one position: assertEquals("triplemulti multi3 multi2", qp.Parse("triplemulti").toString()); assertEquals("foo (triplemulti multi3 multi2) foobar", qp.Parse("foo triplemulti foobar").toString()); // phrase with non-default slop: assertEquals("\"(multi multi2) foo\"~10", qp.Parse("\"multi foo\"~10").toString()); // phrase with non-default boost: assertEquals("\"(multi multi2) foo\"^2.0", qp.Parse("\"multi foo\"^2").toString()); // phrase after changing default slop qp.PhraseSlop=(99); assertEquals("\"(multi multi2) foo\"~99 bar", qp.Parse("\"multi foo\" bar").toString()); assertEquals("\"(multi multi2) foo\"~99 \"foo bar\"~2", qp.Parse("\"multi foo\" \"foo bar\"~2").toString()); qp.PhraseSlop=(0); // non-default operator: qp.DefaultOperator=(QueryParserBase.AND_OPERATOR); assertEquals("+(multi multi2) +foo", qp.Parse("multi foo").toString()); } [Test] public virtual void TestMultiAnalyzerWithSubclassOfQueryParser() { DumbQueryParser qp = new DumbQueryParser("", new MultiAnalyzer()); qp.PhraseSlop = (99); // modified default slop // direct call to (super's) getFieldQuery to demonstrate differnce // between phrase and multiphrase with modified default slop assertEquals("\"foo bar\"~99", qp.GetSuperFieldQuery("", "foo bar", true).toString()); assertEquals("\"(multi multi2) bar\"~99", qp.GetSuperFieldQuery("", "multi bar", true).toString()); // ask sublcass to parse phrase with modified default slop assertEquals("\"(multi multi2) foo\"~99 bar", qp.Parse("\"multi foo\" bar").toString()); } [Test] public virtual void TestPosIncrementAnalyzer() { #pragma warning disable 612, 618 QueryParser qp = new QueryParser(LuceneVersion.LUCENE_40, "", new PosIncrementAnalyzer()); #pragma warning restore 612, 618 assertEquals("quick brown", qp.Parse("the quick brown").toString()); assertEquals("quick brown fox", qp.Parse("the quick brown fox").toString()); } /// <summary> /// Expands "multi" to "multi" and "multi2", both at the same position, /// and expands "triplemulti" to "triplemulti", "multi3", and "multi2". /// </summary> private class MultiAnalyzer : Analyzer { protected internal override TokenStreamComponents CreateComponents(string fieldName, System.IO.TextReader reader) { Tokenizer result = new MockTokenizer(reader, MockTokenizer.WHITESPACE, true); return new TokenStreamComponents(result, new TestFilter(result)); } } private sealed class TestFilter : TokenFilter { private string prevType; private int prevStartOffset; private int prevEndOffset; private readonly ICharTermAttribute termAtt; private readonly IPositionIncrementAttribute posIncrAtt; private readonly IOffsetAttribute offsetAtt; private readonly ITypeAttribute typeAtt; public TestFilter(TokenStream @in) : base(@in) { termAtt = AddAttribute<ICharTermAttribute>(); posIncrAtt = AddAttribute<IPositionIncrementAttribute>(); offsetAtt = AddAttribute<IOffsetAttribute>(); typeAtt = AddAttribute<ITypeAttribute>(); } public override sealed bool IncrementToken() { if (multiToken > 0) { termAtt.SetEmpty().Append("multi" + (multiToken + 1)); offsetAtt.SetOffset(prevStartOffset, prevEndOffset); typeAtt.Type = (prevType); posIncrAtt.PositionIncrement = (0); multiToken--; return true; } else { bool next = m_input.IncrementToken(); if (!next) { return false; } prevType = typeAtt.Type; prevStartOffset = offsetAtt.StartOffset; prevEndOffset = offsetAtt.EndOffset; string text = termAtt.toString(); if (text.equals("triplemulti")) { multiToken = 2; return true; } else if (text.equals("multi")) { multiToken = 1; return true; } else { return true; } } } public override void Reset() { base.Reset(); this.prevType = null; this.prevStartOffset = 0; this.prevEndOffset = 0; } } /// <summary> /// Analyzes "the quick brown" as: quick(incr=2) brown(incr=1). /// Does not work correctly for input other than "the quick brown ...". /// </summary> private class PosIncrementAnalyzer : Analyzer { protected internal override TokenStreamComponents CreateComponents(string fieldName, System.IO.TextReader reader) { Tokenizer result = new MockTokenizer(reader, MockTokenizer.WHITESPACE, true); return new TokenStreamComponents(result, new TestPosIncrementFilter(result)); } } private sealed class TestPosIncrementFilter : TokenFilter { ICharTermAttribute termAtt; IPositionIncrementAttribute posIncrAtt; public TestPosIncrementFilter(TokenStream @in) : base(@in) { termAtt = AddAttribute<ICharTermAttribute>(); posIncrAtt = AddAttribute<IPositionIncrementAttribute>(); } public override sealed bool IncrementToken() { while (m_input.IncrementToken()) { if (termAtt.toString().equals("the")) { // stopword, do nothing } else if (termAtt.toString().equals("quick")) { posIncrAtt.PositionIncrement = (2); return true; } else { posIncrAtt.PositionIncrement = (1); return true; } } return false; } } /// <summary> /// a very simple subclass of QueryParser /// </summary> private sealed class DumbQueryParser : QueryParser { public DumbQueryParser(string f, Analyzer a) : base(TEST_VERSION_CURRENT, f, a) { } // expose super's version public Query GetSuperFieldQuery(string f, string t, bool quoted) { return base.GetFieldQuery(f, t, quoted); } // wrap super's version protected internal override Query GetFieldQuery(string field, string queryText, bool quoted) { return new DumbQueryWrapper(GetSuperFieldQuery(field, queryText, quoted)); } } /// <summary> /// A very simple wrapper to prevent instanceof checks but uses /// the toString of the query it wraps. /// </summary> private sealed class DumbQueryWrapper : Query { private Query q; public DumbQueryWrapper(Query q) { this.q = q; } public override string ToString(string field) { return q.ToString(field); } } } }
apache-2.0
denis-colliot/fscf-contacts
src/main/java/fr/fscf/contacts/shared/command/result/SecureNavigationResult.java
1090
package fr.fscf.contacts.shared.command.result; import fr.fscf.contacts.client.util.ToStringBuilder; import fr.fscf.contacts.shared.command.SecureNavigationCommand; import fr.fscf.contacts.shared.command.result.base.Result; /** * {@link SecureNavigationCommand} corresponding result. * * @author Denis */ public class SecureNavigationResult implements Result { private Authentication authentication; private boolean granted; public SecureNavigationResult() { // Serialization. } public SecureNavigationResult(Authentication authentication, boolean granted) { this.authentication = authentication; this.granted = granted; } @Override public String toString() { final ToStringBuilder builder = new ToStringBuilder(this); builder.append("authentication", authentication); builder.append("granted", granted); return builder.toString(); } public Authentication getAuthentication() { return authentication; } public boolean isGranted() { return granted; } }
apache-2.0
elarasu/roverz-chat
src/components/general/Loading.js
1306
/** * Loading Screen * <Loading text={'Server is down'} /> * * React Native Starter App * https://github.com/mcnamee/react-native-starter-app */ import React from 'react'; import PropTypes from 'prop-types'; import { View, ActivityIndicator } from 'react-native'; // Consts and Libs import { AppStyles, AppColors } from '../../theme/'; // Components import { Spacer, Text } from '../ui/'; const animateYesColor = AppColors.brand().lD_animYesColor; const animateNoColor = AppColors.brand().lD_animNoColor; /* Component ==================================================================== */ const Loading = ({ text, transparent }) => ( <View style={[ AppStyles.container, AppStyles.containerCentered, transparent && { backgroundColor: AppColors.brand().lD_style }, ]} > <ActivityIndicator animating size={'large'} color={transparent ? animateYesColor : animateNoColor} /> <Spacer size={10} /> {!!text && <Text>{text}</Text>} </View> ); Loading.propTypes = { text: PropTypes.string, transparent: PropTypes.bool }; Loading.defaultProps = { text: null, transparent: false }; Loading.componentName = 'Loading'; /* Export Component ==================================================================== */ export default Loading;
apache-2.0
lu4242/ext-myfaces-2.0.2-patch
trunk/myfaces-impl-2021override/src/main/java/org/apache/myfaces/ov2021/view/facelets/el/ELText.java
16882
/* * 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.myfaces.ov2021.view.facelets.el; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.List; import javax.el.ELContext; import javax.el.ELException; import javax.el.ExpressionFactory; import javax.el.ValueExpression; import javax.faces.component.UIComponent; import javax.faces.context.ResponseWriter; import javax.faces.view.Location; import org.apache.myfaces.ov2021.util.ExternalSpecifications; import org.apache.myfaces.ov2021.view.facelets.AbstractFaceletContext; /** * Handles parsing EL Strings in accordance with the EL-API Specification. The parser accepts either <code>${..}</code> * or <code>#{..}</code>. * * @author Jacob Hookom * @version $Id: ELText.java 1351627 2012-06-19 09:50:21Z lu4242 $ */ public class ELText { private static final class LiteralValueExpression extends ValueExpression { /** * */ private static final long serialVersionUID = 1L; private final String text; public LiteralValueExpression(String text) { this.text = text; } public boolean isLiteralText() { return false; } public int hashCode() { return 0; } public String getExpressionString() { return this.text; } public boolean equals(Object obj) { return false; } public void setValue(ELContext context, Object value) { } public boolean isReadOnly(ELContext context) { return false; } public Object getValue(ELContext context) { return null; } public Class<?> getType(ELContext context) { return null; } public Class<?> getExpectedType() { return null; } } private static final class ELTextComposite extends ELText { private final ELText[] txt; public ELTextComposite(ELText[] txt) { super(null); this.txt = txt; } public void write(Writer out, ELContext ctx) throws ELException, IOException { for (int i = 0; i < this.txt.length; i++) { this.txt[i].write(out, ctx); } } public void writeText(ResponseWriter out, ELContext ctx) throws ELException, IOException { for (int i = 0; i < this.txt.length; i++) { this.txt[i].writeText(out, ctx); } } public String toString(ELContext ctx) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < this.txt.length; i++) { sb.append(this.txt[i].toString(ctx)); } return sb.toString(); } /* * public String toString(ELContext ctx) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < * this.txt.length; i++) { sb.append(this.txt[i].toString(ctx)); } return sb.toString(); } */ public String toString() { StringBuffer sb = new StringBuffer(); for (int i = 0; i < this.txt.length; i++) { sb.append(this.txt[i].toString()); } return sb.toString(); } public boolean isLiteral() { return false; } public ELText apply(ExpressionFactory factory, ELContext ctx) { int len = this.txt.length; ELText[] nt = new ELText[len]; for (int i = 0; i < len; i++) { nt[i] = this.txt[i].apply(factory, ctx); } return new ELTextComposite(nt); } } private static final class ELTextVariable extends ELText { private final ValueExpression ve; public ELTextVariable(ValueExpression ve) { super(ve.getExpressionString()); this.ve = ve; } public boolean isLiteral() { return false; } public ELText apply(ExpressionFactory factory, ELContext ctx) { return new ELTextVariable(factory.createValueExpression(ctx, this.ve.getExpressionString(), String.class)); } public void write(Writer out, ELContext ctx) throws ELException, IOException { Object v = this.ve.getValue(ctx); if (v != null) { out.write((String) v); } } public String toString(ELContext ctx) throws ELException { Object v = this.ve.getValue(ctx); if (v != null) { return v.toString(); } return null; } public void writeText(ResponseWriter out, ELContext ctx) throws ELException, IOException { Object v = this.ve.getValue(ctx); if (v != null) { out.writeText((String) v, null); } } } private static final class ELCacheableTextVariable extends ELText { private final ValueExpression ve; //Just like TagAttributeImpl private final static int EL_CC = 2; private final int capabilities; private volatile ELTextVariable cached; public ELCacheableTextVariable(ValueExpression ve) { super(ve.getExpressionString()); this.ve = ve; boolean compositeComponentExpression = CompositeComponentELUtils.isCompositeComponentExpression(ve.getExpressionString()); this.capabilities = (compositeComponentExpression ? EL_CC : 0); } public boolean isLiteral() { return false; } public ELText apply(ExpressionFactory factory, ELContext ctx) { AbstractFaceletContext actx = (AbstractFaceletContext) ctx; if (actx.isAllowCacheELExpressions() && cached != null) { // In TagAttributeImpl.getValueExpression(), it is necessary to do an // special logic to detect the cases where #{cc} is included into the // EL expression and set the proper ccLevel. In this case, it is usual // the parent composite component is always on top, but it is possible to // write a nesting case with <composite:insertChildren>, and // pass a flat EL expression over itself. So, it is necessary to update // the ccLevel to make possible to find the right parent where this // expression belongs to. if ((this.capabilities & EL_CC) != 0) { return new ELTextVariable(((LocationValueExpression)cached.ve).apply( actx.getFaceletCompositionContext().getCompositeComponentLevel())); } return cached; } actx.beforeConstructELExpression(); try { ValueExpression valueExpression = factory.createValueExpression(ctx, this.ve.getExpressionString(), String.class); if ((this.capabilities & EL_CC) != 0) { UIComponent cc = actx.getFaceletCompositionContext().getCompositeComponentFromStack(); if (cc != null) { Location location = (Location) cc.getAttributes().get(CompositeComponentELUtils.LOCATION_KEY); if (location != null) { if (ExternalSpecifications.isUnifiedELAvailable()) { valueExpression = new LocationValueExpressionUEL(location, valueExpression, actx.getFaceletCompositionContext().getCompositeComponentLevel()); } else { valueExpression = new LocationValueExpression(location, valueExpression, actx.getFaceletCompositionContext().getCompositeComponentLevel()); } } } } ELTextVariable eltv = new ELTextVariable(valueExpression); if (actx.isAllowCacheELExpressions() && !actx.isAnyFaceletsVariableResolved()) { cached = eltv; } return eltv; } finally { actx.afterConstructELExpression(); } } public void write(Writer out, ELContext ctx) throws ELException, IOException { Object v = this.ve.getValue(ctx); if (v != null) { out.write((String) v); } } public String toString(ELContext ctx) throws ELException { Object v = this.ve.getValue(ctx); if (v != null) { return v.toString(); } return null; } public void writeText(ResponseWriter out, ELContext ctx) throws ELException, IOException { Object v = this.ve.getValue(ctx); if (v != null) { out.writeText((String) v, null); } } } protected final String literal; public ELText(String literal) { this.literal = literal; } /** * If it's literal text * * @return true if the String is literal (doesn't contain <code>#{..}</code> or <code>${..}</code>) */ public boolean isLiteral() { return true; } /** * Return an instance of <code>this</code> that is applicable given the ELContext and ExpressionFactory state. * * @param factory * the ExpressionFactory to use * @param ctx * the ELContext to use * @return an ELText instance */ public ELText apply(ExpressionFactory factory, ELContext ctx) { return this; } /** * Allow this instance to write to the passed Writer, given the ELContext state * * @param out * Writer to write to * @param ctx * current ELContext state * @throws ELException * @throws IOException */ public void write(Writer out, ELContext ctx) throws ELException, IOException { out.write(this.literal); } public void writeText(ResponseWriter out, ELContext ctx) throws ELException, IOException { out.writeText(this.literal, null); } /** * Evaluates the ELText to a String * * @param ctx * current ELContext state * @throws ELException * @return the evaluated String */ public String toString(ELContext ctx) throws ELException { return this.literal; } public String toString() { return this.literal; } /** * Parses the passed string to determine if it's literal or not * * @param in * input String * @return true if the String is literal (doesn't contain <code>#{..}</code> or <code>${..}</code>) */ public static boolean isLiteral(String in) { ELText txt = parse(in); return txt == null || txt.isLiteral(); } /** * Factory method for creating an unvalidated ELText instance. NOTE: All expressions in the passed String are * treated as {@link org.apache.myfaces.ov2021.view.facelets.el.LiteralValueExpression LiteralValueExpressions}. * * @param in * String to parse * @return ELText instance that knows if the String was literal or not * @throws javax.el.ELException */ public static ELText parse(String in) throws ELException { return parse(null, null, in); } /** * Factory method for creating a validated ELText instance. When an Expression is hit, it will use the * ExpressionFactory to create a ValueExpression instance, resolving any functions at that time. <p/> Variables and * properties will not be evaluated. * * @param fact * ExpressionFactory to use * @param ctx * ELContext to validate against * @param in * String to parse * @return ELText that can be re-applied later * @throws javax.el.ELException */ public static ELText parse(ExpressionFactory fact, ELContext ctx, String in) throws ELException { char[] ca = in.toCharArray(); int i = 0; char c = 0; int len = ca.length; int end = len - 1; boolean esc = false; int vlen = 0; StringBuffer buff = new StringBuffer(128); List<ELText> text = new ArrayList<ELText>(); ELText t = null; ValueExpression ve = null; while (i < len) { c = ca[i]; if ('\\' == c) { esc = !esc; if (esc && i < end && (ca[i + 1] == '$' || ca[i + 1] == '#')) { i++; continue; } } else if (!esc && ('$' == c || '#' == c)) { if (i < end) { if ('{' == ca[i + 1]) { if (buff.length() > 0) { text.add(new ELText(buff.toString())); buff.setLength(0); } vlen = findVarLength(ca, i); if (ctx != null && fact != null) { ve = fact.createValueExpression(ctx, new String(ca, i, vlen), String.class); t = new ELCacheableTextVariable(ve); } else { t = new ELCacheableTextVariable(new LiteralValueExpression(new String(ca, i, vlen))); } text.add(t); i += vlen; continue; } } } esc = false; buff.append(c); i++; } if (buff.length() > 0) { text.add(new ELText(new String(buff.toString()))); buff.setLength(0); } if (text.size() == 0) { return null; } else if (text.size() == 1) { return (ELText) text.get(0); } else { ELText[] ta = (ELText[]) text.toArray(new ELText[text.size()]); return new ELTextComposite(ta); } } private static int findVarLength(char[] ca, int s) throws ELException { int i = s; int len = ca.length; char c = 0; int str = 0; while (i < len) { c = ca[i]; if ('\\' == c && i < len - 1) { i++; } else if ('\'' == c || '"' == c) { if (str == c) { str = 0; } else { str = c; } } else if (str == 0 && ('}' == c)) { return i - s + 1; } i++; } throw new ELException("EL Expression Unbalanced: ... " + new String(ca, s, i - s)); } }
apache-2.0
taichi/org.handwerkszeug.mvnhack
src/org/handwerkszeug/common/util/Streams.java
2463
package org.handwerkszeug.common.util; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.util.logging.Level; import java.util.logging.Logger; import org.handwerkszeug.common.exception.IORuntimeException; public class Streams { static final Logger LOG = Logger.getLogger(Streams.class.getName()); public static abstract class using<STREAM extends Closeable, T extends Exception> { /** * @param t * is trick parameter. needless to assign. */ @SuppressWarnings("unchecked") public using(T... t) { $(this, (Class<T>) t.getClass().getComponentType()); } public abstract STREAM open() throws T; public abstract void handle(STREAM stream) throws T; public abstract void happen(T exception); } @SuppressWarnings("unchecked") static <STREAM extends Closeable, T extends Exception> void $( using<STREAM, T> _, Class<T> clazz) { STREAM in = null; try { in = _.open(); _.handle(in); } catch (Exception e) { if (clazz.isAssignableFrom(e.getClass())) { _.happen((T) e); } throw new IllegalStateException(e); } finally { close(in); } } public static void close(Closeable c) { try { if (c != null) { c.close(); } } catch (IOException e) { LOG.log(Level.WARNING, e.getLocalizedMessage(), e); } } public static final int BUF_SIZE = 128 * 128; /** * @param in * @param out * @see FileUtil#copy(InputStream, java.io.File) */ public static void copy(InputStream in, OutputStream out) throws IORuntimeException { byte[] buf = new byte[BUF_SIZE]; try { int len = 0; do { len = in.read(buf, 0, BUF_SIZE); if (0 < len) { out.write(buf, 0, len); } else { break; } } while (true); } catch (IOException e) { throw new IORuntimeException(e); } } public static String readText(InputStream in) throws IORuntimeException { return readText(in, "UTF-8"); } public static String readText(InputStream in, String charset) throws IORuntimeException { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); copy(in, out); return out.toString(charset); } catch (UnsupportedEncodingException e) { throw new IORuntimeException(e); } } }
apache-2.0
LearnLib/learnlib
algorithms/active/adt/src/main/java/de/learnlib/algorithms/adt/config/model/calculator/BestEffortDefensiveCalculator.java
1683
/* Copyright (C) 2013-2022 TU Dortmund * This file is part of LearnLib, http://www.learnlib.de/. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.learnlib.algorithms.adt.config.model.calculator; import java.util.Optional; import java.util.Set; import de.learnlib.algorithms.adt.ads.DefensiveADS; import de.learnlib.algorithms.adt.adt.ADTNode; import de.learnlib.algorithms.adt.api.PartialTransitionAnalyzer; import de.learnlib.algorithms.adt.config.model.DefensiveADSCalculator; import net.automatalib.automata.transducers.MealyMachine; import net.automatalib.words.Alphabet; /** * @author frohme */ public class BestEffortDefensiveCalculator implements DefensiveADSCalculator { @Override public <S, I, O> Optional<ADTNode<S, I, O>> compute(MealyMachine<S, I, ?, O> automaton, Alphabet<I> alphabet, Set<S> states, PartialTransitionAnalyzer<S, I> partialTransitionAnalyzer) { return DefensiveADS.compute(automaton, alphabet, states, partialTransitionAnalyzer); } }
apache-2.0
milg0/onvif-java-lib
src/org/onvif/ver10/device/wsdl/GetHostname.java
1151
// // Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2 generiert // Siehe <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // �nderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren. // Generiert: 2014.02.04 um 12:22:03 PM CET // package org.onvif.ver10.device.wsdl; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p> * Java-Klasse f�r anonymous complex type. * * <p> * Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist. * * <pre> * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * </sequence> * </restriction> * </complexContent> * </complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") @XmlRootElement(name = "GetHostname") public class GetHostname { }
apache-2.0
metacloud/python-troveclient
troveclient/compat/utils.py
1914
# Copyright 2012 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. import os from troveclient.openstack.common import strutils class HookableMixin(object): """Mixin so classes can register and run hooks.""" _hooks_map = {} @classmethod def add_hook(cls, hook_type, hook_func): if hook_type not in cls._hooks_map: cls._hooks_map[hook_type] = [] cls._hooks_map[hook_type].append(hook_func) @classmethod def run_hooks(cls, hook_type, *args, **kwargs): hook_funcs = cls._hooks_map.get(hook_type) or [] for hook_func in hook_funcs: hook_func(*args, **kwargs) def env(*vars, **kwargs): """ returns the first environment variable set if none are non-empty, defaults to '' or keyword arg default """ for v in vars: value = os.environ.get(v, None) if value: return value return kwargs.get('default', '') # http://code.activestate.com/recipes/ # 577257-slugify-make-a-string-usable-in-a-url-or-filename/ def slugify(value): """ Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens. From Django's "django/template/defaultfilters.py". Make use of strutils.to_slug from openstack common """ return strutils.to_slug(value, incoming=None, errors="strict")
apache-2.0
epidataio/epidata-community
play/test/AutomatedTestsTypeSpecs.scala
49101
/* * Copyright (c) 2015-2017 EpiData, Inc. */ import cassandra.DB import com.epidata.lib.models.{ AutomatedTest => Model } import com.epidata.lib.models.util.Binary import com.epidata.lib.models.util.Datatype import java.util.Date import javax.xml.bind.DatatypeConverter import models.{ MeasurementService, AutomatedTest } import org.specs2.mutable._ import org.specs2.runner._ import org.junit.runner._ import org.specs2.specification.Fixture import play.api.Application import play.api.GlobalSettings import play.api.libs.json.JsArray import play.api.libs.json.Json import play.api.mvc.Handler import play.api.mvc.RequestHeader import play.api.test._ import play.api.test.Helpers._ import securesocialtest.WithLoggedUser import util.Ordering // scalastyle:off magic.number @RunWith(classOf[JUnitRunner]) class AutomatedTestsTypeSpecs extends Specification { object Fixtures { val truncateSQL = s"TRUNCATE ${com.epidata.lib.models.Measurement.DBTableName}" def truncate = DB.cql(truncateSQL) def cleanUp = { truncate MeasurementService.reset } def install = { cleanUp AutomatedTest.insert(measurement1) AutomatedTest.insert(measurement2) AutomatedTest.insert(measurement3) } val measurement1 = Model("company0", "site0", "device_group0", "tester0", new Date(111000000000L), "dn0", "tn0", "mn0", Some("double"), 0.0, Some("un0"), Some("st0"), Some(0.0), Some(1.0), Some("de0"), Some("ds0"), Some("ts0")) val measurement2 = Model("company0", "site0", "device_group0", "tester0", new Date(111000000001L), "dn0", "tn0", "mn0", Some("double"), 0.0, Some("un0"), Some("st0"), Some(0.0), Some(1.0), Some("de0"), Some("ds0"), Some("ts0")) val measurement3 = Model("company0", "site0", "device_group0", "tester0", new Date(111000000002L), "dn0", "tn0", "mn0", Some("string"), "STRINGVAL", None, Some("st0"), None, None, Some("de0"), Some("ds0"), Some("ts0")) var measurements = new Array[String](64) measurements(0) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"double\", \"meas_value\": 64.76, \"meas_lower_limit\": -30.2, \"meas_upper_limit\": 200.2, \"tester\": \"tester-5\"}" measurements(1) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"double\", \"meas_value\": 64.76, \"meas_lower_limit\": -30, \"meas_upper_limit\": 200, \"tester\": \"tester-6\"}" measurements(2) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"double\", \"meas_value\": 64.76, \"meas_lower_limit\": \"-30\", \"meas_upper_limit\": \"200\", \"tester\": \"tester-7\"}" measurements(3) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"double\", \"meas_value\": 64.76, \"tester\": \"tester-8\"}" measurements(4) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"double\", \"meas_value\": 64, \"meas_lower_limit\": -30.2, \"meas_upper_limit\": 200.2, \"tester\": \"tester-9\"}" measurements(5) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"double\", \"meas_value\": 64, \"meas_lower_limit\": -30, \"meas_upper_limit\": 200, \"tester\": \"tester-10\"}" measurements(6) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"double\", \"meas_value\": 64, \"meas_lower_limit\": \"-30\", \"meas_upper_limit\": \"200\", \"tester\": \"tester-11\"}" measurements(7) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"double\", \"meas_value\": 64, \"tester\": \"tester-12\"}" measurements(8) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"double\", \"meas_value\": \"64\", \"meas_lower_limit\": -30.2, \"meas_upper_limit\": 200.2, \"tester\": \"tester-13\"}" measurements(9) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"double\", \"meas_value\": \"64\", \"meas_lower_limit\": -30, \"meas_upper_limit\": 200, \"tester\": \"tester-14\"}" measurements(10) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"double\", \"meas_value\": \"64\", \"meas_lower_limit\": \"-30\", \"meas_upper_limit\": \"200\", \"tester\": \"tester-15\"}" measurements(11) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"double\", \"meas_value\": \"64\", \"tester\": \"tester-16\"}" measurements(12) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"double\", \"meas_lower_limit\": -30.2, \"meas_upper_limit\": 200.2, \"tester\": \"tester-17\"}" measurements(13) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"double\", \"meas_lower_limit\": -30, \"meas_upper_limit\": 200, \"tester\": \"tester-18\"}" measurements(14) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"double\", \"meas_lower_limit\": \"-30\", \"meas_upper_limit\": \"200\", \"tester\": \"tester-19\"}" measurements(15) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"double\", \"tester\": \"tester-20\"}" measurements(16) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"long\",\"meas_value\": 64.5,\"meas_lower_limit\": -30.2, \"meas_upper_limit\": 200.2, \"tester\": \"tester-21\"}" measurements(17) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"long\",\"meas_value\": 64.5,\"meas_lower_limit\": -30, \"meas_upper_limit\": 200, \"tester\": \"tester-22\"}" measurements(18) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"long\",\"meas_value\": 64.5,\"meas_lower_limit\": \"-30\", \"meas_upper_limit\": \"200\", \"tester\": \"tester-23\"}" measurements(19) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"long\",\"meas_value\": 64.5,\"tester\": \"tester-24\"}" measurements(20) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"long\",\"meas_value\": 64,\"meas_lower_limit\": -30.2, \"meas_upper_limit\": 200.2, \"tester\": \"tester-25\"}" measurements(21) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"long\",\"meas_value\": 64,\"meas_lower_limit\": -30, \"meas_upper_limit\": 200, \"tester\": \"tester-26\"}" measurements(22) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"long\",\"meas_value\": 64,\"meas_lower_limit\": \"-30\", \"meas_upper_limit\": \"200\", \"tester\": \"tester-27\"}" measurements(23) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"long\",\"meas_value\": 64,\"tester\": \"tester-28\"}" measurements(24) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"long\",\"meas_value\": \"64\",\"meas_lower_limit\": -30.2, \"meas_upper_limit\": 200.2, \"tester\": \"tester-29\"}" measurements(25) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"long\",\"meas_value\": \"64\",\"meas_lower_limit\": -30, \"meas_upper_limit\": 200, \"tester\": \"tester-30\"}" measurements(26) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"long\",\"meas_value\": \"64\",\"meas_lower_limit\": \"-30\", \"meas_upper_limit\": \"200\", \"tester\": \"tester-31\"}" measurements(27) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"long\",\"meas_value\": \"64\",\"tester\": \"tester-32\"}" measurements(28) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"long\",\"meas_lower_limit\": -30.2, \"meas_upper_limit\": 200.2, \"tester\": \"tester-33\"}" measurements(29) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"long\",\"meas_lower_limit\": -30, \"meas_upper_limit\": 200, \"tester\": \"tester-34\"}" measurements(30) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"long\",\"meas_lower_limit\": \"-30\", \"meas_upper_limit\": \"200\", \"tester\": \"tester-35\"}" measurements(31) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"long\",\"tester\": \"tester-36\"}" measurements(32) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"string\",\"meas_value\": 64.5,\"meas_lower_limit\": -30.2, \"meas_upper_limit\": 200.2, \"tester\": \"tester-37\"}" measurements(33) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"string\",\"meas_value\": 64.5,\"meas_lower_limit\": -30, \"meas_upper_limit\": 200, \"tester\": \"tester-38\"}" measurements(34) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"string\",\"meas_value\": 64.5,\"meas_lower_limit\": \"-30\", \"meas_upper_limit\": \"200\", \"tester\": \"tester-39\"}" measurements(35) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"string\",\"meas_value\": 64.5,\"tester\": \"tester-40\"}" measurements(36) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"string\",\"meas_value\": 64,\"meas_lower_limit\": -30.2, \"meas_upper_limit\": 200.2, \"tester\": \"tester-41\"}" measurements(37) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"string\",\"meas_value\": 64,\"meas_lower_limit\": -30, \"meas_upper_limit\": 200, \"tester\": \"tester-42\"}" measurements(38) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"string\",\"meas_value\": 64,\"meas_lower_limit\": \"-30\", \"meas_upper_limit\": \"200\", \"tester\": \"tester-43\"}" measurements(39) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"string\",\"meas_value\": 64,\"tester\": \"tester-44\"}" measurements(40) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"string\",\"meas_value\": \"64\",\"meas_lower_limit\": -30.2, \"meas_upper_limit\": 200.2, \"tester\": \"tester-45\"}" measurements(41) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"string\",\"meas_value\": \"64\",\"meas_lower_limit\": -30, \"meas_upper_limit\": 200, \"tester\": \"tester-46\"}" measurements(42) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"string\",\"meas_value\": \"64\",\"meas_lower_limit\": \"-30\", \"meas_upper_limit\": \"200\", \"tester\": \"tester-47\"}" measurements(43) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"string\",\"meas_value\": \"64\",\"tester\": \"tester-48\"}" measurements(44) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"string\",\"meas_lower_limit\": -30.2, \"meas_upper_limit\": 200.2, \"tester\": \"tester-49\"}" measurements(45) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"string\",\"meas_lower_limit\": -30, \"meas_upper_limit\": 200, \"tester\": \"tester-50\"}" measurements(46) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"string\",\"meas_lower_limit\": \"-30\", \"meas_upper_limit\": \"200\", \"tester\": \"tester-51\"}" measurements(47) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\", \"meas_datatype\": \"string\",\"tester\": \"tester-52\"}" measurements(48) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\",\"meas_value\": 64.5,\"meas_lower_limit\": -30.2, \"meas_upper_limit\": 200.2, \"tester\": \"tester-53\"}" measurements(49) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\",\"meas_value\": 64.5,\"meas_lower_limit\": -30, \"meas_upper_limit\": 200, \"tester\": \"tester-54\"}" measurements(50) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\",\"meas_value\": 64.5,\"meas_lower_limit\": \"-30\", \"meas_upper_limit\": \"200\", \"tester\": \"tester-55\"}" measurements(51) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\",\"meas_value\": 64.5,\"tester\": \"tester-56\"}" measurements(52) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\",\"meas_value\": 64,\"meas_lower_limit\": -30.2, \"meas_upper_limit\": 200.2, \"tester\": \"tester-57\"}" measurements(53) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\",\"meas_value\": 64,\"meas_lower_limit\": -30, \"meas_upper_limit\": 200, \"tester\": \"tester-58\"}" measurements(54) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\",\"meas_value\": 64,\"meas_lower_limit\": \"-30\", \"meas_upper_limit\": \"200\", \"tester\": \"tester-59\"}" measurements(55) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\",\"meas_value\": 64,\"tester\": \"tester-60\"}" measurements(56) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\",\"meas_value\": \"64\",\"meas_lower_limit\": -30.2, \"meas_upper_limit\": 200.2, \"tester\": \"tester-61\"}" measurements(57) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\",\"meas_value\": \"64\",\"meas_lower_limit\": -30, \"meas_upper_limit\": 200, \"tester\": \"tester-62\"}" measurements(58) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\",\"meas_value\": \"64\",\"meas_lower_limit\": \"-30\", \"meas_upper_limit\": \"200\", \"tester\": \"tester-63\"}" measurements(59) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\",\"meas_value\": \"64\",\"tester\": \"tester-64\"}" measurements(60) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\",\"meas_lower_limit\": -30.2, \"meas_upper_limit\": 200.2, \"tester\": \"tester-65\"}" measurements(61) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\",\"meas_lower_limit\": -30, \"meas_upper_limit\": 200, \"tester\": \"tester-66\"}" measurements(62) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\",\"meas_lower_limit\": \"-30\", \"meas_upper_limit\": \"200\", \"tester\": \"tester-67\"}" measurements(63) = "{\"meas_name\": \"Temperature\", \"company\": \"company0\", \"site\": \"site0\", \"device_group\": \"Device_Group-1\", \"test_name\": \"Temperature_Test\", \"meas_status\": \"PASS\", \"ts\": 1505970910038, \"device_name\": \"Device-1\", \"meas_unit\": \"deg F\", \"meas_description\": \"\",\"tester\": \"tester-68\"}" val measurementsJson = "[" + measurements.mkString(",") + "]" } /** * A fake application to ensure automated test routing is enabled and * appropriate plugins are used. */ class FakeApp ////(withoutPlugins: List[String], additionalPlugins: List[String]) extends FakeApplication( // withoutPlugins = withoutPlugins, // additionalPlugins = additionalPlugins, withGlobal = Some(new GlobalSettings { override def onStart(app: Application) = Global.onStart(app) override def onRouteRequest(req: RequestHeader): Option[Handler] = automated_test.Routes.handlerFor(req) orElse super.onRouteRequest(req) override def onStop(app: Application) = Global.onStop(app) }) ) import WithLoggedUser._ object FakeApp { def apply() = new FakeApp( // withoutPlugins = excludedPlugins, // additionalPlugins = includedPlugins ) } "AutomatedTests" should { "insert a automated tests with all combination datatype" in new WithLoggedUser(FakeApp()) { Fixtures.cleanUp val create = route(FakeRequest( POST, "/measurements", FakeHeaders(("Content-Type", Seq("text/json")) :: Nil), Json.parse( Fixtures.measurementsJson ) ).withCookies(cookie)).get status(create) must equalTo(BAD_REQUEST) var results = new Array[Model](70) results(56) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-56", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(68) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-68", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(46) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-46", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(20) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-20", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(48) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-48", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(44) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-44", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(66) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-66", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(14) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-14", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(37) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-37", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(49) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-49", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(65) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-65", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(52) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-52", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(13) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-13", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(58) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-58", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(54) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-54", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(50) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-50", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(45) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-45", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(26) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-26", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(41) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-41", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(62) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-62", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(10) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-10", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(29) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-29", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(57) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-57", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(42) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-42", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(36) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-36", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(17) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-17", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(34) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-34", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(61) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-61", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(22) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-22", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(32) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-32", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(25) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-25", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(21) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-21", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(60) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-60", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(9) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-9", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(33) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-33", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(6) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-6", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(12) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-12", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(18) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-18", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(16) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-16", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(24) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-24", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(28) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-28", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(30) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-30", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(8) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-8", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(53) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-53", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(40) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-40", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(38) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-38", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(5) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-5", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(64) = AutomatedTest.find("company0", "site0", "Device_Group-1", "tester-64", new Date(1505970910037L), new Date(1505970910040L), Ordering.Unspecified)(0) results(56).meas_value must equalTo(64.5) results(68).meas_value must equalTo(None) results(46).meas_value must equalTo("64") results(20).meas_value must equalTo(None) results(48).meas_value must equalTo("64") results(44).meas_value must equalTo(64) results(66).meas_value must equalTo(None) results(14).meas_value must equalTo("64") results(37).meas_value must equalTo(64.5) results(49).meas_value must equalTo(None) results(65).meas_value must equalTo(None) results(52).meas_value must equalTo(None) results(13).meas_value must equalTo("64") results(58).meas_value must equalTo(64) results(54).meas_value must equalTo(64.5) results(50).meas_value must equalTo(None) results(45).meas_value must equalTo("64") results(26).meas_value must equalTo(64) results(41).meas_value must equalTo(64) results(62).meas_value must equalTo("64") results(10).meas_value must equalTo(64) results(29).meas_value must equalTo("64") results(57).meas_value must equalTo(64) results(42).meas_value must equalTo(64) results(36).meas_value must equalTo(None) results(17).meas_value must equalTo(None) results(34).meas_value must equalTo(None) results(61).meas_value must equalTo("64") results(22).meas_value must equalTo(64.5) results(32).meas_value must equalTo("64") results(25).meas_value must equalTo(64) results(21).meas_value must equalTo(64.5) results(60).meas_value must equalTo(64) results(9).meas_value must equalTo(64) results(33).meas_value must equalTo(None) results(6).meas_value must equalTo(64.76) results(12).meas_value must equalTo(64) results(18).meas_value must equalTo(None) results(16).meas_value must equalTo("64") results(24).meas_value must equalTo(64.5) results(28).meas_value must equalTo(64) results(30).meas_value must equalTo("64") results(8).meas_value must equalTo(64.76) results(53).meas_value must equalTo(64.5) results(40).meas_value must equalTo(64.5) results(38).meas_value must equalTo(64.5) results(5).meas_value must equalTo(64.76) results(64).meas_value must equalTo("64") (results(56).meas_datatype, results(56).meas_value, results(56).meas_upper_limit, results(56).meas_lower_limit) must equalTo(Some(""), 64.5, None, None) (results(68).meas_datatype, results(68).meas_value, results(68).meas_upper_limit, results(68).meas_lower_limit) must equalTo(Some(""), None, None, None) (results(46).meas_datatype, results(46).meas_value, results(46).meas_upper_limit, results(46).meas_lower_limit) must equalTo(Some("string"), "64", Some(200), Some(-30)) (results(20).meas_datatype, results(20).meas_value, results(20).meas_upper_limit, results(20).meas_lower_limit) must equalTo(Some("double"), None, None, None) (results(48).meas_datatype, results(48).meas_value, results(48).meas_upper_limit, results(48).meas_lower_limit) must equalTo(Some("string"), "64", None, None) (results(44).meas_datatype, results(44).meas_value, results(44).meas_upper_limit, results(44).meas_lower_limit) must equalTo(Some("string"), 64, None, None) (results(66).meas_datatype, results(66).meas_value, results(66).meas_upper_limit, results(66).meas_lower_limit) must equalTo(Some(""), None, Some(200), Some(-30)) (results(14).meas_datatype, results(14).meas_value, results(14).meas_upper_limit, results(14).meas_lower_limit) must equalTo(Some("double"), "64", Some(200), Some(-30)) (results(37).meas_datatype, results(37).meas_value, results(37).meas_upper_limit, results(37).meas_lower_limit) must equalTo(Some("string"), 64.5, Some(200.2), Some(-30.2)) (results(49).meas_datatype, results(49).meas_value, results(49).meas_upper_limit, results(49).meas_lower_limit) must equalTo(Some("string"), None, Some(200.2), Some(-30.2)) (results(65).meas_datatype, results(65).meas_value, results(65).meas_upper_limit, results(65).meas_lower_limit) must equalTo(Some(""), None, Some(200.2), Some(-30.2)) (results(52).meas_datatype, results(52).meas_value, results(52).meas_upper_limit, results(52).meas_lower_limit) must equalTo(Some("string"), None, None, None) (results(13).meas_datatype, results(13).meas_value, results(13).meas_upper_limit, results(13).meas_lower_limit) must equalTo(Some("double"), "64", Some(200.2), Some(-30.2)) (results(58).meas_datatype, results(58).meas_value, results(58).meas_upper_limit, results(58).meas_lower_limit) must equalTo(Some(""), 64, Some(200), Some(-30)) (results(54).meas_datatype, results(54).meas_value, results(54).meas_upper_limit, results(54).meas_lower_limit) must equalTo(Some(""), 64.5, Some(200), Some(-30)) (results(50).meas_datatype, results(50).meas_value, results(50).meas_upper_limit, results(50).meas_lower_limit) must equalTo(Some("string"), None, Some(200), Some(-30)) (results(45).meas_datatype, results(45).meas_value, results(45).meas_upper_limit, results(45).meas_lower_limit) must equalTo(Some("string"), "64", Some(200.2), Some(-30.2)) (results(26).meas_datatype, results(26).meas_value, results(26).meas_upper_limit, results(26).meas_lower_limit) must equalTo(Some("long"), 64, Some(200), Some(-30)) (results(41).meas_datatype, results(41).meas_value, results(41).meas_upper_limit, results(41).meas_lower_limit) must equalTo(Some("string"), 64, Some(200.2), Some(-30.2)) (results(62).meas_datatype, results(62).meas_value, results(62).meas_upper_limit, results(62).meas_lower_limit) must equalTo(Some(""), "64", Some(200), Some(-30)) (results(10).meas_datatype, results(10).meas_value, results(10).meas_upper_limit, results(10).meas_lower_limit) must equalTo(Some("double"), 64, Some(200), Some(-30)) (results(29).meas_datatype, results(29).meas_value, results(29).meas_upper_limit, results(29).meas_lower_limit) must equalTo(Some("long"), "64", Some(200.2), Some(-30.2)) (results(57).meas_datatype, results(57).meas_value, results(57).meas_upper_limit, results(57).meas_lower_limit) must equalTo(Some(""), 64, Some(200.2), Some(-30.2)) (results(42).meas_datatype, results(42).meas_value, results(42).meas_upper_limit, results(42).meas_lower_limit) must equalTo(Some("string"), 64, Some(200), Some(-30)) (results(36).meas_datatype, results(36).meas_value, results(36).meas_upper_limit, results(36).meas_lower_limit) must equalTo(Some("long"), None, None, None) (results(17).meas_datatype, results(17).meas_value, results(17).meas_upper_limit, results(17).meas_lower_limit) must equalTo(Some("double"), None, Some(200.2), Some(-30.2)) (results(34).meas_datatype, results(34).meas_value, results(34).meas_upper_limit, results(34).meas_lower_limit) must equalTo(Some("long"), None, Some(200), Some(-30)) (results(61).meas_datatype, results(61).meas_value, results(61).meas_upper_limit, results(61).meas_lower_limit) must equalTo(Some(""), "64", Some(200.2), Some(-30.2)) (results(22).meas_datatype, results(22).meas_value, results(22).meas_upper_limit, results(22).meas_lower_limit) must equalTo(Some("long"), 64.5, Some(200), Some(-30)) (results(32).meas_datatype, results(32).meas_value, results(32).meas_upper_limit, results(32).meas_lower_limit) must equalTo(Some("long"), "64", None, None) (results(25).meas_datatype, results(25).meas_value, results(25).meas_upper_limit, results(25).meas_lower_limit) must equalTo(Some("long"), 64, Some(200.2), Some(-30.2)) (results(21).meas_datatype, results(21).meas_value, results(21).meas_upper_limit, results(21).meas_lower_limit) must equalTo(Some("long"), 64.5, Some(200.2), Some(-30.2)) (results(60).meas_datatype, results(60).meas_value, results(60).meas_upper_limit, results(60).meas_lower_limit) must equalTo(Some(""), 64, None, None) (results(9).meas_datatype, results(9).meas_value, results(9).meas_upper_limit, results(9).meas_lower_limit) must equalTo(Some("double"), 64, Some(200.2), Some(-30.2)) (results(33).meas_datatype, results(33).meas_value, results(33).meas_upper_limit, results(33).meas_lower_limit) must equalTo(Some("long"), None, Some(200.2), Some(-30.2)) (results(6).meas_datatype, results(6).meas_value, results(6).meas_upper_limit, results(6).meas_lower_limit) must equalTo(Some("double"), 64.76, Some(200), Some(-30)) (results(12).meas_datatype, results(12).meas_value, results(12).meas_upper_limit, results(12).meas_lower_limit) must equalTo(Some("double"), 64, None, None) (results(18).meas_datatype, results(18).meas_value, results(18).meas_upper_limit, results(18).meas_lower_limit) must equalTo(Some("double"), None, Some(200), Some(-30)) (results(16).meas_datatype, results(16).meas_value, results(16).meas_upper_limit, results(16).meas_lower_limit) must equalTo(Some("double"), "64", None, None) (results(24).meas_datatype, results(24).meas_value, results(24).meas_upper_limit, results(24).meas_lower_limit) must equalTo(Some("long"), 64.5, None, None) (results(28).meas_datatype, results(28).meas_value, results(28).meas_upper_limit, results(28).meas_lower_limit) must equalTo(Some("long"), 64, None, None) (results(30).meas_datatype, results(30).meas_value, results(30).meas_upper_limit, results(30).meas_lower_limit) must equalTo(Some("long"), "64", Some(200), Some(-30)) (results(8).meas_datatype, results(8).meas_value, results(8).meas_upper_limit, results(8).meas_lower_limit) must equalTo(Some("double"), 64.76, None, None) (results(53).meas_datatype, results(53).meas_value, results(53).meas_upper_limit, results(53).meas_lower_limit) must equalTo(Some(""), 64.5, Some(200.2), Some(-30.2)) (results(40).meas_datatype, results(40).meas_value, results(40).meas_upper_limit, results(40).meas_lower_limit) must equalTo(Some("string"), 64.5, None, None) (results(38).meas_datatype, results(38).meas_value, results(38).meas_upper_limit, results(38).meas_lower_limit) must equalTo(Some("string"), 64.5, Some(200), Some(-30)) (results(5).meas_datatype, results(5).meas_value, results(5).meas_upper_limit, results(5).meas_lower_limit) must equalTo(Some("double"), 64.76, Some(200.2), Some(-30.2)) (results(64).meas_datatype, results(64).meas_value, results(64).meas_upper_limit, results(64).meas_lower_limit) must equalTo(Some(""), "64", None, None) } } }
apache-2.0
c-knowles/kube-aws
vendor/github.com/aws/amazon-vpc-cni-k8s/pkg/networkutils/mocks/network_mocks.go
2657
// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may // not use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either // express or implied. See the License for the specific language governing // permissions and limitations under the License. // Code generated by MockGen. DO NOT EDIT. // Source: github.com/aws/amazon-vpc-cni-k8s/pkg/networkutils (interfaces: NetworkAPIs) // Package mock_networkutils is a generated GoMock package. package mock_networkutils import ( net "net" reflect "reflect" gomock "github.com/golang/mock/gomock" ) // MockNetworkAPIs is a mock of NetworkAPIs interface type MockNetworkAPIs struct { ctrl *gomock.Controller recorder *MockNetworkAPIsMockRecorder } // MockNetworkAPIsMockRecorder is the mock recorder for MockNetworkAPIs type MockNetworkAPIsMockRecorder struct { mock *MockNetworkAPIs } // NewMockNetworkAPIs creates a new mock instance func NewMockNetworkAPIs(ctrl *gomock.Controller) *MockNetworkAPIs { mock := &MockNetworkAPIs{ctrl: ctrl} mock.recorder = &MockNetworkAPIsMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use func (m *MockNetworkAPIs) EXPECT() *MockNetworkAPIsMockRecorder { return m.recorder } // SetupENINetwork mocks base method func (m *MockNetworkAPIs) SetupENINetwork(arg0, arg1 string, arg2 int, arg3 string) error { ret := m.ctrl.Call(m, "SetupENINetwork", arg0, arg1, arg2, arg3) ret0, _ := ret[0].(error) return ret0 } // SetupENINetwork indicates an expected call of SetupENINetwork func (mr *MockNetworkAPIsMockRecorder) SetupENINetwork(arg0, arg1, arg2, arg3 interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetupENINetwork", reflect.TypeOf((*MockNetworkAPIs)(nil).SetupENINetwork), arg0, arg1, arg2, arg3) } // SetupHostNetwork mocks base method func (m *MockNetworkAPIs) SetupHostNetwork(arg0 *net.IPNet, arg1 *net.IP) error { ret := m.ctrl.Call(m, "SetupHostNetwork", arg0, arg1) ret0, _ := ret[0].(error) return ret0 } // SetupHostNetwork indicates an expected call of SetupHostNetwork func (mr *MockNetworkAPIsMockRecorder) SetupHostNetwork(arg0, arg1 interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetupHostNetwork", reflect.TypeOf((*MockNetworkAPIs)(nil).SetupHostNetwork), arg0, arg1) }
apache-2.0
felislynx-silae/GearBugSample
app/src/main/java/eu/lynxit/sampleapp/SceneObjectEventListener.java
169
package eu.lynxit.sampleapp; public abstract class SceneObjectEventListener { public abstract void onLoadingFinished(PresentationThumbnailGVRSceneObject object); }
apache-2.0
shantanusharma/closure-compiler
src/com/google/javascript/jscomp/gwt/client/JsfileParser.java
16383
/* * Copyright 2015 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp.gwt.client; import com.google.common.base.Joiner; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Multiset; import com.google.common.collect.Ordering; import com.google.common.collect.TreeMultiset; import com.google.javascript.jscomp.BasicErrorManager; import com.google.javascript.jscomp.CheckLevel; import com.google.javascript.jscomp.Compiler; import com.google.javascript.jscomp.CompilerOptions; import com.google.javascript.jscomp.GatherModuleMetadata; import com.google.javascript.jscomp.JSError; import com.google.javascript.jscomp.ModuleMetadataMap.ModuleMetadata; import com.google.javascript.jscomp.SourceFile; import com.google.javascript.jscomp.deps.ModuleLoader.ResolutionMode; import com.google.javascript.jscomp.gwt.client.Util.JsArray; import com.google.javascript.jscomp.gwt.client.Util.JsObject; import com.google.javascript.jscomp.gwt.client.Util.JsRegExp; import com.google.javascript.jscomp.parsing.Config; import com.google.javascript.jscomp.parsing.ParserRunner; import com.google.javascript.jscomp.parsing.parser.trees.Comment; import com.google.javascript.rhino.ErrorReporter; import com.google.javascript.rhino.InputId; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.TreeSet; import javax.annotation.Nullable; import jsinterop.annotations.JsFunction; import jsinterop.annotations.JsMethod; /** * GWT module to parse files for dependency and * {@literal @}{@code fileoverview} annotation * information. */ public class JsfileParser { /** * All the information parsed out of a single file. * Exported as a JSON object: * <pre> {@code { * "custom_annotations": {?Array<[string, string]>}, @.* * "goog": {?bool}, whether 'goog' is implicitly required * "has_soy_delcalls": {?Array<string>}, @fileoverview @hassoydelcall {.*} * "has_soy_deltemplates": {?Array<string>}, @fileoverview @hassoydeltemplate {.*} * "imported_modules": {?Array<string>}, import ... from .* * "is_config": {?bool}, @fileoverview @config * "is_externs": {?bool}, @fileoverview @externs * "load_flags": {?Array<[string, string]>}, * "mod_name": {?Array<string>}, @fileoverview @modName .*, @modName {.*} * "mods": {?Array<string>}, @fileoverview @mods {.*} * "provide_goog": {?bool}, @fileoverview @provideGoog * "provides": {?Array<string>}, * "requires": {?Array<string>}, note: look for goog.* for 'goog' * "requires_css": {?Array<string>}, @fileoverview @requirecss {.*} * "testonly": {?bool}, goog.setTestOnly * "type_requires": {?Array<string>}, * "visibility: {?Array<string>}, @fileoverview @visibility {.*} * }}</pre> * Any trivial values are omitted. */ static final class FileInfo { final ErrorReporter reporter; boolean goog = false; boolean isConfig = false; boolean isExterns = false; boolean provideGoog = false; boolean testonly = false; final Set<String> hasSoyDelcalls = new TreeSet<>(); final Set<String> hasSoyDeltemplates = new TreeSet<>(); // Use a LinkedHashSet as import order matters! final Set<String> importedModules = new LinkedHashSet<>(); final List<String> modName = new ArrayList<>(); final List<String> mods = new ArrayList<>(); // Note: multiple copies doesn't make much sense, but we report // each copy so that calling code can choose how to handle it final Multiset<String> provides = TreeMultiset.create(); final Multiset<String> requires = TreeMultiset.create(); final Multiset<String> typeRequires = TreeMultiset.create(); final Multiset<String> requiresCss = TreeMultiset.create(); final Multiset<String> visibility = TreeMultiset.create(); final Set<JsArray<String>> customAnnotations = assoc(); final Set<JsArray<String>> loadFlags = assoc(); FileInfo(ErrorReporter reporter) { this.reporter = reporter; } private void handleGoog() { if (provideGoog) { provides.add("goog"); } else if (goog) { requires.add("goog"); } } /** Exports the file info as a JSON object. */ JsObject<Object> full() { handleGoog(); return new SparseObject() .set("custom_annotations", customAnnotations) .set("goog", goog) .set("has_soy_delcalls", hasSoyDelcalls) .set("has_soy_deltemplates", hasSoyDeltemplates) .set("imported_modules", importedModules) .set("is_config", isConfig) .set("is_externs", isExterns) .set("load_flags", loadFlags) .set("modName", modName) .set("mods", mods) .set("provide_goog", provideGoog) .set("provides", provides) .set("requires", requires) .set("requiresCss", requiresCss) .set("testonly", testonly) .set("type_requires", typeRequires) .set("visibility", visibility) .object; } } /** * Exports the {@link #compile} method via JSNI. * * <p>This will be placed on {@code module.exports.gjd} or the global {@code jscomp.gjd}. */ public native void exportGjd() /*-{ var fn = $entry(@com.google.javascript.jscomp.gwt.client.JsfileParser::gjd(*)); if (typeof module !== 'undefined' && module.exports) { module.exports.gjd = fn; } }-*/; /** Represents a single JSDoc annotation, with an optional argument. */ private static class CommentAnnotation { /** Annotation name, e.g. "@fileoverview" or "@externs". */ final String name; /** * Annotation value: either the bare identifier immediately after the * annotation, or else string in braces. */ final String value; CommentAnnotation(String name, String value) { this.name = name; this.value = value; } /** Returns all the annotations in a given comment string. */ static List<CommentAnnotation> parse(String comment) { // TODO(sdh): This is reinventing a large part of JSDocInfoParser. We should // try to consolidate as much as possible. This requires several steps: // 1. Make all the annotations we look for first-class in JSDocInfo // 2. Support custom annotations (may already be done?) // 3. Fix up existing code so that all these annotations are in @fileoverview // 4. Change this code to simply inspect the script's JSDocInfo instead of re-parsing JsRegExp re = new JsRegExp( ANNOTATION_RE, "g"); JsRegExp.Match match; List<CommentAnnotation> out = new ArrayList<>(); while ((match = re.exec(comment)) != null) { boolean modName = match.get(OTHER_ANNOTATION_GROUP) == null; String name = modName ? "@modName" : match.get(OTHER_ANNOTATION_GROUP); String value = Strings.nullToEmpty(match.get(modName ? MODNAME_VALUE_GROUP : OTHER_VALUE_GROUP)); out.add(new CommentAnnotation(name, value)); } return out; } private static final String ANNOTATION_RE = Joiner.on("").join( // Don't match "@" in the middle of a word "(?:[^a-zA-Z0-9_$]|^)", "(?:", // Case 1: @modName with a single identifier and no braces "@modName[\\t\\v\\f ]*([^{\\t\\n\\v\\f\\r ][^\\t\\n\\v\\f\\r ]*)", "|", // Case 2: Everything else, with an optional brace-delimited argument "(@[a-zA-Z]+)(?:\\s*\\{\\s*([^}\\t\\n\\v\\f\\r ]+)\\s*\\})?", ")"); private static final int MODNAME_VALUE_GROUP = 1; private static final int OTHER_ANNOTATION_GROUP = 2; private static final int OTHER_VALUE_GROUP = 3; } /** Method exported to JS to parse a file for dependencies and annotations. */ @JsMethod(namespace = "jscomp") public static JsObject<Object> gjd(String code, String filename, @Nullable Reporter reporter) { return parse(code, filename, reporter).full(); } /** Internal implementation to produce the {@link FileInfo} object. */ private static FileInfo parse(String code, String filename, @Nullable Reporter reporter) { ErrorReporter errorReporter = new DelegatingReporter(reporter); Compiler compiler = new Compiler( new BasicErrorManager() { @Override public void println(CheckLevel level, JSError error) { if (level == CheckLevel.ERROR) { errorReporter.error( error.description, error.sourceName, error.getLineNumber(), error.getCharno()); } else if (level == CheckLevel.WARNING) { errorReporter.warning( error.description, error.sourceName, error.getLineNumber(), error.getCharno()); } } @Override protected void printSummary() {} }); SourceFile source = SourceFile.fromCode(filename, code); compiler.init( ImmutableList.<SourceFile>of(), ImmutableList.<SourceFile>of(source), new CompilerOptions()); Config config = ParserRunner.createConfig( // TODO(sdh): ES8 STRICT, with a non-strict fallback - then give warnings. Config.LanguageMode.ECMASCRIPT8, Config.JsDocParsing.INCLUDE_DESCRIPTIONS_NO_WHITESPACE, Config.RunMode.KEEP_GOING, /* extraAnnotationNames */ ImmutableSet.<String>of(), /* parseInlineSourceMaps */ true, Config.StrictMode.SLOPPY); FileInfo info = new FileInfo(errorReporter); ParserRunner.ParseResult parsed = ParserRunner.parse(source, code, config, errorReporter); parsed.ast.setInputId(new InputId(filename)); String version = parsed.features.version(); if (!version.equals("es3")) { info.loadFlags.add(JsArray.of("lang", version)); } for (Comment comment : parsed.comments) { if (comment.type == Comment.Type.JSDOC) { parseComment(comment, info); } } GatherModuleMetadata gatherModuleMetadata = new GatherModuleMetadata( compiler, /* processCommonJsModules= */ false, ResolutionMode.BROWSER); gatherModuleMetadata.process(new Node(Token.ROOT), parsed.ast); compiler.generateReport(); ModuleMetadata module = Iterables.getOnlyElement( compiler.getModuleMetadataMap().getModulesByPath().values()); if (module.isEs6Module()) { info.loadFlags.add(JsArray.of("module", "es6")); } else if (module.isGoogModule()) { info.loadFlags.add(JsArray.of("module", "goog")); } info.goog = module.usesClosure(); // If something doesn't have an external dependency on Closure, then it does not have any // externally required files or symbols to provide. This is needed for bundles that contain // base.js as well as other files. These bundles should look like they do not require or provide // anything at all. if (module.usesClosure()) { info.provides.addAll(module.googNamespaces()); info.requires.addAll(module.requiredGoogNamespaces()); info.typeRequires.addAll(module.requiredTypes()); info.testonly = module.isTestOnly(); } info.importedModules.addAll(module.es6ImportSpecifiers().elementSet()); return info; } /** Mutates {@code info} with information from the given {@code comment}. */ private static void parseComment(Comment comment, FileInfo info) { boolean fileOverview = comment.value.contains("@fileoverview"); for (CommentAnnotation annotation : CommentAnnotation.parse(comment.value)) { switch (annotation.name) { case "@fileoverview": case "@author": case "@see": case "@link": break; case "@mods": if (!annotation.value.isEmpty()) { info.mods.add(annotation.value); } break; case "@visibility": if (!annotation.value.isEmpty()) { info.visibility.add(annotation.value); } break; case "@modName": if (!annotation.value.isEmpty()) { info.modName.add(annotation.value); } break; case "@config": info.isConfig = true; break; case "@provideGoog": info.provideGoog = true; break; case "@requirecss": if (!annotation.value.isEmpty()) { info.requiresCss.add(annotation.value); } break; case "@hassoydeltemplate": if (!annotation.value.isEmpty()) { info.hasSoyDeltemplates.add(annotation.value); } break; case "@hassoydelcall": if (!annotation.value.isEmpty()) { info.hasSoyDelcalls.add(annotation.value); } break; case "@externs": info.isExterns = true; break; case "@enhanceable": case "@pintomodule": info.customAnnotations.add( JsArray.of(annotation.name.substring(1), annotation.value)); break; case "@enhance": if (!annotation.value.isEmpty()) { info.customAnnotations.add( JsArray.of(annotation.name.substring(1), annotation.value)); } break; default: if (fileOverview) { info.customAnnotations.add( JsArray.of(annotation.name.substring(1), annotation.value)); } } } } /** JS function interface for reporting errors. */ @JsFunction public interface Reporter { void report(boolean fatal, String message, String sourceName, int line, int lineOffset); } private static final class DelegatingReporter implements ErrorReporter { final Reporter delegate; DelegatingReporter(Reporter delegate) { this.delegate = delegate != null ? delegate : NULL_REPORTER; } @Override public void warning(String message, String sourceName, int line, int lineOffset) { delegate.report(false, message, sourceName, line, lineOffset); } @Override public void error(String message, String sourceName, int line, int lineOffset) { delegate.report(true, message, sourceName, line, lineOffset); } } private static final Reporter NULL_REPORTER = new Reporter() { @Override public void report( boolean fatal, String message, String sourceName, int line, int lineOffset) {} }; /** Returns an associative multimap. */ private static Set<JsArray<String>> assoc() { return new TreeSet<>(Ordering.<String>natural().lexicographical().onResultOf(JsArray::asList)); } /** Sparse object helper class: only adds non-trivial values. */ private static class SparseObject { final JsObject<Object> object = new JsObject<>(); SparseObject set(String key, Iterable<?> iterable) { JsArray<?> array = JsArray.copyOf(iterable); if (array.getLength() > 0) { object.set(key, array); } return this; } SparseObject set(String key, String value) { if (value != null && !value.isEmpty()) { object.set(key, value); } return this; } SparseObject set(String key, boolean value) { if (value) { object.set(key, value); } return this; } } }
apache-2.0
fxzjshm/Polyfiter
core/src/main/java/net/hakugyokurou/fds/parser/MathExpressionParserConstants.java
1023
/* Generated By:JavaCC: Do not edit this line. MathExpressionParserConstants.java */ package net.hakugyokurou.fds.parser; /** * Token literal values and constants. * Generated by org.javacc.parser.OtherFilesGen#start() */ interface MathExpressionParserConstants { /** End of File. */ int EOF = 0; /** RegularExpression Id. */ int ADD = 4; /** RegularExpression Id. */ int SUB = 5; /** RegularExpression Id. */ int MUL = 6; /** RegularExpression Id. */ int DIV = 7; /** RegularExpression Id. */ int EOL = 8; /** RegularExpression Id. */ int INTEGER = 9; /** RegularExpression Id. */ int RATIONAL = 10; /** RegularExpression Id. */ int DIGIT = 11; /** Lexical state. */ int DEFAULT = 0; /** Literal token values. */ String[] tokenImage = { "<EOF>", "\" \"", "\"\\r\"", "\"\\t\"", "\"+\"", "\"-\"", "\"*\"", "\"/\"", "\"\\n\"", "<INTEGER>", "<RATIONAL>", "<DIGIT>", "\"[\"", "\"]\"", "\"(\"", "\")\"", }; }
apache-2.0
liwei3380/coolweather
src/com/coolweather/app/util/Utility.java
4902
package com.coolweather.app.util; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.R.integer; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.text.TextUtils; import com.coolweather.app.model.City; import com.coolweather.app.model.CoolWeatherDB; import com.coolweather.app.model.County; import com.coolweather.app.model.Province; public class Utility { /** * ½âÎö·þÎñÆ÷·µ»ØµÄjsonÊý¾Ý£¬²¢½«½âÎö³öµÄÊý¾Ý´æ´¢µ½±¾µØ¡£ * @param context * @param response */ public static void handleWeatherResponse(Context context,String response){ try { JSONObject jsonObject = new JSONObject(response); //JSONObject weatherInfo = jsonObject.getJSONObject("weatherinfo"); JSONObject weatherInfo = jsonObject.getJSONObject("data"); JSONArray WeatherArray = weatherInfo.getJSONArray("forecast"); /*String cityName = weatherInfo.getString("city"); String weatherCode = weatherInfo.getString("cityid"); String temp1 = weatherInfo.getString("temp1"); String temp2 = weatherInfo.getString("temp2"); String weatherDesp = weatherInfo.getString("weather"); String publishTime = weatherInfo.getString("ptime");*/ String cityName = weatherInfo.getString("city"); String weatherCode = weatherInfo.getString("wendu"); String publishTime = weatherInfo.getString("ganmao"); String temp1 = WeatherArray.getJSONObject(0).getString("low"); String temp2 = WeatherArray.getJSONObject(0).getString("high"); String weatherDesp = WeatherArray.getJSONObject(0).getString("type"); saveWeatherInfo(context, cityName, weatherCode, temp1, temp2, weatherDesp, publishTime); } catch (JSONException e) { e.printStackTrace(); } } /** * ½«·þÎñÆ÷·µ»ØµÄËùÓÐÌìÆøÐÅÏ¢´æ´¢µ½sharePreferencesÎļþÖÐ * @param context * @param cityName * @param weaterCode * @param temp1 * @param temp2 * @param weatherDesp * @param publishTime */ public static void saveWeatherInfo(Context context, String cityName, String weatherCode, String temp1, String temp2, String weatherDesp, String publishTime){ SimpleDateFormat sdf = new SimpleDateFormat("yyyyÄêMÔÂdÈÕ",Locale.CHINA); SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit(); editor.putBoolean("city_selected", true); editor.putString("city_name", cityName); //editor.putString("wendu", wendu); //editor.putString("ganmao", ganmao); //editor.putString("aqi", aqi); editor.putString("temp1", temp1); editor.putString("temp2", temp2); editor.putString("weather_desp", weatherDesp); editor.putString("weather_code", weatherCode); editor.putString("publish_time", publishTime); editor.putString("current_date", sdf.format(new Date())); editor.commit(); } /** * ½âÎöºÍ´¦Àí·þÎñÆ÷·µ»ØµÄÊ¡¼¶Êý¾Ý * @param coolWeatherDB * @param response * @return */ public synchronized static boolean handleProvincesResponse(CoolWeatherDB coolWeatherDB, String response){ if (!TextUtils.isEmpty(response)) { String[] allProvince = response.split(","); if (allProvince != null && allProvince.length > 0) { for (String pString : allProvince) { String[] array = pString.split("\\|"); Province province = new Province(); province.setProvinceCode(array[0]); province.setProvinceName(array[1]); coolWeatherDB.saveProvince(province); } return true; } } return false; } /** * ½âÎöºÍ´¦Àí·þÎñÆ÷·µ»ØµÄÊм¶Êý¾Ý * @param coolWeatherDB * @param response * @param provinceId * @return */ public static boolean handleCitiesResponse(CoolWeatherDB coolWeatherDB, String response, int provinceId){ if (!TextUtils.isEmpty(response)) { String[] allCities = response.split(","); if (allCities != null && allCities.length > 0) { for (String c : allCities) { String[] array = c.split("\\|"); City city = new City(); city.setCityCode(array[0]); city.setCityName(array[1]); city.setProvinceId(provinceId); coolWeatherDB.saveCity(city); } return true; } } return false; } /** * ½âÎöºÍ´¦Àí·þÎñÆ÷·µ»ØµÄÏØ¼¶Êý¾Ý * @param coolWeatherDB * @param response * @param cityId * @return */ public static boolean handleCountiesResponse(CoolWeatherDB coolWeatherDB, String response, int cityId){ if (!TextUtils.isEmpty(response)) { String[] allCounties = response.split(","); if (allCounties != null && allCounties.length > 0) { for(String c : allCounties){ String[] array = c.split("\\|"); County county = new County(); county.setCountyCode(array[0]); county.setCountyName(array[1]); county.setCityId(cityId); coolWeatherDB.saveCounty(county); } return true; } } return false; } }
apache-2.0
xirun/panamax-api
spec/builders/template_builder/from_fig_spec.rb
3419
require 'spec_helper' describe TemplateBuilder::FromFig do let(:fig_yml) { File.open("#{Rails.root}/spec/support/fixtures/fig.yml").read } let(:options) do HashWithIndifferentAccess.new( 'name' => 'figgy-template', 'description' => 'some template', 'keywords' => 'foo,baz,bar', 'authors' => [], 'documentation' => '---\n\nBlah\n\n', 'type' => 'wordpress', 'fig_yml' => fig_yml ) end subject { described_class.new options } context '.create_template' do it 'creates a template from the fig.yml' do expect(subject.create_template).to be_a(Template) end describe 'assigns the options provided to the template' do subject { described_class.new(options).create_template } its(:name) { should eq options[:name] } its(:description) { should eq options[:description] } its(:keywords) { should eq options[:keywords] } its(:type) { should eq options[:type] } its(:documentation) { should eq options[:documentation] } it 'creates images for each service defined in fig.yml' do expect(subject.images).to have_exactly(2).items expect(subject.images.map(&:name)).to match_array(%w(web db)) expect(subject.images.map(&:source)).to match_array(%w(wordpress mysql)) expect(subject.images.find_by(name: 'web').ports).to eq([{ 'host_port' => '8080', 'container_port' => '80' }]) expect(subject.images.find_by(name: 'db').ports).to be_blank expect(subject.images.find_by(name: 'web').links).to eq([{ 'service' => 'db', 'alias' => 'db' }]) expect(subject.images.find_by(name: 'db').links).to be_blank expect(subject.images.find_by(name: 'web').environment).to eq([ { 'variable' => 'MYSQL_PORT_3306_TCP_ADDR', 'value' => '172.17.0.4' }, { 'variable' => 'WORDPRESS_DB_PASSWORD', 'value' => 'mysecretpassword' } ]) expect(subject.images.find_by(name: 'db').environment).to eq([ { 'variable' => 'MYSQL_ROOT_PASSWORD', 'value' => 'mysecretpassword' } ]) expect(subject.images.find_by(name: 'web').volumes).to eq([ { 'host_path' => 'cache/', 'container_path' => '/tmp/cache' } ]) expect(subject.images.find_by(name: 'db').volumes).to be_blank expect(subject.images.find_by(name: 'web').expose).to be_blank expect(subject.images.find_by(name: 'db').expose).to eq(['3306']) expect(subject.images.find_by(name: 'web').volumes_from).to be_blank expect(subject.images.find_by(name: 'db').volumes_from).to eq([{ 'service' => 'web' }]) end end it 'persists the template if the json data is valid' do expect(subject.create_template).to be_persisted end it 'returns the template with errors if the fig.yml is not supported' do invalid_fig_yml = options.merge('fig_yml' => "wordpress:\n build:\n .") strategy = described_class.new invalid_fig_yml expect(strategy.create_template).to_not be_valid expect(strategy.create_template).to_not be_persisted expect(strategy.create_template.errors).to_not be_empty end context 'when persisted flag is false' do it 'returns an unpersisted template ' do t = subject.create_template(false) expect(t.persisted?).to be_false end end end end
apache-2.0
sdeleuze/reactor-core
reactor-core/src/test/java/reactor/core/publisher/MonoDelayUntilTest.java
9453
/* * Copyright (c) 2011-2017 Pivotal Software Inc, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package reactor.core.publisher; import java.time.Duration; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import org.junit.Test; import org.reactivestreams.Publisher; import org.reactivestreams.Subscription; import reactor.core.CoreSubscriber; import reactor.core.Disposable; import reactor.core.Scannable; import reactor.test.StepVerifier; import static org.assertj.core.api.Assertions.assertThat; public class MonoDelayUntilTest { @Test public void testMonoValuedAndPublisherVoid() { Publisher<Void> voidPublisher = Mono.fromRunnable(() -> { }); StepVerifier.create(Mono.just("foo").delayUntil(a -> voidPublisher)) .expectNext("foo") .verifyComplete(); } @Test public void testMonoEmptyAndPublisherVoid() { Publisher<Void> voidPublisher = Mono.fromRunnable(() -> { }); StepVerifier.create(Mono.<String>empty().delayUntil(a -> voidPublisher)) .verifyComplete(); } @Test public void triggerSequenceWithDelays() { StepVerifier.withVirtualTime(() -> Mono.just("foo") .delayUntil(a -> Flux.just(1, 2, 3) .hide() .delayElements(Duration.ofMillis(500)))) .expectSubscription() .expectNoEvent(Duration.ofMillis(1400)) .thenAwait(Duration.ofMillis(100)) .expectNext("foo") .verifyComplete(); } @Test public void triggerSequenceHasMultipleValuesNotCancelled() { AtomicBoolean triggerCancelled = new AtomicBoolean(); StepVerifier.create(Mono.just("foo") .delayUntil( a -> Flux.just(1, 2, 3).hide() .doOnCancel(() -> triggerCancelled.set(true)))) .expectNext("foo") .verifyComplete(); assertThat(triggerCancelled.get()).isFalse(); } @Test public void triggerSequenceHasSingleValueNotCancelled() { AtomicBoolean triggerCancelled = new AtomicBoolean(); StepVerifier.create(Mono.just("foo") .delayUntil( a -> Mono.just(1) .doOnCancel(() -> triggerCancelled.set(true)))) .expectNext("foo") .verifyComplete(); assertThat(triggerCancelled.get()).isFalse(); } @Test public void triggerSequenceDoneFirst() { StepVerifier.withVirtualTime(() -> Mono.delay(Duration.ofSeconds(2)) .delayUntil(a -> Mono.just("foo"))) .expectSubscription() .expectNoEvent(Duration.ofSeconds(2)) .expectNext(0L) .verifyComplete(); } @Test public void sourceHasError() { StepVerifier.create(Mono.<String>error(new IllegalStateException("boom")) .delayUntil(a -> Mono.just("foo"))) .verifyErrorMessage("boom"); } @Test public void triggerHasError() { StepVerifier.create(Mono.just("foo") .delayUntil(a -> Mono.<String>error(new IllegalStateException("boom")))) .verifyErrorMessage("boom"); } @Test public void sourceAndTriggerHaveErrorsNotDelayed() { StepVerifier.create(Mono.<String>error(new IllegalStateException("boom1")) .delayUntil(a -> Mono.<Integer>error(new IllegalStateException("boom2")))) .verifyErrorMessage("boom1"); } @Test public void testAPIDelayUntil() { StepVerifier.withVirtualTime(() -> Mono.just("foo") .delayUntil(a -> Mono.delay(Duration.ofSeconds(2)))) .expectSubscription() .expectNoEvent(Duration.ofSeconds(2)) .expectNext("foo") .verifyComplete(); } @Test public void testAPIDelayUntilErrorsImmediately() { IllegalArgumentException boom = new IllegalArgumentException("boom"); StepVerifier.create(Mono.error(boom) .delayUntil(a -> Mono.delay(Duration.ofSeconds(2)))) .expectErrorMessage("boom") .verify(Duration.ofMillis(200)); //at least, less than 2s } @SuppressWarnings("unchecked") @Test public void testAPIchainingCombines() { Mono<String> source = Mono.just("foo"); Function<String, Flux<Integer>> generator1 = a -> Flux.just(1, 2, 3); Function<Object, Mono<Long>> generator2 = a -> Mono.delay(Duration.ofMillis(800)); MonoDelayUntil<String> until1 = (MonoDelayUntil<String>) source.delayUntil(generator1); MonoDelayUntil<String> until2 = (MonoDelayUntil<String>) until1.delayUntil(generator2); assertThat(until1) .isNotSameAs(until2) ; assertThat(until1.source) .isSameAs(until2.source) ; assertThat(until1.otherGenerators).containsExactly(generator1); assertThat(until2.otherGenerators).containsExactly(generator1, generator2); StepVerifier.create(until2) .expectSubscription() .expectNoEvent(Duration.ofMillis(700)) .thenAwait(Duration.ofMillis(100)) .expectNext("foo") .verifyComplete(); } @Test public void testAPIchainingCumulatesDelaysAfterValueGenerated() { AtomicInteger generator1Used = new AtomicInteger(); AtomicInteger generator2Used = new AtomicInteger(); Function<String, Mono<Long>> generator1 = a -> { generator1Used.incrementAndGet(); return Mono.delay(Duration.ofMillis(400)); }; Function<Object, Mono<Long>> generator2 = a -> { generator2Used.incrementAndGet(); return Mono.delay(Duration.ofMillis(800)); }; StepVerifier.withVirtualTime(() -> Mono.just("foo") .delayElement(Duration.ofSeconds(3)) .delayUntil(generator1) .delayUntil(generator2)) .expectSubscription() .expectNoEvent(Duration.ofMillis(2900)) .then(() -> assertThat(generator1Used.get()).isZero()) .then(() -> assertThat(generator2Used.get()).isZero()) .expectNoEvent(Duration.ofMillis(100)) .then(() -> assertThat(generator1Used.get()).isEqualTo(1)) .then(() -> assertThat(generator2Used.get()).isEqualTo(0)) .expectNoEvent(Duration.ofMillis(400)) .then(() -> assertThat(generator2Used.get()).isEqualTo(1)) .expectNoEvent(Duration.ofMillis(800)) .expectNext("foo") .verifyComplete(); } @Test public void scanCoordinator() { CoreSubscriber<String> actual = new LambdaMonoSubscriber<>(null, e -> {}, null, null); @SuppressWarnings("unchecked") Function<? super String, ? extends Publisher<?>>[] otherGenerators = new Function[3]; MonoDelayUntil.DelayUntilCoordinator<String> test = new MonoDelayUntil.DelayUntilCoordinator<>(actual, otherGenerators); Subscription subscription = Operators.emptySubscription(); test.onSubscribe(subscription); assertThat(test.scan(Scannable.Attr.PARENT)).isNull(); assertThat(test.scan(Scannable.Attr.ACTUAL)).isSameAs(actual); assertThat(test.scan(Scannable.Attr.PREFETCH)).isEqualTo(Integer.MAX_VALUE); assertThat(test.scan(Scannable.Attr.TERMINATED)).isFalse(); test.done = 2; assertThat(test.scan(Scannable.Attr.TERMINATED)).isFalse(); test.done = 3; assertThat(test.scan(Scannable.Attr.TERMINATED)).isTrue(); assertThat(test.scan(Scannable.Attr.CANCELLED)).isFalse(); test.cancel(); assertThat(test.scan(Scannable.Attr.CANCELLED)).isTrue(); } @Test public void scanTrigger() { CoreSubscriber<String> actual = new LambdaMonoSubscriber<>(null, e -> {}, null, null); @SuppressWarnings("unchecked") Function<? super String, ? extends Publisher<?>>[] otherGenerators = new Function[3]; MonoDelayUntil.DelayUntilCoordinator<String> main = new MonoDelayUntil.DelayUntilCoordinator<>( actual, otherGenerators); MonoDelayUntil.DelayUntilTrigger<String> test = new MonoDelayUntil.DelayUntilTrigger<>(main); Subscription subscription = Operators.emptySubscription(); test.onSubscribe(subscription); assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(subscription); assertThat(test.scan(Scannable.Attr.ACTUAL)).isSameAs(main); assertThat(test.scan(Scannable.Attr.PREFETCH)).isEqualTo(Integer.MAX_VALUE); assertThat(test.scan(Scannable.Attr.CANCELLED)).isFalse(); test.cancel(); assertThat(test.scan(Scannable.Attr.CANCELLED)).isTrue(); test.error = new IllegalStateException("boom"); assertThat(test.scan(Scannable.Attr.ERROR)).hasMessage("boom"); } }
apache-2.0
Thangiee/Personal-Health-Monitoring-System
PHMS/libs/LibWizardPager/src/co/juliansuarez/libwizardpager/wizard/model/SingleFixedChoicePage.java
2010
/* * Copyright 2012 Roman Nurik * * 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 co.juliansuarez.libwizardpager.wizard.model; import android.support.v4.app.Fragment; import android.text.TextUtils; import co.juliansuarez.libwizardpager.wizard.ui.SingleChoiceFragment; import java.util.ArrayList; import java.util.Arrays; /** * A page offering the user a number of mutually exclusive choices. */ public class SingleFixedChoicePage extends Page { protected ArrayList<String> mChoices = new ArrayList<String>(); public SingleFixedChoicePage(ModelCallbacks callbacks, String title) { super(callbacks, title); } @Override public Fragment createFragment() { return SingleChoiceFragment.create(getKey()); } public String getOptionAt(int position) { return mChoices.get(position); } public int getOptionCount() { return mChoices.size(); } @Override public void getReviewItems(ArrayList<ReviewItem> dest) { dest.add(new ReviewItem(getTitle(), mData.getString(SIMPLE_DATA_KEY), getKey())); } @Override public boolean isCompleted() { return !TextUtils.isEmpty(mData.getString(SIMPLE_DATA_KEY)); } public SingleFixedChoicePage setChoices(String... choices) { mChoices.addAll(Arrays.asList(choices)); return this; } public SingleFixedChoicePage setValue(String value) { mData.putString(SIMPLE_DATA_KEY, value); return this; } }
apache-2.0
BenzChe/CoolWeather
app/src/main/java/com/example/benzche/coolweather/util/HttpCallBackListener.java
216
package com.example.benzche.coolweather.util; /** * Created by benz.che on 4/20/2016. */ public interface HttpCallBackListener { public void onFinish(String response); public void onError(Exception e); }
apache-2.0
kindlejiang/jkb
addons/library/Http.class.php
16130
<?php // +---------------------------------------------------------------------- // | ThinkPHP // +---------------------------------------------------------------------- // | Copyright (c) 2009 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ /** +------------------------------------------------------------------------------ * Http 工具类 * 提供一系列的Http方法 +------------------------------------------------------------------------------ * @category ORG * @package ORG * @subpackage Net * @author liu21st <liu21st@gmail.com> * @version $Id$ +------------------------------------------------------------------------------ */ class Http extends Think {//类定义开始 /** +---------------------------------------------------------- * 采集远程文件 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $remote 远程文件名 * @param string $local 本地保存文件名 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ static public function curl_download($remote,$local) { $cp = curl_init($remote); $fp = fopen($local,"w"); curl_setopt($cp, CURLOPT_FILE, $fp); curl_setopt($cp, CURLOPT_HEADER, 0); curl_exec($cp); curl_close($cp); fclose($fp); } /** +---------------------------------------------------------- * 下载文件 * 可以指定下载显示的文件名,并自动发送相应的Header信息 * 如果指定了content参数,则下载该参数的内容 +---------------------------------------------------------- * @static * @access public +---------------------------------------------------------- * @param string $filename 下载文件名 * @param string $showname 下载显示的文件名 * @param string $content 下载的内容 * @param integer $expire 下载内容浏览器缓存时间 +---------------------------------------------------------- * @return void +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ static public function download ($filename, $showname='',$content='',$expire=180) { if(is_file($filename)) { $length = filesize($filename); }elseif(is_file(UPLOAD_PATH.$filename)) { $filename = UPLOAD_PATH.$filename; $length = filesize($filename); }elseif($content != '') { $length = strlen($content); }else { throw_exception(L('PUBLIC_ATTACH_ISNULL')); //throw_exception($filename.L('PUBLIC_ATTACH_ISNULL')); } if(empty($showname)) { $showname = $filename; } //造成部分中文文件的乱码问题 //$showname = basename($showname); if(!empty($filename)) { $type = mime_content_type($filename); }else{ $type = "application/octet-stream"; } //发送Http Header信息 开始下载 header("Pragma: public"); header("Cache-control: max-age=".$expire); //header('Cache-Control: no-store, no-cache, must-revalidate'); header("Expires: " . gmdate("D, d M Y H:i:s",time()+$expire) . "GMT"); header("Last-Modified: " . gmdate("D, d M Y H:i:s",time()) . "GMT"); header("Content-Length: ".$length); header("Content-type: ".$type); header("Content-Disposition: attachment; filename= ".$showname." "); header('Content-Encoding: none'); header("Content-Transfer-Encoding: binary" ); if($content == '' ) { readfile($filename); }else { echo($content); } exit(); } /** +---------------------------------------------------------- * 显示HTTP Header 信息 +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ static function get_header_info($header='',$echo=true) { ob_start(); $headers = getallheaders(); if(!empty($header)) { $info = $headers[$header]; echo($header.':'.$info."\n"); ; }else { foreach($headers as $key=>$val) { echo("$key:$val\n"); } } $output = ob_get_clean(); if ($echo) { echo (nl2br($output)); }else { return $output; } } /** * HTTP Protocol defined status codes * @param int $num */ static function send_http_status($code) { static $_status = array( // Informational 1xx 100 => 'Continue', 101 => 'Switching Protocols', // Success 2xx 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content', // Redirection 3xx 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', // 1.1 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', // 306 is deprecated but reserved 307 => 'Temporary Redirect', // Client Error 4xx 400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Timeout', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Long', 415 => 'Unsupported Media Type', 416 => 'Requested Range Not Satisfiable', 417 => 'Expectation Failed', // Server Error 5xx 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Timeout', 505 => 'HTTP Version Not Supported', 509 => 'Bandwidth Limit Exceeded' ); if(array_key_exists($code,$_status)) { header('HTTP/1.1 '.$code.' '.$_status[$code]); } } }//类定义结束 if( !function_exists ('mime_content_type')) { /** +---------------------------------------------------------- * 获取文件的mime_content类型 +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ function mime_content_type($filename) { static $contentType = array( 'ai' => 'application/postscript', 'aif' => 'audio/x-aiff', 'aifc' => 'audio/x-aiff', 'aiff' => 'audio/x-aiff', 'asc' => 'application/pgp', //changed by skwashd - was text/plain 'asf' => 'video/x-ms-asf', 'asx' => 'video/x-ms-asf', 'au' => 'audio/basic', 'avi' => 'video/x-msvideo', 'bcpio' => 'application/x-bcpio', 'bin' => 'application/octet-stream', 'bmp' => 'image/bmp', 'c' => 'text/plain', // or 'text/x-csrc', //added by skwashd 'cc' => 'text/plain', // or 'text/x-c++src', //added by skwashd 'cs' => 'text/plain', //added by skwashd - for C# src 'cpp' => 'text/x-c++src', //added by skwashd 'cxx' => 'text/x-c++src', //added by skwashd 'cdf' => 'application/x-netcdf', 'class' => 'application/octet-stream',//secure but application/java-class is correct 'com' => 'application/octet-stream',//added by skwashd 'cpio' => 'application/x-cpio', 'cpt' => 'application/mac-compactpro', 'csh' => 'application/x-csh', 'css' => 'text/css', 'csv' => 'text/comma-separated-values',//added by skwashd 'dcr' => 'application/x-director', 'diff' => 'text/diff', 'dir' => 'application/x-director', 'dll' => 'application/octet-stream', 'dms' => 'application/octet-stream', 'doc' => 'application/msword', 'dot' => 'application/msword',//added by skwashd 'dvi' => 'application/x-dvi', 'dxr' => 'application/x-director', 'eps' => 'application/postscript', 'etx' => 'text/x-setext', 'exe' => 'application/octet-stream', 'ez' => 'application/andrew-inset', 'gif' => 'image/gif', 'gtar' => 'application/x-gtar', 'gz' => 'application/x-gzip', 'h' => 'text/plain', // or 'text/x-chdr',//added by skwashd 'h++' => 'text/plain', // or 'text/x-c++hdr', //added by skwashd 'hh' => 'text/plain', // or 'text/x-c++hdr', //added by skwashd 'hpp' => 'text/plain', // or 'text/x-c++hdr', //added by skwashd 'hxx' => 'text/plain', // or 'text/x-c++hdr', //added by skwashd 'hdf' => 'application/x-hdf', 'hqx' => 'application/mac-binhex40', 'htm' => 'text/html', 'html' => 'text/html', 'ice' => 'x-conference/x-cooltalk', 'ics' => 'text/calendar', 'ief' => 'image/ief', 'ifb' => 'text/calendar', 'iges' => 'model/iges', 'igs' => 'model/iges', 'jar' => 'application/x-jar', //added by skwashd - alternative mime type 'java' => 'text/x-java-source', //added by skwashd 'jpe' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'jpg' => 'image/jpeg', 'js' => 'application/x-javascript', 'kar' => 'audio/midi', 'latex' => 'application/x-latex', 'lha' => 'application/octet-stream', 'log' => 'text/plain', 'lzh' => 'application/octet-stream', 'm3u' => 'audio/x-mpegurl', 'man' => 'application/x-troff-man', 'me' => 'application/x-troff-me', 'mesh' => 'model/mesh', 'mid' => 'audio/midi', 'midi' => 'audio/midi', 'mif' => 'application/vnd.mif', 'mov' => 'video/quicktime', 'movie' => 'video/x-sgi-movie', 'mp2' => 'audio/mpeg', 'mp3' => 'audio/mpeg', 'mpe' => 'video/mpeg', 'mpeg' => 'video/mpeg', 'mpg' => 'video/mpeg', 'mpga' => 'audio/mpeg', 'ms' => 'application/x-troff-ms', 'msh' => 'model/mesh', 'mxu' => 'video/vnd.mpegurl', 'nc' => 'application/x-netcdf', 'oda' => 'application/oda', 'patch' => 'text/diff', 'pbm' => 'image/x-portable-bitmap', 'pdb' => 'chemical/x-pdb', 'pdf' => 'application/pdf', 'pgm' => 'image/x-portable-graymap', 'pgn' => 'application/x-chess-pgn', 'pgp' => 'application/pgp',//added by skwashd 'php' => 'application/x-httpd-php', 'php3' => 'application/x-httpd-php3', 'pl' => 'application/x-perl', 'pm' => 'application/x-perl', 'png' => 'image/png', 'pnm' => 'image/x-portable-anymap', 'po' => 'text/plain', 'ppm' => 'image/x-portable-pixmap', 'ppt' => 'application/vnd.ms-powerpoint', 'ps' => 'application/postscript', 'qt' => 'video/quicktime', 'ra' => 'audio/x-realaudio', 'rar'=>'application/octet-stream', 'ram' => 'audio/x-pn-realaudio', 'ras' => 'image/x-cmu-raster', 'rgb' => 'image/x-rgb', 'rm' => 'audio/x-pn-realaudio', 'roff' => 'application/x-troff', 'rpm' => 'audio/x-pn-realaudio-plugin', 'rtf' => 'text/rtf', 'rtx' => 'text/richtext', 'sgm' => 'text/sgml', 'sgml' => 'text/sgml', 'sh' => 'application/x-sh', 'shar' => 'application/x-shar', 'shtml' => 'text/html', 'silo' => 'model/mesh', 'sit' => 'application/x-stuffit', 'skd' => 'application/x-koan', 'skm' => 'application/x-koan', 'skp' => 'application/x-koan', 'skt' => 'application/x-koan', 'smi' => 'application/smil', 'smil' => 'application/smil', 'snd' => 'audio/basic', 'so' => 'application/octet-stream', 'spl' => 'application/x-futuresplash', 'src' => 'application/x-wais-source', 'stc' => 'application/vnd.sun.xml.calc.template', 'std' => 'application/vnd.sun.xml.draw.template', 'sti' => 'application/vnd.sun.xml.impress.template', 'stw' => 'application/vnd.sun.xml.writer.template', 'sv4cpio' => 'application/x-sv4cpio', 'sv4crc' => 'application/x-sv4crc', 'swf' => 'application/x-shockwave-flash', 'sxc' => 'application/vnd.sun.xml.calc', 'sxd' => 'application/vnd.sun.xml.draw', 'sxg' => 'application/vnd.sun.xml.writer.global', 'sxi' => 'application/vnd.sun.xml.impress', 'sxm' => 'application/vnd.sun.xml.math', 'sxw' => 'application/vnd.sun.xml.writer', 't' => 'application/x-troff', 'tar' => 'application/x-tar', 'tcl' => 'application/x-tcl', 'tex' => 'application/x-tex', 'texi' => 'application/x-texinfo', 'texinfo' => 'application/x-texinfo', 'tgz' => 'application/x-gtar', 'tif' => 'image/tiff', 'tiff' => 'image/tiff', 'tr' => 'application/x-troff', 'tsv' => 'text/tab-separated-values', 'txt' => 'text/plain', 'ustar' => 'application/x-ustar', 'vbs' => 'text/plain', //added by skwashd - for obvious reasons 'vcd' => 'application/x-cdlink', 'vcf' => 'text/x-vcard', 'vcs' => 'text/calendar', 'vfb' => 'text/calendar', 'vrml' => 'model/vrml', 'vsd' => 'application/vnd.visio', 'wav' => 'audio/x-wav', 'wax' => 'audio/x-ms-wax', 'wbmp' => 'image/vnd.wap.wbmp', 'wbxml' => 'application/vnd.wap.wbxml', 'wm' => 'video/x-ms-wm', 'wma' => 'audio/x-ms-wma', 'wmd' => 'application/x-ms-wmd', 'wml' => 'text/vnd.wap.wml', 'wmlc' => 'application/vnd.wap.wmlc', 'wmls' => 'text/vnd.wap.wmlscript', 'wmlsc' => 'application/vnd.wap.wmlscriptc', 'wmv' => 'video/x-ms-wmv', 'wmx' => 'video/x-ms-wmx', 'wmz' => 'application/x-ms-wmz', 'wrl' => 'model/vrml', 'wvx' => 'video/x-ms-wvx', 'xbm' => 'image/x-xbitmap', 'xht' => 'application/xhtml+xml', 'xhtml' => 'application/xhtml+xml', 'xls' => 'application/vnd.ms-excel', 'xlt' => 'application/vnd.ms-excel', 'xml' => 'application/xml', 'xpm' => 'image/x-xpixmap', 'xsl' => 'text/xml', 'xwd' => 'image/x-xwindowdump', 'xyz' => 'chemical/x-xyz', 'z' => 'application/x-compress', 'zip' => 'application/zip', ); $type = strtolower(substr(strrchr($filename, '.'),1)); if(isset($contentType[$type])) { $mime = $contentType[$type]; }else { $mime = 'application/octet-stream'; } return $mime; } } if(!function_exists('image_type_to_extension')) { function image_type_to_extension($imagetype) { if(empty($imagetype)) return false; switch($imagetype) { case IMAGETYPE_GIF : return '.gif'; case IMAGETYPE_JPEG : return '.jpg'; case IMAGETYPE_PNG : return '.png'; case IMAGETYPE_SWF : return '.swf'; case IMAGETYPE_PSD : return '.psd'; case IMAGETYPE_BMP : return '.bmp'; case IMAGETYPE_TIFF_II : return '.tiff'; case IMAGETYPE_TIFF_MM : return '.tiff'; case IMAGETYPE_JPC : return '.jpc'; case IMAGETYPE_JP2 : return '.jp2'; case IMAGETYPE_JPX : return '.jpf'; case IMAGETYPE_JB2 : return '.jb2'; case IMAGETYPE_SWC : return '.swc'; case IMAGETYPE_IFF : return '.aiff'; case IMAGETYPE_WBMP : return '.wbmp'; case IMAGETYPE_XBM : return '.xbm'; default : return false; } } } ?>
apache-2.0
bibliolabs/rome
rome-modules/src/test/java/com/rometools/modules/base/types/FloatUnitTest.java
1865
/* * FloatUnitTest.java * JUnit based test * * Created on November 18, 2005, 5:16 PM * * 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.rometools.modules.base.types; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.rometools.modules.base.types.FloatUnit; /** * * @author rcooper */ public class FloatUnitTest extends TestCase { private static final Logger LOG = LoggerFactory.getLogger(FloatUnitTest.class); public FloatUnitTest(final String testName) { super(testName); } public static Test suite() { final TestSuite suite = new TestSuite(FloatUnitTest.class); return suite; } /** * Test of getUnits method, of class com.totsp.xml.syndication.base.types.FloatUnit. */ public void testFloatUnit() { LOG.debug("testFloatUnit"); FloatUnit fu = new FloatUnit("1.22km"); assertEquals((float) 1.22, fu.getValue(), 0); assertEquals("km", fu.getUnits()); fu = new FloatUnit("1 gb"); assertEquals(1, fu.getValue(), 0); assertEquals("gb", fu.getUnits()); fu = new FloatUnit("-3.1"); assertEquals((float) -3.1, fu.getValue(), 0); assertEquals(null, fu.getUnits()); } }
apache-2.0
googleinterns/voxetta
ui/src/components/ReRecordButton.js
1420
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import {LitElement, html} from 'lit-element'; import {CollectionStates} from '../utils/CollectionStatesEnum'; import style from '../styles/components/ReRecordButton.css.js'; export class ReRecordButton extends LitElement { static get properties() { return {}; } static get styles() { return style; } /** * Sends an event to trigger re-record logic */ dispatchReRecord() { const event = new CustomEvent('re-record', { bubbles: true, composed: true, }); this.dispatchEvent(event); } render() { return html` <button @click="${this.dispatchReRecord}"> <mwc-icon>refresh</mwc-icon> re-record </button>`; } } customElements.define('vox-re-record-button', ReRecordButton);
apache-2.0
nateman145/bracketologizer
app/controllers/application_controller.rb
347
# Filters added to this controller apply to all controllers in the application. # Likewise, all the methods added will be available for all controllers. class ApplicationController < ActionController::Base helper :all # include all helpers, all the time protect_from_forgery # See ActionController::RequestForgeryProtection for details end
apache-2.0
mchernev/barcode-scanner
server/backend/serverexpress.js
5223
const express = require('express') const app = express() var bodyParser = require("body-parser"); const redis = require('./redistest.js') const model = require('./model.js') app.get('/', function (req, res) { res.send('Hello World!') }) // app.use(express.logger()); // app.use(function(req, res, next) { // //allows localhost:3000 to communicate with this server // // res.header("Access-Control-Allow-Origin", "http://localhost:3000"); // res.header("Access-Control-Allow-Origin", "https://774b09a6.ngrok.io"); // res.header("Access-Control-Allow-Credentials", "true"); // res.header("Access-Control-Allow-Headers", "Origin,Content-Type, Authorization"); // res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); // next(); // }); // app.get('/ass', function (req, res) { // res.send('Hello Ass!') // }) // app.use(bodyParser.urlencoded({ extended: false })); // app.use(bodyParser.json()); // app.post('/ass', function (req, res) { // //res.send('Add an ass!') // console.log(req.body); // res.send(req.body); // }) // app.get('/*', function (req, res) { // res.send('Hello') // }) // var msg = "default"; // redis.exists('string key', function(err, reply) { // if (reply === 1) { // // console.log('exists'); // msg = 'wooow'; // } else { // // console.log('doesn\'t exist'); // msg = 'noooo' // } // }); // // app.get('/wooow', function (req, res) { // res.send(msg); // }); app.get('/get', function (req, res) { redis.get('post', function (err, reply) { res.send(reply); }); }); //// redis.set("another key", "some string", function(err, reply){ //// // console.log(reply); //// //// .then((x) => { //// return model.transferCoin("", ""); //// }).then((x) => { //// // ... //// }).then(()) //// }); app.post('/post', function (req, res) { var json_response = JSON.stringify(req.body); redis.set('post', json_response, function (err, reply) { console.log(json_response); var idFrom = JSON.parse(json_response).id; var idTo = JSON.parse(json_response).sendToId; var amount = JSON.parse(json_response).sendAmount; // model.transferCoins(idFrom, idTo, amount); }); res.send(json_response); }); // function asd(id) { // return new Promise((resolve, reject) => { // redis.get(id, (err, reply) => { // if(err){ // reject('Something went wrong'); // } // else{ // resolve(reply); // } // }); // }); // }; // // asd('100').then((x) => console.log(x)).catch((x) => console.log(x)); var json = { "id":"100", "name":"pe6o", "company":"oracle", "sendToId":"101", "sendAmount":10 }; json = JSON.parse(JSON.stringify(json)); // model.transferCoins(json) app.listen(3001, function () { console.log('Example app listening on port 3001!') }); // redis.set('100', '{"barcoins":100}', function (err, reply) { // console.log(reply); // }); // redis.set('101', '{"barcoins":100}', function (err, reply) { // console.log(reply); // }); // redis.get('100', (err, reply) => { // console.log(reply); // }); // redis.get('101', (err, reply) => { // console.log(reply); // }); // redis.get('id100', function (err, reply) { // console.log(JSON.parse(reply).barcoins); // }); // redis.get('id101', function (err, reply) { // console.log(JSON.parse(reply).barcoins); // }); // redis.get('post', function (err, reply) { // console.log(JSON.parse(reply).barcoins); // }); // redis.exists('post', function(err, reply){ // if (reply) { // redis.get('post', function (err, reply) { // app.get ('/post', function (req, res) { // res.send (reply); // }); // }) // } // else { // app.get ('/post', function (req, res) { // res.send ("Nothing here"); // }); // } // }); // if(redis.exists('post', function(err, reply) { // if (reply === 1) { // var p; // redis.get('post', function(err, reply) { // p = reply; // }); // app.get('/post', function (req, res) { // res.send(p); // }); // } else { // app.get('/post', function (req, res) { // res.send('Nothing here'); // }); // } // })) // var redis = require("redis"), // client = redis.createClient(); // // // if you'd like to select database 3, instead of 0 (default), call // // client.select(3, function() { /* ... */ }); // // client.on("error", function (err) { // console.log("Error " + err); // }); // // client.set("string key", "string val", function(err, reply){ // console.log(reply); // }); // // client.get('string key', function(err, reply) { // console.log(reply); // }); // var msg = "default"; // client.exists('string key', function(err, reply) { // if (reply === 1) { // console.log('exists'); // msg = 'Wooow'; // } else { // console.log('doesn\'t exist'); // } // }); // // app.get('/wooow', function (req, res) { // res.send(msg); // }) // // client.quit();
apache-2.0
Nike-Inc/cerberus-lifecycle-cli
src/main/java/com/nike/cerberus/domain/cloudformation/CloudFormationParametersDelegate.java
2154
/* * Copyright (c) 2019 Nike, 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.nike.cerberus.domain.cloudformation; import com.amazonaws.regions.Regions; import com.beust.jcommander.DynamicParameter; import com.beust.jcommander.Parameter; import java.util.HashMap; import java.util.Map; import java.util.Optional; /** * CloudFormation input parameters common to all Cerberus CloudFormation stacks. */ public class CloudFormationParametersDelegate { public static final String TAG_LONG_ARG = "--TAG"; public static final String TAG_SHORT_ARG = "-T"; public static final String STACK_REGION = "--stack-region"; public static final String STACK_REGION_DESCRIPTION = "The region for the stack, ex: us-west-2, will default to the primary region."; @DynamicParameter( names = { TAG_LONG_ARG, TAG_SHORT_ARG }, description = "Dynamic parameters for setting tags to be used on generated aws resources." ) private Map<String, String> tags = new HashMap<>(); @Parameter(names = STACK_REGION, description = STACK_REGION_DESCRIPTION) private String stackRegion; public Map<String, String> getTags() { return tags; } public Optional<Regions> getStackRegion() { return stackRegion == null ? Optional.empty() : Optional.of(Regions.fromName(stackRegion)); } public String[] getArgs(){ return tags.entrySet() .stream() .map(e -> String.format("%s%s=%s", TAG_LONG_ARG, e.getKey(), e.getValue())) .toArray(String[]::new); } }
apache-2.0
googleapis/nodejs-service-control
protos/protos.d.ts
368034
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import * as Long from "long"; import {protobuf as $protobuf} from "google-gax"; /** Namespace google. */ export namespace google { /** Namespace protobuf. */ namespace protobuf { /** Properties of an Any. */ interface IAny { /** Any type_url */ type_url?: (string|null); /** Any value */ value?: (Uint8Array|string|null); } /** Represents an Any. */ class Any implements IAny { /** * Constructs a new Any. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IAny); /** Any type_url. */ public type_url: string; /** Any value. */ public value: (Uint8Array|string); /** * Creates a new Any instance using the specified properties. * @param [properties] Properties to set * @returns Any instance */ public static create(properties?: google.protobuf.IAny): google.protobuf.Any; /** * Encodes the specified Any message. Does not implicitly {@link google.protobuf.Any.verify|verify} messages. * @param message Any message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IAny, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Any message, length delimited. Does not implicitly {@link google.protobuf.Any.verify|verify} messages. * @param message Any message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IAny, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an Any message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Any * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Any; /** * Decodes an Any message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Any * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Any; /** * Verifies an Any message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an Any message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Any */ public static fromObject(object: { [k: string]: any }): google.protobuf.Any; /** * Creates a plain object from an Any message. Also converts values to other types if specified. * @param message Any * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.Any, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Any to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a Timestamp. */ interface ITimestamp { /** Timestamp seconds */ seconds?: (number|Long|string|null); /** Timestamp nanos */ nanos?: (number|null); } /** Represents a Timestamp. */ class Timestamp implements ITimestamp { /** * Constructs a new Timestamp. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.ITimestamp); /** Timestamp seconds. */ public seconds: (number|Long|string); /** Timestamp nanos. */ public nanos: number; /** * Creates a new Timestamp instance using the specified properties. * @param [properties] Properties to set * @returns Timestamp instance */ public static create(properties?: google.protobuf.ITimestamp): google.protobuf.Timestamp; /** * Encodes the specified Timestamp message. Does not implicitly {@link google.protobuf.Timestamp.verify|verify} messages. * @param message Timestamp message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.ITimestamp, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Timestamp message, length delimited. Does not implicitly {@link google.protobuf.Timestamp.verify|verify} messages. * @param message Timestamp message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.ITimestamp, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Timestamp message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Timestamp * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Timestamp; /** * Decodes a Timestamp message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Timestamp * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Timestamp; /** * Verifies a Timestamp message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Timestamp message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Timestamp */ public static fromObject(object: { [k: string]: any }): google.protobuf.Timestamp; /** * Creates a plain object from a Timestamp message. Also converts values to other types if specified. * @param message Timestamp * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.Timestamp, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Timestamp to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a Duration. */ interface IDuration { /** Duration seconds */ seconds?: (number|Long|string|null); /** Duration nanos */ nanos?: (number|null); } /** Represents a Duration. */ class Duration implements IDuration { /** * Constructs a new Duration. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IDuration); /** Duration seconds. */ public seconds: (number|Long|string); /** Duration nanos. */ public nanos: number; /** * Creates a new Duration instance using the specified properties. * @param [properties] Properties to set * @returns Duration instance */ public static create(properties?: google.protobuf.IDuration): google.protobuf.Duration; /** * Encodes the specified Duration message. Does not implicitly {@link google.protobuf.Duration.verify|verify} messages. * @param message Duration message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IDuration, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Duration message, length delimited. Does not implicitly {@link google.protobuf.Duration.verify|verify} messages. * @param message Duration message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IDuration, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Duration message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Duration * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Duration; /** * Decodes a Duration message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Duration * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Duration; /** * Verifies a Duration message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Duration message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Duration */ public static fromObject(object: { [k: string]: any }): google.protobuf.Duration; /** * Creates a plain object from a Duration message. Also converts values to other types if specified. * @param message Duration * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.Duration, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Duration to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a FileDescriptorSet. */ interface IFileDescriptorSet { /** FileDescriptorSet file */ file?: (google.protobuf.IFileDescriptorProto[]|null); } /** Represents a FileDescriptorSet. */ class FileDescriptorSet implements IFileDescriptorSet { /** * Constructs a new FileDescriptorSet. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IFileDescriptorSet); /** FileDescriptorSet file. */ public file: google.protobuf.IFileDescriptorProto[]; /** * Creates a new FileDescriptorSet instance using the specified properties. * @param [properties] Properties to set * @returns FileDescriptorSet instance */ public static create(properties?: google.protobuf.IFileDescriptorSet): google.protobuf.FileDescriptorSet; /** * Encodes the specified FileDescriptorSet message. Does not implicitly {@link google.protobuf.FileDescriptorSet.verify|verify} messages. * @param message FileDescriptorSet message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IFileDescriptorSet, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified FileDescriptorSet message, length delimited. Does not implicitly {@link google.protobuf.FileDescriptorSet.verify|verify} messages. * @param message FileDescriptorSet message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IFileDescriptorSet, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a FileDescriptorSet message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns FileDescriptorSet * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FileDescriptorSet; /** * Decodes a FileDescriptorSet message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns FileDescriptorSet * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FileDescriptorSet; /** * Verifies a FileDescriptorSet message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a FileDescriptorSet message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns FileDescriptorSet */ public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorSet; /** * Creates a plain object from a FileDescriptorSet message. Also converts values to other types if specified. * @param message FileDescriptorSet * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.FileDescriptorSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this FileDescriptorSet to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a FileDescriptorProto. */ interface IFileDescriptorProto { /** FileDescriptorProto name */ name?: (string|null); /** FileDescriptorProto package */ "package"?: (string|null); /** FileDescriptorProto dependency */ dependency?: (string[]|null); /** FileDescriptorProto publicDependency */ publicDependency?: (number[]|null); /** FileDescriptorProto weakDependency */ weakDependency?: (number[]|null); /** FileDescriptorProto messageType */ messageType?: (google.protobuf.IDescriptorProto[]|null); /** FileDescriptorProto enumType */ enumType?: (google.protobuf.IEnumDescriptorProto[]|null); /** FileDescriptorProto service */ service?: (google.protobuf.IServiceDescriptorProto[]|null); /** FileDescriptorProto extension */ extension?: (google.protobuf.IFieldDescriptorProto[]|null); /** FileDescriptorProto options */ options?: (google.protobuf.IFileOptions|null); /** FileDescriptorProto sourceCodeInfo */ sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); /** FileDescriptorProto syntax */ syntax?: (string|null); } /** Represents a FileDescriptorProto. */ class FileDescriptorProto implements IFileDescriptorProto { /** * Constructs a new FileDescriptorProto. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IFileDescriptorProto); /** FileDescriptorProto name. */ public name: string; /** FileDescriptorProto package. */ public package: string; /** FileDescriptorProto dependency. */ public dependency: string[]; /** FileDescriptorProto publicDependency. */ public publicDependency: number[]; /** FileDescriptorProto weakDependency. */ public weakDependency: number[]; /** FileDescriptorProto messageType. */ public messageType: google.protobuf.IDescriptorProto[]; /** FileDescriptorProto enumType. */ public enumType: google.protobuf.IEnumDescriptorProto[]; /** FileDescriptorProto service. */ public service: google.protobuf.IServiceDescriptorProto[]; /** FileDescriptorProto extension. */ public extension: google.protobuf.IFieldDescriptorProto[]; /** FileDescriptorProto options. */ public options?: (google.protobuf.IFileOptions|null); /** FileDescriptorProto sourceCodeInfo. */ public sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); /** FileDescriptorProto syntax. */ public syntax: string; /** * Creates a new FileDescriptorProto instance using the specified properties. * @param [properties] Properties to set * @returns FileDescriptorProto instance */ public static create(properties?: google.protobuf.IFileDescriptorProto): google.protobuf.FileDescriptorProto; /** * Encodes the specified FileDescriptorProto message. Does not implicitly {@link google.protobuf.FileDescriptorProto.verify|verify} messages. * @param message FileDescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IFileDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified FileDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.FileDescriptorProto.verify|verify} messages. * @param message FileDescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IFileDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a FileDescriptorProto message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns FileDescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FileDescriptorProto; /** * Decodes a FileDescriptorProto message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns FileDescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FileDescriptorProto; /** * Verifies a FileDescriptorProto message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a FileDescriptorProto message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns FileDescriptorProto */ public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorProto; /** * Creates a plain object from a FileDescriptorProto message. Also converts values to other types if specified. * @param message FileDescriptorProto * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.FileDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this FileDescriptorProto to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a DescriptorProto. */ interface IDescriptorProto { /** DescriptorProto name */ name?: (string|null); /** DescriptorProto field */ field?: (google.protobuf.IFieldDescriptorProto[]|null); /** DescriptorProto extension */ extension?: (google.protobuf.IFieldDescriptorProto[]|null); /** DescriptorProto nestedType */ nestedType?: (google.protobuf.IDescriptorProto[]|null); /** DescriptorProto enumType */ enumType?: (google.protobuf.IEnumDescriptorProto[]|null); /** DescriptorProto extensionRange */ extensionRange?: (google.protobuf.DescriptorProto.IExtensionRange[]|null); /** DescriptorProto oneofDecl */ oneofDecl?: (google.protobuf.IOneofDescriptorProto[]|null); /** DescriptorProto options */ options?: (google.protobuf.IMessageOptions|null); /** DescriptorProto reservedRange */ reservedRange?: (google.protobuf.DescriptorProto.IReservedRange[]|null); /** DescriptorProto reservedName */ reservedName?: (string[]|null); } /** Represents a DescriptorProto. */ class DescriptorProto implements IDescriptorProto { /** * Constructs a new DescriptorProto. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IDescriptorProto); /** DescriptorProto name. */ public name: string; /** DescriptorProto field. */ public field: google.protobuf.IFieldDescriptorProto[]; /** DescriptorProto extension. */ public extension: google.protobuf.IFieldDescriptorProto[]; /** DescriptorProto nestedType. */ public nestedType: google.protobuf.IDescriptorProto[]; /** DescriptorProto enumType. */ public enumType: google.protobuf.IEnumDescriptorProto[]; /** DescriptorProto extensionRange. */ public extensionRange: google.protobuf.DescriptorProto.IExtensionRange[]; /** DescriptorProto oneofDecl. */ public oneofDecl: google.protobuf.IOneofDescriptorProto[]; /** DescriptorProto options. */ public options?: (google.protobuf.IMessageOptions|null); /** DescriptorProto reservedRange. */ public reservedRange: google.protobuf.DescriptorProto.IReservedRange[]; /** DescriptorProto reservedName. */ public reservedName: string[]; /** * Creates a new DescriptorProto instance using the specified properties. * @param [properties] Properties to set * @returns DescriptorProto instance */ public static create(properties?: google.protobuf.IDescriptorProto): google.protobuf.DescriptorProto; /** * Encodes the specified DescriptorProto message. Does not implicitly {@link google.protobuf.DescriptorProto.verify|verify} messages. * @param message DescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified DescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.DescriptorProto.verify|verify} messages. * @param message DescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a DescriptorProto message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns DescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.DescriptorProto; /** * Decodes a DescriptorProto message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns DescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.DescriptorProto; /** * Verifies a DescriptorProto message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a DescriptorProto message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns DescriptorProto */ public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto; /** * Creates a plain object from a DescriptorProto message. Also converts values to other types if specified. * @param message DescriptorProto * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.DescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this DescriptorProto to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace DescriptorProto { /** Properties of an ExtensionRange. */ interface IExtensionRange { /** ExtensionRange start */ start?: (number|null); /** ExtensionRange end */ end?: (number|null); /** ExtensionRange options */ options?: (google.protobuf.IExtensionRangeOptions|null); } /** Represents an ExtensionRange. */ class ExtensionRange implements IExtensionRange { /** * Constructs a new ExtensionRange. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.DescriptorProto.IExtensionRange); /** ExtensionRange start. */ public start: number; /** ExtensionRange end. */ public end: number; /** ExtensionRange options. */ public options?: (google.protobuf.IExtensionRangeOptions|null); /** * Creates a new ExtensionRange instance using the specified properties. * @param [properties] Properties to set * @returns ExtensionRange instance */ public static create(properties?: google.protobuf.DescriptorProto.IExtensionRange): google.protobuf.DescriptorProto.ExtensionRange; /** * Encodes the specified ExtensionRange message. Does not implicitly {@link google.protobuf.DescriptorProto.ExtensionRange.verify|verify} messages. * @param message ExtensionRange message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.DescriptorProto.IExtensionRange, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ExtensionRange message, length delimited. Does not implicitly {@link google.protobuf.DescriptorProto.ExtensionRange.verify|verify} messages. * @param message ExtensionRange message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.DescriptorProto.IExtensionRange, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an ExtensionRange message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ExtensionRange * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.DescriptorProto.ExtensionRange; /** * Decodes an ExtensionRange message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ExtensionRange * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.DescriptorProto.ExtensionRange; /** * Verifies an ExtensionRange message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an ExtensionRange message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ExtensionRange */ public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ExtensionRange; /** * Creates a plain object from an ExtensionRange message. Also converts values to other types if specified. * @param message ExtensionRange * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.DescriptorProto.ExtensionRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ExtensionRange to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a ReservedRange. */ interface IReservedRange { /** ReservedRange start */ start?: (number|null); /** ReservedRange end */ end?: (number|null); } /** Represents a ReservedRange. */ class ReservedRange implements IReservedRange { /** * Constructs a new ReservedRange. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.DescriptorProto.IReservedRange); /** ReservedRange start. */ public start: number; /** ReservedRange end. */ public end: number; /** * Creates a new ReservedRange instance using the specified properties. * @param [properties] Properties to set * @returns ReservedRange instance */ public static create(properties?: google.protobuf.DescriptorProto.IReservedRange): google.protobuf.DescriptorProto.ReservedRange; /** * Encodes the specified ReservedRange message. Does not implicitly {@link google.protobuf.DescriptorProto.ReservedRange.verify|verify} messages. * @param message ReservedRange message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.DescriptorProto.IReservedRange, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ReservedRange message, length delimited. Does not implicitly {@link google.protobuf.DescriptorProto.ReservedRange.verify|verify} messages. * @param message ReservedRange message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.DescriptorProto.IReservedRange, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ReservedRange message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ReservedRange * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.DescriptorProto.ReservedRange; /** * Decodes a ReservedRange message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ReservedRange * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.DescriptorProto.ReservedRange; /** * Verifies a ReservedRange message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ReservedRange message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ReservedRange */ public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ReservedRange; /** * Creates a plain object from a ReservedRange message. Also converts values to other types if specified. * @param message ReservedRange * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.DescriptorProto.ReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ReservedRange to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } /** Properties of an ExtensionRangeOptions. */ interface IExtensionRangeOptions { /** ExtensionRangeOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); } /** Represents an ExtensionRangeOptions. */ class ExtensionRangeOptions implements IExtensionRangeOptions { /** * Constructs a new ExtensionRangeOptions. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IExtensionRangeOptions); /** ExtensionRangeOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; /** * Creates a new ExtensionRangeOptions instance using the specified properties. * @param [properties] Properties to set * @returns ExtensionRangeOptions instance */ public static create(properties?: google.protobuf.IExtensionRangeOptions): google.protobuf.ExtensionRangeOptions; /** * Encodes the specified ExtensionRangeOptions message. Does not implicitly {@link google.protobuf.ExtensionRangeOptions.verify|verify} messages. * @param message ExtensionRangeOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IExtensionRangeOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ExtensionRangeOptions message, length delimited. Does not implicitly {@link google.protobuf.ExtensionRangeOptions.verify|verify} messages. * @param message ExtensionRangeOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IExtensionRangeOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an ExtensionRangeOptions message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ExtensionRangeOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.ExtensionRangeOptions; /** * Decodes an ExtensionRangeOptions message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ExtensionRangeOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.ExtensionRangeOptions; /** * Verifies an ExtensionRangeOptions message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an ExtensionRangeOptions message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ExtensionRangeOptions */ public static fromObject(object: { [k: string]: any }): google.protobuf.ExtensionRangeOptions; /** * Creates a plain object from an ExtensionRangeOptions message. Also converts values to other types if specified. * @param message ExtensionRangeOptions * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.ExtensionRangeOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ExtensionRangeOptions to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a FieldDescriptorProto. */ interface IFieldDescriptorProto { /** FieldDescriptorProto name */ name?: (string|null); /** FieldDescriptorProto number */ number?: (number|null); /** FieldDescriptorProto label */ label?: (google.protobuf.FieldDescriptorProto.Label|keyof typeof google.protobuf.FieldDescriptorProto.Label|null); /** FieldDescriptorProto type */ type?: (google.protobuf.FieldDescriptorProto.Type|keyof typeof google.protobuf.FieldDescriptorProto.Type|null); /** FieldDescriptorProto typeName */ typeName?: (string|null); /** FieldDescriptorProto extendee */ extendee?: (string|null); /** FieldDescriptorProto defaultValue */ defaultValue?: (string|null); /** FieldDescriptorProto oneofIndex */ oneofIndex?: (number|null); /** FieldDescriptorProto jsonName */ jsonName?: (string|null); /** FieldDescriptorProto options */ options?: (google.protobuf.IFieldOptions|null); /** FieldDescriptorProto proto3Optional */ proto3Optional?: (boolean|null); } /** Represents a FieldDescriptorProto. */ class FieldDescriptorProto implements IFieldDescriptorProto { /** * Constructs a new FieldDescriptorProto. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IFieldDescriptorProto); /** FieldDescriptorProto name. */ public name: string; /** FieldDescriptorProto number. */ public number: number; /** FieldDescriptorProto label. */ public label: (google.protobuf.FieldDescriptorProto.Label|keyof typeof google.protobuf.FieldDescriptorProto.Label); /** FieldDescriptorProto type. */ public type: (google.protobuf.FieldDescriptorProto.Type|keyof typeof google.protobuf.FieldDescriptorProto.Type); /** FieldDescriptorProto typeName. */ public typeName: string; /** FieldDescriptorProto extendee. */ public extendee: string; /** FieldDescriptorProto defaultValue. */ public defaultValue: string; /** FieldDescriptorProto oneofIndex. */ public oneofIndex: number; /** FieldDescriptorProto jsonName. */ public jsonName: string; /** FieldDescriptorProto options. */ public options?: (google.protobuf.IFieldOptions|null); /** FieldDescriptorProto proto3Optional. */ public proto3Optional: boolean; /** * Creates a new FieldDescriptorProto instance using the specified properties. * @param [properties] Properties to set * @returns FieldDescriptorProto instance */ public static create(properties?: google.protobuf.IFieldDescriptorProto): google.protobuf.FieldDescriptorProto; /** * Encodes the specified FieldDescriptorProto message. Does not implicitly {@link google.protobuf.FieldDescriptorProto.verify|verify} messages. * @param message FieldDescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IFieldDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified FieldDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.FieldDescriptorProto.verify|verify} messages. * @param message FieldDescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IFieldDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a FieldDescriptorProto message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns FieldDescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FieldDescriptorProto; /** * Decodes a FieldDescriptorProto message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns FieldDescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FieldDescriptorProto; /** * Verifies a FieldDescriptorProto message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a FieldDescriptorProto message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns FieldDescriptorProto */ public static fromObject(object: { [k: string]: any }): google.protobuf.FieldDescriptorProto; /** * Creates a plain object from a FieldDescriptorProto message. Also converts values to other types if specified. * @param message FieldDescriptorProto * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.FieldDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this FieldDescriptorProto to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace FieldDescriptorProto { /** Type enum. */ enum Type { TYPE_DOUBLE = 1, TYPE_FLOAT = 2, TYPE_INT64 = 3, TYPE_UINT64 = 4, TYPE_INT32 = 5, TYPE_FIXED64 = 6, TYPE_FIXED32 = 7, TYPE_BOOL = 8, TYPE_STRING = 9, TYPE_GROUP = 10, TYPE_MESSAGE = 11, TYPE_BYTES = 12, TYPE_UINT32 = 13, TYPE_ENUM = 14, TYPE_SFIXED32 = 15, TYPE_SFIXED64 = 16, TYPE_SINT32 = 17, TYPE_SINT64 = 18 } /** Label enum. */ enum Label { LABEL_OPTIONAL = 1, LABEL_REQUIRED = 2, LABEL_REPEATED = 3 } } /** Properties of an OneofDescriptorProto. */ interface IOneofDescriptorProto { /** OneofDescriptorProto name */ name?: (string|null); /** OneofDescriptorProto options */ options?: (google.protobuf.IOneofOptions|null); } /** Represents an OneofDescriptorProto. */ class OneofDescriptorProto implements IOneofDescriptorProto { /** * Constructs a new OneofDescriptorProto. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IOneofDescriptorProto); /** OneofDescriptorProto name. */ public name: string; /** OneofDescriptorProto options. */ public options?: (google.protobuf.IOneofOptions|null); /** * Creates a new OneofDescriptorProto instance using the specified properties. * @param [properties] Properties to set * @returns OneofDescriptorProto instance */ public static create(properties?: google.protobuf.IOneofDescriptorProto): google.protobuf.OneofDescriptorProto; /** * Encodes the specified OneofDescriptorProto message. Does not implicitly {@link google.protobuf.OneofDescriptorProto.verify|verify} messages. * @param message OneofDescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IOneofDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified OneofDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.OneofDescriptorProto.verify|verify} messages. * @param message OneofDescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IOneofDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an OneofDescriptorProto message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns OneofDescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.OneofDescriptorProto; /** * Decodes an OneofDescriptorProto message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns OneofDescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.OneofDescriptorProto; /** * Verifies an OneofDescriptorProto message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an OneofDescriptorProto message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns OneofDescriptorProto */ public static fromObject(object: { [k: string]: any }): google.protobuf.OneofDescriptorProto; /** * Creates a plain object from an OneofDescriptorProto message. Also converts values to other types if specified. * @param message OneofDescriptorProto * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.OneofDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this OneofDescriptorProto to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of an EnumDescriptorProto. */ interface IEnumDescriptorProto { /** EnumDescriptorProto name */ name?: (string|null); /** EnumDescriptorProto value */ value?: (google.protobuf.IEnumValueDescriptorProto[]|null); /** EnumDescriptorProto options */ options?: (google.protobuf.IEnumOptions|null); /** EnumDescriptorProto reservedRange */ reservedRange?: (google.protobuf.EnumDescriptorProto.IEnumReservedRange[]|null); /** EnumDescriptorProto reservedName */ reservedName?: (string[]|null); } /** Represents an EnumDescriptorProto. */ class EnumDescriptorProto implements IEnumDescriptorProto { /** * Constructs a new EnumDescriptorProto. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IEnumDescriptorProto); /** EnumDescriptorProto name. */ public name: string; /** EnumDescriptorProto value. */ public value: google.protobuf.IEnumValueDescriptorProto[]; /** EnumDescriptorProto options. */ public options?: (google.protobuf.IEnumOptions|null); /** EnumDescriptorProto reservedRange. */ public reservedRange: google.protobuf.EnumDescriptorProto.IEnumReservedRange[]; /** EnumDescriptorProto reservedName. */ public reservedName: string[]; /** * Creates a new EnumDescriptorProto instance using the specified properties. * @param [properties] Properties to set * @returns EnumDescriptorProto instance */ public static create(properties?: google.protobuf.IEnumDescriptorProto): google.protobuf.EnumDescriptorProto; /** * Encodes the specified EnumDescriptorProto message. Does not implicitly {@link google.protobuf.EnumDescriptorProto.verify|verify} messages. * @param message EnumDescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IEnumDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified EnumDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.EnumDescriptorProto.verify|verify} messages. * @param message EnumDescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IEnumDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an EnumDescriptorProto message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns EnumDescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumDescriptorProto; /** * Decodes an EnumDescriptorProto message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns EnumDescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumDescriptorProto; /** * Verifies an EnumDescriptorProto message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an EnumDescriptorProto message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns EnumDescriptorProto */ public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto; /** * Creates a plain object from an EnumDescriptorProto message. Also converts values to other types if specified. * @param message EnumDescriptorProto * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.EnumDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this EnumDescriptorProto to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace EnumDescriptorProto { /** Properties of an EnumReservedRange. */ interface IEnumReservedRange { /** EnumReservedRange start */ start?: (number|null); /** EnumReservedRange end */ end?: (number|null); } /** Represents an EnumReservedRange. */ class EnumReservedRange implements IEnumReservedRange { /** * Constructs a new EnumReservedRange. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.EnumDescriptorProto.IEnumReservedRange); /** EnumReservedRange start. */ public start: number; /** EnumReservedRange end. */ public end: number; /** * Creates a new EnumReservedRange instance using the specified properties. * @param [properties] Properties to set * @returns EnumReservedRange instance */ public static create(properties?: google.protobuf.EnumDescriptorProto.IEnumReservedRange): google.protobuf.EnumDescriptorProto.EnumReservedRange; /** * Encodes the specified EnumReservedRange message. Does not implicitly {@link google.protobuf.EnumDescriptorProto.EnumReservedRange.verify|verify} messages. * @param message EnumReservedRange message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.EnumDescriptorProto.IEnumReservedRange, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified EnumReservedRange message, length delimited. Does not implicitly {@link google.protobuf.EnumDescriptorProto.EnumReservedRange.verify|verify} messages. * @param message EnumReservedRange message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.EnumDescriptorProto.IEnumReservedRange, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an EnumReservedRange message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns EnumReservedRange * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumDescriptorProto.EnumReservedRange; /** * Decodes an EnumReservedRange message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns EnumReservedRange * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumDescriptorProto.EnumReservedRange; /** * Verifies an EnumReservedRange message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an EnumReservedRange message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns EnumReservedRange */ public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto.EnumReservedRange; /** * Creates a plain object from an EnumReservedRange message. Also converts values to other types if specified. * @param message EnumReservedRange * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.EnumDescriptorProto.EnumReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this EnumReservedRange to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } /** Properties of an EnumValueDescriptorProto. */ interface IEnumValueDescriptorProto { /** EnumValueDescriptorProto name */ name?: (string|null); /** EnumValueDescriptorProto number */ number?: (number|null); /** EnumValueDescriptorProto options */ options?: (google.protobuf.IEnumValueOptions|null); } /** Represents an EnumValueDescriptorProto. */ class EnumValueDescriptorProto implements IEnumValueDescriptorProto { /** * Constructs a new EnumValueDescriptorProto. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IEnumValueDescriptorProto); /** EnumValueDescriptorProto name. */ public name: string; /** EnumValueDescriptorProto number. */ public number: number; /** EnumValueDescriptorProto options. */ public options?: (google.protobuf.IEnumValueOptions|null); /** * Creates a new EnumValueDescriptorProto instance using the specified properties. * @param [properties] Properties to set * @returns EnumValueDescriptorProto instance */ public static create(properties?: google.protobuf.IEnumValueDescriptorProto): google.protobuf.EnumValueDescriptorProto; /** * Encodes the specified EnumValueDescriptorProto message. Does not implicitly {@link google.protobuf.EnumValueDescriptorProto.verify|verify} messages. * @param message EnumValueDescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IEnumValueDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified EnumValueDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.EnumValueDescriptorProto.verify|verify} messages. * @param message EnumValueDescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IEnumValueDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an EnumValueDescriptorProto message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns EnumValueDescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumValueDescriptorProto; /** * Decodes an EnumValueDescriptorProto message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns EnumValueDescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumValueDescriptorProto; /** * Verifies an EnumValueDescriptorProto message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an EnumValueDescriptorProto message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns EnumValueDescriptorProto */ public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueDescriptorProto; /** * Creates a plain object from an EnumValueDescriptorProto message. Also converts values to other types if specified. * @param message EnumValueDescriptorProto * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.EnumValueDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this EnumValueDescriptorProto to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a ServiceDescriptorProto. */ interface IServiceDescriptorProto { /** ServiceDescriptorProto name */ name?: (string|null); /** ServiceDescriptorProto method */ method?: (google.protobuf.IMethodDescriptorProto[]|null); /** ServiceDescriptorProto options */ options?: (google.protobuf.IServiceOptions|null); } /** Represents a ServiceDescriptorProto. */ class ServiceDescriptorProto implements IServiceDescriptorProto { /** * Constructs a new ServiceDescriptorProto. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IServiceDescriptorProto); /** ServiceDescriptorProto name. */ public name: string; /** ServiceDescriptorProto method. */ public method: google.protobuf.IMethodDescriptorProto[]; /** ServiceDescriptorProto options. */ public options?: (google.protobuf.IServiceOptions|null); /** * Creates a new ServiceDescriptorProto instance using the specified properties. * @param [properties] Properties to set * @returns ServiceDescriptorProto instance */ public static create(properties?: google.protobuf.IServiceDescriptorProto): google.protobuf.ServiceDescriptorProto; /** * Encodes the specified ServiceDescriptorProto message. Does not implicitly {@link google.protobuf.ServiceDescriptorProto.verify|verify} messages. * @param message ServiceDescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IServiceDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ServiceDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.ServiceDescriptorProto.verify|verify} messages. * @param message ServiceDescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IServiceDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ServiceDescriptorProto message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ServiceDescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.ServiceDescriptorProto; /** * Decodes a ServiceDescriptorProto message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ServiceDescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.ServiceDescriptorProto; /** * Verifies a ServiceDescriptorProto message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ServiceDescriptorProto message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ServiceDescriptorProto */ public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceDescriptorProto; /** * Creates a plain object from a ServiceDescriptorProto message. Also converts values to other types if specified. * @param message ServiceDescriptorProto * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.ServiceDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ServiceDescriptorProto to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a MethodDescriptorProto. */ interface IMethodDescriptorProto { /** MethodDescriptorProto name */ name?: (string|null); /** MethodDescriptorProto inputType */ inputType?: (string|null); /** MethodDescriptorProto outputType */ outputType?: (string|null); /** MethodDescriptorProto options */ options?: (google.protobuf.IMethodOptions|null); /** MethodDescriptorProto clientStreaming */ clientStreaming?: (boolean|null); /** MethodDescriptorProto serverStreaming */ serverStreaming?: (boolean|null); } /** Represents a MethodDescriptorProto. */ class MethodDescriptorProto implements IMethodDescriptorProto { /** * Constructs a new MethodDescriptorProto. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IMethodDescriptorProto); /** MethodDescriptorProto name. */ public name: string; /** MethodDescriptorProto inputType. */ public inputType: string; /** MethodDescriptorProto outputType. */ public outputType: string; /** MethodDescriptorProto options. */ public options?: (google.protobuf.IMethodOptions|null); /** MethodDescriptorProto clientStreaming. */ public clientStreaming: boolean; /** MethodDescriptorProto serverStreaming. */ public serverStreaming: boolean; /** * Creates a new MethodDescriptorProto instance using the specified properties. * @param [properties] Properties to set * @returns MethodDescriptorProto instance */ public static create(properties?: google.protobuf.IMethodDescriptorProto): google.protobuf.MethodDescriptorProto; /** * Encodes the specified MethodDescriptorProto message. Does not implicitly {@link google.protobuf.MethodDescriptorProto.verify|verify} messages. * @param message MethodDescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IMethodDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified MethodDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.MethodDescriptorProto.verify|verify} messages. * @param message MethodDescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IMethodDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a MethodDescriptorProto message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns MethodDescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.MethodDescriptorProto; /** * Decodes a MethodDescriptorProto message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns MethodDescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.MethodDescriptorProto; /** * Verifies a MethodDescriptorProto message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a MethodDescriptorProto message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns MethodDescriptorProto */ public static fromObject(object: { [k: string]: any }): google.protobuf.MethodDescriptorProto; /** * Creates a plain object from a MethodDescriptorProto message. Also converts values to other types if specified. * @param message MethodDescriptorProto * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.MethodDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this MethodDescriptorProto to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a FileOptions. */ interface IFileOptions { /** FileOptions javaPackage */ javaPackage?: (string|null); /** FileOptions javaOuterClassname */ javaOuterClassname?: (string|null); /** FileOptions javaMultipleFiles */ javaMultipleFiles?: (boolean|null); /** FileOptions javaGenerateEqualsAndHash */ javaGenerateEqualsAndHash?: (boolean|null); /** FileOptions javaStringCheckUtf8 */ javaStringCheckUtf8?: (boolean|null); /** FileOptions optimizeFor */ optimizeFor?: (google.protobuf.FileOptions.OptimizeMode|keyof typeof google.protobuf.FileOptions.OptimizeMode|null); /** FileOptions goPackage */ goPackage?: (string|null); /** FileOptions ccGenericServices */ ccGenericServices?: (boolean|null); /** FileOptions javaGenericServices */ javaGenericServices?: (boolean|null); /** FileOptions pyGenericServices */ pyGenericServices?: (boolean|null); /** FileOptions phpGenericServices */ phpGenericServices?: (boolean|null); /** FileOptions deprecated */ deprecated?: (boolean|null); /** FileOptions ccEnableArenas */ ccEnableArenas?: (boolean|null); /** FileOptions objcClassPrefix */ objcClassPrefix?: (string|null); /** FileOptions csharpNamespace */ csharpNamespace?: (string|null); /** FileOptions swiftPrefix */ swiftPrefix?: (string|null); /** FileOptions phpClassPrefix */ phpClassPrefix?: (string|null); /** FileOptions phpNamespace */ phpNamespace?: (string|null); /** FileOptions phpMetadataNamespace */ phpMetadataNamespace?: (string|null); /** FileOptions rubyPackage */ rubyPackage?: (string|null); /** FileOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); } /** Represents a FileOptions. */ class FileOptions implements IFileOptions { /** * Constructs a new FileOptions. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IFileOptions); /** FileOptions javaPackage. */ public javaPackage: string; /** FileOptions javaOuterClassname. */ public javaOuterClassname: string; /** FileOptions javaMultipleFiles. */ public javaMultipleFiles: boolean; /** FileOptions javaGenerateEqualsAndHash. */ public javaGenerateEqualsAndHash: boolean; /** FileOptions javaStringCheckUtf8. */ public javaStringCheckUtf8: boolean; /** FileOptions optimizeFor. */ public optimizeFor: (google.protobuf.FileOptions.OptimizeMode|keyof typeof google.protobuf.FileOptions.OptimizeMode); /** FileOptions goPackage. */ public goPackage: string; /** FileOptions ccGenericServices. */ public ccGenericServices: boolean; /** FileOptions javaGenericServices. */ public javaGenericServices: boolean; /** FileOptions pyGenericServices. */ public pyGenericServices: boolean; /** FileOptions phpGenericServices. */ public phpGenericServices: boolean; /** FileOptions deprecated. */ public deprecated: boolean; /** FileOptions ccEnableArenas. */ public ccEnableArenas: boolean; /** FileOptions objcClassPrefix. */ public objcClassPrefix: string; /** FileOptions csharpNamespace. */ public csharpNamespace: string; /** FileOptions swiftPrefix. */ public swiftPrefix: string; /** FileOptions phpClassPrefix. */ public phpClassPrefix: string; /** FileOptions phpNamespace. */ public phpNamespace: string; /** FileOptions phpMetadataNamespace. */ public phpMetadataNamespace: string; /** FileOptions rubyPackage. */ public rubyPackage: string; /** FileOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; /** * Creates a new FileOptions instance using the specified properties. * @param [properties] Properties to set * @returns FileOptions instance */ public static create(properties?: google.protobuf.IFileOptions): google.protobuf.FileOptions; /** * Encodes the specified FileOptions message. Does not implicitly {@link google.protobuf.FileOptions.verify|verify} messages. * @param message FileOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IFileOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified FileOptions message, length delimited. Does not implicitly {@link google.protobuf.FileOptions.verify|verify} messages. * @param message FileOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IFileOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a FileOptions message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns FileOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FileOptions; /** * Decodes a FileOptions message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns FileOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FileOptions; /** * Verifies a FileOptions message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a FileOptions message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns FileOptions */ public static fromObject(object: { [k: string]: any }): google.protobuf.FileOptions; /** * Creates a plain object from a FileOptions message. Also converts values to other types if specified. * @param message FileOptions * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.FileOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this FileOptions to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace FileOptions { /** OptimizeMode enum. */ enum OptimizeMode { SPEED = 1, CODE_SIZE = 2, LITE_RUNTIME = 3 } } /** Properties of a MessageOptions. */ interface IMessageOptions { /** MessageOptions messageSetWireFormat */ messageSetWireFormat?: (boolean|null); /** MessageOptions noStandardDescriptorAccessor */ noStandardDescriptorAccessor?: (boolean|null); /** MessageOptions deprecated */ deprecated?: (boolean|null); /** MessageOptions mapEntry */ mapEntry?: (boolean|null); /** MessageOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); } /** Represents a MessageOptions. */ class MessageOptions implements IMessageOptions { /** * Constructs a new MessageOptions. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IMessageOptions); /** MessageOptions messageSetWireFormat. */ public messageSetWireFormat: boolean; /** MessageOptions noStandardDescriptorAccessor. */ public noStandardDescriptorAccessor: boolean; /** MessageOptions deprecated. */ public deprecated: boolean; /** MessageOptions mapEntry. */ public mapEntry: boolean; /** MessageOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; /** * Creates a new MessageOptions instance using the specified properties. * @param [properties] Properties to set * @returns MessageOptions instance */ public static create(properties?: google.protobuf.IMessageOptions): google.protobuf.MessageOptions; /** * Encodes the specified MessageOptions message. Does not implicitly {@link google.protobuf.MessageOptions.verify|verify} messages. * @param message MessageOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IMessageOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified MessageOptions message, length delimited. Does not implicitly {@link google.protobuf.MessageOptions.verify|verify} messages. * @param message MessageOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IMessageOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a MessageOptions message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns MessageOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.MessageOptions; /** * Decodes a MessageOptions message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns MessageOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.MessageOptions; /** * Verifies a MessageOptions message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a MessageOptions message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns MessageOptions */ public static fromObject(object: { [k: string]: any }): google.protobuf.MessageOptions; /** * Creates a plain object from a MessageOptions message. Also converts values to other types if specified. * @param message MessageOptions * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.MessageOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this MessageOptions to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a FieldOptions. */ interface IFieldOptions { /** FieldOptions ctype */ ctype?: (google.protobuf.FieldOptions.CType|keyof typeof google.protobuf.FieldOptions.CType|null); /** FieldOptions packed */ packed?: (boolean|null); /** FieldOptions jstype */ jstype?: (google.protobuf.FieldOptions.JSType|keyof typeof google.protobuf.FieldOptions.JSType|null); /** FieldOptions lazy */ lazy?: (boolean|null); /** FieldOptions deprecated */ deprecated?: (boolean|null); /** FieldOptions weak */ weak?: (boolean|null); /** FieldOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); } /** Represents a FieldOptions. */ class FieldOptions implements IFieldOptions { /** * Constructs a new FieldOptions. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IFieldOptions); /** FieldOptions ctype. */ public ctype: (google.protobuf.FieldOptions.CType|keyof typeof google.protobuf.FieldOptions.CType); /** FieldOptions packed. */ public packed: boolean; /** FieldOptions jstype. */ public jstype: (google.protobuf.FieldOptions.JSType|keyof typeof google.protobuf.FieldOptions.JSType); /** FieldOptions lazy. */ public lazy: boolean; /** FieldOptions deprecated. */ public deprecated: boolean; /** FieldOptions weak. */ public weak: boolean; /** FieldOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; /** * Creates a new FieldOptions instance using the specified properties. * @param [properties] Properties to set * @returns FieldOptions instance */ public static create(properties?: google.protobuf.IFieldOptions): google.protobuf.FieldOptions; /** * Encodes the specified FieldOptions message. Does not implicitly {@link google.protobuf.FieldOptions.verify|verify} messages. * @param message FieldOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IFieldOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified FieldOptions message, length delimited. Does not implicitly {@link google.protobuf.FieldOptions.verify|verify} messages. * @param message FieldOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IFieldOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a FieldOptions message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns FieldOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FieldOptions; /** * Decodes a FieldOptions message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns FieldOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FieldOptions; /** * Verifies a FieldOptions message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a FieldOptions message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns FieldOptions */ public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions; /** * Creates a plain object from a FieldOptions message. Also converts values to other types if specified. * @param message FieldOptions * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.FieldOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this FieldOptions to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace FieldOptions { /** CType enum. */ enum CType { STRING = 0, CORD = 1, STRING_PIECE = 2 } /** JSType enum. */ enum JSType { JS_NORMAL = 0, JS_STRING = 1, JS_NUMBER = 2 } } /** Properties of an OneofOptions. */ interface IOneofOptions { /** OneofOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); } /** Represents an OneofOptions. */ class OneofOptions implements IOneofOptions { /** * Constructs a new OneofOptions. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IOneofOptions); /** OneofOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; /** * Creates a new OneofOptions instance using the specified properties. * @param [properties] Properties to set * @returns OneofOptions instance */ public static create(properties?: google.protobuf.IOneofOptions): google.protobuf.OneofOptions; /** * Encodes the specified OneofOptions message. Does not implicitly {@link google.protobuf.OneofOptions.verify|verify} messages. * @param message OneofOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IOneofOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified OneofOptions message, length delimited. Does not implicitly {@link google.protobuf.OneofOptions.verify|verify} messages. * @param message OneofOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IOneofOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an OneofOptions message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns OneofOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.OneofOptions; /** * Decodes an OneofOptions message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns OneofOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.OneofOptions; /** * Verifies an OneofOptions message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an OneofOptions message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns OneofOptions */ public static fromObject(object: { [k: string]: any }): google.protobuf.OneofOptions; /** * Creates a plain object from an OneofOptions message. Also converts values to other types if specified. * @param message OneofOptions * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.OneofOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this OneofOptions to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of an EnumOptions. */ interface IEnumOptions { /** EnumOptions allowAlias */ allowAlias?: (boolean|null); /** EnumOptions deprecated */ deprecated?: (boolean|null); /** EnumOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); } /** Represents an EnumOptions. */ class EnumOptions implements IEnumOptions { /** * Constructs a new EnumOptions. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IEnumOptions); /** EnumOptions allowAlias. */ public allowAlias: boolean; /** EnumOptions deprecated. */ public deprecated: boolean; /** EnumOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; /** * Creates a new EnumOptions instance using the specified properties. * @param [properties] Properties to set * @returns EnumOptions instance */ public static create(properties?: google.protobuf.IEnumOptions): google.protobuf.EnumOptions; /** * Encodes the specified EnumOptions message. Does not implicitly {@link google.protobuf.EnumOptions.verify|verify} messages. * @param message EnumOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IEnumOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified EnumOptions message, length delimited. Does not implicitly {@link google.protobuf.EnumOptions.verify|verify} messages. * @param message EnumOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IEnumOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an EnumOptions message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns EnumOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumOptions; /** * Decodes an EnumOptions message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns EnumOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumOptions; /** * Verifies an EnumOptions message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an EnumOptions message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns EnumOptions */ public static fromObject(object: { [k: string]: any }): google.protobuf.EnumOptions; /** * Creates a plain object from an EnumOptions message. Also converts values to other types if specified. * @param message EnumOptions * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.EnumOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this EnumOptions to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of an EnumValueOptions. */ interface IEnumValueOptions { /** EnumValueOptions deprecated */ deprecated?: (boolean|null); /** EnumValueOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); } /** Represents an EnumValueOptions. */ class EnumValueOptions implements IEnumValueOptions { /** * Constructs a new EnumValueOptions. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IEnumValueOptions); /** EnumValueOptions deprecated. */ public deprecated: boolean; /** EnumValueOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; /** * Creates a new EnumValueOptions instance using the specified properties. * @param [properties] Properties to set * @returns EnumValueOptions instance */ public static create(properties?: google.protobuf.IEnumValueOptions): google.protobuf.EnumValueOptions; /** * Encodes the specified EnumValueOptions message. Does not implicitly {@link google.protobuf.EnumValueOptions.verify|verify} messages. * @param message EnumValueOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IEnumValueOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified EnumValueOptions message, length delimited. Does not implicitly {@link google.protobuf.EnumValueOptions.verify|verify} messages. * @param message EnumValueOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IEnumValueOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an EnumValueOptions message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns EnumValueOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumValueOptions; /** * Decodes an EnumValueOptions message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns EnumValueOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumValueOptions; /** * Verifies an EnumValueOptions message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an EnumValueOptions message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns EnumValueOptions */ public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueOptions; /** * Creates a plain object from an EnumValueOptions message. Also converts values to other types if specified. * @param message EnumValueOptions * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.EnumValueOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this EnumValueOptions to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a ServiceOptions. */ interface IServiceOptions { /** ServiceOptions deprecated */ deprecated?: (boolean|null); /** ServiceOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); /** ServiceOptions .google.api.defaultHost */ ".google.api.defaultHost"?: (string|null); /** ServiceOptions .google.api.oauthScopes */ ".google.api.oauthScopes"?: (string|null); } /** Represents a ServiceOptions. */ class ServiceOptions implements IServiceOptions { /** * Constructs a new ServiceOptions. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IServiceOptions); /** ServiceOptions deprecated. */ public deprecated: boolean; /** ServiceOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; /** * Creates a new ServiceOptions instance using the specified properties. * @param [properties] Properties to set * @returns ServiceOptions instance */ public static create(properties?: google.protobuf.IServiceOptions): google.protobuf.ServiceOptions; /** * Encodes the specified ServiceOptions message. Does not implicitly {@link google.protobuf.ServiceOptions.verify|verify} messages. * @param message ServiceOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IServiceOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ServiceOptions message, length delimited. Does not implicitly {@link google.protobuf.ServiceOptions.verify|verify} messages. * @param message ServiceOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IServiceOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ServiceOptions message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ServiceOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.ServiceOptions; /** * Decodes a ServiceOptions message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ServiceOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.ServiceOptions; /** * Verifies a ServiceOptions message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ServiceOptions message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ServiceOptions */ public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceOptions; /** * Creates a plain object from a ServiceOptions message. Also converts values to other types if specified. * @param message ServiceOptions * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.ServiceOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ServiceOptions to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a MethodOptions. */ interface IMethodOptions { /** MethodOptions deprecated */ deprecated?: (boolean|null); /** MethodOptions idempotencyLevel */ idempotencyLevel?: (google.protobuf.MethodOptions.IdempotencyLevel|keyof typeof google.protobuf.MethodOptions.IdempotencyLevel|null); /** MethodOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); /** MethodOptions .google.api.http */ ".google.api.http"?: (google.api.IHttpRule|null); /** MethodOptions .google.api.methodSignature */ ".google.api.methodSignature"?: (string[]|null); } /** Represents a MethodOptions. */ class MethodOptions implements IMethodOptions { /** * Constructs a new MethodOptions. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IMethodOptions); /** MethodOptions deprecated. */ public deprecated: boolean; /** MethodOptions idempotencyLevel. */ public idempotencyLevel: (google.protobuf.MethodOptions.IdempotencyLevel|keyof typeof google.protobuf.MethodOptions.IdempotencyLevel); /** MethodOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; /** * Creates a new MethodOptions instance using the specified properties. * @param [properties] Properties to set * @returns MethodOptions instance */ public static create(properties?: google.protobuf.IMethodOptions): google.protobuf.MethodOptions; /** * Encodes the specified MethodOptions message. Does not implicitly {@link google.protobuf.MethodOptions.verify|verify} messages. * @param message MethodOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IMethodOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified MethodOptions message, length delimited. Does not implicitly {@link google.protobuf.MethodOptions.verify|verify} messages. * @param message MethodOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IMethodOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a MethodOptions message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns MethodOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.MethodOptions; /** * Decodes a MethodOptions message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns MethodOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.MethodOptions; /** * Verifies a MethodOptions message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a MethodOptions message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns MethodOptions */ public static fromObject(object: { [k: string]: any }): google.protobuf.MethodOptions; /** * Creates a plain object from a MethodOptions message. Also converts values to other types if specified. * @param message MethodOptions * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.MethodOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this MethodOptions to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace MethodOptions { /** IdempotencyLevel enum. */ enum IdempotencyLevel { IDEMPOTENCY_UNKNOWN = 0, NO_SIDE_EFFECTS = 1, IDEMPOTENT = 2 } } /** Properties of an UninterpretedOption. */ interface IUninterpretedOption { /** UninterpretedOption name */ name?: (google.protobuf.UninterpretedOption.INamePart[]|null); /** UninterpretedOption identifierValue */ identifierValue?: (string|null); /** UninterpretedOption positiveIntValue */ positiveIntValue?: (number|Long|string|null); /** UninterpretedOption negativeIntValue */ negativeIntValue?: (number|Long|string|null); /** UninterpretedOption doubleValue */ doubleValue?: (number|null); /** UninterpretedOption stringValue */ stringValue?: (Uint8Array|string|null); /** UninterpretedOption aggregateValue */ aggregateValue?: (string|null); } /** Represents an UninterpretedOption. */ class UninterpretedOption implements IUninterpretedOption { /** * Constructs a new UninterpretedOption. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IUninterpretedOption); /** UninterpretedOption name. */ public name: google.protobuf.UninterpretedOption.INamePart[]; /** UninterpretedOption identifierValue. */ public identifierValue: string; /** UninterpretedOption positiveIntValue. */ public positiveIntValue: (number|Long|string); /** UninterpretedOption negativeIntValue. */ public negativeIntValue: (number|Long|string); /** UninterpretedOption doubleValue. */ public doubleValue: number; /** UninterpretedOption stringValue. */ public stringValue: (Uint8Array|string); /** UninterpretedOption aggregateValue. */ public aggregateValue: string; /** * Creates a new UninterpretedOption instance using the specified properties. * @param [properties] Properties to set * @returns UninterpretedOption instance */ public static create(properties?: google.protobuf.IUninterpretedOption): google.protobuf.UninterpretedOption; /** * Encodes the specified UninterpretedOption message. Does not implicitly {@link google.protobuf.UninterpretedOption.verify|verify} messages. * @param message UninterpretedOption message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IUninterpretedOption, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified UninterpretedOption message, length delimited. Does not implicitly {@link google.protobuf.UninterpretedOption.verify|verify} messages. * @param message UninterpretedOption message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IUninterpretedOption, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an UninterpretedOption message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns UninterpretedOption * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.UninterpretedOption; /** * Decodes an UninterpretedOption message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns UninterpretedOption * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.UninterpretedOption; /** * Verifies an UninterpretedOption message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an UninterpretedOption message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns UninterpretedOption */ public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption; /** * Creates a plain object from an UninterpretedOption message. Also converts values to other types if specified. * @param message UninterpretedOption * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.UninterpretedOption, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this UninterpretedOption to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace UninterpretedOption { /** Properties of a NamePart. */ interface INamePart { /** NamePart namePart */ namePart: string; /** NamePart isExtension */ isExtension: boolean; } /** Represents a NamePart. */ class NamePart implements INamePart { /** * Constructs a new NamePart. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.UninterpretedOption.INamePart); /** NamePart namePart. */ public namePart: string; /** NamePart isExtension. */ public isExtension: boolean; /** * Creates a new NamePart instance using the specified properties. * @param [properties] Properties to set * @returns NamePart instance */ public static create(properties?: google.protobuf.UninterpretedOption.INamePart): google.protobuf.UninterpretedOption.NamePart; /** * Encodes the specified NamePart message. Does not implicitly {@link google.protobuf.UninterpretedOption.NamePart.verify|verify} messages. * @param message NamePart message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.UninterpretedOption.INamePart, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified NamePart message, length delimited. Does not implicitly {@link google.protobuf.UninterpretedOption.NamePart.verify|verify} messages. * @param message NamePart message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.UninterpretedOption.INamePart, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a NamePart message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns NamePart * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.UninterpretedOption.NamePart; /** * Decodes a NamePart message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns NamePart * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.UninterpretedOption.NamePart; /** * Verifies a NamePart message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a NamePart message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns NamePart */ public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption.NamePart; /** * Creates a plain object from a NamePart message. Also converts values to other types if specified. * @param message NamePart * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.UninterpretedOption.NamePart, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this NamePart to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } /** Properties of a SourceCodeInfo. */ interface ISourceCodeInfo { /** SourceCodeInfo location */ location?: (google.protobuf.SourceCodeInfo.ILocation[]|null); } /** Represents a SourceCodeInfo. */ class SourceCodeInfo implements ISourceCodeInfo { /** * Constructs a new SourceCodeInfo. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.ISourceCodeInfo); /** SourceCodeInfo location. */ public location: google.protobuf.SourceCodeInfo.ILocation[]; /** * Creates a new SourceCodeInfo instance using the specified properties. * @param [properties] Properties to set * @returns SourceCodeInfo instance */ public static create(properties?: google.protobuf.ISourceCodeInfo): google.protobuf.SourceCodeInfo; /** * Encodes the specified SourceCodeInfo message. Does not implicitly {@link google.protobuf.SourceCodeInfo.verify|verify} messages. * @param message SourceCodeInfo message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.ISourceCodeInfo, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified SourceCodeInfo message, length delimited. Does not implicitly {@link google.protobuf.SourceCodeInfo.verify|verify} messages. * @param message SourceCodeInfo message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.ISourceCodeInfo, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a SourceCodeInfo message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns SourceCodeInfo * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.SourceCodeInfo; /** * Decodes a SourceCodeInfo message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns SourceCodeInfo * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.SourceCodeInfo; /** * Verifies a SourceCodeInfo message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a SourceCodeInfo message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns SourceCodeInfo */ public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo; /** * Creates a plain object from a SourceCodeInfo message. Also converts values to other types if specified. * @param message SourceCodeInfo * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.SourceCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this SourceCodeInfo to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace SourceCodeInfo { /** Properties of a Location. */ interface ILocation { /** Location path */ path?: (number[]|null); /** Location span */ span?: (number[]|null); /** Location leadingComments */ leadingComments?: (string|null); /** Location trailingComments */ trailingComments?: (string|null); /** Location leadingDetachedComments */ leadingDetachedComments?: (string[]|null); } /** Represents a Location. */ class Location implements ILocation { /** * Constructs a new Location. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.SourceCodeInfo.ILocation); /** Location path. */ public path: number[]; /** Location span. */ public span: number[]; /** Location leadingComments. */ public leadingComments: string; /** Location trailingComments. */ public trailingComments: string; /** Location leadingDetachedComments. */ public leadingDetachedComments: string[]; /** * Creates a new Location instance using the specified properties. * @param [properties] Properties to set * @returns Location instance */ public static create(properties?: google.protobuf.SourceCodeInfo.ILocation): google.protobuf.SourceCodeInfo.Location; /** * Encodes the specified Location message. Does not implicitly {@link google.protobuf.SourceCodeInfo.Location.verify|verify} messages. * @param message Location message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.SourceCodeInfo.ILocation, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Location message, length delimited. Does not implicitly {@link google.protobuf.SourceCodeInfo.Location.verify|verify} messages. * @param message Location message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.SourceCodeInfo.ILocation, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Location message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Location * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.SourceCodeInfo.Location; /** * Decodes a Location message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Location * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.SourceCodeInfo.Location; /** * Verifies a Location message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Location message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Location */ public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo.Location; /** * Creates a plain object from a Location message. Also converts values to other types if specified. * @param message Location * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.SourceCodeInfo.Location, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Location to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } /** Properties of a GeneratedCodeInfo. */ interface IGeneratedCodeInfo { /** GeneratedCodeInfo annotation */ annotation?: (google.protobuf.GeneratedCodeInfo.IAnnotation[]|null); } /** Represents a GeneratedCodeInfo. */ class GeneratedCodeInfo implements IGeneratedCodeInfo { /** * Constructs a new GeneratedCodeInfo. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IGeneratedCodeInfo); /** GeneratedCodeInfo annotation. */ public annotation: google.protobuf.GeneratedCodeInfo.IAnnotation[]; /** * Creates a new GeneratedCodeInfo instance using the specified properties. * @param [properties] Properties to set * @returns GeneratedCodeInfo instance */ public static create(properties?: google.protobuf.IGeneratedCodeInfo): google.protobuf.GeneratedCodeInfo; /** * Encodes the specified GeneratedCodeInfo message. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.verify|verify} messages. * @param message GeneratedCodeInfo message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IGeneratedCodeInfo, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified GeneratedCodeInfo message, length delimited. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.verify|verify} messages. * @param message GeneratedCodeInfo message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IGeneratedCodeInfo, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a GeneratedCodeInfo message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns GeneratedCodeInfo * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.GeneratedCodeInfo; /** * Decodes a GeneratedCodeInfo message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns GeneratedCodeInfo * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.GeneratedCodeInfo; /** * Verifies a GeneratedCodeInfo message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a GeneratedCodeInfo message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns GeneratedCodeInfo */ public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo; /** * Creates a plain object from a GeneratedCodeInfo message. Also converts values to other types if specified. * @param message GeneratedCodeInfo * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.GeneratedCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this GeneratedCodeInfo to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace GeneratedCodeInfo { /** Properties of an Annotation. */ interface IAnnotation { /** Annotation path */ path?: (number[]|null); /** Annotation sourceFile */ sourceFile?: (string|null); /** Annotation begin */ begin?: (number|null); /** Annotation end */ end?: (number|null); } /** Represents an Annotation. */ class Annotation implements IAnnotation { /** * Constructs a new Annotation. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.GeneratedCodeInfo.IAnnotation); /** Annotation path. */ public path: number[]; /** Annotation sourceFile. */ public sourceFile: string; /** Annotation begin. */ public begin: number; /** Annotation end. */ public end: number; /** * Creates a new Annotation instance using the specified properties. * @param [properties] Properties to set * @returns Annotation instance */ public static create(properties?: google.protobuf.GeneratedCodeInfo.IAnnotation): google.protobuf.GeneratedCodeInfo.Annotation; /** * Encodes the specified Annotation message. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.Annotation.verify|verify} messages. * @param message Annotation message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.GeneratedCodeInfo.IAnnotation, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Annotation message, length delimited. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.Annotation.verify|verify} messages. * @param message Annotation message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.GeneratedCodeInfo.IAnnotation, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an Annotation message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Annotation * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.GeneratedCodeInfo.Annotation; /** * Decodes an Annotation message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Annotation * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.GeneratedCodeInfo.Annotation; /** * Verifies an Annotation message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an Annotation message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Annotation */ public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo.Annotation; /** * Creates a plain object from an Annotation message. Also converts values to other types if specified. * @param message Annotation * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.GeneratedCodeInfo.Annotation, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Annotation to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } /** Properties of a Struct. */ interface IStruct { /** Struct fields */ fields?: ({ [k: string]: google.protobuf.IValue }|null); } /** Represents a Struct. */ class Struct implements IStruct { /** * Constructs a new Struct. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IStruct); /** Struct fields. */ public fields: { [k: string]: google.protobuf.IValue }; /** * Creates a new Struct instance using the specified properties. * @param [properties] Properties to set * @returns Struct instance */ public static create(properties?: google.protobuf.IStruct): google.protobuf.Struct; /** * Encodes the specified Struct message. Does not implicitly {@link google.protobuf.Struct.verify|verify} messages. * @param message Struct message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IStruct, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Struct message, length delimited. Does not implicitly {@link google.protobuf.Struct.verify|verify} messages. * @param message Struct message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IStruct, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Struct message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Struct * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Struct; /** * Decodes a Struct message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Struct * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Struct; /** * Verifies a Struct message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Struct message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Struct */ public static fromObject(object: { [k: string]: any }): google.protobuf.Struct; /** * Creates a plain object from a Struct message. Also converts values to other types if specified. * @param message Struct * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.Struct, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Struct to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a Value. */ interface IValue { /** Value nullValue */ nullValue?: (google.protobuf.NullValue|keyof typeof google.protobuf.NullValue|null); /** Value numberValue */ numberValue?: (number|null); /** Value stringValue */ stringValue?: (string|null); /** Value boolValue */ boolValue?: (boolean|null); /** Value structValue */ structValue?: (google.protobuf.IStruct|null); /** Value listValue */ listValue?: (google.protobuf.IListValue|null); } /** Represents a Value. */ class Value implements IValue { /** * Constructs a new Value. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IValue); /** Value nullValue. */ public nullValue?: (google.protobuf.NullValue|keyof typeof google.protobuf.NullValue|null); /** Value numberValue. */ public numberValue?: (number|null); /** Value stringValue. */ public stringValue?: (string|null); /** Value boolValue. */ public boolValue?: (boolean|null); /** Value structValue. */ public structValue?: (google.protobuf.IStruct|null); /** Value listValue. */ public listValue?: (google.protobuf.IListValue|null); /** Value kind. */ public kind?: ("nullValue"|"numberValue"|"stringValue"|"boolValue"|"structValue"|"listValue"); /** * Creates a new Value instance using the specified properties. * @param [properties] Properties to set * @returns Value instance */ public static create(properties?: google.protobuf.IValue): google.protobuf.Value; /** * Encodes the specified Value message. Does not implicitly {@link google.protobuf.Value.verify|verify} messages. * @param message Value message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IValue, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Value message, length delimited. Does not implicitly {@link google.protobuf.Value.verify|verify} messages. * @param message Value message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IValue, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Value message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Value * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Value; /** * Decodes a Value message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Value * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Value; /** * Verifies a Value message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Value message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Value */ public static fromObject(object: { [k: string]: any }): google.protobuf.Value; /** * Creates a plain object from a Value message. Also converts values to other types if specified. * @param message Value * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Value to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** NullValue enum. */ enum NullValue { NULL_VALUE = 0 } /** Properties of a ListValue. */ interface IListValue { /** ListValue values */ values?: (google.protobuf.IValue[]|null); } /** Represents a ListValue. */ class ListValue implements IListValue { /** * Constructs a new ListValue. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IListValue); /** ListValue values. */ public values: google.protobuf.IValue[]; /** * Creates a new ListValue instance using the specified properties. * @param [properties] Properties to set * @returns ListValue instance */ public static create(properties?: google.protobuf.IListValue): google.protobuf.ListValue; /** * Encodes the specified ListValue message. Does not implicitly {@link google.protobuf.ListValue.verify|verify} messages. * @param message ListValue message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IListValue, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ListValue message, length delimited. Does not implicitly {@link google.protobuf.ListValue.verify|verify} messages. * @param message ListValue message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IListValue, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ListValue message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ListValue * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.ListValue; /** * Decodes a ListValue message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ListValue * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.ListValue; /** * Verifies a ListValue message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ListValue message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ListValue */ public static fromObject(object: { [k: string]: any }): google.protobuf.ListValue; /** * Creates a plain object from a ListValue message. Also converts values to other types if specified. * @param message ListValue * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.ListValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ListValue to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } /** Namespace api. */ namespace api { /** Namespace servicecontrol. */ namespace servicecontrol { /** Namespace v1. */ namespace v1 { /** Properties of a CheckError. */ interface ICheckError { /** CheckError code */ code?: (google.api.servicecontrol.v1.CheckError.Code|keyof typeof google.api.servicecontrol.v1.CheckError.Code|null); /** CheckError subject */ subject?: (string|null); /** CheckError detail */ detail?: (string|null); /** CheckError status */ status?: (google.rpc.IStatus|null); } /** Represents a CheckError. */ class CheckError implements ICheckError { /** * Constructs a new CheckError. * @param [properties] Properties to set */ constructor(properties?: google.api.servicecontrol.v1.ICheckError); /** CheckError code. */ public code: (google.api.servicecontrol.v1.CheckError.Code|keyof typeof google.api.servicecontrol.v1.CheckError.Code); /** CheckError subject. */ public subject: string; /** CheckError detail. */ public detail: string; /** CheckError status. */ public status?: (google.rpc.IStatus|null); /** * Creates a new CheckError instance using the specified properties. * @param [properties] Properties to set * @returns CheckError instance */ public static create(properties?: google.api.servicecontrol.v1.ICheckError): google.api.servicecontrol.v1.CheckError; /** * Encodes the specified CheckError message. Does not implicitly {@link google.api.servicecontrol.v1.CheckError.verify|verify} messages. * @param message CheckError message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.api.servicecontrol.v1.ICheckError, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified CheckError message, length delimited. Does not implicitly {@link google.api.servicecontrol.v1.CheckError.verify|verify} messages. * @param message CheckError message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.api.servicecontrol.v1.ICheckError, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a CheckError message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns CheckError * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.servicecontrol.v1.CheckError; /** * Decodes a CheckError message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns CheckError * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.servicecontrol.v1.CheckError; /** * Verifies a CheckError message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a CheckError message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns CheckError */ public static fromObject(object: { [k: string]: any }): google.api.servicecontrol.v1.CheckError; /** * Creates a plain object from a CheckError message. Also converts values to other types if specified. * @param message CheckError * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.api.servicecontrol.v1.CheckError, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this CheckError to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace CheckError { /** Code enum. */ enum Code { ERROR_CODE_UNSPECIFIED = 0, NOT_FOUND = 5, PERMISSION_DENIED = 7, RESOURCE_EXHAUSTED = 8, SERVICE_NOT_ACTIVATED = 104, BILLING_DISABLED = 107, PROJECT_DELETED = 108, PROJECT_INVALID = 114, CONSUMER_INVALID = 125, IP_ADDRESS_BLOCKED = 109, REFERER_BLOCKED = 110, CLIENT_APP_BLOCKED = 111, API_TARGET_BLOCKED = 122, API_KEY_INVALID = 105, API_KEY_EXPIRED = 112, API_KEY_NOT_FOUND = 113, INVALID_CREDENTIAL = 123, NAMESPACE_LOOKUP_UNAVAILABLE = 300, SERVICE_STATUS_UNAVAILABLE = 301, BILLING_STATUS_UNAVAILABLE = 302, CLOUD_RESOURCE_MANAGER_BACKEND_UNAVAILABLE = 305 } } /** Properties of a Distribution. */ interface IDistribution { /** Distribution count */ count?: (number|Long|string|null); /** Distribution mean */ mean?: (number|null); /** Distribution minimum */ minimum?: (number|null); /** Distribution maximum */ maximum?: (number|null); /** Distribution sumOfSquaredDeviation */ sumOfSquaredDeviation?: (number|null); /** Distribution bucketCounts */ bucketCounts?: ((number|Long|string)[]|null); /** Distribution linearBuckets */ linearBuckets?: (google.api.servicecontrol.v1.Distribution.ILinearBuckets|null); /** Distribution exponentialBuckets */ exponentialBuckets?: (google.api.servicecontrol.v1.Distribution.IExponentialBuckets|null); /** Distribution explicitBuckets */ explicitBuckets?: (google.api.servicecontrol.v1.Distribution.IExplicitBuckets|null); /** Distribution exemplars */ exemplars?: (google.api.Distribution.IExemplar[]|null); } /** Represents a Distribution. */ class Distribution implements IDistribution { /** * Constructs a new Distribution. * @param [properties] Properties to set */ constructor(properties?: google.api.servicecontrol.v1.IDistribution); /** Distribution count. */ public count: (number|Long|string); /** Distribution mean. */ public mean: number; /** Distribution minimum. */ public minimum: number; /** Distribution maximum. */ public maximum: number; /** Distribution sumOfSquaredDeviation. */ public sumOfSquaredDeviation: number; /** Distribution bucketCounts. */ public bucketCounts: (number|Long|string)[]; /** Distribution linearBuckets. */ public linearBuckets?: (google.api.servicecontrol.v1.Distribution.ILinearBuckets|null); /** Distribution exponentialBuckets. */ public exponentialBuckets?: (google.api.servicecontrol.v1.Distribution.IExponentialBuckets|null); /** Distribution explicitBuckets. */ public explicitBuckets?: (google.api.servicecontrol.v1.Distribution.IExplicitBuckets|null); /** Distribution exemplars. */ public exemplars: google.api.Distribution.IExemplar[]; /** Distribution bucketOption. */ public bucketOption?: ("linearBuckets"|"exponentialBuckets"|"explicitBuckets"); /** * Creates a new Distribution instance using the specified properties. * @param [properties] Properties to set * @returns Distribution instance */ public static create(properties?: google.api.servicecontrol.v1.IDistribution): google.api.servicecontrol.v1.Distribution; /** * Encodes the specified Distribution message. Does not implicitly {@link google.api.servicecontrol.v1.Distribution.verify|verify} messages. * @param message Distribution message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.api.servicecontrol.v1.IDistribution, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Distribution message, length delimited. Does not implicitly {@link google.api.servicecontrol.v1.Distribution.verify|verify} messages. * @param message Distribution message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.api.servicecontrol.v1.IDistribution, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Distribution message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Distribution * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.servicecontrol.v1.Distribution; /** * Decodes a Distribution message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Distribution * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.servicecontrol.v1.Distribution; /** * Verifies a Distribution message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Distribution message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Distribution */ public static fromObject(object: { [k: string]: any }): google.api.servicecontrol.v1.Distribution; /** * Creates a plain object from a Distribution message. Also converts values to other types if specified. * @param message Distribution * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.api.servicecontrol.v1.Distribution, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Distribution to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace Distribution { /** Properties of a LinearBuckets. */ interface ILinearBuckets { /** LinearBuckets numFiniteBuckets */ numFiniteBuckets?: (number|null); /** LinearBuckets width */ width?: (number|null); /** LinearBuckets offset */ offset?: (number|null); } /** Represents a LinearBuckets. */ class LinearBuckets implements ILinearBuckets { /** * Constructs a new LinearBuckets. * @param [properties] Properties to set */ constructor(properties?: google.api.servicecontrol.v1.Distribution.ILinearBuckets); /** LinearBuckets numFiniteBuckets. */ public numFiniteBuckets: number; /** LinearBuckets width. */ public width: number; /** LinearBuckets offset. */ public offset: number; /** * Creates a new LinearBuckets instance using the specified properties. * @param [properties] Properties to set * @returns LinearBuckets instance */ public static create(properties?: google.api.servicecontrol.v1.Distribution.ILinearBuckets): google.api.servicecontrol.v1.Distribution.LinearBuckets; /** * Encodes the specified LinearBuckets message. Does not implicitly {@link google.api.servicecontrol.v1.Distribution.LinearBuckets.verify|verify} messages. * @param message LinearBuckets message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.api.servicecontrol.v1.Distribution.ILinearBuckets, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified LinearBuckets message, length delimited. Does not implicitly {@link google.api.servicecontrol.v1.Distribution.LinearBuckets.verify|verify} messages. * @param message LinearBuckets message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.api.servicecontrol.v1.Distribution.ILinearBuckets, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a LinearBuckets message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns LinearBuckets * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.servicecontrol.v1.Distribution.LinearBuckets; /** * Decodes a LinearBuckets message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns LinearBuckets * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.servicecontrol.v1.Distribution.LinearBuckets; /** * Verifies a LinearBuckets message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a LinearBuckets message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns LinearBuckets */ public static fromObject(object: { [k: string]: any }): google.api.servicecontrol.v1.Distribution.LinearBuckets; /** * Creates a plain object from a LinearBuckets message. Also converts values to other types if specified. * @param message LinearBuckets * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.api.servicecontrol.v1.Distribution.LinearBuckets, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this LinearBuckets to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of an ExponentialBuckets. */ interface IExponentialBuckets { /** ExponentialBuckets numFiniteBuckets */ numFiniteBuckets?: (number|null); /** ExponentialBuckets growthFactor */ growthFactor?: (number|null); /** ExponentialBuckets scale */ scale?: (number|null); } /** Represents an ExponentialBuckets. */ class ExponentialBuckets implements IExponentialBuckets { /** * Constructs a new ExponentialBuckets. * @param [properties] Properties to set */ constructor(properties?: google.api.servicecontrol.v1.Distribution.IExponentialBuckets); /** ExponentialBuckets numFiniteBuckets. */ public numFiniteBuckets: number; /** ExponentialBuckets growthFactor. */ public growthFactor: number; /** ExponentialBuckets scale. */ public scale: number; /** * Creates a new ExponentialBuckets instance using the specified properties. * @param [properties] Properties to set * @returns ExponentialBuckets instance */ public static create(properties?: google.api.servicecontrol.v1.Distribution.IExponentialBuckets): google.api.servicecontrol.v1.Distribution.ExponentialBuckets; /** * Encodes the specified ExponentialBuckets message. Does not implicitly {@link google.api.servicecontrol.v1.Distribution.ExponentialBuckets.verify|verify} messages. * @param message ExponentialBuckets message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.api.servicecontrol.v1.Distribution.IExponentialBuckets, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ExponentialBuckets message, length delimited. Does not implicitly {@link google.api.servicecontrol.v1.Distribution.ExponentialBuckets.verify|verify} messages. * @param message ExponentialBuckets message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.api.servicecontrol.v1.Distribution.IExponentialBuckets, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an ExponentialBuckets message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ExponentialBuckets * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.servicecontrol.v1.Distribution.ExponentialBuckets; /** * Decodes an ExponentialBuckets message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ExponentialBuckets * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.servicecontrol.v1.Distribution.ExponentialBuckets; /** * Verifies an ExponentialBuckets message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an ExponentialBuckets message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ExponentialBuckets */ public static fromObject(object: { [k: string]: any }): google.api.servicecontrol.v1.Distribution.ExponentialBuckets; /** * Creates a plain object from an ExponentialBuckets message. Also converts values to other types if specified. * @param message ExponentialBuckets * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.api.servicecontrol.v1.Distribution.ExponentialBuckets, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ExponentialBuckets to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of an ExplicitBuckets. */ interface IExplicitBuckets { /** ExplicitBuckets bounds */ bounds?: (number[]|null); } /** Represents an ExplicitBuckets. */ class ExplicitBuckets implements IExplicitBuckets { /** * Constructs a new ExplicitBuckets. * @param [properties] Properties to set */ constructor(properties?: google.api.servicecontrol.v1.Distribution.IExplicitBuckets); /** ExplicitBuckets bounds. */ public bounds: number[]; /** * Creates a new ExplicitBuckets instance using the specified properties. * @param [properties] Properties to set * @returns ExplicitBuckets instance */ public static create(properties?: google.api.servicecontrol.v1.Distribution.IExplicitBuckets): google.api.servicecontrol.v1.Distribution.ExplicitBuckets; /** * Encodes the specified ExplicitBuckets message. Does not implicitly {@link google.api.servicecontrol.v1.Distribution.ExplicitBuckets.verify|verify} messages. * @param message ExplicitBuckets message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.api.servicecontrol.v1.Distribution.IExplicitBuckets, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ExplicitBuckets message, length delimited. Does not implicitly {@link google.api.servicecontrol.v1.Distribution.ExplicitBuckets.verify|verify} messages. * @param message ExplicitBuckets message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.api.servicecontrol.v1.Distribution.IExplicitBuckets, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an ExplicitBuckets message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ExplicitBuckets * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.servicecontrol.v1.Distribution.ExplicitBuckets; /** * Decodes an ExplicitBuckets message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ExplicitBuckets * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.servicecontrol.v1.Distribution.ExplicitBuckets; /** * Verifies an ExplicitBuckets message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an ExplicitBuckets message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ExplicitBuckets */ public static fromObject(object: { [k: string]: any }): google.api.servicecontrol.v1.Distribution.ExplicitBuckets; /** * Creates a plain object from an ExplicitBuckets message. Also converts values to other types if specified. * @param message ExplicitBuckets * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.api.servicecontrol.v1.Distribution.ExplicitBuckets, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ExplicitBuckets to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } /** Properties of a HttpRequest. */ interface IHttpRequest { /** HttpRequest requestMethod */ requestMethod?: (string|null); /** HttpRequest requestUrl */ requestUrl?: (string|null); /** HttpRequest requestSize */ requestSize?: (number|Long|string|null); /** HttpRequest status */ status?: (number|null); /** HttpRequest responseSize */ responseSize?: (number|Long|string|null); /** HttpRequest userAgent */ userAgent?: (string|null); /** HttpRequest remoteIp */ remoteIp?: (string|null); /** HttpRequest serverIp */ serverIp?: (string|null); /** HttpRequest referer */ referer?: (string|null); /** HttpRequest latency */ latency?: (google.protobuf.IDuration|null); /** HttpRequest cacheLookup */ cacheLookup?: (boolean|null); /** HttpRequest cacheHit */ cacheHit?: (boolean|null); /** HttpRequest cacheValidatedWithOriginServer */ cacheValidatedWithOriginServer?: (boolean|null); /** HttpRequest cacheFillBytes */ cacheFillBytes?: (number|Long|string|null); /** HttpRequest protocol */ protocol?: (string|null); } /** Represents a HttpRequest. */ class HttpRequest implements IHttpRequest { /** * Constructs a new HttpRequest. * @param [properties] Properties to set */ constructor(properties?: google.api.servicecontrol.v1.IHttpRequest); /** HttpRequest requestMethod. */ public requestMethod: string; /** HttpRequest requestUrl. */ public requestUrl: string; /** HttpRequest requestSize. */ public requestSize: (number|Long|string); /** HttpRequest status. */ public status: number; /** HttpRequest responseSize. */ public responseSize: (number|Long|string); /** HttpRequest userAgent. */ public userAgent: string; /** HttpRequest remoteIp. */ public remoteIp: string; /** HttpRequest serverIp. */ public serverIp: string; /** HttpRequest referer. */ public referer: string; /** HttpRequest latency. */ public latency?: (google.protobuf.IDuration|null); /** HttpRequest cacheLookup. */ public cacheLookup: boolean; /** HttpRequest cacheHit. */ public cacheHit: boolean; /** HttpRequest cacheValidatedWithOriginServer. */ public cacheValidatedWithOriginServer: boolean; /** HttpRequest cacheFillBytes. */ public cacheFillBytes: (number|Long|string); /** HttpRequest protocol. */ public protocol: string; /** * Creates a new HttpRequest instance using the specified properties. * @param [properties] Properties to set * @returns HttpRequest instance */ public static create(properties?: google.api.servicecontrol.v1.IHttpRequest): google.api.servicecontrol.v1.HttpRequest; /** * Encodes the specified HttpRequest message. Does not implicitly {@link google.api.servicecontrol.v1.HttpRequest.verify|verify} messages. * @param message HttpRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.api.servicecontrol.v1.IHttpRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified HttpRequest message, length delimited. Does not implicitly {@link google.api.servicecontrol.v1.HttpRequest.verify|verify} messages. * @param message HttpRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.api.servicecontrol.v1.IHttpRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a HttpRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns HttpRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.servicecontrol.v1.HttpRequest; /** * Decodes a HttpRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns HttpRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.servicecontrol.v1.HttpRequest; /** * Verifies a HttpRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a HttpRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns HttpRequest */ public static fromObject(object: { [k: string]: any }): google.api.servicecontrol.v1.HttpRequest; /** * Creates a plain object from a HttpRequest message. Also converts values to other types if specified. * @param message HttpRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.api.servicecontrol.v1.HttpRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this HttpRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a LogEntry. */ interface ILogEntry { /** LogEntry name */ name?: (string|null); /** LogEntry timestamp */ timestamp?: (google.protobuf.ITimestamp|null); /** LogEntry severity */ severity?: (google.logging.type.LogSeverity|keyof typeof google.logging.type.LogSeverity|null); /** LogEntry httpRequest */ httpRequest?: (google.api.servicecontrol.v1.IHttpRequest|null); /** LogEntry trace */ trace?: (string|null); /** LogEntry insertId */ insertId?: (string|null); /** LogEntry labels */ labels?: ({ [k: string]: string }|null); /** LogEntry protoPayload */ protoPayload?: (google.protobuf.IAny|null); /** LogEntry textPayload */ textPayload?: (string|null); /** LogEntry structPayload */ structPayload?: (google.protobuf.IStruct|null); /** LogEntry operation */ operation?: (google.api.servicecontrol.v1.ILogEntryOperation|null); /** LogEntry sourceLocation */ sourceLocation?: (google.api.servicecontrol.v1.ILogEntrySourceLocation|null); } /** Represents a LogEntry. */ class LogEntry implements ILogEntry { /** * Constructs a new LogEntry. * @param [properties] Properties to set */ constructor(properties?: google.api.servicecontrol.v1.ILogEntry); /** LogEntry name. */ public name: string; /** LogEntry timestamp. */ public timestamp?: (google.protobuf.ITimestamp|null); /** LogEntry severity. */ public severity: (google.logging.type.LogSeverity|keyof typeof google.logging.type.LogSeverity); /** LogEntry httpRequest. */ public httpRequest?: (google.api.servicecontrol.v1.IHttpRequest|null); /** LogEntry trace. */ public trace: string; /** LogEntry insertId. */ public insertId: string; /** LogEntry labels. */ public labels: { [k: string]: string }; /** LogEntry protoPayload. */ public protoPayload?: (google.protobuf.IAny|null); /** LogEntry textPayload. */ public textPayload?: (string|null); /** LogEntry structPayload. */ public structPayload?: (google.protobuf.IStruct|null); /** LogEntry operation. */ public operation?: (google.api.servicecontrol.v1.ILogEntryOperation|null); /** LogEntry sourceLocation. */ public sourceLocation?: (google.api.servicecontrol.v1.ILogEntrySourceLocation|null); /** LogEntry payload. */ public payload?: ("protoPayload"|"textPayload"|"structPayload"); /** * Creates a new LogEntry instance using the specified properties. * @param [properties] Properties to set * @returns LogEntry instance */ public static create(properties?: google.api.servicecontrol.v1.ILogEntry): google.api.servicecontrol.v1.LogEntry; /** * Encodes the specified LogEntry message. Does not implicitly {@link google.api.servicecontrol.v1.LogEntry.verify|verify} messages. * @param message LogEntry message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.api.servicecontrol.v1.ILogEntry, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified LogEntry message, length delimited. Does not implicitly {@link google.api.servicecontrol.v1.LogEntry.verify|verify} messages. * @param message LogEntry message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.api.servicecontrol.v1.ILogEntry, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a LogEntry message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns LogEntry * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.servicecontrol.v1.LogEntry; /** * Decodes a LogEntry message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns LogEntry * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.servicecontrol.v1.LogEntry; /** * Verifies a LogEntry message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a LogEntry message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns LogEntry */ public static fromObject(object: { [k: string]: any }): google.api.servicecontrol.v1.LogEntry; /** * Creates a plain object from a LogEntry message. Also converts values to other types if specified. * @param message LogEntry * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.api.servicecontrol.v1.LogEntry, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this LogEntry to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a LogEntryOperation. */ interface ILogEntryOperation { /** LogEntryOperation id */ id?: (string|null); /** LogEntryOperation producer */ producer?: (string|null); /** LogEntryOperation first */ first?: (boolean|null); /** LogEntryOperation last */ last?: (boolean|null); } /** Represents a LogEntryOperation. */ class LogEntryOperation implements ILogEntryOperation { /** * Constructs a new LogEntryOperation. * @param [properties] Properties to set */ constructor(properties?: google.api.servicecontrol.v1.ILogEntryOperation); /** LogEntryOperation id. */ public id: string; /** LogEntryOperation producer. */ public producer: string; /** LogEntryOperation first. */ public first: boolean; /** LogEntryOperation last. */ public last: boolean; /** * Creates a new LogEntryOperation instance using the specified properties. * @param [properties] Properties to set * @returns LogEntryOperation instance */ public static create(properties?: google.api.servicecontrol.v1.ILogEntryOperation): google.api.servicecontrol.v1.LogEntryOperation; /** * Encodes the specified LogEntryOperation message. Does not implicitly {@link google.api.servicecontrol.v1.LogEntryOperation.verify|verify} messages. * @param message LogEntryOperation message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.api.servicecontrol.v1.ILogEntryOperation, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified LogEntryOperation message, length delimited. Does not implicitly {@link google.api.servicecontrol.v1.LogEntryOperation.verify|verify} messages. * @param message LogEntryOperation message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.api.servicecontrol.v1.ILogEntryOperation, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a LogEntryOperation message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns LogEntryOperation * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.servicecontrol.v1.LogEntryOperation; /** * Decodes a LogEntryOperation message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns LogEntryOperation * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.servicecontrol.v1.LogEntryOperation; /** * Verifies a LogEntryOperation message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a LogEntryOperation message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns LogEntryOperation */ public static fromObject(object: { [k: string]: any }): google.api.servicecontrol.v1.LogEntryOperation; /** * Creates a plain object from a LogEntryOperation message. Also converts values to other types if specified. * @param message LogEntryOperation * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.api.servicecontrol.v1.LogEntryOperation, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this LogEntryOperation to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a LogEntrySourceLocation. */ interface ILogEntrySourceLocation { /** LogEntrySourceLocation file */ file?: (string|null); /** LogEntrySourceLocation line */ line?: (number|Long|string|null); /** LogEntrySourceLocation function */ "function"?: (string|null); } /** Represents a LogEntrySourceLocation. */ class LogEntrySourceLocation implements ILogEntrySourceLocation { /** * Constructs a new LogEntrySourceLocation. * @param [properties] Properties to set */ constructor(properties?: google.api.servicecontrol.v1.ILogEntrySourceLocation); /** LogEntrySourceLocation file. */ public file: string; /** LogEntrySourceLocation line. */ public line: (number|Long|string); /** LogEntrySourceLocation function. */ public function: string; /** * Creates a new LogEntrySourceLocation instance using the specified properties. * @param [properties] Properties to set * @returns LogEntrySourceLocation instance */ public static create(properties?: google.api.servicecontrol.v1.ILogEntrySourceLocation): google.api.servicecontrol.v1.LogEntrySourceLocation; /** * Encodes the specified LogEntrySourceLocation message. Does not implicitly {@link google.api.servicecontrol.v1.LogEntrySourceLocation.verify|verify} messages. * @param message LogEntrySourceLocation message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.api.servicecontrol.v1.ILogEntrySourceLocation, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified LogEntrySourceLocation message, length delimited. Does not implicitly {@link google.api.servicecontrol.v1.LogEntrySourceLocation.verify|verify} messages. * @param message LogEntrySourceLocation message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.api.servicecontrol.v1.ILogEntrySourceLocation, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a LogEntrySourceLocation message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns LogEntrySourceLocation * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.servicecontrol.v1.LogEntrySourceLocation; /** * Decodes a LogEntrySourceLocation message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns LogEntrySourceLocation * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.servicecontrol.v1.LogEntrySourceLocation; /** * Verifies a LogEntrySourceLocation message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a LogEntrySourceLocation message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns LogEntrySourceLocation */ public static fromObject(object: { [k: string]: any }): google.api.servicecontrol.v1.LogEntrySourceLocation; /** * Creates a plain object from a LogEntrySourceLocation message. Also converts values to other types if specified. * @param message LogEntrySourceLocation * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.api.servicecontrol.v1.LogEntrySourceLocation, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this LogEntrySourceLocation to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a MetricValue. */ interface IMetricValue { /** MetricValue labels */ labels?: ({ [k: string]: string }|null); /** MetricValue startTime */ startTime?: (google.protobuf.ITimestamp|null); /** MetricValue endTime */ endTime?: (google.protobuf.ITimestamp|null); /** MetricValue boolValue */ boolValue?: (boolean|null); /** MetricValue int64Value */ int64Value?: (number|Long|string|null); /** MetricValue doubleValue */ doubleValue?: (number|null); /** MetricValue stringValue */ stringValue?: (string|null); /** MetricValue distributionValue */ distributionValue?: (google.api.servicecontrol.v1.IDistribution|null); } /** Represents a MetricValue. */ class MetricValue implements IMetricValue { /** * Constructs a new MetricValue. * @param [properties] Properties to set */ constructor(properties?: google.api.servicecontrol.v1.IMetricValue); /** MetricValue labels. */ public labels: { [k: string]: string }; /** MetricValue startTime. */ public startTime?: (google.protobuf.ITimestamp|null); /** MetricValue endTime. */ public endTime?: (google.protobuf.ITimestamp|null); /** MetricValue boolValue. */ public boolValue?: (boolean|null); /** MetricValue int64Value. */ public int64Value?: (number|Long|string|null); /** MetricValue doubleValue. */ public doubleValue?: (number|null); /** MetricValue stringValue. */ public stringValue?: (string|null); /** MetricValue distributionValue. */ public distributionValue?: (google.api.servicecontrol.v1.IDistribution|null); /** MetricValue value. */ public value?: ("boolValue"|"int64Value"|"doubleValue"|"stringValue"|"distributionValue"); /** * Creates a new MetricValue instance using the specified properties. * @param [properties] Properties to set * @returns MetricValue instance */ public static create(properties?: google.api.servicecontrol.v1.IMetricValue): google.api.servicecontrol.v1.MetricValue; /** * Encodes the specified MetricValue message. Does not implicitly {@link google.api.servicecontrol.v1.MetricValue.verify|verify} messages. * @param message MetricValue message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.api.servicecontrol.v1.IMetricValue, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified MetricValue message, length delimited. Does not implicitly {@link google.api.servicecontrol.v1.MetricValue.verify|verify} messages. * @param message MetricValue message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.api.servicecontrol.v1.IMetricValue, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a MetricValue message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns MetricValue * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.servicecontrol.v1.MetricValue; /** * Decodes a MetricValue message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns MetricValue * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.servicecontrol.v1.MetricValue; /** * Verifies a MetricValue message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a MetricValue message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns MetricValue */ public static fromObject(object: { [k: string]: any }): google.api.servicecontrol.v1.MetricValue; /** * Creates a plain object from a MetricValue message. Also converts values to other types if specified. * @param message MetricValue * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.api.servicecontrol.v1.MetricValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this MetricValue to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a MetricValueSet. */ interface IMetricValueSet { /** MetricValueSet metricName */ metricName?: (string|null); /** MetricValueSet metricValues */ metricValues?: (google.api.servicecontrol.v1.IMetricValue[]|null); } /** Represents a MetricValueSet. */ class MetricValueSet implements IMetricValueSet { /** * Constructs a new MetricValueSet. * @param [properties] Properties to set */ constructor(properties?: google.api.servicecontrol.v1.IMetricValueSet); /** MetricValueSet metricName. */ public metricName: string; /** MetricValueSet metricValues. */ public metricValues: google.api.servicecontrol.v1.IMetricValue[]; /** * Creates a new MetricValueSet instance using the specified properties. * @param [properties] Properties to set * @returns MetricValueSet instance */ public static create(properties?: google.api.servicecontrol.v1.IMetricValueSet): google.api.servicecontrol.v1.MetricValueSet; /** * Encodes the specified MetricValueSet message. Does not implicitly {@link google.api.servicecontrol.v1.MetricValueSet.verify|verify} messages. * @param message MetricValueSet message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.api.servicecontrol.v1.IMetricValueSet, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified MetricValueSet message, length delimited. Does not implicitly {@link google.api.servicecontrol.v1.MetricValueSet.verify|verify} messages. * @param message MetricValueSet message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.api.servicecontrol.v1.IMetricValueSet, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a MetricValueSet message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns MetricValueSet * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.servicecontrol.v1.MetricValueSet; /** * Decodes a MetricValueSet message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns MetricValueSet * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.servicecontrol.v1.MetricValueSet; /** * Verifies a MetricValueSet message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a MetricValueSet message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns MetricValueSet */ public static fromObject(object: { [k: string]: any }): google.api.servicecontrol.v1.MetricValueSet; /** * Creates a plain object from a MetricValueSet message. Also converts values to other types if specified. * @param message MetricValueSet * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.api.servicecontrol.v1.MetricValueSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this MetricValueSet to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of an Operation. */ interface IOperation { /** Operation operationId */ operationId?: (string|null); /** Operation operationName */ operationName?: (string|null); /** Operation consumerId */ consumerId?: (string|null); /** Operation startTime */ startTime?: (google.protobuf.ITimestamp|null); /** Operation endTime */ endTime?: (google.protobuf.ITimestamp|null); /** Operation labels */ labels?: ({ [k: string]: string }|null); /** Operation metricValueSets */ metricValueSets?: (google.api.servicecontrol.v1.IMetricValueSet[]|null); /** Operation logEntries */ logEntries?: (google.api.servicecontrol.v1.ILogEntry[]|null); /** Operation importance */ importance?: (google.api.servicecontrol.v1.Operation.Importance|keyof typeof google.api.servicecontrol.v1.Operation.Importance|null); /** Operation extensions */ extensions?: (google.protobuf.IAny[]|null); } /** Represents an Operation. */ class Operation implements IOperation { /** * Constructs a new Operation. * @param [properties] Properties to set */ constructor(properties?: google.api.servicecontrol.v1.IOperation); /** Operation operationId. */ public operationId: string; /** Operation operationName. */ public operationName: string; /** Operation consumerId. */ public consumerId: string; /** Operation startTime. */ public startTime?: (google.protobuf.ITimestamp|null); /** Operation endTime. */ public endTime?: (google.protobuf.ITimestamp|null); /** Operation labels. */ public labels: { [k: string]: string }; /** Operation metricValueSets. */ public metricValueSets: google.api.servicecontrol.v1.IMetricValueSet[]; /** Operation logEntries. */ public logEntries: google.api.servicecontrol.v1.ILogEntry[]; /** Operation importance. */ public importance: (google.api.servicecontrol.v1.Operation.Importance|keyof typeof google.api.servicecontrol.v1.Operation.Importance); /** Operation extensions. */ public extensions: google.protobuf.IAny[]; /** * Creates a new Operation instance using the specified properties. * @param [properties] Properties to set * @returns Operation instance */ public static create(properties?: google.api.servicecontrol.v1.IOperation): google.api.servicecontrol.v1.Operation; /** * Encodes the specified Operation message. Does not implicitly {@link google.api.servicecontrol.v1.Operation.verify|verify} messages. * @param message Operation message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.api.servicecontrol.v1.IOperation, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Operation message, length delimited. Does not implicitly {@link google.api.servicecontrol.v1.Operation.verify|verify} messages. * @param message Operation message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.api.servicecontrol.v1.IOperation, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an Operation message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Operation * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.servicecontrol.v1.Operation; /** * Decodes an Operation message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Operation * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.servicecontrol.v1.Operation; /** * Verifies an Operation message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an Operation message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Operation */ public static fromObject(object: { [k: string]: any }): google.api.servicecontrol.v1.Operation; /** * Creates a plain object from an Operation message. Also converts values to other types if specified. * @param message Operation * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.api.servicecontrol.v1.Operation, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Operation to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace Operation { /** Importance enum. */ enum Importance { LOW = 0, HIGH = 1 } } /** Represents a QuotaController */ class QuotaController extends $protobuf.rpc.Service { /** * Constructs a new QuotaController service. * @param rpcImpl RPC implementation * @param [requestDelimited=false] Whether requests are length-delimited * @param [responseDelimited=false] Whether responses are length-delimited */ constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); /** * Creates new QuotaController service using the specified rpc implementation. * @param rpcImpl RPC implementation * @param [requestDelimited=false] Whether requests are length-delimited * @param [responseDelimited=false] Whether responses are length-delimited * @returns RPC service. Useful where requests and/or responses are streamed. */ public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): QuotaController; /** * Calls AllocateQuota. * @param request AllocateQuotaRequest message or plain object * @param callback Node-style callback called with the error, if any, and AllocateQuotaResponse */ public allocateQuota(request: google.api.servicecontrol.v1.IAllocateQuotaRequest, callback: google.api.servicecontrol.v1.QuotaController.AllocateQuotaCallback): void; /** * Calls AllocateQuota. * @param request AllocateQuotaRequest message or plain object * @returns Promise */ public allocateQuota(request: google.api.servicecontrol.v1.IAllocateQuotaRequest): Promise<google.api.servicecontrol.v1.AllocateQuotaResponse>; } namespace QuotaController { /** * Callback as used by {@link google.api.servicecontrol.v1.QuotaController#allocateQuota}. * @param error Error, if any * @param [response] AllocateQuotaResponse */ type AllocateQuotaCallback = (error: (Error|null), response?: google.api.servicecontrol.v1.AllocateQuotaResponse) => void; } /** Properties of an AllocateQuotaRequest. */ interface IAllocateQuotaRequest { /** AllocateQuotaRequest serviceName */ serviceName?: (string|null); /** AllocateQuotaRequest allocateOperation */ allocateOperation?: (google.api.servicecontrol.v1.IQuotaOperation|null); /** AllocateQuotaRequest serviceConfigId */ serviceConfigId?: (string|null); } /** Represents an AllocateQuotaRequest. */ class AllocateQuotaRequest implements IAllocateQuotaRequest { /** * Constructs a new AllocateQuotaRequest. * @param [properties] Properties to set */ constructor(properties?: google.api.servicecontrol.v1.IAllocateQuotaRequest); /** AllocateQuotaRequest serviceName. */ public serviceName: string; /** AllocateQuotaRequest allocateOperation. */ public allocateOperation?: (google.api.servicecontrol.v1.IQuotaOperation|null); /** AllocateQuotaRequest serviceConfigId. */ public serviceConfigId: string; /** * Creates a new AllocateQuotaRequest instance using the specified properties. * @param [properties] Properties to set * @returns AllocateQuotaRequest instance */ public static create(properties?: google.api.servicecontrol.v1.IAllocateQuotaRequest): google.api.servicecontrol.v1.AllocateQuotaRequest; /** * Encodes the specified AllocateQuotaRequest message. Does not implicitly {@link google.api.servicecontrol.v1.AllocateQuotaRequest.verify|verify} messages. * @param message AllocateQuotaRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.api.servicecontrol.v1.IAllocateQuotaRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified AllocateQuotaRequest message, length delimited. Does not implicitly {@link google.api.servicecontrol.v1.AllocateQuotaRequest.verify|verify} messages. * @param message AllocateQuotaRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.api.servicecontrol.v1.IAllocateQuotaRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an AllocateQuotaRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns AllocateQuotaRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.servicecontrol.v1.AllocateQuotaRequest; /** * Decodes an AllocateQuotaRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns AllocateQuotaRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.servicecontrol.v1.AllocateQuotaRequest; /** * Verifies an AllocateQuotaRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an AllocateQuotaRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns AllocateQuotaRequest */ public static fromObject(object: { [k: string]: any }): google.api.servicecontrol.v1.AllocateQuotaRequest; /** * Creates a plain object from an AllocateQuotaRequest message. Also converts values to other types if specified. * @param message AllocateQuotaRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.api.servicecontrol.v1.AllocateQuotaRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this AllocateQuotaRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a QuotaOperation. */ interface IQuotaOperation { /** QuotaOperation operationId */ operationId?: (string|null); /** QuotaOperation methodName */ methodName?: (string|null); /** QuotaOperation consumerId */ consumerId?: (string|null); /** QuotaOperation labels */ labels?: ({ [k: string]: string }|null); /** QuotaOperation quotaMetrics */ quotaMetrics?: (google.api.servicecontrol.v1.IMetricValueSet[]|null); /** QuotaOperation quotaMode */ quotaMode?: (google.api.servicecontrol.v1.QuotaOperation.QuotaMode|keyof typeof google.api.servicecontrol.v1.QuotaOperation.QuotaMode|null); } /** Represents a QuotaOperation. */ class QuotaOperation implements IQuotaOperation { /** * Constructs a new QuotaOperation. * @param [properties] Properties to set */ constructor(properties?: google.api.servicecontrol.v1.IQuotaOperation); /** QuotaOperation operationId. */ public operationId: string; /** QuotaOperation methodName. */ public methodName: string; /** QuotaOperation consumerId. */ public consumerId: string; /** QuotaOperation labels. */ public labels: { [k: string]: string }; /** QuotaOperation quotaMetrics. */ public quotaMetrics: google.api.servicecontrol.v1.IMetricValueSet[]; /** QuotaOperation quotaMode. */ public quotaMode: (google.api.servicecontrol.v1.QuotaOperation.QuotaMode|keyof typeof google.api.servicecontrol.v1.QuotaOperation.QuotaMode); /** * Creates a new QuotaOperation instance using the specified properties. * @param [properties] Properties to set * @returns QuotaOperation instance */ public static create(properties?: google.api.servicecontrol.v1.IQuotaOperation): google.api.servicecontrol.v1.QuotaOperation; /** * Encodes the specified QuotaOperation message. Does not implicitly {@link google.api.servicecontrol.v1.QuotaOperation.verify|verify} messages. * @param message QuotaOperation message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.api.servicecontrol.v1.IQuotaOperation, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified QuotaOperation message, length delimited. Does not implicitly {@link google.api.servicecontrol.v1.QuotaOperation.verify|verify} messages. * @param message QuotaOperation message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.api.servicecontrol.v1.IQuotaOperation, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a QuotaOperation message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns QuotaOperation * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.servicecontrol.v1.QuotaOperation; /** * Decodes a QuotaOperation message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns QuotaOperation * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.servicecontrol.v1.QuotaOperation; /** * Verifies a QuotaOperation message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a QuotaOperation message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns QuotaOperation */ public static fromObject(object: { [k: string]: any }): google.api.servicecontrol.v1.QuotaOperation; /** * Creates a plain object from a QuotaOperation message. Also converts values to other types if specified. * @param message QuotaOperation * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.api.servicecontrol.v1.QuotaOperation, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this QuotaOperation to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace QuotaOperation { /** QuotaMode enum. */ enum QuotaMode { UNSPECIFIED = 0, NORMAL = 1, BEST_EFFORT = 2, CHECK_ONLY = 3, QUERY_ONLY = 4, ADJUST_ONLY = 5 } } /** Properties of an AllocateQuotaResponse. */ interface IAllocateQuotaResponse { /** AllocateQuotaResponse operationId */ operationId?: (string|null); /** AllocateQuotaResponse allocateErrors */ allocateErrors?: (google.api.servicecontrol.v1.IQuotaError[]|null); /** AllocateQuotaResponse quotaMetrics */ quotaMetrics?: (google.api.servicecontrol.v1.IMetricValueSet[]|null); /** AllocateQuotaResponse serviceConfigId */ serviceConfigId?: (string|null); } /** Represents an AllocateQuotaResponse. */ class AllocateQuotaResponse implements IAllocateQuotaResponse { /** * Constructs a new AllocateQuotaResponse. * @param [properties] Properties to set */ constructor(properties?: google.api.servicecontrol.v1.IAllocateQuotaResponse); /** AllocateQuotaResponse operationId. */ public operationId: string; /** AllocateQuotaResponse allocateErrors. */ public allocateErrors: google.api.servicecontrol.v1.IQuotaError[]; /** AllocateQuotaResponse quotaMetrics. */ public quotaMetrics: google.api.servicecontrol.v1.IMetricValueSet[]; /** AllocateQuotaResponse serviceConfigId. */ public serviceConfigId: string; /** * Creates a new AllocateQuotaResponse instance using the specified properties. * @param [properties] Properties to set * @returns AllocateQuotaResponse instance */ public static create(properties?: google.api.servicecontrol.v1.IAllocateQuotaResponse): google.api.servicecontrol.v1.AllocateQuotaResponse; /** * Encodes the specified AllocateQuotaResponse message. Does not implicitly {@link google.api.servicecontrol.v1.AllocateQuotaResponse.verify|verify} messages. * @param message AllocateQuotaResponse message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.api.servicecontrol.v1.IAllocateQuotaResponse, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified AllocateQuotaResponse message, length delimited. Does not implicitly {@link google.api.servicecontrol.v1.AllocateQuotaResponse.verify|verify} messages. * @param message AllocateQuotaResponse message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.api.servicecontrol.v1.IAllocateQuotaResponse, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an AllocateQuotaResponse message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns AllocateQuotaResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.servicecontrol.v1.AllocateQuotaResponse; /** * Decodes an AllocateQuotaResponse message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns AllocateQuotaResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.servicecontrol.v1.AllocateQuotaResponse; /** * Verifies an AllocateQuotaResponse message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an AllocateQuotaResponse message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns AllocateQuotaResponse */ public static fromObject(object: { [k: string]: any }): google.api.servicecontrol.v1.AllocateQuotaResponse; /** * Creates a plain object from an AllocateQuotaResponse message. Also converts values to other types if specified. * @param message AllocateQuotaResponse * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.api.servicecontrol.v1.AllocateQuotaResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this AllocateQuotaResponse to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a QuotaError. */ interface IQuotaError { /** QuotaError code */ code?: (google.api.servicecontrol.v1.QuotaError.Code|keyof typeof google.api.servicecontrol.v1.QuotaError.Code|null); /** QuotaError subject */ subject?: (string|null); /** QuotaError description */ description?: (string|null); /** QuotaError status */ status?: (google.rpc.IStatus|null); } /** Represents a QuotaError. */ class QuotaError implements IQuotaError { /** * Constructs a new QuotaError. * @param [properties] Properties to set */ constructor(properties?: google.api.servicecontrol.v1.IQuotaError); /** QuotaError code. */ public code: (google.api.servicecontrol.v1.QuotaError.Code|keyof typeof google.api.servicecontrol.v1.QuotaError.Code); /** QuotaError subject. */ public subject: string; /** QuotaError description. */ public description: string; /** QuotaError status. */ public status?: (google.rpc.IStatus|null); /** * Creates a new QuotaError instance using the specified properties. * @param [properties] Properties to set * @returns QuotaError instance */ public static create(properties?: google.api.servicecontrol.v1.IQuotaError): google.api.servicecontrol.v1.QuotaError; /** * Encodes the specified QuotaError message. Does not implicitly {@link google.api.servicecontrol.v1.QuotaError.verify|verify} messages. * @param message QuotaError message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.api.servicecontrol.v1.IQuotaError, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified QuotaError message, length delimited. Does not implicitly {@link google.api.servicecontrol.v1.QuotaError.verify|verify} messages. * @param message QuotaError message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.api.servicecontrol.v1.IQuotaError, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a QuotaError message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns QuotaError * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.servicecontrol.v1.QuotaError; /** * Decodes a QuotaError message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns QuotaError * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.servicecontrol.v1.QuotaError; /** * Verifies a QuotaError message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a QuotaError message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns QuotaError */ public static fromObject(object: { [k: string]: any }): google.api.servicecontrol.v1.QuotaError; /** * Creates a plain object from a QuotaError message. Also converts values to other types if specified. * @param message QuotaError * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.api.servicecontrol.v1.QuotaError, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this QuotaError to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace QuotaError { /** Code enum. */ enum Code { UNSPECIFIED = 0, RESOURCE_EXHAUSTED = 8, BILLING_NOT_ACTIVE = 107, PROJECT_DELETED = 108, API_KEY_INVALID = 105, API_KEY_EXPIRED = 112 } } /** Represents a ServiceController */ class ServiceController extends $protobuf.rpc.Service { /** * Constructs a new ServiceController service. * @param rpcImpl RPC implementation * @param [requestDelimited=false] Whether requests are length-delimited * @param [responseDelimited=false] Whether responses are length-delimited */ constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); /** * Creates new ServiceController service using the specified rpc implementation. * @param rpcImpl RPC implementation * @param [requestDelimited=false] Whether requests are length-delimited * @param [responseDelimited=false] Whether responses are length-delimited * @returns RPC service. Useful where requests and/or responses are streamed. */ public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): ServiceController; /** * Calls Check. * @param request CheckRequest message or plain object * @param callback Node-style callback called with the error, if any, and CheckResponse */ public check(request: google.api.servicecontrol.v1.ICheckRequest, callback: google.api.servicecontrol.v1.ServiceController.CheckCallback): void; /** * Calls Check. * @param request CheckRequest message or plain object * @returns Promise */ public check(request: google.api.servicecontrol.v1.ICheckRequest): Promise<google.api.servicecontrol.v1.CheckResponse>; /** * Calls Report. * @param request ReportRequest message or plain object * @param callback Node-style callback called with the error, if any, and ReportResponse */ public report(request: google.api.servicecontrol.v1.IReportRequest, callback: google.api.servicecontrol.v1.ServiceController.ReportCallback): void; /** * Calls Report. * @param request ReportRequest message or plain object * @returns Promise */ public report(request: google.api.servicecontrol.v1.IReportRequest): Promise<google.api.servicecontrol.v1.ReportResponse>; } namespace ServiceController { /** * Callback as used by {@link google.api.servicecontrol.v1.ServiceController#check}. * @param error Error, if any * @param [response] CheckResponse */ type CheckCallback = (error: (Error|null), response?: google.api.servicecontrol.v1.CheckResponse) => void; /** * Callback as used by {@link google.api.servicecontrol.v1.ServiceController#report}. * @param error Error, if any * @param [response] ReportResponse */ type ReportCallback = (error: (Error|null), response?: google.api.servicecontrol.v1.ReportResponse) => void; } /** Properties of a CheckRequest. */ interface ICheckRequest { /** CheckRequest serviceName */ serviceName?: (string|null); /** CheckRequest operation */ operation?: (google.api.servicecontrol.v1.IOperation|null); /** CheckRequest serviceConfigId */ serviceConfigId?: (string|null); } /** Represents a CheckRequest. */ class CheckRequest implements ICheckRequest { /** * Constructs a new CheckRequest. * @param [properties] Properties to set */ constructor(properties?: google.api.servicecontrol.v1.ICheckRequest); /** CheckRequest serviceName. */ public serviceName: string; /** CheckRequest operation. */ public operation?: (google.api.servicecontrol.v1.IOperation|null); /** CheckRequest serviceConfigId. */ public serviceConfigId: string; /** * Creates a new CheckRequest instance using the specified properties. * @param [properties] Properties to set * @returns CheckRequest instance */ public static create(properties?: google.api.servicecontrol.v1.ICheckRequest): google.api.servicecontrol.v1.CheckRequest; /** * Encodes the specified CheckRequest message. Does not implicitly {@link google.api.servicecontrol.v1.CheckRequest.verify|verify} messages. * @param message CheckRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.api.servicecontrol.v1.ICheckRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified CheckRequest message, length delimited. Does not implicitly {@link google.api.servicecontrol.v1.CheckRequest.verify|verify} messages. * @param message CheckRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.api.servicecontrol.v1.ICheckRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a CheckRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns CheckRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.servicecontrol.v1.CheckRequest; /** * Decodes a CheckRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns CheckRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.servicecontrol.v1.CheckRequest; /** * Verifies a CheckRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a CheckRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns CheckRequest */ public static fromObject(object: { [k: string]: any }): google.api.servicecontrol.v1.CheckRequest; /** * Creates a plain object from a CheckRequest message. Also converts values to other types if specified. * @param message CheckRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.api.servicecontrol.v1.CheckRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this CheckRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a CheckResponse. */ interface ICheckResponse { /** CheckResponse operationId */ operationId?: (string|null); /** CheckResponse checkErrors */ checkErrors?: (google.api.servicecontrol.v1.ICheckError[]|null); /** CheckResponse serviceConfigId */ serviceConfigId?: (string|null); /** CheckResponse serviceRolloutId */ serviceRolloutId?: (string|null); /** CheckResponse checkInfo */ checkInfo?: (google.api.servicecontrol.v1.CheckResponse.ICheckInfo|null); } /** Represents a CheckResponse. */ class CheckResponse implements ICheckResponse { /** * Constructs a new CheckResponse. * @param [properties] Properties to set */ constructor(properties?: google.api.servicecontrol.v1.ICheckResponse); /** CheckResponse operationId. */ public operationId: string; /** CheckResponse checkErrors. */ public checkErrors: google.api.servicecontrol.v1.ICheckError[]; /** CheckResponse serviceConfigId. */ public serviceConfigId: string; /** CheckResponse serviceRolloutId. */ public serviceRolloutId: string; /** CheckResponse checkInfo. */ public checkInfo?: (google.api.servicecontrol.v1.CheckResponse.ICheckInfo|null); /** * Creates a new CheckResponse instance using the specified properties. * @param [properties] Properties to set * @returns CheckResponse instance */ public static create(properties?: google.api.servicecontrol.v1.ICheckResponse): google.api.servicecontrol.v1.CheckResponse; /** * Encodes the specified CheckResponse message. Does not implicitly {@link google.api.servicecontrol.v1.CheckResponse.verify|verify} messages. * @param message CheckResponse message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.api.servicecontrol.v1.ICheckResponse, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified CheckResponse message, length delimited. Does not implicitly {@link google.api.servicecontrol.v1.CheckResponse.verify|verify} messages. * @param message CheckResponse message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.api.servicecontrol.v1.ICheckResponse, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a CheckResponse message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns CheckResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.servicecontrol.v1.CheckResponse; /** * Decodes a CheckResponse message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns CheckResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.servicecontrol.v1.CheckResponse; /** * Verifies a CheckResponse message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a CheckResponse message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns CheckResponse */ public static fromObject(object: { [k: string]: any }): google.api.servicecontrol.v1.CheckResponse; /** * Creates a plain object from a CheckResponse message. Also converts values to other types if specified. * @param message CheckResponse * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.api.servicecontrol.v1.CheckResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this CheckResponse to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace CheckResponse { /** Properties of a CheckInfo. */ interface ICheckInfo { /** CheckInfo unusedArguments */ unusedArguments?: (string[]|null); /** CheckInfo consumerInfo */ consumerInfo?: (google.api.servicecontrol.v1.CheckResponse.IConsumerInfo|null); } /** Represents a CheckInfo. */ class CheckInfo implements ICheckInfo { /** * Constructs a new CheckInfo. * @param [properties] Properties to set */ constructor(properties?: google.api.servicecontrol.v1.CheckResponse.ICheckInfo); /** CheckInfo unusedArguments. */ public unusedArguments: string[]; /** CheckInfo consumerInfo. */ public consumerInfo?: (google.api.servicecontrol.v1.CheckResponse.IConsumerInfo|null); /** * Creates a new CheckInfo instance using the specified properties. * @param [properties] Properties to set * @returns CheckInfo instance */ public static create(properties?: google.api.servicecontrol.v1.CheckResponse.ICheckInfo): google.api.servicecontrol.v1.CheckResponse.CheckInfo; /** * Encodes the specified CheckInfo message. Does not implicitly {@link google.api.servicecontrol.v1.CheckResponse.CheckInfo.verify|verify} messages. * @param message CheckInfo message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.api.servicecontrol.v1.CheckResponse.ICheckInfo, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified CheckInfo message, length delimited. Does not implicitly {@link google.api.servicecontrol.v1.CheckResponse.CheckInfo.verify|verify} messages. * @param message CheckInfo message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.api.servicecontrol.v1.CheckResponse.ICheckInfo, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a CheckInfo message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns CheckInfo * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.servicecontrol.v1.CheckResponse.CheckInfo; /** * Decodes a CheckInfo message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns CheckInfo * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.servicecontrol.v1.CheckResponse.CheckInfo; /** * Verifies a CheckInfo message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a CheckInfo message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns CheckInfo */ public static fromObject(object: { [k: string]: any }): google.api.servicecontrol.v1.CheckResponse.CheckInfo; /** * Creates a plain object from a CheckInfo message. Also converts values to other types if specified. * @param message CheckInfo * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.api.servicecontrol.v1.CheckResponse.CheckInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this CheckInfo to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a ConsumerInfo. */ interface IConsumerInfo { /** ConsumerInfo projectNumber */ projectNumber?: (number|Long|string|null); /** ConsumerInfo type */ type?: (google.api.servicecontrol.v1.CheckResponse.ConsumerInfo.ConsumerType|keyof typeof google.api.servicecontrol.v1.CheckResponse.ConsumerInfo.ConsumerType|null); /** ConsumerInfo consumerNumber */ consumerNumber?: (number|Long|string|null); } /** Represents a ConsumerInfo. */ class ConsumerInfo implements IConsumerInfo { /** * Constructs a new ConsumerInfo. * @param [properties] Properties to set */ constructor(properties?: google.api.servicecontrol.v1.CheckResponse.IConsumerInfo); /** ConsumerInfo projectNumber. */ public projectNumber: (number|Long|string); /** ConsumerInfo type. */ public type: (google.api.servicecontrol.v1.CheckResponse.ConsumerInfo.ConsumerType|keyof typeof google.api.servicecontrol.v1.CheckResponse.ConsumerInfo.ConsumerType); /** ConsumerInfo consumerNumber. */ public consumerNumber: (number|Long|string); /** * Creates a new ConsumerInfo instance using the specified properties. * @param [properties] Properties to set * @returns ConsumerInfo instance */ public static create(properties?: google.api.servicecontrol.v1.CheckResponse.IConsumerInfo): google.api.servicecontrol.v1.CheckResponse.ConsumerInfo; /** * Encodes the specified ConsumerInfo message. Does not implicitly {@link google.api.servicecontrol.v1.CheckResponse.ConsumerInfo.verify|verify} messages. * @param message ConsumerInfo message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.api.servicecontrol.v1.CheckResponse.IConsumerInfo, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ConsumerInfo message, length delimited. Does not implicitly {@link google.api.servicecontrol.v1.CheckResponse.ConsumerInfo.verify|verify} messages. * @param message ConsumerInfo message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.api.servicecontrol.v1.CheckResponse.IConsumerInfo, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ConsumerInfo message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ConsumerInfo * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.servicecontrol.v1.CheckResponse.ConsumerInfo; /** * Decodes a ConsumerInfo message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ConsumerInfo * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.servicecontrol.v1.CheckResponse.ConsumerInfo; /** * Verifies a ConsumerInfo message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ConsumerInfo message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ConsumerInfo */ public static fromObject(object: { [k: string]: any }): google.api.servicecontrol.v1.CheckResponse.ConsumerInfo; /** * Creates a plain object from a ConsumerInfo message. Also converts values to other types if specified. * @param message ConsumerInfo * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.api.servicecontrol.v1.CheckResponse.ConsumerInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ConsumerInfo to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace ConsumerInfo { /** ConsumerType enum. */ enum ConsumerType { CONSUMER_TYPE_UNSPECIFIED = 0, PROJECT = 1, FOLDER = 2, ORGANIZATION = 3, SERVICE_SPECIFIC = 4 } } } /** Properties of a ReportRequest. */ interface IReportRequest { /** ReportRequest serviceName */ serviceName?: (string|null); /** ReportRequest operations */ operations?: (google.api.servicecontrol.v1.IOperation[]|null); /** ReportRequest serviceConfigId */ serviceConfigId?: (string|null); } /** Represents a ReportRequest. */ class ReportRequest implements IReportRequest { /** * Constructs a new ReportRequest. * @param [properties] Properties to set */ constructor(properties?: google.api.servicecontrol.v1.IReportRequest); /** ReportRequest serviceName. */ public serviceName: string; /** ReportRequest operations. */ public operations: google.api.servicecontrol.v1.IOperation[]; /** ReportRequest serviceConfigId. */ public serviceConfigId: string; /** * Creates a new ReportRequest instance using the specified properties. * @param [properties] Properties to set * @returns ReportRequest instance */ public static create(properties?: google.api.servicecontrol.v1.IReportRequest): google.api.servicecontrol.v1.ReportRequest; /** * Encodes the specified ReportRequest message. Does not implicitly {@link google.api.servicecontrol.v1.ReportRequest.verify|verify} messages. * @param message ReportRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.api.servicecontrol.v1.IReportRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ReportRequest message, length delimited. Does not implicitly {@link google.api.servicecontrol.v1.ReportRequest.verify|verify} messages. * @param message ReportRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.api.servicecontrol.v1.IReportRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ReportRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ReportRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.servicecontrol.v1.ReportRequest; /** * Decodes a ReportRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ReportRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.servicecontrol.v1.ReportRequest; /** * Verifies a ReportRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ReportRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ReportRequest */ public static fromObject(object: { [k: string]: any }): google.api.servicecontrol.v1.ReportRequest; /** * Creates a plain object from a ReportRequest message. Also converts values to other types if specified. * @param message ReportRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.api.servicecontrol.v1.ReportRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ReportRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a ReportResponse. */ interface IReportResponse { /** ReportResponse reportErrors */ reportErrors?: (google.api.servicecontrol.v1.ReportResponse.IReportError[]|null); /** ReportResponse serviceConfigId */ serviceConfigId?: (string|null); /** ReportResponse serviceRolloutId */ serviceRolloutId?: (string|null); } /** Represents a ReportResponse. */ class ReportResponse implements IReportResponse { /** * Constructs a new ReportResponse. * @param [properties] Properties to set */ constructor(properties?: google.api.servicecontrol.v1.IReportResponse); /** ReportResponse reportErrors. */ public reportErrors: google.api.servicecontrol.v1.ReportResponse.IReportError[]; /** ReportResponse serviceConfigId. */ public serviceConfigId: string; /** ReportResponse serviceRolloutId. */ public serviceRolloutId: string; /** * Creates a new ReportResponse instance using the specified properties. * @param [properties] Properties to set * @returns ReportResponse instance */ public static create(properties?: google.api.servicecontrol.v1.IReportResponse): google.api.servicecontrol.v1.ReportResponse; /** * Encodes the specified ReportResponse message. Does not implicitly {@link google.api.servicecontrol.v1.ReportResponse.verify|verify} messages. * @param message ReportResponse message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.api.servicecontrol.v1.IReportResponse, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ReportResponse message, length delimited. Does not implicitly {@link google.api.servicecontrol.v1.ReportResponse.verify|verify} messages. * @param message ReportResponse message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.api.servicecontrol.v1.IReportResponse, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ReportResponse message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ReportResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.servicecontrol.v1.ReportResponse; /** * Decodes a ReportResponse message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ReportResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.servicecontrol.v1.ReportResponse; /** * Verifies a ReportResponse message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ReportResponse message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ReportResponse */ public static fromObject(object: { [k: string]: any }): google.api.servicecontrol.v1.ReportResponse; /** * Creates a plain object from a ReportResponse message. Also converts values to other types if specified. * @param message ReportResponse * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.api.servicecontrol.v1.ReportResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ReportResponse to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace ReportResponse { /** Properties of a ReportError. */ interface IReportError { /** ReportError operationId */ operationId?: (string|null); /** ReportError status */ status?: (google.rpc.IStatus|null); } /** Represents a ReportError. */ class ReportError implements IReportError { /** * Constructs a new ReportError. * @param [properties] Properties to set */ constructor(properties?: google.api.servicecontrol.v1.ReportResponse.IReportError); /** ReportError operationId. */ public operationId: string; /** ReportError status. */ public status?: (google.rpc.IStatus|null); /** * Creates a new ReportError instance using the specified properties. * @param [properties] Properties to set * @returns ReportError instance */ public static create(properties?: google.api.servicecontrol.v1.ReportResponse.IReportError): google.api.servicecontrol.v1.ReportResponse.ReportError; /** * Encodes the specified ReportError message. Does not implicitly {@link google.api.servicecontrol.v1.ReportResponse.ReportError.verify|verify} messages. * @param message ReportError message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.api.servicecontrol.v1.ReportResponse.IReportError, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ReportError message, length delimited. Does not implicitly {@link google.api.servicecontrol.v1.ReportResponse.ReportError.verify|verify} messages. * @param message ReportError message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.api.servicecontrol.v1.ReportResponse.IReportError, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ReportError message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ReportError * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.servicecontrol.v1.ReportResponse.ReportError; /** * Decodes a ReportError message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ReportError * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.servicecontrol.v1.ReportResponse.ReportError; /** * Verifies a ReportError message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ReportError message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ReportError */ public static fromObject(object: { [k: string]: any }): google.api.servicecontrol.v1.ReportResponse.ReportError; /** * Creates a plain object from a ReportError message. Also converts values to other types if specified. * @param message ReportError * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.api.servicecontrol.v1.ReportResponse.ReportError, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ReportError to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } } } /** Properties of a Distribution. */ interface IDistribution { /** Distribution count */ count?: (number|Long|string|null); /** Distribution mean */ mean?: (number|null); /** Distribution sumOfSquaredDeviation */ sumOfSquaredDeviation?: (number|null); /** Distribution range */ range?: (google.api.Distribution.IRange|null); /** Distribution bucketOptions */ bucketOptions?: (google.api.Distribution.IBucketOptions|null); /** Distribution bucketCounts */ bucketCounts?: ((number|Long|string)[]|null); /** Distribution exemplars */ exemplars?: (google.api.Distribution.IExemplar[]|null); } /** Represents a Distribution. */ class Distribution implements IDistribution { /** * Constructs a new Distribution. * @param [properties] Properties to set */ constructor(properties?: google.api.IDistribution); /** Distribution count. */ public count: (number|Long|string); /** Distribution mean. */ public mean: number; /** Distribution sumOfSquaredDeviation. */ public sumOfSquaredDeviation: number; /** Distribution range. */ public range?: (google.api.Distribution.IRange|null); /** Distribution bucketOptions. */ public bucketOptions?: (google.api.Distribution.IBucketOptions|null); /** Distribution bucketCounts. */ public bucketCounts: (number|Long|string)[]; /** Distribution exemplars. */ public exemplars: google.api.Distribution.IExemplar[]; /** * Creates a new Distribution instance using the specified properties. * @param [properties] Properties to set * @returns Distribution instance */ public static create(properties?: google.api.IDistribution): google.api.Distribution; /** * Encodes the specified Distribution message. Does not implicitly {@link google.api.Distribution.verify|verify} messages. * @param message Distribution message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.api.IDistribution, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Distribution message, length delimited. Does not implicitly {@link google.api.Distribution.verify|verify} messages. * @param message Distribution message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.api.IDistribution, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Distribution message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Distribution * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.Distribution; /** * Decodes a Distribution message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Distribution * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.Distribution; /** * Verifies a Distribution message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Distribution message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Distribution */ public static fromObject(object: { [k: string]: any }): google.api.Distribution; /** * Creates a plain object from a Distribution message. Also converts values to other types if specified. * @param message Distribution * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.api.Distribution, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Distribution to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace Distribution { /** Properties of a Range. */ interface IRange { /** Range min */ min?: (number|null); /** Range max */ max?: (number|null); } /** Represents a Range. */ class Range implements IRange { /** * Constructs a new Range. * @param [properties] Properties to set */ constructor(properties?: google.api.Distribution.IRange); /** Range min. */ public min: number; /** Range max. */ public max: number; /** * Creates a new Range instance using the specified properties. * @param [properties] Properties to set * @returns Range instance */ public static create(properties?: google.api.Distribution.IRange): google.api.Distribution.Range; /** * Encodes the specified Range message. Does not implicitly {@link google.api.Distribution.Range.verify|verify} messages. * @param message Range message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.api.Distribution.IRange, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Range message, length delimited. Does not implicitly {@link google.api.Distribution.Range.verify|verify} messages. * @param message Range message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.api.Distribution.IRange, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Range message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Range * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.Distribution.Range; /** * Decodes a Range message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Range * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.Distribution.Range; /** * Verifies a Range message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Range message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Range */ public static fromObject(object: { [k: string]: any }): google.api.Distribution.Range; /** * Creates a plain object from a Range message. Also converts values to other types if specified. * @param message Range * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.api.Distribution.Range, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Range to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a BucketOptions. */ interface IBucketOptions { /** BucketOptions linearBuckets */ linearBuckets?: (google.api.Distribution.BucketOptions.ILinear|null); /** BucketOptions exponentialBuckets */ exponentialBuckets?: (google.api.Distribution.BucketOptions.IExponential|null); /** BucketOptions explicitBuckets */ explicitBuckets?: (google.api.Distribution.BucketOptions.IExplicit|null); } /** Represents a BucketOptions. */ class BucketOptions implements IBucketOptions { /** * Constructs a new BucketOptions. * @param [properties] Properties to set */ constructor(properties?: google.api.Distribution.IBucketOptions); /** BucketOptions linearBuckets. */ public linearBuckets?: (google.api.Distribution.BucketOptions.ILinear|null); /** BucketOptions exponentialBuckets. */ public exponentialBuckets?: (google.api.Distribution.BucketOptions.IExponential|null); /** BucketOptions explicitBuckets. */ public explicitBuckets?: (google.api.Distribution.BucketOptions.IExplicit|null); /** BucketOptions options. */ public options?: ("linearBuckets"|"exponentialBuckets"|"explicitBuckets"); /** * Creates a new BucketOptions instance using the specified properties. * @param [properties] Properties to set * @returns BucketOptions instance */ public static create(properties?: google.api.Distribution.IBucketOptions): google.api.Distribution.BucketOptions; /** * Encodes the specified BucketOptions message. Does not implicitly {@link google.api.Distribution.BucketOptions.verify|verify} messages. * @param message BucketOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.api.Distribution.IBucketOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified BucketOptions message, length delimited. Does not implicitly {@link google.api.Distribution.BucketOptions.verify|verify} messages. * @param message BucketOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.api.Distribution.IBucketOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a BucketOptions message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns BucketOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.Distribution.BucketOptions; /** * Decodes a BucketOptions message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns BucketOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.Distribution.BucketOptions; /** * Verifies a BucketOptions message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a BucketOptions message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns BucketOptions */ public static fromObject(object: { [k: string]: any }): google.api.Distribution.BucketOptions; /** * Creates a plain object from a BucketOptions message. Also converts values to other types if specified. * @param message BucketOptions * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.api.Distribution.BucketOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this BucketOptions to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace BucketOptions { /** Properties of a Linear. */ interface ILinear { /** Linear numFiniteBuckets */ numFiniteBuckets?: (number|null); /** Linear width */ width?: (number|null); /** Linear offset */ offset?: (number|null); } /** Represents a Linear. */ class Linear implements ILinear { /** * Constructs a new Linear. * @param [properties] Properties to set */ constructor(properties?: google.api.Distribution.BucketOptions.ILinear); /** Linear numFiniteBuckets. */ public numFiniteBuckets: number; /** Linear width. */ public width: number; /** Linear offset. */ public offset: number; /** * Creates a new Linear instance using the specified properties. * @param [properties] Properties to set * @returns Linear instance */ public static create(properties?: google.api.Distribution.BucketOptions.ILinear): google.api.Distribution.BucketOptions.Linear; /** * Encodes the specified Linear message. Does not implicitly {@link google.api.Distribution.BucketOptions.Linear.verify|verify} messages. * @param message Linear message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.api.Distribution.BucketOptions.ILinear, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Linear message, length delimited. Does not implicitly {@link google.api.Distribution.BucketOptions.Linear.verify|verify} messages. * @param message Linear message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.api.Distribution.BucketOptions.ILinear, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Linear message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Linear * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.Distribution.BucketOptions.Linear; /** * Decodes a Linear message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Linear * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.Distribution.BucketOptions.Linear; /** * Verifies a Linear message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Linear message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Linear */ public static fromObject(object: { [k: string]: any }): google.api.Distribution.BucketOptions.Linear; /** * Creates a plain object from a Linear message. Also converts values to other types if specified. * @param message Linear * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.api.Distribution.BucketOptions.Linear, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Linear to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of an Exponential. */ interface IExponential { /** Exponential numFiniteBuckets */ numFiniteBuckets?: (number|null); /** Exponential growthFactor */ growthFactor?: (number|null); /** Exponential scale */ scale?: (number|null); } /** Represents an Exponential. */ class Exponential implements IExponential { /** * Constructs a new Exponential. * @param [properties] Properties to set */ constructor(properties?: google.api.Distribution.BucketOptions.IExponential); /** Exponential numFiniteBuckets. */ public numFiniteBuckets: number; /** Exponential growthFactor. */ public growthFactor: number; /** Exponential scale. */ public scale: number; /** * Creates a new Exponential instance using the specified properties. * @param [properties] Properties to set * @returns Exponential instance */ public static create(properties?: google.api.Distribution.BucketOptions.IExponential): google.api.Distribution.BucketOptions.Exponential; /** * Encodes the specified Exponential message. Does not implicitly {@link google.api.Distribution.BucketOptions.Exponential.verify|verify} messages. * @param message Exponential message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.api.Distribution.BucketOptions.IExponential, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Exponential message, length delimited. Does not implicitly {@link google.api.Distribution.BucketOptions.Exponential.verify|verify} messages. * @param message Exponential message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.api.Distribution.BucketOptions.IExponential, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an Exponential message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Exponential * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.Distribution.BucketOptions.Exponential; /** * Decodes an Exponential message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Exponential * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.Distribution.BucketOptions.Exponential; /** * Verifies an Exponential message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an Exponential message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Exponential */ public static fromObject(object: { [k: string]: any }): google.api.Distribution.BucketOptions.Exponential; /** * Creates a plain object from an Exponential message. Also converts values to other types if specified. * @param message Exponential * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.api.Distribution.BucketOptions.Exponential, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Exponential to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of an Explicit. */ interface IExplicit { /** Explicit bounds */ bounds?: (number[]|null); } /** Represents an Explicit. */ class Explicit implements IExplicit { /** * Constructs a new Explicit. * @param [properties] Properties to set */ constructor(properties?: google.api.Distribution.BucketOptions.IExplicit); /** Explicit bounds. */ public bounds: number[]; /** * Creates a new Explicit instance using the specified properties. * @param [properties] Properties to set * @returns Explicit instance */ public static create(properties?: google.api.Distribution.BucketOptions.IExplicit): google.api.Distribution.BucketOptions.Explicit; /** * Encodes the specified Explicit message. Does not implicitly {@link google.api.Distribution.BucketOptions.Explicit.verify|verify} messages. * @param message Explicit message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.api.Distribution.BucketOptions.IExplicit, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Explicit message, length delimited. Does not implicitly {@link google.api.Distribution.BucketOptions.Explicit.verify|verify} messages. * @param message Explicit message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.api.Distribution.BucketOptions.IExplicit, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an Explicit message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Explicit * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.Distribution.BucketOptions.Explicit; /** * Decodes an Explicit message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Explicit * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.Distribution.BucketOptions.Explicit; /** * Verifies an Explicit message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an Explicit message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Explicit */ public static fromObject(object: { [k: string]: any }): google.api.Distribution.BucketOptions.Explicit; /** * Creates a plain object from an Explicit message. Also converts values to other types if specified. * @param message Explicit * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.api.Distribution.BucketOptions.Explicit, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Explicit to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } /** Properties of an Exemplar. */ interface IExemplar { /** Exemplar value */ value?: (number|null); /** Exemplar timestamp */ timestamp?: (google.protobuf.ITimestamp|null); /** Exemplar attachments */ attachments?: (google.protobuf.IAny[]|null); } /** Represents an Exemplar. */ class Exemplar implements IExemplar { /** * Constructs a new Exemplar. * @param [properties] Properties to set */ constructor(properties?: google.api.Distribution.IExemplar); /** Exemplar value. */ public value: number; /** Exemplar timestamp. */ public timestamp?: (google.protobuf.ITimestamp|null); /** Exemplar attachments. */ public attachments: google.protobuf.IAny[]; /** * Creates a new Exemplar instance using the specified properties. * @param [properties] Properties to set * @returns Exemplar instance */ public static create(properties?: google.api.Distribution.IExemplar): google.api.Distribution.Exemplar; /** * Encodes the specified Exemplar message. Does not implicitly {@link google.api.Distribution.Exemplar.verify|verify} messages. * @param message Exemplar message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.api.Distribution.IExemplar, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Exemplar message, length delimited. Does not implicitly {@link google.api.Distribution.Exemplar.verify|verify} messages. * @param message Exemplar message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.api.Distribution.IExemplar, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an Exemplar message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Exemplar * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.Distribution.Exemplar; /** * Decodes an Exemplar message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Exemplar * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.Distribution.Exemplar; /** * Verifies an Exemplar message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an Exemplar message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Exemplar */ public static fromObject(object: { [k: string]: any }): google.api.Distribution.Exemplar; /** * Creates a plain object from an Exemplar message. Also converts values to other types if specified. * @param message Exemplar * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.api.Distribution.Exemplar, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Exemplar to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } /** Properties of a Http. */ interface IHttp { /** Http rules */ rules?: (google.api.IHttpRule[]|null); /** Http fullyDecodeReservedExpansion */ fullyDecodeReservedExpansion?: (boolean|null); } /** Represents a Http. */ class Http implements IHttp { /** * Constructs a new Http. * @param [properties] Properties to set */ constructor(properties?: google.api.IHttp); /** Http rules. */ public rules: google.api.IHttpRule[]; /** Http fullyDecodeReservedExpansion. */ public fullyDecodeReservedExpansion: boolean; /** * Creates a new Http instance using the specified properties. * @param [properties] Properties to set * @returns Http instance */ public static create(properties?: google.api.IHttp): google.api.Http; /** * Encodes the specified Http message. Does not implicitly {@link google.api.Http.verify|verify} messages. * @param message Http message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.api.IHttp, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Http message, length delimited. Does not implicitly {@link google.api.Http.verify|verify} messages. * @param message Http message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.api.IHttp, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Http message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Http * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.Http; /** * Decodes a Http message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Http * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.Http; /** * Verifies a Http message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Http message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Http */ public static fromObject(object: { [k: string]: any }): google.api.Http; /** * Creates a plain object from a Http message. Also converts values to other types if specified. * @param message Http * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.api.Http, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Http to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a HttpRule. */ interface IHttpRule { /** HttpRule selector */ selector?: (string|null); /** HttpRule get */ get?: (string|null); /** HttpRule put */ put?: (string|null); /** HttpRule post */ post?: (string|null); /** HttpRule delete */ "delete"?: (string|null); /** HttpRule patch */ patch?: (string|null); /** HttpRule custom */ custom?: (google.api.ICustomHttpPattern|null); /** HttpRule body */ body?: (string|null); /** HttpRule responseBody */ responseBody?: (string|null); /** HttpRule additionalBindings */ additionalBindings?: (google.api.IHttpRule[]|null); } /** Represents a HttpRule. */ class HttpRule implements IHttpRule { /** * Constructs a new HttpRule. * @param [properties] Properties to set */ constructor(properties?: google.api.IHttpRule); /** HttpRule selector. */ public selector: string; /** HttpRule get. */ public get?: (string|null); /** HttpRule put. */ public put?: (string|null); /** HttpRule post. */ public post?: (string|null); /** HttpRule delete. */ public delete?: (string|null); /** HttpRule patch. */ public patch?: (string|null); /** HttpRule custom. */ public custom?: (google.api.ICustomHttpPattern|null); /** HttpRule body. */ public body: string; /** HttpRule responseBody. */ public responseBody: string; /** HttpRule additionalBindings. */ public additionalBindings: google.api.IHttpRule[]; /** HttpRule pattern. */ public pattern?: ("get"|"put"|"post"|"delete"|"patch"|"custom"); /** * Creates a new HttpRule instance using the specified properties. * @param [properties] Properties to set * @returns HttpRule instance */ public static create(properties?: google.api.IHttpRule): google.api.HttpRule; /** * Encodes the specified HttpRule message. Does not implicitly {@link google.api.HttpRule.verify|verify} messages. * @param message HttpRule message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.api.IHttpRule, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified HttpRule message, length delimited. Does not implicitly {@link google.api.HttpRule.verify|verify} messages. * @param message HttpRule message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.api.IHttpRule, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a HttpRule message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns HttpRule * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.HttpRule; /** * Decodes a HttpRule message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns HttpRule * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.HttpRule; /** * Verifies a HttpRule message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a HttpRule message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns HttpRule */ public static fromObject(object: { [k: string]: any }): google.api.HttpRule; /** * Creates a plain object from a HttpRule message. Also converts values to other types if specified. * @param message HttpRule * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.api.HttpRule, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this HttpRule to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a CustomHttpPattern. */ interface ICustomHttpPattern { /** CustomHttpPattern kind */ kind?: (string|null); /** CustomHttpPattern path */ path?: (string|null); } /** Represents a CustomHttpPattern. */ class CustomHttpPattern implements ICustomHttpPattern { /** * Constructs a new CustomHttpPattern. * @param [properties] Properties to set */ constructor(properties?: google.api.ICustomHttpPattern); /** CustomHttpPattern kind. */ public kind: string; /** CustomHttpPattern path. */ public path: string; /** * Creates a new CustomHttpPattern instance using the specified properties. * @param [properties] Properties to set * @returns CustomHttpPattern instance */ public static create(properties?: google.api.ICustomHttpPattern): google.api.CustomHttpPattern; /** * Encodes the specified CustomHttpPattern message. Does not implicitly {@link google.api.CustomHttpPattern.verify|verify} messages. * @param message CustomHttpPattern message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.api.ICustomHttpPattern, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified CustomHttpPattern message, length delimited. Does not implicitly {@link google.api.CustomHttpPattern.verify|verify} messages. * @param message CustomHttpPattern message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.api.ICustomHttpPattern, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a CustomHttpPattern message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns CustomHttpPattern * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.CustomHttpPattern; /** * Decodes a CustomHttpPattern message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns CustomHttpPattern * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.CustomHttpPattern; /** * Verifies a CustomHttpPattern message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a CustomHttpPattern message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns CustomHttpPattern */ public static fromObject(object: { [k: string]: any }): google.api.CustomHttpPattern; /** * Creates a plain object from a CustomHttpPattern message. Also converts values to other types if specified. * @param message CustomHttpPattern * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.api.CustomHttpPattern, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this CustomHttpPattern to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } /** Namespace rpc. */ namespace rpc { /** Properties of a Status. */ interface IStatus { /** Status code */ code?: (number|null); /** Status message */ message?: (string|null); /** Status details */ details?: (google.protobuf.IAny[]|null); } /** Represents a Status. */ class Status implements IStatus { /** * Constructs a new Status. * @param [properties] Properties to set */ constructor(properties?: google.rpc.IStatus); /** Status code. */ public code: number; /** Status message. */ public message: string; /** Status details. */ public details: google.protobuf.IAny[]; /** * Creates a new Status instance using the specified properties. * @param [properties] Properties to set * @returns Status instance */ public static create(properties?: google.rpc.IStatus): google.rpc.Status; /** * Encodes the specified Status message. Does not implicitly {@link google.rpc.Status.verify|verify} messages. * @param message Status message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.rpc.IStatus, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Status message, length delimited. Does not implicitly {@link google.rpc.Status.verify|verify} messages. * @param message Status message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.rpc.IStatus, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Status message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Status * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.Status; /** * Decodes a Status message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Status * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.Status; /** * Verifies a Status message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Status message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Status */ public static fromObject(object: { [k: string]: any }): google.rpc.Status; /** * Creates a plain object from a Status message. Also converts values to other types if specified. * @param message Status * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.rpc.Status, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Status to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } /** Namespace logging. */ namespace logging { /** Namespace type. */ namespace type { /** LogSeverity enum. */ enum LogSeverity { DEFAULT = 0, DEBUG = 100, INFO = 200, NOTICE = 300, WARNING = 400, ERROR = 500, CRITICAL = 600, ALERT = 700, EMERGENCY = 800 } } } }
apache-2.0
seiffert/amazon-ecs-agent
agent/api/json_test.go
5243
// Copyright 2014-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may // not use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either // express or implied. See the License for the specific language governing // permissions and limitations under the License. package api import ( "encoding/json" "reflect" "testing" ) type testTaskStatus struct { SomeStatus TaskStatus `json:"status"` } func TestUnmarshalTaskStatus(t *testing.T) { status := TaskStatusNone err := json.Unmarshal([]byte(`"RUNNING"`), &status) if err != nil { t.Error(err) } if status != TaskRunning { t.Error("RUNNING should unmarshal to RUNNING, not " + status.String()) } var test testTaskStatus err = json.Unmarshal([]byte(`{"status":"STOPPED"}`), &test) if err != nil { t.Error(err) } if test.SomeStatus != TaskStopped { t.Error("STOPPED should unmarshal to STOPPED, not " + test.SomeStatus.String()) } } type testContainerStatus struct { SomeStatus ContainerStatus `json:"status"` } func TestUnmarshalContainerStatus(t *testing.T) { status := ContainerStatusNone err := json.Unmarshal([]byte(`"RUNNING"`), &status) if err != nil { t.Error(err) } if status != ContainerRunning { t.Error("RUNNING should unmarshal to RUNNING, not " + status.String()) } var test testContainerStatus err = json.Unmarshal([]byte(`{"status":"STOPPED"}`), &test) if err != nil { t.Error(err) } if test.SomeStatus != ContainerStopped { t.Error("STOPPED should unmarshal to STOPPED, not " + test.SomeStatus.String()) } } type testContainerOverrides struct { SomeContainerOverrides ContainerOverrides `json:"overrides"` } type testContainerOverrideInput struct { SomeContainerOverrides string `json:"overrides"` } func TestUnmarshalContainerOverrides(t *testing.T) { overrides := &ContainerOverrides{} err := json.Unmarshal([]byte(`{"command": ["sh", "-c", "sleep 300"]}`), &overrides) if err != nil { t.Error(err) } if !reflect.DeepEqual(overrides.Command, &[]string{"sh", "-c", "sleep 300"}) { t.Error("Unmarshalled wrong result", overrides.Command) } var overrides3 testContainerOverrides err = json.Unmarshal([]byte(`{"overrides":{"command":["sh", "-c", "sleep 15"]}}`), &overrides3) if err != nil { t.Error(err) } if !reflect.DeepEqual(overrides3.SomeContainerOverrides.Command, &[]string{"sh", "-c", "sleep 15"}) { t.Error("unmarshalled wrong result", overrides3) } overrides2 := ContainerOverrides{Command: &[]string{"sh", "-c", "sleep 1"}} strOverrides, err := json.Marshal(overrides2) if err != nil { t.Error(err) } input := testContainerOverrideInput{SomeContainerOverrides: string(strOverrides)} strInput, err := json.Marshal(input) if err != nil { t.Error(err) } var overrides4 testContainerOverrides err = json.Unmarshal(strInput, &overrides4) if err != nil { t.Error(err) } if !reflect.DeepEqual(overrides4.SomeContainerOverrides.Command, &[]string{"sh", "-c", "sleep 1"}) { t.Error("Unmarshalled wrong result", overrides4) } // Test that marshalling an unknown key fails hard var overrides5 testContainerOverrides err = json.Unmarshal([]byte(`{"overrides":{"command":["ash","-c","sleep 1"],"containerPlanet":"mars"}}`), &overrides5) if err == nil { t.Error("No error on unknown json field containerPlanet") } // Test the same for the string err = json.Unmarshal([]byte(`{"overrides":"{\"command\":[\"ash\",\"-c\",\"sleep 1\"],\"containerPlanet\":\"mars\"}"}`), &overrides5) if err == nil { t.Error("No error for unknown json field in string, containerPlanet") } // Now error cases err = json.Unmarshal([]byte(`{"overrides":"a string that can't be json unmarshalled }{"}`), &overrides5) if err == nil { t.Error("No error when unmarshalling an invalid json string") } err = json.Unmarshal([]byte(`{"overrides": ["must be a string or object"] }`), &overrides5) if err == nil { t.Error("No error when unmarshalling a really invalid json string") } } func TestMarshalUnmarshalTaskVolumes(t *testing.T) { task := &Task{ Arn: "test", Volumes: []TaskVolume{ TaskVolume{Name: "1", Volume: &EmptyHostVolume{}}, TaskVolume{Name: "2", Volume: &FSHostVolume{FSSourcePath: "/path"}}, }, } marshal, err := json.Marshal(task) if err != nil { t.Fatal("Could not marshal: ", err) } var out Task err = json.Unmarshal(marshal, &out) if err != nil { t.Fatal("Could not unmarshal: ", err) } if len(out.Volumes) != 2 { t.Fatal("Incorrect number of volumes") } var v1, v2 TaskVolume for _, v := range out.Volumes { if v.Name == "1" { v1 = v } else { v2 = v } } if _, ok := v1.Volume.(*EmptyHostVolume); !ok { t.Error("Expected v1 to be an empty volume") } if v2.Volume.SourcePath() != "/path" { t.Error("Expected v2 to have 'sourcepath' work correctly") } fs, ok := v2.Volume.(*FSHostVolume) if !ok || fs.FSSourcePath != "/path" { t.Error("Unmarshaled v2 didn't match marshalled v2") } }
apache-2.0
caryll/Megaminx
types/glyph.js
2823
"use strict"; const clone = require("clone"); const Point = require("typo-geom").Point; const Transform = require("../geometry/transform"); const { mix } = require("../support/calc"); class Glyph { constructor(em, format) { this.em = em; this.tag = null; this.format = format; this.advanceWidth = 0; this.advanceHeight = 0; this.verticalOrigin = 0; this.contours = []; this.references = []; } unhint() { this.instructions = []; } transform(tfm) { for (let c of this.contours) { for (let j = 0; j < c.length; j++) { c[j] = tfm.applyTo(c[j]); } } this.unhint(); return this; } createPoint(Z) { if (Z instanceof Function) { return Z.call(this, this); } else { return Z; } } rz(rx, ry) { return new Point(this.advanceWidth * rx, this.em * ry); } vrz(rx, ry) { return new Point(this.advanceWidth * rx, this.verticalOrigin - this.advanceHeight * ry); } cbox() { let xmin = 0xffff, xmax = -0xffff, ymin = 0xffff, ymax = -0xffff; for (let contour of this.contours) { for (let point of contour) { if (point.x < xmin) xmin = point.x; if (point.x > xmax) xmax = point.x; if (point.y < ymin) ymin = point.y; if (point.y > ymax) ymax = point.y; } } return { xmin, xmax, ymin, ymax }; } mixz(u, v) { const { xmin, xmax, ymin, ymax } = this.cbox(); return new Point(mix(xmin, xmax, u), mix(ymin, ymax, v)); } center() { return this.mixz(1 / 2, 1 / 2); } setWidth(w) { this.advanceWidth = w; return this; } setVerticalLayout(top, adh) { this.verticalOrigin = top; this.advanceHeight = adh; return this; } overlay(...thats) { for (let that of thats) this.contours = this.contours.concat(clone(that.contours)); return this; } clone() { return clone(this); } assign(o) { Object.assign(this, o); return this; } } Glyph.from = function(font, glyph, name, format) { if (!glyph) return glyph; const g = new Glyph(font.head.unitsPerEm, format); Object.assign(g, glyph); g.sourceName = name; return g; }; Glyph.fromCopy = function(font, glyph, name, format) { if (!glyph) return glyph; const g = new Glyph(font.head.unitsPerEm); Object.assign(g, copyglyph(glyph, font)); g.sourceName = name; return g; }; function copyglyph(g, f) { const g1 = clone(g); g1.tag = null; if (f && g1.references) { if (!g1.contours) g1.contours = []; for (let ref of g1.references) { let g2 = Glyph.fromCopy(f, f.glyf[ref.glyph], ref.glyph); g2.transform(new Transform(ref.a, ref.b, ref.c, ref.d, ref.x, ref.y)); g1.contours = [...g1.contours, ...g2.contours]; } g1.references = []; } return g1; } Glyph.formats = { CUBIC: 3, QUADRATIC: 2 }; module.exports = Glyph;
apache-2.0
mikrain/appletv
ARSoft.Tools.Net/Dns/DnsRecord/MxRecord.cs
2776
#region Copyright and License // Copyright 2010..2012 Alexander Reinert // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ARSoft.Tools.Net.Dns { /// <summary> /// <para>Mail exchange</para> <para>Defined in /// <see cref="!:http://tools.ietf.org/html/rfc1035">RFC 1035</see> /// </para> /// </summary> public class MxRecord : DnsRecordBase { /// <summary> /// Preference of the record /// </summary> public ushort Preference { get; private set; } /// <summary> /// Host name of the mail exchanger /// </summary> public string ExchangeDomainName { get; private set; } internal MxRecord() {} /// <summary> /// Creates a new instance of the MxRecord class /// </summary> /// <param name="name"> Name of the zone </param> /// <param name="timeToLive"> Seconds the record should be cached at most </param> /// <param name="preference"> Preference of the record </param> /// <param name="exchangeDomainName"> Host name of the mail exchanger </param> public MxRecord(string name, int timeToLive, ushort preference, string exchangeDomainName) : base(name, RecordType.Mx, RecordClass.INet, timeToLive) { Preference = preference; ExchangeDomainName = exchangeDomainName ?? String.Empty; } internal override void ParseRecordData(byte[] resultData, int startPosition, int length) { Preference = DnsMessageBase.ParseUShort(resultData, ref startPosition); ExchangeDomainName = DnsMessageBase.ParseDomainName(resultData, ref startPosition); } internal override string RecordDataToString() { return Preference + " " + ExchangeDomainName; } protected internal override int MaximumRecordDataLength { get { return ExchangeDomainName.Length + 4; } } protected internal override void EncodeRecordData(byte[] messageData, int offset, ref int currentPosition, Dictionary<string, ushort> domainNames) { DnsMessageBase.EncodeUShort(messageData, ref currentPosition, Preference); DnsMessageBase.EncodeDomainName(messageData, offset, ref currentPosition, ExchangeDomainName, true, domainNames); } } }
apache-2.0
mfornos/humanize
humanize-slim/src/main/java/humanize/util/Constants.java
5494
package humanize.util; import humanize.spi.context.DefaultContext; import java.math.BigDecimal; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import com.google.common.base.Joiner; /** * Humanize constants * */ public final class Constants { public enum TimeStyle { STANDARD { public String format(DefaultContext ctx, boolean neg, int h, int m, int s) { return String.format("%s%d:%02d:%02d", neg ? '-' : "", h, m, s); } }, FRENCH_DECIMAL { public String format(DefaultContext ctx, boolean neg, int h, int m, int s) { String r; if (h == 0) { r = (m == 0) ? String.format("%d%s", s, ctx.timeSuffix(2)) : (s == 0) ? String.format("%d%s", m, ctx.timeSuffix(1)) : String.format("%d%s %d%s", m, ctx.timeSuffix(1), s, ctx.timeSuffix(2)); } else { r = (m == 0) ? ((s == 0) ? String.format("%d%s", h, ctx.timeSuffix(0)) : String.format("%d%s %d%s", h, ctx.timeSuffix(0), s, ctx.timeSuffix(2))) : (s == 0) ? String.format("%d%s %d%s", h, ctx.timeSuffix(0), m, ctx.timeSuffix(1)) : String.format("%d%s %d%s %d%s", h, ctx.timeSuffix(0), m, ctx.timeSuffix(1), s, ctx.timeSuffix(2)); } return (neg ? '-' : "") + r; } }; public abstract String format(DefaultContext defaultContext, boolean neg, int h, int m, int s); } public static final Pattern SPLIT_CAMEL = Pattern .compile("(?<=[A-Z])(?=[A-Z][a-z])|(?<=[^A-Z])(?=[A-Z])|(?<=[A-Za-z])(?=[^A-Za-z])"); public static final Pattern ONLY_SLUG_CHARS = Pattern.compile("[^-\\w\\s]"); public static final String DEFAULT_SLUG_SEPARATOR = "-"; public static final Pattern PUNCTUATION = Pattern.compile("\\p{Punct}+"); public static final Pattern COMB_DIACRITICAL = Pattern.compile("\\p{InCombiningDiacriticalMarks}+"); public static final Pattern HYPEN_SPACE = Pattern.compile("[-\\s]+"); // See http://en.wikipedia.org/wiki/UTF-16 public static final Pattern NOT_IN_BMP = Pattern.compile("([^\u0000-\uD7FF\uE000-\uFFFF])"); public static final String SPACE = " "; public static final String EMPTY = ""; public static final String ORDINAL_FMT = "%d%s"; public static final int ND_FACTOR = 1000 * 60 * 60 * 23; public static final BigDecimal THOUSAND = BigDecimal.valueOf(1000); public static final Map<BigDecimal, String> bigDecExponents = new LinkedHashMap<BigDecimal, String>(); static { bigDecExponents.put(BigDecimal.TEN.pow(3), "thousand"); bigDecExponents.put(BigDecimal.TEN.pow(6), "million"); bigDecExponents.put(BigDecimal.TEN.pow(9), "billion"); bigDecExponents.put(BigDecimal.TEN.pow(12), "trillion"); bigDecExponents.put(BigDecimal.TEN.pow(15), "quadrillion"); bigDecExponents.put(BigDecimal.TEN.pow(18), "quintillion"); bigDecExponents.put(BigDecimal.TEN.pow(21), "sextillion"); bigDecExponents.put(BigDecimal.TEN.pow(24), "septillion"); bigDecExponents.put(BigDecimal.TEN.pow(27), "octillion"); bigDecExponents.put(BigDecimal.TEN.pow(30), "nonillion"); bigDecExponents.put(BigDecimal.TEN.pow(33), "decillion"); bigDecExponents.put(BigDecimal.TEN.pow(36), "undecillion"); bigDecExponents.put(BigDecimal.TEN.pow(39), "duodecillion"); // bigDecExponents.put(BigDecimal.TEN.pow(100), "googol"); } public static final Map<Long, String> binPrefixes = new LinkedHashMap<Long, String>(); static { binPrefixes.put(1125899906842624L, "#.## PB"); binPrefixes.put(1099511627776L, "#.## TB"); binPrefixes.put(1073741824L, "#.## GB"); binPrefixes.put(1048576L, "#.## MB"); binPrefixes.put(1024L, "#.# KB"); binPrefixes.put(0L, "# bytes"); } public static final Map<Long, String> metricPrefixes = new LinkedHashMap<Long, String>(); static { metricPrefixes.put(1000000000000000L, "#.##P"); metricPrefixes.put(1000000000000L, "#.##T"); metricPrefixes.put(1000000000L, "#.##G"); metricPrefixes.put(1000000L, "#.##M"); metricPrefixes.put(1000L, "#.#k"); metricPrefixes.put(0L, "#.#"); } public static final Map<Long, String> nanoTimePrefixes = new LinkedHashMap<Long, String>(); static { nanoTimePrefixes.put(1000000000L, "#.##s"); nanoTimePrefixes.put(1000000L, "#.###ms"); nanoTimePrefixes.put(1000L, "#.####µs"); nanoTimePrefixes.put(0L, "#.####ns"); } public static final Joiner commaJoiner = Joiner.on(", ").skipNulls(); public static final List<String> titleIgnoredWords = Arrays.asList(new String[] { "a", "an", "and", "but", "nor", "it", "the", "to", "with", "in", "on", "of", "up", "or", "at", "into", "onto", "by", "from", "then", "for", "via", "versus" }); public static final Pattern titleWordSperator = Pattern.compile(".+(\\||-|/).+"); }
apache-2.0
StellarCN/py-stellar-base
stellar_sdk/xdr/account_entry_extension_v2_ext.py
1728
# This is an automatically generated file. # DO NOT EDIT or your changes may be overwritten import base64 from xdrlib import Packer, Unpacker from ..type_checked import type_checked from .base import Integer __all__ = ["AccountEntryExtensionV2Ext"] @type_checked class AccountEntryExtensionV2Ext: """ XDR Source Code:: union switch (int v) { case 0: void; } """ def __init__( self, v: int, ) -> None: self.v = v def pack(self, packer: Packer) -> None: Integer(self.v).pack(packer) if self.v == 0: return @classmethod def unpack(cls, unpacker: Unpacker) -> "AccountEntryExtensionV2Ext": v = Integer.unpack(unpacker) if v == 0: return cls(v=v) return cls(v=v) def to_xdr_bytes(self) -> bytes: packer = Packer() self.pack(packer) return packer.get_buffer() @classmethod def from_xdr_bytes(cls, xdr: bytes) -> "AccountEntryExtensionV2Ext": unpacker = Unpacker(xdr) return cls.unpack(unpacker) def to_xdr(self) -> str: xdr_bytes = self.to_xdr_bytes() return base64.b64encode(xdr_bytes).decode() @classmethod def from_xdr(cls, xdr: str) -> "AccountEntryExtensionV2Ext": xdr_bytes = base64.b64decode(xdr.encode()) return cls.from_xdr_bytes(xdr_bytes) def __eq__(self, other: object): if not isinstance(other, self.__class__): return NotImplemented return self.v == other.v def __str__(self): out = [] out.append(f"v={self.v}") return f"<AccountEntryExtensionV2Ext {[', '.join(out)]}>"
apache-2.0
googleapis/java-monitoring
samples/snippets/src/main/java/com/example/monitoring/GetMonitoredResource.java
1984
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.monitoring; // [START monitoring_get_resource] import com.google.api.MonitoredResourceDescriptor; import com.google.api.gax.rpc.ApiException; import com.google.cloud.monitoring.v3.MetricServiceClient; import com.google.monitoring.v3.MonitoredResourceDescriptorName; import java.io.IOException; // Sample to get monitored resource public class GetMonitoredResource { public static void main(String[] args) throws ApiException, IOException { // TODO(developer): Replace these variables before running the sample. String projectId = "your-project-id"; String resourceId = "your-resource-id"; getMonitoredResource(projectId, resourceId); } public static void getMonitoredResource(String projectId, String resourceId) throws ApiException, IOException { // Initialize client that will be used to send requests. This client only needs to be created // once, and can be reused for multiple requests. try (MetricServiceClient metricServiceClient = MetricServiceClient.create()) { MonitoredResourceDescriptorName name = MonitoredResourceDescriptorName.of(projectId, resourceId); // Prepare get monitor resource descriptor MonitoredResourceDescriptor response = metricServiceClient.getMonitoredResourceDescriptor(name); System.out.println(response); } } } // [END monitoring_get_resource]
apache-2.0
mihaip/overplot
geocode-locations.py
2220
#!/usr/bin/python MANHATTAN_ZIP_CODES = [ 10001, 10002, 10003, 10004, 10005, 10006, 10007, 10008, 10009, 10010, 10011, 10012, 10013, 10014, 10015, 10016, 10017, 10018, 10019, 10020, 10021, 10022, 10023, 10024, 10025, 10026, 10027, 10029, 10030, 10031, 10032, 10033, 10034, 10035, 10036, 10037, 10038, 10039, 10040, 10044, 10046, 10047, 10048, 10055, 10060, 10069, 10072, 10082, 10087, 10090, 10095, 10099, 10101, 10102, 10103, 10104, 10105, 10106, 10107, 10108, 10109, 10110, 10111, 10112, 10113, 10114, 10115, 10116, 10117, 10118, 10119, 10120, 10121, 10122, 10123, 10124, 10125, 10126, 10128, 10129, 10130, 10131, 10132, 10133, 10138, 10149, 10150, 10151, 10152, 10153, 10154, 10155, 10156, 10157, 10158, 10159, 10160, 10161, 10162, 10163, 10164, 10165, 10166, 10167, 10168, 10169, 10170, 10171, 10172, 10173, 10174, 10175, 10176, 10177, 10178, 10179, 10185, 10197, 10199, 10211, 10259, 10261, 10272, 10276 ] import csv, xmlrpclib geocoded_file = open("geocoded-locations.csv", "r") geocodes = {} for (address, lat, long) in csv.reader(geocoded_file): geocodes[address] = (lat, long) geocoded_file.close() locations_file = open("locations.csv", "r") server = xmlrpclib.Server("http://rpc.geocoder.us/service/xmlrpc") for (address,) in csv.reader(locations_file): if address.find("&") == -1 or address in geocodes: continue print "geocoding %s" % address result = server.geocode("%s, New York, NY" % address) geocoded_results = filter(lambda x: "lat" in x and "long" in x, result) if len(geocoded_results) > 1: manhattan_results = filter(lambda x: x["zip"] in MANHATTAN_ZIP_CODES, geocoded_results) if len(manhattan_results) == 1: geocoded_results = manhattan_results if len(geocoded_results) > 1: print " ambiguous geocode" elif len(geocoded_results) == 0: print " no results" else: (lat, long) = (geocoded_results[0]["lat"], geocoded_results[0]["long"]) geocodes[address] = [lat, long] geocoded_file = open("geocoded-locations.csv", "a") csv.writer(geocoded_file).writerow([address, lat, long]) geocoded_file.close() print " %f,%f" % (lat, long) locations_file.close()
apache-2.0
QISKit/qiskit-sdk-py
examples/python/stochastic_swap.py
6343
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Example of using the StochasticSwap pass.""" from qiskit.transpiler.passes import StochasticSwap from qiskit.transpiler import CouplingMap, Layout from qiskit.converters import circuit_to_dag, dag_to_circuit from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit coupling = CouplingMap([[0, 1], [1, 2], [1, 3]]) qr = QuantumRegister(4, 'q') cr = ClassicalRegister(4, 'c') circ = QuantumCircuit(qr, cr) circ.cx(qr[1], qr[2]) circ.cx(qr[0], qr[3]) circ.measure(qr[0], cr[0]) circ.h(qr) circ.cx(qr[0], qr[1]) circ.cx(qr[2], qr[3]) circ.measure(qr[0], cr[0]) circ.measure(qr[1], cr[1]) circ.measure(qr[2], cr[2]) circ.measure(qr[3], cr[3]) dag = circuit_to_dag(circ) # ┌─┐┌───┐ ┌─┐ # q_0: |0>─────────────────■──────────────────┤M├┤ H ├──■─────┤M├ # ┌───┐ │ └╥┘└───┘┌─┴─┐┌─┐└╥┘ # q_1: |0>──■───────┤ H ├──┼───────────────────╫──────┤ X ├┤M├─╫─ # ┌─┴─┐┌───┐└───┘ │ ┌─┐ ║ └───┘└╥┘ ║ # q_2: |0>┤ X ├┤ H ├───────┼─────────■─────┤M├─╫────────────╫──╫─ # └───┘└───┘ ┌─┴─┐┌───┐┌─┴─┐┌─┐└╥┘ ║ ║ ║ # q_3: |0>───────────────┤ X ├┤ H ├┤ X ├┤M├─╫──╫────────────╫──╫─ # └───┘└───┘└───┘└╥┘ ║ ║ ║ ║ # c_0: 0 ═══════════════════════════════╬══╬══╩════════════╬══╩═ # ║ ║ ║ # c_1: 0 ═══════════════════════════════╬══╬═══════════════╩════ # ║ ║ # c_2: 0 ═══════════════════════════════╬══╩════════════════════ # ║ # c_3: 0 ═══════════════════════════════╩═══════════════════════ # # ┌─┐┌───┐ ┌─┐ # q_0: |0>────────────────────■──┤M├┤ H ├──────────────────■──┤M├────── # ┌─┴─┐└╥┘└───┘┌───┐┌───┐ ┌─┴─┐└╥┘┌─┐ # q_1: |0>──■───X───────────┤ X ├─╫──────┤ H ├┤ X ├─X────┤ X ├─╫─┤M├─── # ┌─┴─┐ │ ┌───┐└───┘ ║ └───┘└─┬─┘ │ └───┘ ║ └╥┘┌─┐ # q_2: |0>┤ X ├─┼──────┤ H ├──────╫─────────────■───┼──────────╫──╫─┤M├ # └───┘ │ ┌───┐└───┘ ║ │ ┌─┐ ║ ║ └╥┘ # q_3: |0>──────X─┤ H ├───────────╫─────────────────X─┤M├──────╫──╫──╫─ # └───┘ ║ └╥┘ ║ ║ ║ # c_0: 0 ════════════════════════╩════════════════════╬═══════╩══╬══╬═ # ║ ║ ║ # c_1: 0 ═════════════════════════════════════════════╬══════════╩══╬═ # ║ ║ # c_2: 0 ═════════════════════════════════════════════╬═════════════╩═ # ║ # c_3: 0 ═════════════════════════════════════════════╩═══════════════ # # # 2 # | # 0 - 1 - 3 # Build the expected output to verify the pass worked expected = QuantumCircuit(qr, cr) expected.cx(qr[1], qr[2]) expected.swap(qr[0], qr[1]) expected.cx(qr[1], qr[3]) expected.h(qr[3]) expected.h(qr[2]) expected.measure(qr[1], cr[0]) expected.h(qr[0]) expected.swap(qr[1], qr[3]) expected.h(qr[3]) expected.cx(qr[2], qr[1]) expected.measure(qr[2], cr[2]) expected.swap(qr[1], qr[3]) expected.measure(qr[3], cr[3]) expected.cx(qr[1], qr[0]) expected.measure(qr[1], cr[0]) expected.measure(qr[0], cr[1]) expected_dag = circuit_to_dag(expected) # Run the pass on the dag from the input circuit pass_ = StochasticSwap(coupling, 20, 13) after = pass_.run(dag) # Verify the output of the pass matches our expectation assert expected_dag == after
apache-2.0
code-doyen/kata
test/src/com/comresource/kata/AllTests.java
242
package com.comresource.kata; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ TestBoard.class, TestView.class }) public class AllTests { }
apache-2.0
dagnir/aws-sdk-java
aws-java-sdk-opsworkscm/src/main/java/com/amazonaws/services/opsworkscm/model/BackupType.java
1619
/* * Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.opsworkscm.model; import javax.annotation.Generated; /** * */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public enum BackupType { AUTOMATED("AUTOMATED"), MANUAL("MANUAL"); private String value; private BackupType(String value) { this.value = value; } @Override public String toString() { return this.value; } /** * Use this in place of valueOf. * * @param value * real value * @return BackupType corresponding to the value */ public static BackupType fromValue(String value) { if (value == null || "".equals(value)) { throw new IllegalArgumentException("Value cannot be null or empty!"); } for (BackupType enumEntry : BackupType.values()) { if (enumEntry.toString().equals(value)) { return enumEntry; } } throw new IllegalArgumentException("Cannot create enum from " + value + " value!"); } }
apache-2.0
laccore/coretools
coretools-model/src/main/java/org/andrill/coretools/model/edit/CreateCommand.java
1551
/* * Copyright (c) Josh Reed, 2009. * * 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.andrill.coretools.model.edit; import org.andrill.coretools.model.Model; import org.andrill.coretools.model.ModelContainer; /** * A command for adding a model to a container. * * @author Josh Reed (jareed@andrill.org) */ public class CreateCommand extends AbstractCommand { protected Model model = null; protected ModelContainer container = null; /** * Create a new CreateCommand. * * @param model * the model. * @param container * the the container. */ public CreateCommand(final Model model, final ModelContainer container) { this.model = model; this.container = container; } /** * {@inheritDoc} */ @Override protected void executeCommand() { container.add(model); } /** * {@inheritDoc} */ public String getLabel() { return "Create: " + model.getModelType(); } /** * {@inheritDoc} */ @Override protected void undoCommand() { container.remove(model); } }
apache-2.0
gentics/mesh
core/src/main/java/com/gentics/mesh/core/endpoint/tagfamily/TagFamilyEndpoint.java
11598
package com.gentics.mesh.core.endpoint.tagfamily; import static com.gentics.mesh.core.rest.MeshEvent.NODE_UNTAGGED; import static com.gentics.mesh.core.rest.MeshEvent.TAG_CREATED; import static com.gentics.mesh.core.rest.MeshEvent.TAG_DELETED; import static com.gentics.mesh.core.rest.MeshEvent.TAG_FAMILY_CREATED; import static com.gentics.mesh.core.rest.MeshEvent.TAG_FAMILY_DELETED; import static com.gentics.mesh.core.rest.MeshEvent.TAG_FAMILY_UPDATED; import static com.gentics.mesh.core.rest.MeshEvent.TAG_UPDATED; import static com.gentics.mesh.example.ExampleUuids.TAGFAMILY_COLORS_UUID; import static com.gentics.mesh.example.ExampleUuids.TAG_BLUE_UUID; import static com.gentics.mesh.http.HttpConstants.APPLICATION_JSON; import static io.netty.handler.codec.http.HttpResponseStatus.CREATED; import static io.netty.handler.codec.http.HttpResponseStatus.NO_CONTENT; import static io.netty.handler.codec.http.HttpResponseStatus.OK; import static io.vertx.core.http.HttpMethod.DELETE; import static io.vertx.core.http.HttpMethod.GET; import static io.vertx.core.http.HttpMethod.POST; import javax.inject.Inject; import com.gentics.mesh.auth.MeshAuthChainImpl; import com.gentics.mesh.cli.BootstrapInitializer; import com.gentics.mesh.context.InternalActionContext; import com.gentics.mesh.core.endpoint.PathParameters; import com.gentics.mesh.core.endpoint.tag.TagCrudHandler; import com.gentics.mesh.parameter.impl.GenericParametersImpl; import com.gentics.mesh.parameter.impl.PagingParametersImpl; import com.gentics.mesh.rest.InternalEndpointRoute; import com.gentics.mesh.router.route.AbstractProjectEndpoint; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; /** * Endpoint for /api/v1/:project/tagFamilies */ public class TagFamilyEndpoint extends AbstractProjectEndpoint { private static final Logger log = LoggerFactory.getLogger(TagFamilyEndpoint.class); @Override public String getDescription() { return "Provides endpoints which allow the manipulation of tag families and tags."; } private TagFamilyCrudHandler tagFamilyCrudHandler; private TagCrudHandler tagCrudHandler; public TagFamilyEndpoint() { super("tagFamilies", null, null); } @Inject public TagFamilyEndpoint(MeshAuthChainImpl chain, BootstrapInitializer boot, TagCrudHandler tagCrudHandler, TagFamilyCrudHandler tagFamilyCrudHandler) { super("tagFamilies", chain, boot); this.tagCrudHandler = tagCrudHandler; this.tagFamilyCrudHandler = tagFamilyCrudHandler; } @Override public void registerEndPoints() { secureAll(); if (tagFamilyCrudHandler != null) { getRouter().routeWithRegex("\\/([^\\/]{32})\\/.*").handler(tagFamilyCrudHandler.getUuidHandler("tagfamily_not_found")); } addTagFamilyReadHandler(); addTagFamilyCreateHandler(); addTagFamilyUpdateHandler(); addTagFamilyDeleteHandler(); // Tags API addTagCreateHandler(); addTagReadHandler(); addTagUpdateHandler(); addTagDeleteHandler(); addTaggedNodesHandler(); if (log.isDebugEnabled()) { log.debug("Registered tagfamily verticle endpoints"); } } private void addTagUpdateHandler() { InternalEndpointRoute endpoint = createRoute(); endpoint.path("/:tagFamilyUuid/tags/:tagUuid"); endpoint.addUriParameter("tagFamilyUuid", "Uuid of the tag family.", TAGFAMILY_COLORS_UUID); endpoint.addUriParameter("tagUuid", "Uuid of the tag.", TAG_BLUE_UUID); endpoint.method(POST); endpoint.consumes(APPLICATION_JSON); endpoint.produces(APPLICATION_JSON); endpoint.description("Update the specified tag. The tag is created if no tag with the specified uuid could be found."); endpoint.exampleRequest(tagExamples.createTagUpdateRequest("Red")); endpoint.exampleResponse(OK, tagExamples.createTagResponse1("Red"), "Updated tag."); endpoint.events(TAG_UPDATED, TAG_CREATED); endpoint.blockingHandler(rc -> { InternalActionContext ac = wrap(rc); String tagFamilyUuid = PathParameters.getTagFamilyUuid(rc); String uuid = PathParameters.getTagUuid(rc); tagCrudHandler.handleUpdate(ac, tagFamilyUuid, uuid); }); } private void addTagCreateHandler() { InternalEndpointRoute createTag = createRoute(); createTag.description("Create a new tag within the tag family."); createTag.path("/:tagFamilyUuid/tags").method(POST).consumes(APPLICATION_JSON).produces(APPLICATION_JSON); createTag.addUriParameter("tagFamilyUuid", "Uuid of the tag family.", TAGFAMILY_COLORS_UUID); createTag.exampleRequest(tagExamples.createTagCreateRequest("red")); createTag.exampleResponse(OK, tagExamples.createTagResponse1("red"), "Created tag"); createTag.events(TAG_CREATED); createTag.blockingHandler(rc -> { InternalActionContext ac = wrap(rc); String tagFamilyUuid = PathParameters.getTagFamilyUuid(rc); tagCrudHandler.handleCreate(ac, tagFamilyUuid); }); } private void addTagReadHandler() { InternalEndpointRoute readOne = createRoute(); readOne.path("/:tagFamilyUuid/tags/:tagUuid"); readOne.addUriParameter("tagFamilyUuid", "Uuid of the tag family.", TAGFAMILY_COLORS_UUID); readOne.addUriParameter("tagUuid", "Uuid of the tag.", TAG_BLUE_UUID); readOne.method(GET); readOne.description("Read the specified tag from the tag family."); readOne.exampleResponse(OK, tagExamples.createTagResponse1("red"), "Loaded tag."); readOne.addQueryParameters(GenericParametersImpl.class); readOne.produces(APPLICATION_JSON); readOne.blockingHandler(rc -> { InternalActionContext ac = wrap(rc); String tagFamilyUuid = PathParameters.getTagFamilyUuid(rc); String uuid = PathParameters.getTagUuid(rc); tagCrudHandler.handleRead(ac, tagFamilyUuid, uuid); }); InternalEndpointRoute readAll = createRoute(); readAll.path("/:tagFamilyUuid/tags"); readAll.addUriParameter("tagFamilyUuid", "Uuid of the tag family.", TAGFAMILY_COLORS_UUID); readAll.method(GET); readAll.description("Load tags which were assigned to this tag family and return a paged list response."); readAll.exampleResponse(OK, tagExamples.createTagListResponse(), "List of tags."); readAll.produces(APPLICATION_JSON); readAll.addQueryParameters(PagingParametersImpl.class); readAll.addQueryParameters(GenericParametersImpl.class); readAll.blockingHandler(rc -> { InternalActionContext ac = wrap(rc); String tagFamilyUuid = PathParameters.getTagFamilyUuid(rc); tagCrudHandler.handleReadTagList(ac, tagFamilyUuid); }); } // TODO filter by projectName private void addTagDeleteHandler() { InternalEndpointRoute endpoint = createRoute(); endpoint.path("/:tagFamilyUuid/tags/:tagUuid"); endpoint.addUriParameter("tagFamilyUuid", "Uuid of the tag family.", TAGFAMILY_COLORS_UUID); endpoint.addUriParameter("tagUuid", "Uuid of the tag.", TAG_BLUE_UUID); endpoint.method(DELETE); endpoint.produces(APPLICATION_JSON); endpoint.description("Remove the tag from the tag family."); endpoint.exampleResponse(NO_CONTENT, "Tag was removed from the tag family"); endpoint.events(TAG_DELETED, NODE_UNTAGGED); endpoint.blockingHandler(rc -> { InternalActionContext ac = wrap(rc); String tagFamilyUuid = PathParameters.getTagFamilyUuid(rc); String uuid = PathParameters.getTagUuid(rc); tagCrudHandler.handleDelete(ac, tagFamilyUuid, uuid); }); } private void addTaggedNodesHandler() { InternalEndpointRoute endpoint = createRoute(); endpoint.path("/:tagFamilyUuid/tags/:tagUuid/nodes"); endpoint.addUriParameter("tagFamilyUuid", "Uuid of the tag family.", TAGFAMILY_COLORS_UUID); endpoint.addUriParameter("tagUuid", "Uuid of the tag.", TAG_BLUE_UUID); endpoint.method(GET); endpoint.produces(APPLICATION_JSON); endpoint.description("Load all nodes that have been tagged with the tag and return a paged list response."); endpoint.addQueryParameters(PagingParametersImpl.class); endpoint.exampleResponse(OK, nodeExamples.getNodeListResponse(), "List of nodes which were tagged using the provided tag."); endpoint.blockingHandler(rc -> { InternalActionContext ac = wrap(rc); String tagFamilyUuid = PathParameters.getTagFamilyUuid(rc); String uuid = PathParameters.getTagUuid(rc); tagCrudHandler.handleTaggedNodesList(ac, tagFamilyUuid, uuid); }); } private void addTagFamilyDeleteHandler() { InternalEndpointRoute endpoint = createRoute(); endpoint.path("/:tagFamilyUuid"); endpoint.addUriParameter("tagFamilyUuid", "Uuid of the tag family.", TAGFAMILY_COLORS_UUID); endpoint.method(DELETE); endpoint.produces(APPLICATION_JSON); endpoint.description("Delete the tag family."); endpoint.exampleResponse(NO_CONTENT, "Tag family was deleted."); endpoint.events(TAG_FAMILY_DELETED, TAG_DELETED, NODE_UNTAGGED); endpoint.blockingHandler(rc -> { InternalActionContext ac = wrap(rc); String tagFamilyUuid = PathParameters.getTagFamilyUuid(rc); tagFamilyCrudHandler.handleDelete(ac, tagFamilyUuid); }); } private void addTagFamilyReadHandler() { InternalEndpointRoute readOne = createRoute(); readOne.path("/:tagFamilyUuid"); readOne.addUriParameter("tagFamilyUuid", "Uuid of the tag family.", TAGFAMILY_COLORS_UUID); readOne.method(GET); readOne.description("Read the tag family with the given uuid."); readOne.produces(APPLICATION_JSON); readOne.exampleResponse(OK, tagFamilyExamples.getTagFamilyResponse("Colors"), "Loaded tag family."); readOne.blockingHandler(rc -> { InternalActionContext ac = wrap(rc); String tagFamilyUuid = PathParameters.getTagFamilyUuid(rc); tagFamilyCrudHandler.handleRead(ac, tagFamilyUuid); }); InternalEndpointRoute readAll = createRoute(); readAll.path("/"); readAll.method(GET); readAll.produces(APPLICATION_JSON); readAll.description("Load multiple tag families and return a paged list response."); readAll.addQueryParameters(PagingParametersImpl.class); readAll.exampleResponse(OK, tagFamilyExamples.getTagFamilyListResponse(), "Loaded tag families."); readAll.blockingHandler(rc -> { InternalActionContext ac = wrap(rc); tagFamilyCrudHandler.handleReadList(ac); }); } private void addTagFamilyCreateHandler() { InternalEndpointRoute endpoint = createRoute(); endpoint.path("/"); endpoint.method(POST); endpoint.description("Create a new tag family."); endpoint.consumes(APPLICATION_JSON); endpoint.produces(APPLICATION_JSON); endpoint.exampleRequest(tagFamilyExamples.getTagFamilyCreateRequest("Colors")); endpoint.exampleResponse(CREATED, tagFamilyExamples.getTagFamilyResponse("Colors"), "Created tag family."); endpoint.events(TAG_FAMILY_CREATED); endpoint.blockingHandler(rc -> { InternalActionContext ac = wrap(rc); tagFamilyCrudHandler.handleCreate(ac); }); } private void addTagFamilyUpdateHandler() { InternalEndpointRoute endpoint = createRoute(); endpoint.path("/:tagFamilyUuid"); endpoint.addUriParameter("tagFamilyUuid", "Uuid of the tag family.", TAGFAMILY_COLORS_UUID); endpoint.method(POST); endpoint.description("Update the tag family with the given uuid. The tag family will be created if it can't be found for the given uuid."); endpoint.consumes(APPLICATION_JSON); endpoint.produces(APPLICATION_JSON); endpoint.exampleRequest(tagFamilyExamples.getTagFamilyUpdateRequest("Nicer colors")); endpoint.exampleResponse(OK, tagFamilyExamples.getTagFamilyResponse("Nicer colors"), "Updated tag family."); endpoint.events(TAG_FAMILY_UPDATED, TAG_FAMILY_CREATED); endpoint.blockingHandler(rc -> { InternalActionContext ac = wrap(rc); String tagFamilyUuid = PathParameters.getTagFamilyUuid(rc); tagFamilyCrudHandler.handleUpdate(ac, tagFamilyUuid); }); } }
apache-2.0
supergiant/supergiant
pkg/workflows/steps/amazon/find_ami.go
3683
package amazon import ( "context" "fmt" "io" "strings" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/service/ec2" "github.com/pkg/errors" "github.com/sirupsen/logrus" "github.com/supergiant/control/pkg/util" "github.com/supergiant/control/pkg/workflows/steps" ) const StepFindAMI = "find_amazon_machine_image" type ImageFinder interface { DescribeImagesWithContext(aws.Context, *ec2.DescribeImagesInput, ...request.Option) (*ec2.DescribeImagesOutput, error) } type FindAMIStep struct { getImageService func(config steps.AWSConfig) (ImageFinder, error) } func NewFindAMIStep(fn GetEC2Fn) *FindAMIStep { return &FindAMIStep{ getImageService: func(config steps.AWSConfig) (ImageFinder, error) { EC2, err := fn(config) if err != nil { logrus.Errorf("[%s] - failed to authorize in AWS: %v", StepFindAMI, err) return nil, errors.Wrap(ErrAuthorization, err.Error()) } return EC2, nil }, } } func InitFindAMI(fn GetEC2Fn) { steps.RegisterStep(StepFindAMI, NewFindAMIStep(fn)) } func (s *FindAMIStep) Run(ctx context.Context, w io.Writer, cfg *steps.Config) error { finder, err := s.getImageService(cfg.AWSConfig) if err != nil { logrus.Errorf("[%s] - failed to authorize in AWS: %v", s.Name(), err) return errors.Wrap(err, StepFindAMI) } err = s.FindAMI(ctx, w, finder, cfg) logrus.Debugf("Found image id %s", cfg.AWSConfig.ImageID) if err != nil { logrus.Errorf("[%s] - failed to find AMI for Ubuntu: %v", s.Name(), err) return errors.Wrap(err, "failed to find AMI") } if err == nil && (cfg.AWSConfig.ImageID == "" || cfg.AWSConfig.DeviceName == "") { logrus.Debugf("[%s] - can't find supported image", s.Name()) return errors.New(fmt.Sprintf("[%s] - can't find "+ "supported image or device name", s.Name())) } logrus.Debugf("Use image id %s root device name %s", cfg.AWSConfig.ImageID, cfg.AWSConfig.DeviceName) return nil } func (*FindAMIStep) Name() string { return StepFindAMI } func (*FindAMIStep) Description() string { return "Step looks for Amazon Machine Image with specified parameters" } func (*FindAMIStep) Depends() []string { return nil } func (*FindAMIStep) Rollback(context.Context, io.Writer, *steps.Config) error { return nil } func (s *FindAMIStep) FindAMI(ctx context.Context, w io.Writer, finder ImageFinder, config *steps.Config) error { // TODO: should it be configurable? out, err := finder.DescribeImagesWithContext(ctx, &ec2.DescribeImagesInput{ Filters: []*ec2.Filter{ { Name: aws.String("architecture"), Values: []*string{ aws.String("x86_64"), }, }, { Name: aws.String("virtualization-type"), Values: []*string{ aws.String("hvm"), }, }, { Name: aws.String("root-device-type"), Values: []*string{ aws.String("ebs"), }, }, //Owner should be Canonical { Name: aws.String("owner-id"), Values: []*string{ aws.String("099720109477"), }, }, { Name: aws.String("description"), Values: []*string{ aws.String("Canonical, Ubuntu, 16.04*"), }, }, }, }) if err != nil { return err } log := util.GetLogger(w) for _, img := range out.Images { if img.Description == nil { continue } if strings.Contains(*img.Description, "UNSUPPORTED") { continue } config.AWSConfig.ImageID = *img.ImageId config.AWSConfig.DeviceName = *img.RootDeviceName logMessage := fmt.Sprintf("[%s] - using AMI (ID: %s) %s with root device name %s", s.Name(), *img.ImageId, *img.Description, *img.RootDeviceName) log.Info(logMessage) logrus.Info(logMessage) break } return nil }
apache-2.0
tndatacommons/OfficeHours-Android
model/src/main/java/org/tndata/officehours/model/Course.java
7584
package org.tndata.officehours.model; import android.os.Parcel; import android.support.annotation.NonNull; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; import java.util.List; /** * Model class for a course. * * @author Ismael Alonso * @version 1.0.0 */ public class Course extends Base{ //@SerializedName("code") //private String code; @SerializedName("name") private String name; @SerializedName("location") private String location; @SerializedName("meetingtime") private String meetingTime; @SerializedName("code") private String accessCode; @SerializedName("teacher") private Person instructor; @SerializedName("students") private List<Person> students; private String formattedMeetingTime; /** * Constructor. This one is meant to be used when creating courses locally, before posting * them to the backend. * * //@param code the code of the course. * @param name the name of the course. * @param location the location of the course. * @param meetingTime a representation of the days and times the course meets. */ public Course(/*@NonNull String code, */@NonNull String name, @NonNull String location, @NonNull String meetingTime){ this(-1, /*code,*/ name, location, meetingTime, ""); } /** * Constructor. This one is meant to be used when creating courses from database records. * * @param id the id of the course. * //@param code the code of the course. * @param name the name of the course. * @param location the location of the course. * @param meetingTime a representation of the days and times the course meets. * @param accessCode the code that grants access to the course. */ public Course(long id, /*@NonNull String code,*/ @NonNull String name, @NonNull String location, @NonNull String meetingTime, @NonNull String accessCode){ super(id); this.name = name; this.location = location; this.meetingTime = meetingTime; formattedMeetingTime = ""; this.accessCode = accessCode; } /** * Code getter. * * @return the course code. */ /*public String getCode(){ return code; }*/ /** * Name getter. * * @return the name of the course. */ public String getName(){ return name; } /** * Display name getter. Formatted <code>: <name> * * @return the display name of the course */ /*public String getDisplayName(){ return code + ": " + name; }*/ /** * Location getter. * * @return the location of the course. */ public String getLocation(){ return location; } /** * Meeting time getter. * * @return the meeting time of the course. */ public String getMeetingTime(){ return meetingTime; } public String getFormattedMeetingTime(){ return formattedMeetingTime; } /** * Access code getter. * * @return the course access code. */ public String getAccessCode(){ return accessCode; } /** * Instructor getter. * * @return the instructor of this course. */ public Person getInstructor(){ return instructor; } /** * Student getter. * * @return the list of students enrolled in this course. */ public List<Person> getStudents(){ return students; } /** * Instructor name getter. * * @return the name of this course's instructor. */ /*public String getInstructorName(){ return instructorName; }*/ /** * Code setter. * * @param code the course code. */ /*public void setCode(String code){ this.code = code; }*/ /** * Name setter. * * @param name the name of the course. */ public void setName(String name){ this.name = name; } /** * Meeting time setter. * * @param meetingTime the meeting time of the course. */ public void setMeetingTime(String meetingTime){ this.meetingTime = meetingTime; } /** * Sets the formatted meeting time. * * @param formattedMeetingTime formatted (K:mm a) meeting time of the course. */ public void setFormattedMeetingTime(String formattedMeetingTime){ this.formattedMeetingTime = formattedMeetingTime; } /** * Instructor setter. * * @param instructor the instructor of this course. */ public void setInstructor(Person instructor){ this.instructor = instructor; } /** * Student setter. * * @param students the students enrolled in this course. */ public void setStudents(List<Person> students){ this.students = students; } /** * Post processes the course after fetching it from the API. */ public void process(){ getInstructor().asInstructor(); for (Person student:getStudents()){ student.asStudent(); } } @Override public String toString(){ return "Course #" + getId() + ": " + getName() + " -> " + getLocation(); } @Override public boolean equals(Object o){ return o instanceof Course && ((Course)o).getId() == getId(); } /** * Compares the courses field by field, whereas equals only compares IDs. * * @param course the course to be compared. * @return true if the course's parameters are the same. */ public boolean parametersMatch(Course course){ if (equals(course)){ boolean match = name.equals(course.getName()); match &= location.equals(course.getLocation()); return match && meetingTime.equals(course.getMeetingTime()); } return false; } public void update(@NonNull Course course){ name = course.getName(); location = course.getLocation(); meetingTime = course.getMeetingTime(); } /*------------------* * PARCELABLE STUFF * *------------------*/ @Override public void writeToParcel(Parcel parcel, int flags){ super.writeToParcel(parcel, flags); //parcel.writeString(code); parcel.writeString(name); parcel.writeString(location); parcel.writeString(meetingTime); parcel.writeString(formattedMeetingTime); parcel.writeString(accessCode); parcel.writeParcelable(instructor, flags); parcel.writeTypedList(students); } public static final Creator<Course> CREATOR = new Creator<Course>(){ @Override public Course createFromParcel(Parcel src){ return new Course(src); } @Override public Course[] newArray(int count){ return new Course[count]; } }; /** * Constructor. Used by the creator. * * @param src the source parcel. */ protected Course(Parcel src){ super(src); //code = src.readString(); name = src.readString(); location = src.readString(); meetingTime = src.readString(); formattedMeetingTime = src.readString(); accessCode = src.readString(); instructor = src.readParcelable(Person.class.getClassLoader()); students = new ArrayList<>(); src.readTypedList(students, Person.CREATOR); } }
apache-2.0
googlecreativelab/lines-of-play
Assets/Scripts/ObjectPooler.cs
8645
using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.SceneManagement; [Serializable] public class ObjectPool { public GameObject ObjectToPool; public string PoolName; public int AmountToPool; public bool ShouldExpand = true; public ObjectPool() { } public ObjectPool(GameObject prefab, string name, int amount, bool expandable = true) { ObjectToPool = prefab; PoolName = name; AmountToPool = amount; ShouldExpand = expandable; } public void Initialize() { if (ObjectToPool != null) { Id = ObjectToPool.GetInstanceID(); Initialized = true; } } public bool Initialized { get; private set; } public int Id { get; private set; } public GameObject ParentPoolObject { get; set; } public LinkedList<GameObjectContainer> Items { get; } = new LinkedList<GameObjectContainer>(); public int Recycles { get; set; } public int Created { get; set; } public int Expands { get; set; } } public interface IPoolable { void Spawn(); void Despawn(); } public class GameObjectContainer { public ObjectPool Pool; public GameObject Object; public List<IPoolable> PoolingEnabledComponents; public int Cycles; public int TimesSkipped; public int TimesSelected; public int Despawns; public int Spawns; public int ObjectId; } public class ObjectPooler : MonoBehaviour { public static ObjectPooler Instance; public string RootPoolName = "Pooled Objects"; public List<ObjectPool> Pools; public Dictionary<int, GameObjectContainer> Map { get; } = new Dictionary<int, GameObjectContainer>(); void Awake() { Instance = this; SceneManager.sceneLoaded += SceneManagerOnSceneLoaded; } private void SceneManagerOnSceneLoaded(Scene arg0, LoadSceneMode loadSceneMode) { Debug.Log("Resetting Object Pools"); Reset(); } private void CreatePools() { foreach (var item in Pools) { for (int i = 0; i < item.AmountToPool; i++) { CreatePooledObject(item); } } } public void Reset() { foreach (var pool in Pools) { if(pool == null) continue; foreach (var item in pool.Items) { if(item == null) continue; if (item.Object != null) { Destroy(item.Object); } item.Object = null; item.Pool = null; item.PoolingEnabledComponents.Clear(); } pool.Items.Clear(); pool.ParentPoolObject = null; } Map.Clear(); CreatePools(); } /// <summary> /// Find/Create the parent which pooled objects should be attached to. /// </summary> private GameObject GetParentPoolObject(string objectPoolName) { if (string.IsNullOrEmpty(objectPoolName)) objectPoolName = RootPoolName; var parentObject = GameObject.Find(objectPoolName); if (parentObject != null) return parentObject; parentObject = new GameObject { name = objectPoolName }; if (objectPoolName == RootPoolName) return parentObject; var root = GameObject.Find(RootPoolName) ?? GetParentPoolObject(RootPoolName); parentObject.transform.parent = root.transform; return parentObject; } /// <summary> /// Create a new item for a given pool /// </summary> private GameObjectContainer CreatePooledObject(ObjectPool pool) { if (pool.ObjectToPool == null) { throw new Exception($"Object pool entry '{pool.PoolName}' needs a prefab attached"); } if (!pool.Initialized) pool.Initialize(); var obj = Instantiate(pool.ObjectToPool); obj.name = obj.name; if (pool.ParentPoolObject == null) pool.ParentPoolObject = GetParentPoolObject(pool.PoolName); obj.transform.parent = pool.ParentPoolObject.transform; obj.SetActive(false); var container = new GameObjectContainer { Object = obj, ObjectId = obj.GetInstanceID(), Pool = pool, PoolingEnabledComponents = obj.GetComponents<IPoolable>().ToList(), }; Map.Add(obj.GetInstanceID(), container); pool.Items.AddFirst(container); pool.Created++; return container; } /// <summary> /// Create an instance of an GameObject prefab. /// A replacment for 'Instantiate(...)'. /// </summary> /// <param name="prefab">A game object prefab to create an instance of</param> /// <param name="position">The position of the spawned GameObject</param> /// <param name="rotation">The rotation of the spawned GameObject</param> /// <returns>pooled GameObject</returns> public GameObject Spawn(GameObject prefab, Vector3 position, Quaternion rotation) { var id = prefab.GetInstanceID(); var pool = GetPoolForPrefab(id); if (pool == null) { pool = new ObjectPool(prefab, prefab.name, 25); //Debug.Log($"Dynamically creating pool for prefab {prefab.name}"); Pools.Add(pool); //throw new Exception($"Unable to find object pool for type"); } var container = FindFreePoolItem(pool); if (container == null) { if (!pool.ShouldExpand) return null; container = CreatePooledObject(pool); pool.Expands++; } else { pool.Recycles++; } container.Spawns++; RecycleItem(container, position, rotation); return container.Object; } /// <summary> /// Return GameObject to the pool. /// A replacement for 'Destroy(...)'. /// </summary> /// <param name="o"></param> public void Despawn(GameObject o) { if (o == null) return; var container = GetContainer(o.GetInstanceID()); if (container != null) { container.Despawns++; foreach (var c in container.PoolingEnabledComponents) { c.Despawn(); } } o.SetActive(false); } /// <summary> /// Reset transform and call IPoolable.Spawn on components. /// </summary> private static void RecycleItem(GameObjectContainer container, Vector3 position, Quaternion rotation) { var t = container.Object.transform; t.rotation = rotation; t.position = position; container.Object.SetActive(true); container.Cycles++; foreach (var c in container.PoolingEnabledComponents) { c.Spawn(); } } /// <summary> /// Get an item from a given pool that is not being used. /// </summary> private GameObjectContainer FindFreePoolItem(ObjectPool pool) { for (int i = 0; i < pool.Items.Count; i++) { var node = pool.Items.First; pool.Items.RemoveFirst(); pool.Items.AddLast(node); // Clean out objects that no longer exist (because of scene unload etc) var obj = node.Value.Object; if (obj == null) { DestroyContainer(node.Value); continue; } if (!obj.activeInHierarchy) { node.Value.TimesSelected++; return node.Value; } node.Value.TimesSkipped++; } return null; } private void DestroyContainer(GameObjectContainer container) { container.Pool.Items.Remove(container); Map.Remove(container.ObjectId); } private ObjectPool GetPoolForPrefab(int prefabInstanceId) { for (int i = 0; i < Pools.Count; i++) { var pool = Pools[i]; if (pool.Id == prefabInstanceId) return pool; } return null; } private GameObjectContainer GetContainer(int gameObjectInstanceId) { GameObjectContainer container; Map.TryGetValue(gameObjectInstanceId, out container); return container; } }
apache-2.0
gosu-lang/gosu-lang
gosu-core-api/src/main/java/gw/plugin/IPluginHost.java
414
package gw.plugin; /** * This simple interface provides the core foundation for component architecture in Gosu. */ public interface IPluginHost { /** * Provides an implementation of a specified interface. * @param apiInterface * @param <T> * @return The implementation of the interface or null if unsupported. */ default <T> T getInterface( Class<T> apiInterface ) { return null; } }
apache-2.0